#include "clang/Sema/DeclSpec.h"
#include "TypeLocBuilder.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/SemaLambda.h"
#include "llvm/ADT/STLExtras.h"
using namespace clang;
using namespace sema;
static inline Optional<unsigned>
getStackIndexOfNearestEnclosingCaptureReadyLambda(
ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
VarDecl *VarToCapture) {
const Optional<unsigned> NoLambdaIsCaptureReady;
unsigned CurScopeIndex = FunctionScopes.size() - 1;
while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
FunctionScopes[CurScopeIndex]))
--CurScopeIndex;
assert(
isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
"The function on the top of sema's function-info stack must be a lambda");
const bool IsCapturingThis = !VarToCapture;
const bool IsCapturingVariable = !IsCapturingThis;
DeclContext *EnclosingDC =
cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
do {
const clang::sema::LambdaScopeInfo *LSI =
cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
if (IsCapturingVariable &&
VarToCapture->getDeclContext()->Equals(EnclosingDC))
return NoLambdaIsCaptureReady;
if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
return NoLambdaIsCaptureReady;
if (IsCapturingThis && !LSI->isCXXThisCaptured())
return NoLambdaIsCaptureReady;
}
EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
assert(CurScopeIndex);
--CurScopeIndex;
} while (!EnclosingDC->isTranslationUnit() &&
EnclosingDC->isDependentContext() &&
isLambdaCallOperator(EnclosingDC));
assert(CurScopeIndex < (FunctionScopes.size() - 1));
if (!EnclosingDC->isDependentContext())
return CurScopeIndex + 1;
return NoLambdaIsCaptureReady;
}
Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
VarDecl *VarToCapture, Sema &S) {
const Optional<unsigned> NoLambdaIsCaptureCapable;
const Optional<unsigned> OptionalStackIndex =
getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
VarToCapture);
if (!OptionalStackIndex)
return NoLambdaIsCaptureCapable;
const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
S.getCurGenericLambda()) &&
"The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda");
const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
const bool IsCapturingThis = !VarToCapture;
const bool IsCapturingVariable = !IsCapturingThis;
if (IsCapturingVariable) {
QualType CaptureType, DeclRefType;
const bool CanCaptureVariable =
!S.tryCaptureVariable(VarToCapture,
SourceLocation(),
clang::Sema::TryCapture_Implicit,
SourceLocation(),
false, CaptureType,
DeclRefType, &IndexOfCaptureReadyLambda);
if (!CanCaptureVariable)
return NoLambdaIsCaptureCapable;
} else {
const bool CanCaptureThis =
!S.CheckCXXThisCapture(
CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
false, false,
&IndexOfCaptureReadyLambda);
if (!CanCaptureThis)
return NoLambdaIsCaptureCapable;
}
return IndexOfCaptureReadyLambda;
}
static inline TemplateParameterList *
getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
LSI->GLTemplateParameterList = TemplateParameterList::Create(
SemaRef.Context,
SourceLocation(),
LSI->ExplicitTemplateParamsRange.getBegin(),
LSI->TemplateParams,
LSI->ExplicitTemplateParamsRange.getEnd(),
LSI->RequiresClause.get());
}
return LSI->GLTemplateParameterList;
}
CXXRecordDecl *
Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
unsigned LambdaDependencyKind,
LambdaCaptureDefault CaptureDefault) {
DeclContext *DC = CurContext;
while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
DC = DC->getParent();
bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
*this);
CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
IsGenericLambda, CaptureDefault);
DC->addDecl(Class);
return Class;
}
static bool isInInlineFunction(const DeclContext *DC) {
while (!DC->isFileContext()) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
if (FD->isInlined())
return true;
DC = DC->getLexicalParent();
}
return false;
}
std::tuple<MangleNumberingContext *, Decl *>
Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
enum ContextKind {
Normal,
DefaultArgument,
DataMember,
StaticDataMember,
InlineVariable,
VariableTemplate
} Kind = Normal;
if (ManglingContextDecl) {
if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
if (const DeclContext *LexicalDC
= Param->getDeclContext()->getLexicalParent())
if (LexicalDC->isRecord())
Kind = DefaultArgument;
} else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
if (Var->getDeclContext()->isRecord())
Kind = StaticDataMember;
else if (Var->getMostRecentDecl()->isInline())
Kind = InlineVariable;
else if (Var->getDescribedVarTemplate())
Kind = VariableTemplate;
else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
if (!VTS->isExplicitSpecialization())
Kind = VariableTemplate;
}
} else if (isa<FieldDecl>(ManglingContextDecl)) {
Kind = DataMember;
}
}
bool IsInNonspecializedTemplate =
inTemplateInstantiation() || CurContext->isDependentContext();
switch (Kind) {
case Normal: {
if ((IsInNonspecializedTemplate &&
!(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
isInInlineFunction(CurContext)) {
while (auto *CD = dyn_cast<CapturedDecl>(DC))
DC = CD->getParent();
return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
}
return std::make_tuple(nullptr, nullptr);
}
case StaticDataMember:
if (!IsInNonspecializedTemplate)
return std::make_tuple(nullptr, ManglingContextDecl);
LLVM_FALLTHROUGH;
case DataMember:
case DefaultArgument:
case InlineVariable:
case VariableTemplate:
return std::make_tuple(
&Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
ManglingContextDecl),
ManglingContextDecl);
}
llvm_unreachable("unexpected context");
}
CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodTypeInfo,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind,
Expr *TrailingRequiresClause) {
QualType MethodType = MethodTypeInfo->getType();
TemplateParameterList *TemplateParams =
getGenericLambdaTemplateParameterList(getCurLambda(), *this);
if (Class->isDependentContext() || TemplateParams) {
const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
QualType Result = FPT->getReturnType();
if (Result->isUndeducedType()) {
Result = SubstAutoTypeDependent(Result);
MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
FPT->getExtProtoInfo());
}
}
DeclarationName MethodName
= Context.DeclarationNames.getCXXOperatorName(OO_Call);
DeclarationNameLoc MethodNameLoc =
DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
CXXMethodDecl *Method = CXXMethodDecl::Create(
Context, Class, EndLoc,
DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
MethodNameLoc),
MethodType, MethodTypeInfo, SC_None, getCurFPFeatures().isFPConstrained(),
true, ConstexprKind, EndLoc, TrailingRequiresClause);
Method->setAccess(AS_public);
if (!TemplateParams)
Class->addDecl(Method);
Method->setLexicalDeclContext(CurContext);
FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
FunctionTemplateDecl::Create(Context, Class,
Method->getLocation(), MethodName,
TemplateParams,
Method) : nullptr;
if (TemplateMethod) {
TemplateMethod->setAccess(AS_public);
Method->setDescribedFunctionTemplate(TemplateMethod);
Class->addDecl(TemplateMethod);
TemplateMethod->setLexicalDeclContext(CurContext);
}
if (!Params.empty()) {
Method->setParams(Params);
CheckParmsForFunctionDef(Params,
false);
for (auto P : Method->parameters())
P->setOwningFunction(Method);
}
return Method;
}
void Sema::handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
if (Mangling) {
bool HasKnownInternalLinkage;
unsigned ManglingNumber, DeviceManglingNumber;
Decl *ManglingContextDecl;
std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
ManglingContextDecl) = *Mangling;
Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
HasKnownInternalLinkage);
Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
return;
}
auto getMangleNumberingContext =
[this](CXXRecordDecl *Class,
Decl *ManglingContextDecl) -> MangleNumberingContext * {
if (ManglingContextDecl)
return &Context.getManglingNumberContext(
ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
auto DC = Class->getDeclContext();
while (auto *CD = dyn_cast<CapturedDecl>(DC))
DC = CD->getParent();
return &Context.getManglingNumberContext(DC);
};
MangleNumberingContext *MCtx;
Decl *ManglingContextDecl;
std::tie(MCtx, ManglingContextDecl) =
getCurrentMangleNumberContext(Class->getDeclContext());
bool HasKnownInternalLinkage = false;
if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
getLangOpts().SYCLIsHost)) {
MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
assert(MCtx && "Retrieving mangle numbering context failed!");
HasKnownInternalLinkage = true;
}
if (MCtx) {
unsigned ManglingNumber = MCtx->getManglingNumber(Method);
Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
HasKnownInternalLinkage);
Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
}
}
void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable) {
LSI->CallOperator = CallOperator;
CXXRecordDecl *LambdaClass = CallOperator->getParent();
LSI->Lambda = LambdaClass;
if (CaptureDefault == LCD_ByCopy)
LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
else if (CaptureDefault == LCD_ByRef)
LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
LSI->CaptureDefaultLoc = CaptureDefaultLoc;
LSI->IntroducerRange = IntroducerRange;
LSI->ExplicitParams = ExplicitParams;
LSI->Mutable = Mutable;
if (ExplicitResultType) {
LSI->ReturnType = CallOperator->getReturnType();
if (!LSI->ReturnType->isDependentType() &&
!LSI->ReturnType->isVoidType()) {
if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
diag::err_lambda_incomplete_result)) {
}
}
} else {
LSI->HasImplicitReturnType = true;
}
}
void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
LSI->finishedExplicitCaptures();
}
void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc,
ExprResult RequiresClause) {
LambdaScopeInfo *LSI = getCurLambda();
assert(LSI && "Expected a lambda scope");
assert(LSI->NumExplicitTemplateParams == 0 &&
"Already acted on explicit template parameters");
assert(LSI->TemplateParams.empty() &&
"Explicit template parameters should come "
"before invented (auto) ones");
assert(!TParams.empty() &&
"No template parameters to act on");
LSI->TemplateParams.append(TParams.begin(), TParams.end());
LSI->NumExplicitTemplateParams = TParams.size();
LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
LSI->RequiresClause = RequiresClause;
}
void Sema::addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope) {
for (unsigned p = 0, NumParams = CallOperator->getNumParams();
p < NumParams; ++p) {
ParmVarDecl *Param = CallOperator->getParamDecl(p);
if (CurScope && Param->getIdentifier()) {
bool Error = false;
for (const auto &Capture : Captures) {
if (Capture.Id == Param->getIdentifier()) {
Error = true;
Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
<< Capture.Id << true;
}
}
if (!Error)
CheckShadow(CurScope, Param);
PushOnScopeChains(Param, CurScope);
}
}
}
static EnumDecl *findEnumForBlockReturn(Expr *E) {
E = E->IgnoreParens();
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (EnumConstantDecl *D
= dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
return cast<EnumDecl>(D->getDeclContext());
}
return nullptr;
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
if (BO->getOpcode() == BO_Comma)
return findEnumForBlockReturn(BO->getRHS());
return nullptr;
}
if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
return findEnumForBlockReturn(last);
return nullptr;
}
if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
return ED;
return nullptr;
}
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
if (ICE->getCastKind() == CK_IntegralCast)
return findEnumForBlockReturn(ICE->getSubExpr());
}
if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
return ET->getDecl();
}
return nullptr;
}
static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
if (Expr *retValue = ret->getRetValue())
return findEnumForBlockReturn(retValue);
return nullptr;
}
static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
EnumDecl *ED = findEnumForBlockReturn(*i);
if (!ED) return nullptr;
for (++i; i != e; ++i) {
if (findEnumForBlockReturn(*i) != ED)
return nullptr;
}
if (!ED->hasNameForLinkage()) return nullptr;
return ED;
}
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
QualType returnType) {
for (ArrayRef<ReturnStmt*>::iterator
i = returns.begin(), e = returns.end(); i != e; ++i) {
ReturnStmt *ret = *i;
Expr *retValue = ret->getRetValue();
if (S.Context.hasSameType(retValue->getType(), returnType))
continue;
assert(returnType->isIntegralOrUnscopedEnumerationType());
assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
nullptr, VK_PRValue,
FPOptionsOverride());
if (cleanups) {
cleanups->setSubExpr(E);
} else {
ret->setRetValue(E);
}
}
}
void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
assert(CSI.HasImplicitReturnType);
assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
"lambda expressions use auto deduction in C++14 onwards");
ASTContext &Ctx = getASTContext();
if (CSI.Returns.empty()) {
if (CSI.ReturnType.isNull())
CSI.ReturnType = Ctx.VoidTy;
return;
}
assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
if (CSI.ReturnType->isDependentType())
return;
if (!getLangOpts().CPlusPlus) {
assert(isa<BlockScopeInfo>(CSI));
const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
if (ED) {
CSI.ReturnType = Context.getTypeDeclType(ED);
adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
return;
}
}
if (CSI.Returns.size() == 1)
return;
for (const ReturnStmt *RS : CSI.Returns) {
const Expr *RetE = RS->getRetValue();
QualType ReturnType =
(RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
if (Context.getCanonicalFunctionResultType(ReturnType) ==
Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
auto RetTyNullability = ReturnType->getNullability(Ctx);
auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
if (BlockNullability &&
(!RetTyNullability ||
hasWeakerNullability(*RetTyNullability, *BlockNullability)))
CSI.ReturnType = ReturnType;
continue;
}
Diag(RS->getBeginLoc(),
diag::err_typecheck_missing_return_type_incompatible)
<< ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
}
}
QualType Sema::buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
Expr *&Init) {
QualType DeductType = Context.getAutoDeductType();
TypeLocBuilder TLB;
AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
TL.setNameLoc(Loc);
if (ByRef) {
DeductType = BuildReferenceType(DeductType, true, Loc, Id);
assert(!DeductType.isNull() && "can't build reference to auto");
TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
}
if (EllipsisLoc.isValid()) {
if (Init->containsUnexpandedParameterPack()) {
Diag(EllipsisLoc, getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_init_capture_pack
: diag::ext_init_capture_pack);
DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
false);
TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
} else {
}
}
TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
QualType DeducedType = deduceVarTypeFromInitializer(
nullptr, DeclarationName(Id), DeductType, TSI,
SourceRange(Loc, Loc), IsDirectInit, Init);
if (DeducedType.isNull())
return QualType();
ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
InitializedEntity Entity =
InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
InitializationKind Kind =
IsDirectInit
? (CXXDirectInit ? InitializationKind::CreateDirect(
Loc, Init->getBeginLoc(), Init->getEndLoc())
: InitializationKind::CreateDirectList(Loc))
: InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
MultiExprArg Args = Init;
if (CXXDirectInit)
Args =
MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
QualType DclT;
InitializationSequence InitSeq(*this, Entity, Kind, Args);
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
if (Result.isInvalid())
return QualType();
Init = Result.getAs<Expr>();
return DeducedType;
}
VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init) {
TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
PETL.setEllipsisLoc(EllipsisLoc);
VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Loc, Id, InitCaptureType, TSI, SC_Auto);
NewVD->setInitCapture(true);
NewVD->setReferenced(true);
NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
NewVD->markUsed(Context);
NewVD->setInit(Init);
if (NewVD->isParameterPack())
getCurLambda()->LocalPacks.push_back(NewVD);
return NewVD;
}
void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
assert(Var->isInitCapture() && "init capture flag should be set");
LSI->addCapture(Var, false, Var->getType()->isReferenceType(),
false, Var->getLocation(), SourceLocation(),
Var->getType(), false);
}
void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo,
Scope *CurScope) {
LambdaScopeInfo *const LSI = getCurLambda();
assert(LSI && "LambdaScopeInfo should be on stack!");
CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
CXXRecordDecl::LDK_Unknown;
if (LSI->NumExplicitTemplateParams > 0) {
auto *TemplateParamScope = CurScope->getTemplateParamParent();
assert(TemplateParamScope &&
"Lambda with explicit template param list should establish a "
"template param scope");
assert(TemplateParamScope->getParent());
if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
} else if (CurScope->getTemplateParamParent() != nullptr) {
LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
}
TypeSourceInfo *MethodTyInfo;
bool ExplicitParams = true;
bool ExplicitResultType = true;
bool ContainsUnexpandedParameterPack = false;
SourceLocation EndLoc;
SmallVector<ParmVarDecl *, 8> Params;
if (ParamInfo.getNumTypeObjects() == 0) {
FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
false, true));
EPI.HasTrailingReturn = true;
EPI.TypeQuals.addConst();
LangAS AS = getDefaultCXXMethodAddrSpace();
if (AS != LangAS::Default)
EPI.TypeQuals.addAddressSpace(AS);
QualType DefaultTypeForNoTrailingReturn =
getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
: Context.DependentTy;
QualType MethodTy =
Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
ExplicitParams = false;
ExplicitResultType = false;
EndLoc = Intro.Range.getEnd();
} else {
assert(ParamInfo.isFunctionDeclarator() &&
"lambda-declarator is a function");
DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
if (!FTI.hasMutableQualifier()) {
FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
SourceLocation());
}
MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
assert(MethodTyInfo && "no type from lambda-declarator");
EndLoc = ParamInfo.getSourceRange().getEnd();
ExplicitResultType = FTI.hasTrailingReturnType();
if (FTIHasNonVoidParameters(FTI)) {
Params.reserve(FTI.NumParams);
for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
}
if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
UPPC_DeclarationType);
}
CXXRecordDecl *Class = createLambdaClosureType(
Intro.Range, MethodTyInfo, LambdaDependencyKind, Intro.Default);
CXXMethodDecl *Method =
startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
ParamInfo.getDeclSpec().getConstexprSpecifier(),
ParamInfo.getTrailingRequiresClause());
if (ExplicitParams)
CheckCXXDefaultArguments(Method);
AddRangeBasedOptnone(Method);
if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, true))
Method->addAttr(A);
ProcessDeclAttributes(CurScope, Method, ParamInfo);
if (getLangOpts().CUDA)
CUDASetLambdaAttrs(Method);
if (LangOpts.OpenMP)
ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
handleLambdaNumbering(Class, Method);
PushDeclContext(CurScope, Method);
buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
ExplicitParams, ExplicitResultType, !Method->isConst());
if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
(getCurrentThisType().isNull() ||
CheckCXXThisCapture(SourceLocation(), true,
false)))
Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
SourceLocation PrevCaptureLoc
= Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
PrevCaptureLoc = C->Loc, ++C) {
if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
if (C->Kind == LCK_StarThis)
Diag(C->Loc, !getLangOpts().CPlusPlus17
? diag::ext_star_this_lambda_capture_cxx17
: diag::warn_cxx14_compat_star_this_lambda_capture);
if (LSI->isCXXThisCaptured()) {
Diag(C->Loc, diag::err_capture_more_than_once)
<< "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
<< FixItHint::CreateRemoval(
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
continue;
}
if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
Diag(C->Loc, !getLangOpts().CPlusPlus20
? diag::ext_equals_this_lambda_capture_cxx20
: diag::warn_cxx17_compat_equals_this_lambda_capture);
QualType ThisCaptureType = getCurrentThisType();
if (ThisCaptureType.isNull()) {
Diag(C->Loc, diag::err_this_capture) << true;
continue;
}
CheckCXXThisCapture(C->Loc, true, true,
nullptr,
C->Kind == LCK_StarThis);
if (!LSI->Captures.empty())
LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
continue;
}
assert(C->Id && "missing identifier for capture");
if (C->Init.isInvalid())
continue;
VarDecl *Var = nullptr;
if (C->Init.isUsable()) {
Diag(C->Loc, getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_init_capture
: diag::ext_init_capture);
if (C->InitCaptureType.get().isNull())
continue;
if (C->Init.get()->containsUnexpandedParameterPack() &&
!C->InitCaptureType.get()->getAs<PackExpansionType>())
DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
unsigned InitStyle;
switch (C->InitKind) {
case LambdaCaptureInitKind::NoInit:
llvm_unreachable("not an init-capture?");
case LambdaCaptureInitKind::CopyInit:
InitStyle = VarDecl::CInit;
break;
case LambdaCaptureInitKind::DirectInit:
InitStyle = VarDecl::CallInit;
break;
case LambdaCaptureInitKind::ListInit:
InitStyle = VarDecl::ListInit;
break;
}
Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
C->EllipsisLoc, C->Id, InitStyle,
C->Init.get());
if (Var)
PushOnScopeChains(Var, CurScope, false);
} else {
assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
"init capture has valid but null init?");
if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Diag(C->Loc, diag::err_reference_capture_with_reference_default)
<< FixItHint::CreateRemoval(
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
continue;
} else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Diag(C->Loc, diag::err_copy_capture_with_copy_default)
<< FixItHint::CreateRemoval(
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
continue;
}
DeclarationNameInfo Name(C->Id, C->Loc);
LookupResult R(*this, Name, LookupOrdinaryName);
LookupName(R, CurScope);
if (R.isAmbiguous())
continue;
if (R.empty()) {
CXXScopeSpec ScopeSpec;
DeclFilterCCC<VarDecl> Validator{};
if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
continue;
}
Var = R.getAsSingle<VarDecl>();
if (Var && DiagnoseUseOfDecl(Var, C->Loc))
continue;
}
if (!CaptureNames.insert(C->Id).second) {
if (Var && LSI->isCaptured(Var)) {
Diag(C->Loc, diag::err_capture_more_than_once)
<< C->Id << SourceRange(LSI->getCapture(Var).getLocation())
<< FixItHint::CreateRemoval(
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
} else
Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
continue;
}
if (!Var) {
Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
continue;
}
if (Var->isInvalidDecl())
continue;
if (!Var->hasLocalStorage()) {
Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
continue;
}
SourceLocation EllipsisLoc;
if (C->EllipsisLoc.isValid()) {
if (Var->isParameterPack()) {
EllipsisLoc = C->EllipsisLoc;
} else {
Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
<< (C->Init.isUsable() ? C->Init.get()->getSourceRange()
: SourceRange(C->Loc));
}
} else if (Var->isParameterPack()) {
ContainsUnexpandedParameterPack = true;
}
if (C->Init.isUsable()) {
addInitCapture(LSI, Var);
} else {
TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
TryCapture_ExplicitByVal;
tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
}
if (!LSI->Captures.empty())
LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
}
finishLambdaExplicitCaptures(LSI);
LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
addLambdaParameters(Intro.Captures, Method, CurScope);
PushExpressionEvaluationContext(
LSI->CallOperator->isConsteval()
? ExpressionEvaluationContext::ImmediateFunctionContext
: ExpressionEvaluationContext::PotentiallyEvaluated);
}
void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation) {
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
DiscardCleanupsInEvaluationContext();
PopExpressionEvaluationContext();
if (!IsInstantiation)
PopDeclContext();
CXXRecordDecl *Class = LSI->Lambda;
Class->setInvalidDecl();
SmallVector<Decl*, 4> Fields(Class->fields());
ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
SourceLocation(), ParsedAttributesView());
CheckCompletedCXXClass(nullptr, Class);
PopFunctionScopeInfo();
}
template <typename Func>
static void repeatForLambdaConversionFunctionCallingConvs(
Sema &S, const FunctionProtoType &CallOpProto, Func F) {
CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
CallOpProto.isVariadic(), false);
CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
CallOpProto.isVariadic(), true);
CallingConv CallOpCC = CallOpProto.getCallConv();
if (S.getLangOpts().MSVCCompat) {
CallingConv Convs[] = {
CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
DefaultFree, DefaultMember, CallOpCC};
llvm::sort(Convs);
llvm::iterator_range<CallingConv *> Range(
std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
const TargetInfo &TI = S.getASTContext().getTargetInfo();
for (CallingConv C : Range) {
if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
F(C);
}
return;
}
if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
F(DefaultFree);
F(DefaultMember);
} else {
F(CallOpCC);
}
}
static CallingConv
getLambdaConversionFunctionCallConv(Sema &S,
const FunctionProtoType *CallOpProto) {
CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
CallOpProto->isVariadic(), false);
CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
CallOpProto->isVariadic(), true);
CallingConv CallOpCC = CallOpProto->getCallConv();
if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
return DefaultFree;
return CallOpCC;
}
QualType Sema::getLambdaConversionFunctionResultType(
const FunctionProtoType *CallOpProto, CallingConv CC) {
const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
CallOpProto->getExtProtoInfo();
FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
InvokerExtInfo.TypeQuals = Qualifiers();
assert(InvokerExtInfo.RefQualifier == RQ_None &&
"Lambda's call operator should not have a reference qualifier");
return Context.getFunctionType(CallOpProto->getReturnType(),
CallOpProto->getParamTypes(), InvokerExtInfo);
}
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
CXXRecordDecl *Class,
CXXMethodDecl *CallOperator,
QualType InvokerFunctionTy) {
auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
return P->hasAttr<PassObjectSizeAttr>();
};
if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
return;
QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
FunctionProtoType::ExtProtoInfo ConvExtInfo(
S.Context.getDefaultCallingConvention(
false, true));
ConvExtInfo.TypeQuals = Qualifiers();
ConvExtInfo.TypeQuals.addConst();
ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
QualType ConvTy =
S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
SourceLocation Loc = IntroducerRange.getBegin();
DeclarationName ConversionName
= S.Context.DeclarationNames.getCXXConversionFunctionName(
S.Context.getCanonicalType(PtrToFunctionTy));
TypeSourceInfo *ConvNamePtrToFunctionTSI =
S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
DeclarationNameLoc ConvNameLoc =
DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
FunctionProtoTypeLoc ConvTL =
ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
PointerTypeLoc PtrToFunctionTL =
ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
PointerTypeLoc ConvNamePtrToFunctionTL =
ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
FunctionProtoTypeLoc CallOpConvTL =
PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
FunctionProtoTypeLoc CallOpConvNameTL =
ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
SmallVector<ParmVarDecl *, 4> InvokerParams;
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
ParmVarDecl *From = CallOperator->getParamDecl(I);
InvokerParams.push_back(ParmVarDecl::Create(
S.Context,
S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
From->getLocation(), From->getIdentifier(), From->getType(),
From->getTypeSourceInfo(), From->getStorageClass(),
nullptr));
CallOpConvTL.setParam(I, From);
CallOpConvNameTL.setParam(I, From);
}
CXXConversionDecl *Conversion = CXXConversionDecl::Create(
S.Context, Class, Loc,
DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
S.getCurFPFeatures().isFPConstrained(),
true, ExplicitSpecifier(),
S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified,
CallOperator->getBody()->getEndLoc());
Conversion->setAccess(AS_public);
Conversion->setImplicit(true);
if (Class->isGenericLambda()) {
FunctionTemplateDecl *TemplateCallOperator =
CallOperator->getDescribedFunctionTemplate();
FunctionTemplateDecl *ConversionTemplate =
FunctionTemplateDecl::Create(S.Context, Class,
Loc, ConversionName,
TemplateCallOperator->getTemplateParameters(),
Conversion);
ConversionTemplate->setAccess(AS_public);
ConversionTemplate->setImplicit(true);
Conversion->setDescribedFunctionTemplate(ConversionTemplate);
Class->addDecl(ConversionTemplate);
} else
Class->addDecl(Conversion);
DeclarationName InvokerName = &S.Context.Idents.get(
getLambdaStaticInvokerName());
CXXMethodDecl *Invoke = CXXMethodDecl::Create(
S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
S.getCurFPFeatures().isFPConstrained(),
true, ConstexprSpecKind::Unspecified,
CallOperator->getBody()->getEndLoc());
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
InvokerParams[I]->setOwningFunction(Invoke);
Invoke->setParams(InvokerParams);
Invoke->setAccess(AS_private);
Invoke->setImplicit(true);
if (Class->isGenericLambda()) {
FunctionTemplateDecl *TemplateCallOperator =
CallOperator->getDescribedFunctionTemplate();
FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
S.Context, Class, Loc, InvokerName,
TemplateCallOperator->getTemplateParameters(),
Invoke);
StaticInvokerTemplate->setAccess(AS_private);
StaticInvokerTemplate->setImplicit(true);
Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
Class->addDecl(StaticInvokerTemplate);
} else
Class->addDecl(Invoke);
}
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
CXXRecordDecl *Class,
CXXMethodDecl *CallOperator) {
const FunctionProtoType *CallOpProto =
CallOperator->getType()->castAs<FunctionProtoType>();
repeatForLambdaConversionFunctionCallingConvs(
S, *CallOpProto, [&](CallingConv CC) {
QualType InvokerFunctionTy =
S.getLambdaConversionFunctionResultType(CallOpProto, CC);
addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
InvokerFunctionTy);
});
}
static void addBlockPointerConversion(Sema &S,
SourceRange IntroducerRange,
CXXRecordDecl *Class,
CXXMethodDecl *CallOperator) {
const FunctionProtoType *CallOpProto =
CallOperator->getType()->castAs<FunctionProtoType>();
QualType FunctionTy = S.getLambdaConversionFunctionResultType(
CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
FunctionProtoType::ExtProtoInfo ConversionEPI(
S.Context.getDefaultCallingConvention(
false, true));
ConversionEPI.TypeQuals = Qualifiers();
ConversionEPI.TypeQuals.addConst();
QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
SourceLocation Loc = IntroducerRange.getBegin();
DeclarationName Name
= S.Context.DeclarationNames.getCXXConversionFunctionName(
S.Context.getCanonicalType(BlockPtrTy));
DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
CXXConversionDecl *Conversion = CXXConversionDecl::Create(
S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
S.getCurFPFeatures().isFPConstrained(),
true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
CallOperator->getBody()->getEndLoc());
Conversion->setAccess(AS_public);
Conversion->setImplicit(true);
Class->addDecl(Conversion);
}
ExprResult Sema::BuildCaptureInit(const Capture &Cap,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping) {
if (Cap.isVLATypeCapture())
return ExprResult();
if (Cap.isInitCapture())
return Cap.getVariable()->getInit();
SourceLocation Loc =
ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
ExprResult Init;
IdentifierInfo *Name = nullptr;
if (Cap.isThisCapture()) {
QualType ThisTy = getCurrentThisType();
Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
if (Cap.isCopyCapture())
Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
else
Init = This;
} else {
assert(Cap.isVariableCapture() && "unknown kind of capture");
VarDecl *Var = Cap.getVariable();
Name = Var->getIdentifier();
Init = BuildDeclarationNameExpr(
CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
}
if (IsOpenMPMapping)
return Init;
if (Init.isInvalid())
return ExprError();
Expr *InitExpr = Init.get();
InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Name, Cap.getCaptureType(), Loc);
InitializationKind InitKind =
InitializationKind::CreateDirect(Loc, Loc, Loc);
InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
}
ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope) {
LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
ActOnFinishFunctionBody(LSI.CallOperator, Body);
return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
}
static LambdaCaptureDefault
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
switch (ICS) {
case CapturingScopeInfo::ImpCap_None:
return LCD_None;
case CapturingScopeInfo::ImpCap_LambdaByval:
return LCD_ByCopy;
case CapturingScopeInfo::ImpCap_CapturedRegion:
case CapturingScopeInfo::ImpCap_LambdaByref:
return LCD_ByRef;
case CapturingScopeInfo::ImpCap_Block:
llvm_unreachable("block capture in lambda");
}
llvm_unreachable("Unknown implicit capture style");
}
bool Sema::CaptureHasSideEffects(const Capture &From) {
if (From.isInitCapture()) {
Expr *Init = From.getVariable()->getInit();
if (Init && Init->HasSideEffects(Context))
return true;
}
if (!From.isCopyCapture())
return false;
const QualType T = From.isThisCapture()
? getCurrentThisType()->getPointeeType()
: From.getCaptureType();
if (T.isVolatileQualified())
return true;
const Type *BaseT = T->getBaseElementTypeUnsafe();
if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
!RD->hasTrivialDestructor();
return false;
}
bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const Capture &From) {
if (CaptureHasSideEffects(From))
return false;
if (From.isVLATypeCapture())
return false;
auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
if (From.isThisCapture())
diag << "'this'";
else
diag << From.getVariable();
diag << From.isNonODRUsed();
diag << FixItHint::CreateRemoval(CaptureRange);
return true;
}
FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
const sema::Capture &Capture) {
SourceLocation Loc = Capture.getLocation();
QualType FieldType = Capture.getCaptureType();
TypeSourceInfo *TSI = nullptr;
if (Capture.isVariableCapture()) {
auto *Var = Capture.getVariable();
if (Var->isInitCapture())
TSI = Capture.getVariable()->getTypeSourceInfo();
}
if (!TSI)
TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
FieldDecl *Field =
FieldDecl::Create(Context, RD, Loc, Loc,
nullptr, FieldType, TSI, nullptr,
false, ICIS_NoInit);
if (!FieldType->isDependentType()) {
if (RequireCompleteSizedType(Loc, FieldType,
diag::err_field_incomplete_or_sizeless)) {
RD->setInvalidDecl();
Field->setInvalidDecl();
} else {
NamedDecl *Def;
FieldType->isIncompleteType(&Def);
if (Def && Def->isInvalidDecl()) {
RD->setInvalidDecl();
Field->setInvalidDecl();
}
}
}
Field->setImplicit(true);
Field->setAccess(AS_private);
RD->addDecl(Field);
if (Capture.isVLATypeCapture())
Field->setCapturedVLAType(Capture.getCapturedVLAType());
return Field;
}
ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
LambdaScopeInfo *LSI) {
SmallVector<LambdaCapture, 4> Captures;
SmallVector<Expr *, 4> CaptureInits;
SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
LambdaCaptureDefault CaptureDefault =
mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
CXXRecordDecl *Class;
CXXMethodDecl *CallOperator;
SourceRange IntroducerRange;
bool ExplicitParams;
bool ExplicitResultType;
CleanupInfo LambdaCleanup;
bool ContainsUnexpandedParameterPack;
bool IsGenericLambda;
{
CallOperator = LSI->CallOperator;
Class = LSI->Lambda;
IntroducerRange = LSI->IntroducerRange;
ExplicitParams = LSI->ExplicitParams;
ExplicitResultType = !LSI->HasImplicitReturnType;
LambdaCleanup = LSI->Cleanup;
ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
IsGenericLambda = Class->isGenericLambda();
CallOperator->setLexicalDeclContext(Class);
Decl *TemplateOrNonTemplateCallOperatorDecl =
CallOperator->getDescribedFunctionTemplate()
? CallOperator->getDescribedFunctionTemplate()
: cast<Decl>(CallOperator);
TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
PopExpressionEvaluationContext();
bool CurHasPreviousCapture = CaptureDefault != LCD_None;
SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
CaptureDefaultLoc : IntroducerRange.getBegin();
for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
const Capture &From = LSI->Captures[I];
if (From.isInvalid())
return ExprError();
assert(!From.isBlockCapture() && "Cannot capture __block variables");
bool IsImplicit = I >= LSI->NumExplicitCaptures;
SourceLocation ImplicitCaptureLoc =
IsImplicit ? CaptureDefaultLoc : SourceLocation();
SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
bool IsCaptureUsed = true;
if (!CurContext->isDependentContext() && !IsImplicit &&
!From.isODRUsed()) {
bool NonODRUsedInitCapture =
IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
if (!NonODRUsedInitCapture) {
bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
SourceRange FixItRange;
if (CaptureRange.isValid()) {
if (!CurHasPreviousCapture && !IsLast) {
FixItRange = SourceRange(CaptureRange.getBegin(),
getLocForEndOfToken(CaptureRange.getEnd()));
} else {
FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
CaptureRange.getEnd());
}
}
IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
}
}
if (CaptureRange.isValid()) {
CurHasPreviousCapture |= IsCaptureUsed;
PrevCaptureLoc = CaptureRange.getEnd();
}
LambdaCapture Capture = [&] {
if (From.isThisCapture()) {
if (getLangOpts().CPlusPlus20 && IsImplicit &&
CaptureDefault == LCD_ByCopy) {
Diag(From.getLocation(), diag::warn_deprecated_this_capture);
Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
<< FixItHint::CreateInsertion(
getLocForEndOfToken(CaptureDefaultLoc), ", this");
}
return LambdaCapture(From.getLocation(), IsImplicit,
From.isCopyCapture() ? LCK_StarThis : LCK_This);
} else if (From.isVLATypeCapture()) {
return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
} else {
assert(From.isVariableCapture() && "unknown kind of capture");
VarDecl *Var = From.getVariable();
LambdaCaptureKind Kind =
From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
From.getEllipsisLoc());
}
}();
ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
BuildCaptureField(Class, From);
Captures.push_back(Capture);
CaptureInits.push_back(Init.get());
if (LangOpts.CUDA)
CUDACheckLambdaCapture(CallOperator, From);
}
Class->setCaptures(Context, Captures);
if (Captures.empty() && CaptureDefault == LCD_None)
addFunctionPointerConversions(*this, IntroducerRange, Class,
CallOperator);
if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
SmallVector<Decl*, 4> Fields(Class->fields());
ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
SourceLocation(), ParsedAttributesView());
CheckCompletedCXXClass(nullptr, Class);
}
Cleanup.mergeFrom(LambdaCleanup);
LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
CaptureDefault, CaptureDefaultLoc,
ExplicitParams, ExplicitResultType,
CaptureInits, EndLoc,
ContainsUnexpandedParameterPack);
if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
!CallOperator->isConstexpr() &&
!isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
!Class->getDeclContext()->isDependentContext()) {
CallOperator->setConstexprKind(
CheckConstexprFunctionDefinition(CallOperator,
CheckConstexprKind::CheckValid)
? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified);
}
DiagnoseShadowingLambdaDecls(LSI);
if (!CurContext->isDependentContext()) {
switch (ExprEvalContexts.back().Context) {
case ExpressionEvaluationContext::Unevaluated:
case ExpressionEvaluationContext::UnevaluatedList:
case ExpressionEvaluationContext::UnevaluatedAbstract:
case ExpressionEvaluationContext::ConstantEvaluated:
case ExpressionEvaluationContext::ImmediateFunctionContext:
ExprEvalContexts.back().Lambdas.push_back(Lambda);
break;
case ExpressionEvaluationContext::DiscardedStatement:
case ExpressionEvaluationContext::PotentiallyEvaluated:
case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
break;
}
}
return MaybeBindToTemporary(Lambda);
}
ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src) {
CXXRecordDecl *Lambda = Conv->getParent();
CXXMethodDecl *CallOperator
= cast<CXXMethodDecl>(
Lambda->lookup(
Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
CallOperator->setReferenced();
CallOperator->markUsed(Context);
ExprResult Init = PerformCopyInitialization(
InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
CurrentLocation, Src);
if (!Init.isInvalid())
Init = ActOnFinishFullExpr(Init.get(), false);
if (Init.isInvalid())
return ExprError();
BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
Block->setIsVariadic(CallOperator->isVariadic());
Block->setBlockMissingReturnType(false);
SmallVector<ParmVarDecl *, 4> BlockParams;
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
ParmVarDecl *From = CallOperator->getParamDecl(I);
BlockParams.push_back(ParmVarDecl::Create(
Context, Block, From->getBeginLoc(), From->getLocation(),
From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
From->getStorageClass(),
nullptr));
}
Block->setParams(BlockParams);
Block->setIsConversionFromLambda(true);
TypeSourceInfo *CapVarTSI =
Context.getTrivialTypeSourceInfo(Src->getType());
VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
ConvLocation, nullptr,
Src->getType(), CapVarTSI,
SC_None);
BlockDecl::Capture Capture(CapVar, false,
false, Init.get());
Block->setCaptures(Context, Capture, false);
Block->setBody(new (Context) CompoundStmt(ConvLocation));
Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
ExprCleanupObjects.push_back(Block);
Cleanup.setExprNeedsCleanups(true);
return BuildBlock;
}