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