[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaLambda.cpp
blob1cf44bd694c54dfedd5e40ae34f6b754fa378eaa
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.
11 //===----------------------------------------------------------------------===//
12 #include "clang/Sema/DeclSpec.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Sema/SemaInternal.h"
22 #include "clang/Sema/SemaLambda.h"
23 #include "llvm/ADT/STLExtras.h"
24 using namespace clang;
25 using namespace sema;
27 /// Examines the FunctionScopeInfo stack to determine the nearest
28 /// enclosing lambda (to the current lambda) that is 'capture-ready' for
29 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
30 /// If successful, returns the index into Sema's FunctionScopeInfo stack
31 /// of the capture-ready lambda's LambdaScopeInfo.
32 ///
33 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34 /// lambda - is on top) to determine the index of the nearest enclosing/outer
35 /// lambda that is ready to capture the \p VarToCapture being referenced in
36 /// the current lambda.
37 /// As we climb down the stack, we want the index of the first such lambda -
38 /// that is the lambda with the highest index that is 'capture-ready'.
39 ///
40 /// A lambda 'L' is capture-ready for 'V' (var or this) if:
41 /// - its enclosing context is non-dependent
42 /// - and if the chain of lambdas between L and the lambda in which
43 /// V is potentially used (i.e. the lambda at the top of the scope info
44 /// stack), can all capture or have already captured V.
45 /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46 ///
47 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48 /// for whether it is 'capture-capable' (see
49 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50 /// capture.
51 ///
52 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
54 /// is at the top of the stack and has the highest index.
55 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
56 ///
57 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59 /// which is capture-ready. If the return value evaluates to 'false' then
60 /// no lambda is capture-ready for \p VarToCapture.
62 static inline Optional<unsigned>
63 getStackIndexOfNearestEnclosingCaptureReadyLambda(
64 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65 VarDecl *VarToCapture) {
66 // Label failure to capture.
67 const Optional<unsigned> NoLambdaIsCaptureReady;
69 // Ignore all inner captured regions.
70 unsigned CurScopeIndex = FunctionScopes.size() - 1;
71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72 FunctionScopes[CurScopeIndex]))
73 --CurScopeIndex;
74 assert(
75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76 "The function on the top of sema's function-info stack must be a lambda");
78 // If VarToCapture is null, we are attempting to capture 'this'.
79 const bool IsCapturingThis = !VarToCapture;
80 const bool IsCapturingVariable = !IsCapturingThis;
82 // Start with the current lambda at the top of the stack (highest index).
83 DeclContext *EnclosingDC =
84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
86 do {
87 const clang::sema::LambdaScopeInfo *LSI =
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89 // IF we have climbed down to an intervening enclosing lambda that contains
90 // the variable declaration - it obviously can/must not capture the
91 // variable.
92 // Since its enclosing DC is dependent, all the lambdas between it and the
93 // innermost nested lambda are dependent (otherwise we wouldn't have
94 // arrived here) - so we don't yet have a lambda that can capture the
95 // variable.
96 if (IsCapturingVariable &&
97 VarToCapture->getDeclContext()->Equals(EnclosingDC))
98 return NoLambdaIsCaptureReady;
100 // For an enclosing lambda to be capture ready for an entity, all
101 // intervening lambda's have to be able to capture that entity. If even
102 // one of the intervening lambda's is not capable of capturing the entity
103 // then no enclosing lambda can ever capture that entity.
104 // For e.g.
105 // const int x = 10;
106 // [=](auto a) { #1
107 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
108 // [=](auto c) { #3
109 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
110 // }; }; };
111 // If they do not have a default implicit capture, check to see
112 // if the entity has already been explicitly captured.
113 // If even a single dependent enclosing lambda lacks the capability
114 // to ever capture this variable, there is no further enclosing
115 // non-dependent lambda that can capture this variable.
116 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
118 return NoLambdaIsCaptureReady;
119 if (IsCapturingThis && !LSI->isCXXThisCaptured())
120 return NoLambdaIsCaptureReady;
122 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
124 assert(CurScopeIndex);
125 --CurScopeIndex;
126 } while (!EnclosingDC->isTranslationUnit() &&
127 EnclosingDC->isDependentContext() &&
128 isLambdaCallOperator(EnclosingDC));
130 assert(CurScopeIndex < (FunctionScopes.size() - 1));
131 // If the enclosingDC is not dependent, then the immediately nested lambda
132 // (one index above) is capture-ready.
133 if (!EnclosingDC->isDependentContext())
134 return CurScopeIndex + 1;
135 return NoLambdaIsCaptureReady;
138 /// Examines the FunctionScopeInfo stack to determine the nearest
139 /// enclosing lambda (to the current lambda) that is 'capture-capable' for
140 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
141 /// If successful, returns the index into Sema's FunctionScopeInfo stack
142 /// of the capture-capable lambda's LambdaScopeInfo.
144 /// Given the current stack of lambdas being processed by Sema and
145 /// the variable of interest, to identify the nearest enclosing lambda (to the
146 /// current lambda at the top of the stack) that can truly capture
147 /// a variable, it has to have the following two properties:
148 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149 /// - climb down the stack (i.e. starting from the innermost and examining
150 /// each outer lambda step by step) checking if each enclosing
151 /// lambda can either implicitly or explicitly capture the variable.
152 /// Record the first such lambda that is enclosed in a non-dependent
153 /// context. If no such lambda currently exists return failure.
154 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155 /// capture the variable by checking all its enclosing lambdas:
156 /// - check if all outer lambdas enclosing the 'capture-ready' lambda
157 /// identified above in 'a' can also capture the variable (this is done
158 /// via tryCaptureVariable for variables and CheckCXXThisCapture for
159 /// 'this' by passing in the index of the Lambda identified in step 'a')
161 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
163 /// is at the top of the stack.
165 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
168 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170 /// which is capture-capable. If the return value evaluates to 'false' then
171 /// no lambda is capture-capable for \p VarToCapture.
173 Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175 VarDecl *VarToCapture, Sema &S) {
177 const Optional<unsigned> NoLambdaIsCaptureCapable;
179 const Optional<unsigned> OptionalStackIndex =
180 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181 VarToCapture);
182 if (!OptionalStackIndex)
183 return NoLambdaIsCaptureCapable;
185 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
187 S.getCurGenericLambda()) &&
188 "The capture ready lambda for a potential capture can only be the "
189 "current lambda if it is a generic lambda");
191 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
194 // If VarToCapture is null, we are attempting to capture 'this'
195 const bool IsCapturingThis = !VarToCapture;
196 const bool IsCapturingVariable = !IsCapturingThis;
198 if (IsCapturingVariable) {
199 // Check if the capture-ready lambda can truly capture the variable, by
200 // checking whether all enclosing lambdas of the capture-ready lambda allow
201 // the capture - i.e. make sure it is capture-capable.
202 QualType CaptureType, DeclRefType;
203 const bool CanCaptureVariable =
204 !S.tryCaptureVariable(VarToCapture,
205 /*ExprVarIsUsedInLoc*/ SourceLocation(),
206 clang::Sema::TryCapture_Implicit,
207 /*EllipsisLoc*/ SourceLocation(),
208 /*BuildAndDiagnose*/ false, CaptureType,
209 DeclRefType, &IndexOfCaptureReadyLambda);
210 if (!CanCaptureVariable)
211 return NoLambdaIsCaptureCapable;
212 } else {
213 // Check if the capture-ready lambda can truly capture 'this' by checking
214 // whether all enclosing lambdas of the capture-ready lambda can capture
215 // 'this'.
216 const bool CanCaptureThis =
217 !S.CheckCXXThisCapture(
218 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220 &IndexOfCaptureReadyLambda);
221 if (!CanCaptureThis)
222 return NoLambdaIsCaptureCapable;
224 return IndexOfCaptureReadyLambda;
227 static inline TemplateParameterList *
228 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
230 LSI->GLTemplateParameterList = TemplateParameterList::Create(
231 SemaRef.Context,
232 /*Template kw loc*/ SourceLocation(),
233 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
234 LSI->TemplateParams,
235 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236 LSI->RequiresClause.get());
238 return LSI->GLTemplateParameterList;
241 CXXRecordDecl *
242 Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
243 unsigned LambdaDependencyKind,
244 LambdaCaptureDefault CaptureDefault) {
245 DeclContext *DC = CurContext;
246 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
247 DC = DC->getParent();
248 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
249 *this);
250 // Start constructing the lambda class.
251 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
252 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
253 IsGenericLambda, CaptureDefault);
254 DC->addDecl(Class);
256 return Class;
259 /// Determine whether the given context is or is enclosed in an inline
260 /// function.
261 static bool isInInlineFunction(const DeclContext *DC) {
262 while (!DC->isFileContext()) {
263 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
264 if (FD->isInlined())
265 return true;
267 DC = DC->getLexicalParent();
270 return false;
273 std::tuple<MangleNumberingContext *, Decl *>
274 Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
275 // Compute the context for allocating mangling numbers in the current
276 // expression, if the ABI requires them.
277 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
279 enum ContextKind {
280 Normal,
281 DefaultArgument,
282 DataMember,
283 StaticDataMember,
284 InlineVariable,
285 VariableTemplate
286 } Kind = Normal;
288 // Default arguments of member function parameters that appear in a class
289 // definition, as well as the initializers of data members, receive special
290 // treatment. Identify them.
291 if (ManglingContextDecl) {
292 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
293 if (const DeclContext *LexicalDC
294 = Param->getDeclContext()->getLexicalParent())
295 if (LexicalDC->isRecord())
296 Kind = DefaultArgument;
297 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
298 if (Var->getDeclContext()->isRecord())
299 Kind = StaticDataMember;
300 else if (Var->getMostRecentDecl()->isInline())
301 Kind = InlineVariable;
302 else if (Var->getDescribedVarTemplate())
303 Kind = VariableTemplate;
304 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
305 if (!VTS->isExplicitSpecialization())
306 Kind = VariableTemplate;
308 } else if (isa<FieldDecl>(ManglingContextDecl)) {
309 Kind = DataMember;
313 // Itanium ABI [5.1.7]:
314 // In the following contexts [...] the one-definition rule requires closure
315 // types in different translation units to "correspond":
316 bool IsInNonspecializedTemplate =
317 inTemplateInstantiation() || CurContext->isDependentContext();
318 switch (Kind) {
319 case Normal: {
320 // -- the bodies of non-exported nonspecialized template functions
321 // -- the bodies of inline functions
322 if ((IsInNonspecializedTemplate &&
323 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
324 isInInlineFunction(CurContext)) {
325 while (auto *CD = dyn_cast<CapturedDecl>(DC))
326 DC = CD->getParent();
327 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
330 return std::make_tuple(nullptr, nullptr);
333 case StaticDataMember:
334 // -- the initializers of nonspecialized static members of template classes
335 if (!IsInNonspecializedTemplate)
336 return std::make_tuple(nullptr, ManglingContextDecl);
337 // Fall through to get the current context.
338 [[fallthrough]];
340 case DataMember:
341 // -- the in-class initializers of class members
342 case DefaultArgument:
343 // -- default arguments appearing in class definitions
344 case InlineVariable:
345 // -- the initializers of inline variables
346 case VariableTemplate:
347 // -- the initializers of templated variables
348 return std::make_tuple(
349 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
350 ManglingContextDecl),
351 ManglingContextDecl);
354 llvm_unreachable("unexpected context");
357 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
358 SourceRange IntroducerRange,
359 TypeSourceInfo *MethodTypeInfo,
360 SourceLocation EndLoc,
361 ArrayRef<ParmVarDecl *> Params,
362 ConstexprSpecKind ConstexprKind,
363 Expr *TrailingRequiresClause) {
364 QualType MethodType = MethodTypeInfo->getType();
365 TemplateParameterList *TemplateParams =
366 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
367 // If a lambda appears in a dependent context or is a generic lambda (has
368 // template parameters) and has an 'auto' return type, deduce it to a
369 // dependent type.
370 if (Class->isDependentContext() || TemplateParams) {
371 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
372 QualType Result = FPT->getReturnType();
373 if (Result->isUndeducedType()) {
374 Result = SubstAutoTypeDependent(Result);
375 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
376 FPT->getExtProtoInfo());
380 // C++11 [expr.prim.lambda]p5:
381 // The closure type for a lambda-expression has a public inline function
382 // call operator (13.5.4) whose parameters and return type are described by
383 // the lambda-expression's parameter-declaration-clause and
384 // trailing-return-type respectively.
385 DeclarationName MethodName
386 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
387 DeclarationNameLoc MethodNameLoc =
388 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
389 CXXMethodDecl *Method = CXXMethodDecl::Create(
390 Context, Class, EndLoc,
391 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
392 MethodNameLoc),
393 MethodType, MethodTypeInfo, SC_None, getCurFPFeatures().isFPConstrained(),
394 /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
395 Method->setAccess(AS_public);
396 if (!TemplateParams)
397 Class->addDecl(Method);
399 // Temporarily set the lexical declaration context to the current
400 // context, so that the Scope stack matches the lexical nesting.
401 Method->setLexicalDeclContext(CurContext);
402 // Create a function template if we have a template parameter list
403 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
404 FunctionTemplateDecl::Create(Context, Class,
405 Method->getLocation(), MethodName,
406 TemplateParams,
407 Method) : nullptr;
408 if (TemplateMethod) {
409 TemplateMethod->setAccess(AS_public);
410 Method->setDescribedFunctionTemplate(TemplateMethod);
411 Class->addDecl(TemplateMethod);
412 TemplateMethod->setLexicalDeclContext(CurContext);
415 // Add parameters.
416 if (!Params.empty()) {
417 Method->setParams(Params);
418 CheckParmsForFunctionDef(Params,
419 /*CheckParameterNames=*/false);
421 for (auto *P : Method->parameters())
422 P->setOwningFunction(Method);
425 return Method;
428 void Sema::handleLambdaNumbering(
429 CXXRecordDecl *Class, CXXMethodDecl *Method,
430 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
431 if (Mangling) {
432 bool HasKnownInternalLinkage;
433 unsigned ManglingNumber, DeviceManglingNumber;
434 Decl *ManglingContextDecl;
435 std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
436 ManglingContextDecl) = *Mangling;
437 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
438 HasKnownInternalLinkage);
439 Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
440 return;
443 auto getMangleNumberingContext =
444 [this](CXXRecordDecl *Class,
445 Decl *ManglingContextDecl) -> MangleNumberingContext * {
446 // Get mangle numbering context if there's any extra decl context.
447 if (ManglingContextDecl)
448 return &Context.getManglingNumberContext(
449 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
450 // Otherwise, from that lambda's decl context.
451 auto DC = Class->getDeclContext();
452 while (auto *CD = dyn_cast<CapturedDecl>(DC))
453 DC = CD->getParent();
454 return &Context.getManglingNumberContext(DC);
457 MangleNumberingContext *MCtx;
458 Decl *ManglingContextDecl;
459 std::tie(MCtx, ManglingContextDecl) =
460 getCurrentMangleNumberContext(Class->getDeclContext());
461 bool HasKnownInternalLinkage = false;
462 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
463 getLangOpts().SYCLIsHost)) {
464 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
465 // ODR. Both device- and host-compilation need to have a consistent naming
466 // on kernel functions. As lambdas are potential part of these `__global__`
467 // function names, they needs numbering following ODR.
468 // Also force for SYCL, since we need this for the
469 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
470 // mangling.
471 MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
472 assert(MCtx && "Retrieving mangle numbering context failed!");
473 HasKnownInternalLinkage = true;
475 if (MCtx) {
476 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
477 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
478 HasKnownInternalLinkage);
479 Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
483 void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
484 CXXMethodDecl *CallOperator,
485 SourceRange IntroducerRange,
486 LambdaCaptureDefault CaptureDefault,
487 SourceLocation CaptureDefaultLoc,
488 bool ExplicitParams,
489 bool ExplicitResultType,
490 bool Mutable) {
491 LSI->CallOperator = CallOperator;
492 CXXRecordDecl *LambdaClass = CallOperator->getParent();
493 LSI->Lambda = LambdaClass;
494 if (CaptureDefault == LCD_ByCopy)
495 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
496 else if (CaptureDefault == LCD_ByRef)
497 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
498 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
499 LSI->IntroducerRange = IntroducerRange;
500 LSI->ExplicitParams = ExplicitParams;
501 LSI->Mutable = Mutable;
503 if (ExplicitResultType) {
504 LSI->ReturnType = CallOperator->getReturnType();
506 if (!LSI->ReturnType->isDependentType() &&
507 !LSI->ReturnType->isVoidType()) {
508 if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
509 diag::err_lambda_incomplete_result)) {
510 // Do nothing.
513 } else {
514 LSI->HasImplicitReturnType = true;
518 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
519 LSI->finishedExplicitCaptures();
522 void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
523 ArrayRef<NamedDecl *> TParams,
524 SourceLocation RAngleLoc,
525 ExprResult RequiresClause) {
526 LambdaScopeInfo *LSI = getCurLambda();
527 assert(LSI && "Expected a lambda scope");
528 assert(LSI->NumExplicitTemplateParams == 0 &&
529 "Already acted on explicit template parameters");
530 assert(LSI->TemplateParams.empty() &&
531 "Explicit template parameters should come "
532 "before invented (auto) ones");
533 assert(!TParams.empty() &&
534 "No template parameters to act on");
535 LSI->TemplateParams.append(TParams.begin(), TParams.end());
536 LSI->NumExplicitTemplateParams = TParams.size();
537 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
538 LSI->RequiresClause = RequiresClause;
541 void Sema::addLambdaParameters(
542 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
543 CXXMethodDecl *CallOperator, Scope *CurScope) {
544 // Introduce our parameters into the function scope
545 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
546 p < NumParams; ++p) {
547 ParmVarDecl *Param = CallOperator->getParamDecl(p);
549 // If this has an identifier, add it to the scope stack.
550 if (CurScope && Param->getIdentifier()) {
551 bool Error = false;
552 // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
553 // retroactively apply it.
554 for (const auto &Capture : Captures) {
555 if (Capture.Id == Param->getIdentifier()) {
556 Error = true;
557 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
558 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
559 << Capture.Id << true;
562 if (!Error)
563 CheckShadow(CurScope, Param);
565 PushOnScopeChains(Param, CurScope);
570 /// If this expression is an enumerator-like expression of some type
571 /// T, return the type T; otherwise, return null.
573 /// Pointer comparisons on the result here should always work because
574 /// it's derived from either the parent of an EnumConstantDecl
575 /// (i.e. the definition) or the declaration returned by
576 /// EnumType::getDecl() (i.e. the definition).
577 static EnumDecl *findEnumForBlockReturn(Expr *E) {
578 // An expression is an enumerator-like expression of type T if,
579 // ignoring parens and parens-like expressions:
580 E = E->IgnoreParens();
582 // - it is an enumerator whose enum type is T or
583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
584 if (EnumConstantDecl *D
585 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
586 return cast<EnumDecl>(D->getDeclContext());
588 return nullptr;
591 // - it is a comma expression whose RHS is an enumerator-like
592 // expression of type T or
593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
594 if (BO->getOpcode() == BO_Comma)
595 return findEnumForBlockReturn(BO->getRHS());
596 return nullptr;
599 // - it is a statement-expression whose value expression is an
600 // enumerator-like expression of type T or
601 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
602 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
603 return findEnumForBlockReturn(last);
604 return nullptr;
607 // - it is a ternary conditional operator (not the GNU ?:
608 // extension) whose second and third operands are
609 // enumerator-like expressions of type T or
610 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
611 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
612 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
613 return ED;
614 return nullptr;
617 // (implicitly:)
618 // - it is an implicit integral conversion applied to an
619 // enumerator-like expression of type T or
620 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
621 // We can sometimes see integral conversions in valid
622 // enumerator-like expressions.
623 if (ICE->getCastKind() == CK_IntegralCast)
624 return findEnumForBlockReturn(ICE->getSubExpr());
626 // Otherwise, just rely on the type.
629 // - it is an expression of that formal enum type.
630 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
631 return ET->getDecl();
634 // Otherwise, nope.
635 return nullptr;
638 /// Attempt to find a type T for which the returned expression of the
639 /// given statement is an enumerator-like expression of that type.
640 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
641 if (Expr *retValue = ret->getRetValue())
642 return findEnumForBlockReturn(retValue);
643 return nullptr;
646 /// Attempt to find a common type T for which all of the returned
647 /// expressions in a block are enumerator-like expressions of that
648 /// type.
649 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
650 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
652 // Try to find one for the first return.
653 EnumDecl *ED = findEnumForBlockReturn(*i);
654 if (!ED) return nullptr;
656 // Check that the rest of the returns have the same enum.
657 for (++i; i != e; ++i) {
658 if (findEnumForBlockReturn(*i) != ED)
659 return nullptr;
662 // Never infer an anonymous enum type.
663 if (!ED->hasNameForLinkage()) return nullptr;
665 return ED;
668 /// Adjust the given return statements so that they formally return
669 /// the given type. It should require, at most, an IntegralCast.
670 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
671 QualType returnType) {
672 for (ArrayRef<ReturnStmt*>::iterator
673 i = returns.begin(), e = returns.end(); i != e; ++i) {
674 ReturnStmt *ret = *i;
675 Expr *retValue = ret->getRetValue();
676 if (S.Context.hasSameType(retValue->getType(), returnType))
677 continue;
679 // Right now we only support integral fixup casts.
680 assert(returnType->isIntegralOrUnscopedEnumerationType());
681 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
683 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
685 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
686 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
687 /*base path*/ nullptr, VK_PRValue,
688 FPOptionsOverride());
689 if (cleanups) {
690 cleanups->setSubExpr(E);
691 } else {
692 ret->setRetValue(E);
697 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
698 assert(CSI.HasImplicitReturnType);
699 // If it was ever a placeholder, it had to been deduced to DependentTy.
700 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
701 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
702 "lambda expressions use auto deduction in C++14 onwards");
704 // C++ core issue 975:
705 // If a lambda-expression does not include a trailing-return-type,
706 // it is as if the trailing-return-type denotes the following type:
707 // - if there are no return statements in the compound-statement,
708 // or all return statements return either an expression of type
709 // void or no expression or braced-init-list, the type void;
710 // - otherwise, if all return statements return an expression
711 // and the types of the returned expressions after
712 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
713 // array-to-pointer conversion (4.2 [conv.array]), and
714 // function-to-pointer conversion (4.3 [conv.func]) are the
715 // same, that common type;
716 // - otherwise, the program is ill-formed.
718 // C++ core issue 1048 additionally removes top-level cv-qualifiers
719 // from the types of returned expressions to match the C++14 auto
720 // deduction rules.
722 // In addition, in blocks in non-C++ modes, if all of the return
723 // statements are enumerator-like expressions of some type T, where
724 // T has a name for linkage, then we infer the return type of the
725 // block to be that type.
727 // First case: no return statements, implicit void return type.
728 ASTContext &Ctx = getASTContext();
729 if (CSI.Returns.empty()) {
730 // It's possible there were simply no /valid/ return statements.
731 // In this case, the first one we found may have at least given us a type.
732 if (CSI.ReturnType.isNull())
733 CSI.ReturnType = Ctx.VoidTy;
734 return;
737 // Second case: at least one return statement has dependent type.
738 // Delay type checking until instantiation.
739 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
740 if (CSI.ReturnType->isDependentType())
741 return;
743 // Try to apply the enum-fuzz rule.
744 if (!getLangOpts().CPlusPlus) {
745 assert(isa<BlockScopeInfo>(CSI));
746 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
747 if (ED) {
748 CSI.ReturnType = Context.getTypeDeclType(ED);
749 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
750 return;
754 // Third case: only one return statement. Don't bother doing extra work!
755 if (CSI.Returns.size() == 1)
756 return;
758 // General case: many return statements.
759 // Check that they all have compatible return types.
761 // We require the return types to strictly match here.
762 // Note that we've already done the required promotions as part of
763 // processing the return statement.
764 for (const ReturnStmt *RS : CSI.Returns) {
765 const Expr *RetE = RS->getRetValue();
767 QualType ReturnType =
768 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
769 if (Context.getCanonicalFunctionResultType(ReturnType) ==
770 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
771 // Use the return type with the strictest possible nullability annotation.
772 auto RetTyNullability = ReturnType->getNullability(Ctx);
773 auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
774 if (BlockNullability &&
775 (!RetTyNullability ||
776 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
777 CSI.ReturnType = ReturnType;
778 continue;
781 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
782 // TODO: It's possible that the *first* return is the divergent one.
783 Diag(RS->getBeginLoc(),
784 diag::err_typecheck_missing_return_type_incompatible)
785 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
786 // Continue iterating so that we keep emitting diagnostics.
790 QualType Sema::buildLambdaInitCaptureInitialization(
791 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
792 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
793 Expr *&Init) {
794 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
795 // deduce against.
796 QualType DeductType = Context.getAutoDeductType();
797 TypeLocBuilder TLB;
798 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
799 TL.setNameLoc(Loc);
800 if (ByRef) {
801 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
802 assert(!DeductType.isNull() && "can't build reference to auto");
803 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
805 if (EllipsisLoc.isValid()) {
806 if (Init->containsUnexpandedParameterPack()) {
807 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
808 ? diag::warn_cxx17_compat_init_capture_pack
809 : diag::ext_init_capture_pack);
810 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
811 /*ExpectPackInType=*/false);
812 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
813 } else {
814 // Just ignore the ellipsis for now and form a non-pack variable. We'll
815 // diagnose this later when we try to capture it.
818 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
820 // Deduce the type of the init capture.
821 QualType DeducedType = deduceVarTypeFromInitializer(
822 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
823 SourceRange(Loc, Loc), IsDirectInit, Init);
824 if (DeducedType.isNull())
825 return QualType();
827 // Are we a non-list direct initialization?
828 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
830 // Perform initialization analysis and ensure any implicit conversions
831 // (such as lvalue-to-rvalue) are enforced.
832 InitializedEntity Entity =
833 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
834 InitializationKind Kind =
835 IsDirectInit
836 ? (CXXDirectInit ? InitializationKind::CreateDirect(
837 Loc, Init->getBeginLoc(), Init->getEndLoc())
838 : InitializationKind::CreateDirectList(Loc))
839 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
841 MultiExprArg Args = Init;
842 if (CXXDirectInit)
843 Args =
844 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
845 QualType DclT;
846 InitializationSequence InitSeq(*this, Entity, Kind, Args);
847 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
849 if (Result.isInvalid())
850 return QualType();
852 Init = Result.getAs<Expr>();
853 return DeducedType;
856 VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
857 QualType InitCaptureType,
858 SourceLocation EllipsisLoc,
859 IdentifierInfo *Id,
860 unsigned InitStyle, Expr *Init) {
861 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
862 // rather than reconstructing it here.
863 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
864 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
865 PETL.setEllipsisLoc(EllipsisLoc);
867 // Create a dummy variable representing the init-capture. This is not actually
868 // used as a variable, and only exists as a way to name and refer to the
869 // init-capture.
870 // FIXME: Pass in separate source locations for '&' and identifier.
871 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
872 Loc, Id, InitCaptureType, TSI, SC_Auto);
873 NewVD->setInitCapture(true);
874 NewVD->setReferenced(true);
875 // FIXME: Pass in a VarDecl::InitializationStyle.
876 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
877 NewVD->markUsed(Context);
878 NewVD->setInit(Init);
879 if (NewVD->isParameterPack())
880 getCurLambda()->LocalPacks.push_back(NewVD);
881 return NewVD;
884 void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
885 assert(Var->isInitCapture() && "init capture flag should be set");
886 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
887 /*isNested*/false, Var->getLocation(), SourceLocation(),
888 Var->getType(), /*Invalid*/false);
891 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
892 Declarator &ParamInfo,
893 Scope *CurScope) {
894 LambdaScopeInfo *const LSI = getCurLambda();
895 assert(LSI && "LambdaScopeInfo should be on stack!");
897 // Determine if we're within a context where we know that the lambda will
898 // be dependent, because there are template parameters in scope.
899 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
900 CXXRecordDecl::LDK_Unknown;
901 if (LSI->NumExplicitTemplateParams > 0) {
902 auto *TemplateParamScope = CurScope->getTemplateParamParent();
903 assert(TemplateParamScope &&
904 "Lambda with explicit template param list should establish a "
905 "template param scope");
906 assert(TemplateParamScope->getParent());
907 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
908 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
909 } else if (CurScope->getTemplateParamParent() != nullptr) {
910 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
913 // Determine the signature of the call operator.
914 TypeSourceInfo *MethodTyInfo;
915 bool ExplicitParams = true;
916 bool ExplicitResultType = true;
917 bool ContainsUnexpandedParameterPack = false;
918 SourceLocation EndLoc;
919 SmallVector<ParmVarDecl *, 8> Params;
920 if (ParamInfo.getNumTypeObjects() == 0) {
921 // C++11 [expr.prim.lambda]p4:
922 // If a lambda-expression does not include a lambda-declarator, it is as
923 // if the lambda-declarator were ().
924 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
925 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
926 EPI.HasTrailingReturn = true;
927 EPI.TypeQuals.addConst();
928 LangAS AS = getDefaultCXXMethodAddrSpace();
929 if (AS != LangAS::Default)
930 EPI.TypeQuals.addAddressSpace(AS);
932 // C++1y [expr.prim.lambda]:
933 // The lambda return type is 'auto', which is replaced by the
934 // trailing-return type if provided and/or deduced from 'return'
935 // statements
936 // We don't do this before C++1y, because we don't support deduced return
937 // types there.
938 QualType DefaultTypeForNoTrailingReturn =
939 getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
940 : Context.DependentTy;
941 QualType MethodTy =
942 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
943 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
944 ExplicitParams = false;
945 ExplicitResultType = false;
946 EndLoc = Intro.Range.getEnd();
947 } else {
948 assert(ParamInfo.isFunctionDeclarator() &&
949 "lambda-declarator is a function");
950 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
952 // C++11 [expr.prim.lambda]p5:
953 // This function call operator is declared const (9.3.1) if and only if
954 // the lambda-expression's parameter-declaration-clause is not followed
955 // by mutable. It is neither virtual nor declared volatile. [...]
956 if (!FTI.hasMutableQualifier()) {
957 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
958 SourceLocation());
961 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
962 assert(MethodTyInfo && "no type from lambda-declarator");
963 EndLoc = ParamInfo.getSourceRange().getEnd();
965 ExplicitResultType = FTI.hasTrailingReturnType();
967 if (FTIHasNonVoidParameters(FTI)) {
968 Params.reserve(FTI.NumParams);
969 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
970 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
973 // Check for unexpanded parameter packs in the method type.
974 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
975 DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
976 UPPC_DeclarationType);
979 CXXRecordDecl *Class = createLambdaClosureType(
980 Intro.Range, MethodTyInfo, LambdaDependencyKind, Intro.Default);
981 CXXMethodDecl *Method =
982 startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
983 ParamInfo.getDeclSpec().getConstexprSpecifier(),
984 ParamInfo.getTrailingRequiresClause());
985 if (ExplicitParams)
986 CheckCXXDefaultArguments(Method);
988 // This represents the function body for the lambda function, check if we
989 // have to apply optnone due to a pragma.
990 AddRangeBasedOptnone(Method);
992 // code_seg attribute on lambda apply to the method.
993 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
994 Method->addAttr(A);
996 // Attributes on the lambda apply to the method.
997 ProcessDeclAttributes(CurScope, Method, ParamInfo);
999 // CUDA lambdas get implicit host and device attributes.
1000 if (getLangOpts().CUDA)
1001 CUDASetLambdaAttrs(Method);
1003 // OpenMP lambdas might get assumumption attributes.
1004 if (LangOpts.OpenMP)
1005 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1007 // Number the lambda for linkage purposes if necessary.
1008 handleLambdaNumbering(Class, Method);
1010 // Introduce the function call operator as the current declaration context.
1011 PushDeclContext(CurScope, Method);
1013 // Build the lambda scope.
1014 buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
1015 ExplicitParams, ExplicitResultType, !Method->isConst());
1017 // C++11 [expr.prim.lambda]p9:
1018 // A lambda-expression whose smallest enclosing scope is a block scope is a
1019 // local lambda expression; any other lambda expression shall not have a
1020 // capture-default or simple-capture in its lambda-introducer.
1022 // For simple-captures, this is covered by the check below that any named
1023 // entity is a variable that can be captured.
1025 // For DR1632, we also allow a capture-default in any context where we can
1026 // odr-use 'this' (in particular, in a default initializer for a non-static
1027 // data member).
1028 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
1029 (getCurrentThisType().isNull() ||
1030 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
1031 /*BuildAndDiagnose*/false)))
1032 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1034 // Distinct capture names, for diagnostics.
1035 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
1037 // Handle explicit captures.
1038 SourceLocation PrevCaptureLoc
1039 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
1040 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1041 PrevCaptureLoc = C->Loc, ++C) {
1042 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1043 if (C->Kind == LCK_StarThis)
1044 Diag(C->Loc, !getLangOpts().CPlusPlus17
1045 ? diag::ext_star_this_lambda_capture_cxx17
1046 : diag::warn_cxx14_compat_star_this_lambda_capture);
1048 // C++11 [expr.prim.lambda]p8:
1049 // An identifier or this shall not appear more than once in a
1050 // lambda-capture.
1051 if (LSI->isCXXThisCaptured()) {
1052 Diag(C->Loc, diag::err_capture_more_than_once)
1053 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1054 << FixItHint::CreateRemoval(
1055 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1056 continue;
1059 // C++2a [expr.prim.lambda]p8:
1060 // If a lambda-capture includes a capture-default that is =,
1061 // each simple-capture of that lambda-capture shall be of the form
1062 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1063 // redundant but accepted for compatibility with ISO C++14. --end note ]
1064 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1065 Diag(C->Loc, !getLangOpts().CPlusPlus20
1066 ? diag::ext_equals_this_lambda_capture_cxx20
1067 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1069 // C++11 [expr.prim.lambda]p12:
1070 // If this is captured by a local lambda expression, its nearest
1071 // enclosing function shall be a non-static member function.
1072 QualType ThisCaptureType = getCurrentThisType();
1073 if (ThisCaptureType.isNull()) {
1074 Diag(C->Loc, diag::err_this_capture) << true;
1075 continue;
1078 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1079 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1080 C->Kind == LCK_StarThis);
1081 if (!LSI->Captures.empty())
1082 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1083 continue;
1086 assert(C->Id && "missing identifier for capture");
1088 if (C->Init.isInvalid())
1089 continue;
1091 ValueDecl *Var = nullptr;
1092 if (C->Init.isUsable()) {
1093 Diag(C->Loc, getLangOpts().CPlusPlus14
1094 ? diag::warn_cxx11_compat_init_capture
1095 : diag::ext_init_capture);
1097 // If the initializer expression is usable, but the InitCaptureType
1098 // is not, then an error has occurred - so ignore the capture for now.
1099 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1100 // FIXME: we should create the init capture variable and mark it invalid
1101 // in this case.
1102 if (C->InitCaptureType.get().isNull())
1103 continue;
1105 if (C->Init.get()->containsUnexpandedParameterPack() &&
1106 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1107 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1109 unsigned InitStyle;
1110 switch (C->InitKind) {
1111 case LambdaCaptureInitKind::NoInit:
1112 llvm_unreachable("not an init-capture?");
1113 case LambdaCaptureInitKind::CopyInit:
1114 InitStyle = VarDecl::CInit;
1115 break;
1116 case LambdaCaptureInitKind::DirectInit:
1117 InitStyle = VarDecl::CallInit;
1118 break;
1119 case LambdaCaptureInitKind::ListInit:
1120 InitStyle = VarDecl::ListInit;
1121 break;
1123 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1124 C->EllipsisLoc, C->Id, InitStyle,
1125 C->Init.get());
1126 // C++1y [expr.prim.lambda]p11:
1127 // An init-capture behaves as if it declares and explicitly
1128 // captures a variable [...] whose declarative region is the
1129 // lambda-expression's compound-statement
1130 if (Var)
1131 PushOnScopeChains(Var, CurScope, false);
1132 } else {
1133 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1134 "init capture has valid but null init?");
1136 // C++11 [expr.prim.lambda]p8:
1137 // If a lambda-capture includes a capture-default that is &, the
1138 // identifiers in the lambda-capture shall not be preceded by &.
1139 // If a lambda-capture includes a capture-default that is =, [...]
1140 // each identifier it contains shall be preceded by &.
1141 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1142 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1143 << FixItHint::CreateRemoval(
1144 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1145 continue;
1146 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1147 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1148 << FixItHint::CreateRemoval(
1149 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1150 continue;
1153 // C++11 [expr.prim.lambda]p10:
1154 // The identifiers in a capture-list are looked up using the usual
1155 // rules for unqualified name lookup (3.4.1)
1156 DeclarationNameInfo Name(C->Id, C->Loc);
1157 LookupResult R(*this, Name, LookupOrdinaryName);
1158 LookupName(R, CurScope);
1159 if (R.isAmbiguous())
1160 continue;
1161 if (R.empty()) {
1162 // FIXME: Disable corrections that would add qualification?
1163 CXXScopeSpec ScopeSpec;
1164 DeclFilterCCC<VarDecl> Validator{};
1165 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1166 continue;
1169 if (auto *BD = R.getAsSingle<BindingDecl>())
1170 Var = BD;
1171 else
1172 Var = R.getAsSingle<VarDecl>();
1173 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1174 continue;
1177 // C++11 [expr.prim.lambda]p8:
1178 // An identifier or this shall not appear more than once in a
1179 // lambda-capture.
1180 if (!CaptureNames.insert(C->Id).second) {
1181 if (Var && LSI->isCaptured(Var)) {
1182 Diag(C->Loc, diag::err_capture_more_than_once)
1183 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1184 << FixItHint::CreateRemoval(
1185 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1186 } else
1187 // Previous capture captured something different (one or both was
1188 // an init-cpature): no fixit.
1189 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1190 continue;
1193 // C++11 [expr.prim.lambda]p10:
1194 // [...] each such lookup shall find a variable with automatic storage
1195 // duration declared in the reaching scope of the local lambda expression.
1196 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1197 if (!Var) {
1198 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1199 continue;
1202 // Ignore invalid decls; they'll just confuse the code later.
1203 if (Var->isInvalidDecl())
1204 continue;
1206 VarDecl *Underlying;
1207 if (auto *BD = dyn_cast<BindingDecl>(Var))
1208 Underlying = dyn_cast<VarDecl>(BD->getDecomposedDecl());
1209 else
1210 Underlying = cast<VarDecl>(Var);
1212 if (!Underlying->hasLocalStorage()) {
1213 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1214 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1215 continue;
1218 // C++11 [expr.prim.lambda]p23:
1219 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1220 SourceLocation EllipsisLoc;
1221 if (C->EllipsisLoc.isValid()) {
1222 if (Var->isParameterPack()) {
1223 EllipsisLoc = C->EllipsisLoc;
1224 } else {
1225 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1226 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1227 : SourceRange(C->Loc));
1229 // Just ignore the ellipsis.
1231 } else if (Var->isParameterPack()) {
1232 ContainsUnexpandedParameterPack = true;
1235 if (C->Init.isUsable()) {
1236 addInitCapture(LSI, cast<VarDecl>(Var));
1237 } else {
1238 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1239 TryCapture_ExplicitByVal;
1240 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1242 if (!LSI->Captures.empty())
1243 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1245 finishLambdaExplicitCaptures(LSI);
1247 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1249 // Add lambda parameters into scope.
1250 addLambdaParameters(Intro.Captures, Method, CurScope);
1252 // Enter a new evaluation context to insulate the lambda from any
1253 // cleanups from the enclosing full-expression.
1254 PushExpressionEvaluationContext(
1255 LSI->CallOperator->isConsteval()
1256 ? ExpressionEvaluationContext::ImmediateFunctionContext
1257 : ExpressionEvaluationContext::PotentiallyEvaluated);
1260 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1261 bool IsInstantiation) {
1262 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1264 // Leave the expression-evaluation context.
1265 DiscardCleanupsInEvaluationContext();
1266 PopExpressionEvaluationContext();
1268 // Leave the context of the lambda.
1269 if (!IsInstantiation)
1270 PopDeclContext();
1272 // Finalize the lambda.
1273 CXXRecordDecl *Class = LSI->Lambda;
1274 Class->setInvalidDecl();
1275 SmallVector<Decl*, 4> Fields(Class->fields());
1276 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1277 SourceLocation(), ParsedAttributesView());
1278 CheckCompletedCXXClass(nullptr, Class);
1280 PopFunctionScopeInfo();
1283 template <typename Func>
1284 static void repeatForLambdaConversionFunctionCallingConvs(
1285 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1286 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1287 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1288 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1289 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1290 CallingConv CallOpCC = CallOpProto.getCallConv();
1292 /// Implement emitting a version of the operator for many of the calling
1293 /// conventions for MSVC, as described here:
1294 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1295 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1296 /// vectorcall are generated by MSVC when it is supported by the target.
1297 /// Additionally, we are ensuring that the default-free/default-member and
1298 /// call-operator calling convention are generated as well.
1299 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1300 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1301 /// that someone who intentionally places 'thiscall' on the lambda call
1302 /// operator will still get that overload, since we don't have the a way of
1303 /// detecting the attribute by the time we get here.
1304 if (S.getLangOpts().MSVCCompat) {
1305 CallingConv Convs[] = {
1306 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1307 DefaultFree, DefaultMember, CallOpCC};
1308 llvm::sort(Convs);
1309 llvm::iterator_range<CallingConv *> Range(
1310 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1311 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1313 for (CallingConv C : Range) {
1314 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1315 F(C);
1317 return;
1320 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1321 F(DefaultFree);
1322 F(DefaultMember);
1323 } else {
1324 F(CallOpCC);
1328 // Returns the 'standard' calling convention to be used for the lambda
1329 // conversion function, that is, the 'free' function calling convention unless
1330 // it is overridden by a non-default calling convention attribute.
1331 static CallingConv
1332 getLambdaConversionFunctionCallConv(Sema &S,
1333 const FunctionProtoType *CallOpProto) {
1334 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1335 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1336 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1337 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1338 CallingConv CallOpCC = CallOpProto->getCallConv();
1340 // If the call-operator hasn't been changed, return both the 'free' and
1341 // 'member' function calling convention.
1342 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1343 return DefaultFree;
1344 return CallOpCC;
1347 QualType Sema::getLambdaConversionFunctionResultType(
1348 const FunctionProtoType *CallOpProto, CallingConv CC) {
1349 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1350 CallOpProto->getExtProtoInfo();
1351 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1352 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1353 InvokerExtInfo.TypeQuals = Qualifiers();
1354 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1355 "Lambda's call operator should not have a reference qualifier");
1356 return Context.getFunctionType(CallOpProto->getReturnType(),
1357 CallOpProto->getParamTypes(), InvokerExtInfo);
1360 /// Add a lambda's conversion to function pointer, as described in
1361 /// C++11 [expr.prim.lambda]p6.
1362 static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1363 CXXRecordDecl *Class,
1364 CXXMethodDecl *CallOperator,
1365 QualType InvokerFunctionTy) {
1366 // This conversion is explicitly disabled if the lambda's function has
1367 // pass_object_size attributes on any of its parameters.
1368 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1369 return P->hasAttr<PassObjectSizeAttr>();
1371 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1372 return;
1374 // Add the conversion to function pointer.
1375 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1377 // Create the type of the conversion function.
1378 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1379 S.Context.getDefaultCallingConvention(
1380 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1381 // The conversion function is always const and noexcept.
1382 ConvExtInfo.TypeQuals = Qualifiers();
1383 ConvExtInfo.TypeQuals.addConst();
1384 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1385 QualType ConvTy =
1386 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1388 SourceLocation Loc = IntroducerRange.getBegin();
1389 DeclarationName ConversionName
1390 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1391 S.Context.getCanonicalType(PtrToFunctionTy));
1392 // Construct a TypeSourceInfo for the conversion function, and wire
1393 // all the parameters appropriately for the FunctionProtoTypeLoc
1394 // so that everything works during transformation/instantiation of
1395 // generic lambdas.
1396 // The main reason for wiring up the parameters of the conversion
1397 // function with that of the call operator is so that constructs
1398 // like the following work:
1399 // auto L = [](auto b) { <-- 1
1400 // return [](auto a) -> decltype(a) { <-- 2
1401 // return a;
1402 // };
1403 // };
1404 // int (*fp)(int) = L(5);
1405 // Because the trailing return type can contain DeclRefExprs that refer
1406 // to the original call operator's variables, we hijack the call
1407 // operators ParmVarDecls below.
1408 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1409 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1410 DeclarationNameLoc ConvNameLoc =
1411 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1413 // The conversion function is a conversion to a pointer-to-function.
1414 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1415 FunctionProtoTypeLoc ConvTL =
1416 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1417 // Get the result of the conversion function which is a pointer-to-function.
1418 PointerTypeLoc PtrToFunctionTL =
1419 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1420 // Do the same for the TypeSourceInfo that is used to name the conversion
1421 // operator.
1422 PointerTypeLoc ConvNamePtrToFunctionTL =
1423 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1425 // Get the underlying function types that the conversion function will
1426 // be converting to (should match the type of the call operator).
1427 FunctionProtoTypeLoc CallOpConvTL =
1428 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1429 FunctionProtoTypeLoc CallOpConvNameTL =
1430 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1432 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1433 // These parameter's are essentially used to transform the name and
1434 // the type of the conversion operator. By using the same parameters
1435 // as the call operator's we don't have to fix any back references that
1436 // the trailing return type of the call operator's uses (such as
1437 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1438 // - we can simply use the return type of the call operator, and
1439 // everything should work.
1440 SmallVector<ParmVarDecl *, 4> InvokerParams;
1441 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1442 ParmVarDecl *From = CallOperator->getParamDecl(I);
1444 InvokerParams.push_back(ParmVarDecl::Create(
1445 S.Context,
1446 // Temporarily add to the TU. This is set to the invoker below.
1447 S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1448 From->getLocation(), From->getIdentifier(), From->getType(),
1449 From->getTypeSourceInfo(), From->getStorageClass(),
1450 /*DefArg=*/nullptr));
1451 CallOpConvTL.setParam(I, From);
1452 CallOpConvNameTL.setParam(I, From);
1455 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1456 S.Context, Class, Loc,
1457 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1458 S.getCurFPFeatures().isFPConstrained(),
1459 /*isInline=*/true, ExplicitSpecifier(),
1460 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1461 : ConstexprSpecKind::Unspecified,
1462 CallOperator->getBody()->getEndLoc());
1463 Conversion->setAccess(AS_public);
1464 Conversion->setImplicit(true);
1466 if (Class->isGenericLambda()) {
1467 // Create a template version of the conversion operator, using the template
1468 // parameter list of the function call operator.
1469 FunctionTemplateDecl *TemplateCallOperator =
1470 CallOperator->getDescribedFunctionTemplate();
1471 FunctionTemplateDecl *ConversionTemplate =
1472 FunctionTemplateDecl::Create(S.Context, Class,
1473 Loc, ConversionName,
1474 TemplateCallOperator->getTemplateParameters(),
1475 Conversion);
1476 ConversionTemplate->setAccess(AS_public);
1477 ConversionTemplate->setImplicit(true);
1478 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1479 Class->addDecl(ConversionTemplate);
1480 } else
1481 Class->addDecl(Conversion);
1482 // Add a non-static member function that will be the result of
1483 // the conversion with a certain unique ID.
1484 DeclarationName InvokerName = &S.Context.Idents.get(
1485 getLambdaStaticInvokerName());
1486 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1487 // we should get a prebuilt TrivialTypeSourceInfo from Context
1488 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1489 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1490 // loop below and then use its Params to set Invoke->setParams(...) below.
1491 // This would avoid the 'const' qualifier of the calloperator from
1492 // contaminating the type of the invoker, which is currently adjusted
1493 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1494 // trailing return type of the invoker would require a visitor to rebuild
1495 // the trailing return type and adjusting all back DeclRefExpr's to refer
1496 // to the new static invoker parameters - not the call operator's.
1497 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1498 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1499 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1500 S.getCurFPFeatures().isFPConstrained(),
1501 /*isInline=*/true, ConstexprSpecKind::Unspecified,
1502 CallOperator->getBody()->getEndLoc());
1503 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1504 InvokerParams[I]->setOwningFunction(Invoke);
1505 Invoke->setParams(InvokerParams);
1506 Invoke->setAccess(AS_private);
1507 Invoke->setImplicit(true);
1508 if (Class->isGenericLambda()) {
1509 FunctionTemplateDecl *TemplateCallOperator =
1510 CallOperator->getDescribedFunctionTemplate();
1511 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1512 S.Context, Class, Loc, InvokerName,
1513 TemplateCallOperator->getTemplateParameters(),
1514 Invoke);
1515 StaticInvokerTemplate->setAccess(AS_private);
1516 StaticInvokerTemplate->setImplicit(true);
1517 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1518 Class->addDecl(StaticInvokerTemplate);
1519 } else
1520 Class->addDecl(Invoke);
1523 /// Add a lambda's conversion to function pointers, as described in
1524 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1525 /// single pointer conversion. In the event that the default calling convention
1526 /// for free and member functions is different, it will emit both conventions.
1527 static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1528 CXXRecordDecl *Class,
1529 CXXMethodDecl *CallOperator) {
1530 const FunctionProtoType *CallOpProto =
1531 CallOperator->getType()->castAs<FunctionProtoType>();
1533 repeatForLambdaConversionFunctionCallingConvs(
1534 S, *CallOpProto, [&](CallingConv CC) {
1535 QualType InvokerFunctionTy =
1536 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1537 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1538 InvokerFunctionTy);
1542 /// Add a lambda's conversion to block pointer.
1543 static void addBlockPointerConversion(Sema &S,
1544 SourceRange IntroducerRange,
1545 CXXRecordDecl *Class,
1546 CXXMethodDecl *CallOperator) {
1547 const FunctionProtoType *CallOpProto =
1548 CallOperator->getType()->castAs<FunctionProtoType>();
1549 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1550 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1551 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1553 FunctionProtoType::ExtProtoInfo ConversionEPI(
1554 S.Context.getDefaultCallingConvention(
1555 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1556 ConversionEPI.TypeQuals = Qualifiers();
1557 ConversionEPI.TypeQuals.addConst();
1558 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1560 SourceLocation Loc = IntroducerRange.getBegin();
1561 DeclarationName Name
1562 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1563 S.Context.getCanonicalType(BlockPtrTy));
1564 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1565 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1566 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1567 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1568 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1569 S.getCurFPFeatures().isFPConstrained(),
1570 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1571 CallOperator->getBody()->getEndLoc());
1572 Conversion->setAccess(AS_public);
1573 Conversion->setImplicit(true);
1574 Class->addDecl(Conversion);
1577 ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1578 SourceLocation ImplicitCaptureLoc,
1579 bool IsOpenMPMapping) {
1580 // VLA captures don't have a stored initialization expression.
1581 if (Cap.isVLATypeCapture())
1582 return ExprResult();
1584 // An init-capture is initialized directly from its stored initializer.
1585 if (Cap.isInitCapture())
1586 return cast<VarDecl>(Cap.getVariable())->getInit();
1588 // For anything else, build an initialization expression. For an implicit
1589 // capture, the capture notionally happens at the capture-default, so use
1590 // that location here.
1591 SourceLocation Loc =
1592 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1594 // C++11 [expr.prim.lambda]p21:
1595 // When the lambda-expression is evaluated, the entities that
1596 // are captured by copy are used to direct-initialize each
1597 // corresponding non-static data member of the resulting closure
1598 // object. (For array members, the array elements are
1599 // direct-initialized in increasing subscript order.) These
1600 // initializations are performed in the (unspecified) order in
1601 // which the non-static data members are declared.
1603 // C++ [expr.prim.lambda]p12:
1604 // An entity captured by a lambda-expression is odr-used (3.2) in
1605 // the scope containing the lambda-expression.
1606 ExprResult Init;
1607 IdentifierInfo *Name = nullptr;
1608 if (Cap.isThisCapture()) {
1609 QualType ThisTy = getCurrentThisType();
1610 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1611 if (Cap.isCopyCapture())
1612 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1613 else
1614 Init = This;
1615 } else {
1616 assert(Cap.isVariableCapture() && "unknown kind of capture");
1617 ValueDecl *Var = Cap.getVariable();
1618 Name = Var->getIdentifier();
1619 Init = BuildDeclarationNameExpr(
1620 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1623 // In OpenMP, the capture kind doesn't actually describe how to capture:
1624 // variables are "mapped" onto the device in a process that does not formally
1625 // make a copy, even for a "copy capture".
1626 if (IsOpenMPMapping)
1627 return Init;
1629 if (Init.isInvalid())
1630 return ExprError();
1632 Expr *InitExpr = Init.get();
1633 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1634 Name, Cap.getCaptureType(), Loc);
1635 InitializationKind InitKind =
1636 InitializationKind::CreateDirect(Loc, Loc, Loc);
1637 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1638 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1641 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1642 Scope *CurScope) {
1643 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1644 ActOnFinishFunctionBody(LSI.CallOperator, Body);
1645 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1648 static LambdaCaptureDefault
1649 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1650 switch (ICS) {
1651 case CapturingScopeInfo::ImpCap_None:
1652 return LCD_None;
1653 case CapturingScopeInfo::ImpCap_LambdaByval:
1654 return LCD_ByCopy;
1655 case CapturingScopeInfo::ImpCap_CapturedRegion:
1656 case CapturingScopeInfo::ImpCap_LambdaByref:
1657 return LCD_ByRef;
1658 case CapturingScopeInfo::ImpCap_Block:
1659 llvm_unreachable("block capture in lambda");
1661 llvm_unreachable("Unknown implicit capture style");
1664 bool Sema::CaptureHasSideEffects(const Capture &From) {
1665 if (From.isInitCapture()) {
1666 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1667 if (Init && Init->HasSideEffects(Context))
1668 return true;
1671 if (!From.isCopyCapture())
1672 return false;
1674 const QualType T = From.isThisCapture()
1675 ? getCurrentThisType()->getPointeeType()
1676 : From.getCaptureType();
1678 if (T.isVolatileQualified())
1679 return true;
1681 const Type *BaseT = T->getBaseElementTypeUnsafe();
1682 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1683 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1684 !RD->hasTrivialDestructor();
1686 return false;
1689 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1690 const Capture &From) {
1691 if (CaptureHasSideEffects(From))
1692 return false;
1694 if (From.isVLATypeCapture())
1695 return false;
1697 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1698 if (From.isThisCapture())
1699 diag << "'this'";
1700 else
1701 diag << From.getVariable();
1702 diag << From.isNonODRUsed();
1703 diag << FixItHint::CreateRemoval(CaptureRange);
1704 return true;
1707 /// Create a field within the lambda class or captured statement record for the
1708 /// given capture.
1709 FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1710 const sema::Capture &Capture) {
1711 SourceLocation Loc = Capture.getLocation();
1712 QualType FieldType = Capture.getCaptureType();
1714 TypeSourceInfo *TSI = nullptr;
1715 if (Capture.isVariableCapture()) {
1716 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1717 if (Var && Var->isInitCapture())
1718 TSI = Var->getTypeSourceInfo();
1721 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1722 // appropriate, at least for an implicit capture.
1723 if (!TSI)
1724 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1726 // Build the non-static data member.
1727 FieldDecl *Field =
1728 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1729 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1730 /*Mutable=*/false, ICIS_NoInit);
1731 // If the variable being captured has an invalid type, mark the class as
1732 // invalid as well.
1733 if (!FieldType->isDependentType()) {
1734 if (RequireCompleteSizedType(Loc, FieldType,
1735 diag::err_field_incomplete_or_sizeless)) {
1736 RD->setInvalidDecl();
1737 Field->setInvalidDecl();
1738 } else {
1739 NamedDecl *Def;
1740 FieldType->isIncompleteType(&Def);
1741 if (Def && Def->isInvalidDecl()) {
1742 RD->setInvalidDecl();
1743 Field->setInvalidDecl();
1747 Field->setImplicit(true);
1748 Field->setAccess(AS_private);
1749 RD->addDecl(Field);
1751 if (Capture.isVLATypeCapture())
1752 Field->setCapturedVLAType(Capture.getCapturedVLAType());
1754 return Field;
1757 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1758 LambdaScopeInfo *LSI) {
1759 // Collect information from the lambda scope.
1760 SmallVector<LambdaCapture, 4> Captures;
1761 SmallVector<Expr *, 4> CaptureInits;
1762 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1763 LambdaCaptureDefault CaptureDefault =
1764 mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1765 CXXRecordDecl *Class;
1766 CXXMethodDecl *CallOperator;
1767 SourceRange IntroducerRange;
1768 bool ExplicitParams;
1769 bool ExplicitResultType;
1770 CleanupInfo LambdaCleanup;
1771 bool ContainsUnexpandedParameterPack;
1772 bool IsGenericLambda;
1774 CallOperator = LSI->CallOperator;
1775 Class = LSI->Lambda;
1776 IntroducerRange = LSI->IntroducerRange;
1777 ExplicitParams = LSI->ExplicitParams;
1778 ExplicitResultType = !LSI->HasImplicitReturnType;
1779 LambdaCleanup = LSI->Cleanup;
1780 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1781 IsGenericLambda = Class->isGenericLambda();
1783 CallOperator->setLexicalDeclContext(Class);
1784 Decl *TemplateOrNonTemplateCallOperatorDecl =
1785 CallOperator->getDescribedFunctionTemplate()
1786 ? CallOperator->getDescribedFunctionTemplate()
1787 : cast<Decl>(CallOperator);
1789 // FIXME: Is this really the best choice? Keeping the lexical decl context
1790 // set as CurContext seems more faithful to the source.
1791 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1793 PopExpressionEvaluationContext();
1795 // True if the current capture has a used capture or default before it.
1796 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1797 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1798 CaptureDefaultLoc : IntroducerRange.getBegin();
1800 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1801 const Capture &From = LSI->Captures[I];
1803 if (From.isInvalid())
1804 return ExprError();
1806 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1807 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1808 SourceLocation ImplicitCaptureLoc =
1809 IsImplicit ? CaptureDefaultLoc : SourceLocation();
1811 // Use source ranges of explicit captures for fixits where available.
1812 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1814 // Warn about unused explicit captures.
1815 bool IsCaptureUsed = true;
1816 if (!CurContext->isDependentContext() && !IsImplicit &&
1817 !From.isODRUsed()) {
1818 // Initialized captures that are non-ODR used may not be eliminated.
1819 // FIXME: Where did the IsGenericLambda here come from?
1820 bool NonODRUsedInitCapture =
1821 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
1822 if (!NonODRUsedInitCapture) {
1823 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1824 SourceRange FixItRange;
1825 if (CaptureRange.isValid()) {
1826 if (!CurHasPreviousCapture && !IsLast) {
1827 // If there are no captures preceding this capture, remove the
1828 // following comma.
1829 FixItRange = SourceRange(CaptureRange.getBegin(),
1830 getLocForEndOfToken(CaptureRange.getEnd()));
1831 } else {
1832 // Otherwise, remove the comma since the last used capture.
1833 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1834 CaptureRange.getEnd());
1838 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1842 if (CaptureRange.isValid()) {
1843 CurHasPreviousCapture |= IsCaptureUsed;
1844 PrevCaptureLoc = CaptureRange.getEnd();
1847 // Map the capture to our AST representation.
1848 LambdaCapture Capture = [&] {
1849 if (From.isThisCapture()) {
1850 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1851 // because it results in a reference capture. Don't warn prior to
1852 // C++2a; there's nothing that can be done about it before then.
1853 if (getLangOpts().CPlusPlus20 && IsImplicit &&
1854 CaptureDefault == LCD_ByCopy) {
1855 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1856 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1857 << FixItHint::CreateInsertion(
1858 getLocForEndOfToken(CaptureDefaultLoc), ", this");
1860 return LambdaCapture(From.getLocation(), IsImplicit,
1861 From.isCopyCapture() ? LCK_StarThis : LCK_This);
1862 } else if (From.isVLATypeCapture()) {
1863 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
1864 } else {
1865 assert(From.isVariableCapture() && "unknown kind of capture");
1866 ValueDecl *Var = From.getVariable();
1867 LambdaCaptureKind Kind =
1868 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
1869 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
1870 From.getEllipsisLoc());
1872 }();
1874 // Form the initializer for the capture field.
1875 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1877 // FIXME: Skip this capture if the capture is not used, the initializer
1878 // has no side-effects, the type of the capture is trivial, and the
1879 // lambda is not externally visible.
1881 // Add a FieldDecl for the capture and form its initializer.
1882 BuildCaptureField(Class, From);
1883 Captures.push_back(Capture);
1884 CaptureInits.push_back(Init.get());
1886 if (LangOpts.CUDA)
1887 CUDACheckLambdaCapture(CallOperator, From);
1890 Class->setCaptures(Context, Captures);
1892 // C++11 [expr.prim.lambda]p6:
1893 // The closure type for a lambda-expression with no lambda-capture
1894 // has a public non-virtual non-explicit const conversion function
1895 // to pointer to function having the same parameter and return
1896 // types as the closure type's function call operator.
1897 if (Captures.empty() && CaptureDefault == LCD_None)
1898 addFunctionPointerConversions(*this, IntroducerRange, Class,
1899 CallOperator);
1901 // Objective-C++:
1902 // The closure type for a lambda-expression has a public non-virtual
1903 // non-explicit const conversion function to a block pointer having the
1904 // same parameter and return types as the closure type's function call
1905 // operator.
1906 // FIXME: Fix generic lambda to block conversions.
1907 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
1908 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1910 // Finalize the lambda class.
1911 SmallVector<Decl*, 4> Fields(Class->fields());
1912 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1913 SourceLocation(), ParsedAttributesView());
1914 CheckCompletedCXXClass(nullptr, Class);
1917 Cleanup.mergeFrom(LambdaCleanup);
1919 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1920 CaptureDefault, CaptureDefaultLoc,
1921 ExplicitParams, ExplicitResultType,
1922 CaptureInits, EndLoc,
1923 ContainsUnexpandedParameterPack);
1924 // If the lambda expression's call operator is not explicitly marked constexpr
1925 // and we are not in a dependent context, analyze the call operator to infer
1926 // its constexpr-ness, suppressing diagnostics while doing so.
1927 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
1928 !CallOperator->isConstexpr() &&
1929 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
1930 !Class->getDeclContext()->isDependentContext()) {
1931 CallOperator->setConstexprKind(
1932 CheckConstexprFunctionDefinition(CallOperator,
1933 CheckConstexprKind::CheckValid)
1934 ? ConstexprSpecKind::Constexpr
1935 : ConstexprSpecKind::Unspecified);
1938 // Emit delayed shadowing warnings now that the full capture list is known.
1939 DiagnoseShadowingLambdaDecls(LSI);
1941 if (!CurContext->isDependentContext()) {
1942 switch (ExprEvalContexts.back().Context) {
1943 // C++11 [expr.prim.lambda]p2:
1944 // A lambda-expression shall not appear in an unevaluated operand
1945 // (Clause 5).
1946 case ExpressionEvaluationContext::Unevaluated:
1947 case ExpressionEvaluationContext::UnevaluatedList:
1948 case ExpressionEvaluationContext::UnevaluatedAbstract:
1949 // C++1y [expr.const]p2:
1950 // A conditional-expression e is a core constant expression unless the
1951 // evaluation of e, following the rules of the abstract machine, would
1952 // evaluate [...] a lambda-expression.
1954 // This is technically incorrect, there are some constant evaluated contexts
1955 // where this should be allowed. We should probably fix this when DR1607 is
1956 // ratified, it lays out the exact set of conditions where we shouldn't
1957 // allow a lambda-expression.
1958 case ExpressionEvaluationContext::ConstantEvaluated:
1959 case ExpressionEvaluationContext::ImmediateFunctionContext:
1960 // We don't actually diagnose this case immediately, because we
1961 // could be within a context where we might find out later that
1962 // the expression is potentially evaluated (e.g., for typeid).
1963 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1964 break;
1966 case ExpressionEvaluationContext::DiscardedStatement:
1967 case ExpressionEvaluationContext::PotentiallyEvaluated:
1968 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1969 break;
1973 return MaybeBindToTemporary(Lambda);
1976 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1977 SourceLocation ConvLocation,
1978 CXXConversionDecl *Conv,
1979 Expr *Src) {
1980 // Make sure that the lambda call operator is marked used.
1981 CXXRecordDecl *Lambda = Conv->getParent();
1982 CXXMethodDecl *CallOperator
1983 = cast<CXXMethodDecl>(
1984 Lambda->lookup(
1985 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1986 CallOperator->setReferenced();
1987 CallOperator->markUsed(Context);
1989 ExprResult Init = PerformCopyInitialization(
1990 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
1991 CurrentLocation, Src);
1992 if (!Init.isInvalid())
1993 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
1995 if (Init.isInvalid())
1996 return ExprError();
1998 // Create the new block to be returned.
1999 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
2001 // Set the type information.
2002 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2003 Block->setIsVariadic(CallOperator->isVariadic());
2004 Block->setBlockMissingReturnType(false);
2006 // Add parameters.
2007 SmallVector<ParmVarDecl *, 4> BlockParams;
2008 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2009 ParmVarDecl *From = CallOperator->getParamDecl(I);
2010 BlockParams.push_back(ParmVarDecl::Create(
2011 Context, Block, From->getBeginLoc(), From->getLocation(),
2012 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2013 From->getStorageClass(),
2014 /*DefArg=*/nullptr));
2016 Block->setParams(BlockParams);
2018 Block->setIsConversionFromLambda(true);
2020 // Add capture. The capture uses a fake variable, which doesn't correspond
2021 // to any actual memory location. However, the initializer copy-initializes
2022 // the lambda object.
2023 TypeSourceInfo *CapVarTSI =
2024 Context.getTrivialTypeSourceInfo(Src->getType());
2025 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2026 ConvLocation, nullptr,
2027 Src->getType(), CapVarTSI,
2028 SC_None);
2029 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2030 /*nested=*/false, /*copy=*/Init.get());
2031 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2033 // Add a fake function body to the block. IR generation is responsible
2034 // for filling in the actual body, which cannot be expressed as an AST.
2035 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2037 // Create the block literal expression.
2038 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2039 ExprCleanupObjects.push_back(Block);
2040 Cleanup.setExprNeedsCleanups(true);
2042 return BuildBlock;