23 #include "llvm/ADT/STLExtras.h" 24 using namespace clang;
70 unsigned CurScopeIndex = FunctionScopes.size() - 1;
71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72 FunctionScopes[CurScopeIndex]))
75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76 "The function on the top of sema's function-info stack must be a lambda");
79 const bool IsCapturingThis = !VarToCapture;
80 const bool IsCapturingVariable = !IsCapturingThis;
84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
96 if (IsCapturingVariable &&
98 return NoLambdaIsCaptureReady;
117 if (IsCapturingVariable && !LSI->
isCaptured(VarToCapture))
118 return NoLambdaIsCaptureReady;
120 return NoLambdaIsCaptureReady;
124 assert(CurScopeIndex);
130 assert(CurScopeIndex < (FunctionScopes.size() - 1));
134 return CurScopeIndex + 1;
135 return NoLambdaIsCaptureReady;
182 if (!OptionalStackIndex)
183 return NoLambdaIsCaptureCapable;
185 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
188 "The capture ready lambda for a potential capture can only be the " 189 "current lambda if it is a generic lambda");
192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
195 const bool IsCapturingThis = !VarToCapture;
196 const bool IsCapturingVariable = !IsCapturingThis;
198 if (IsCapturingVariable) {
203 const bool CanCaptureVariable =
209 DeclRefType, &IndexOfCaptureReadyLambda);
210 if (!CanCaptureVariable)
211 return NoLambdaIsCaptureCapable;
216 const bool CanCaptureThis =
220 &IndexOfCaptureReadyLambda);
222 return NoLambdaIsCaptureCapable;
224 return IndexOfCaptureReadyLambda;
265 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
275 std::tuple<MangleNumberingContext *, Decl *>
279 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
293 if (ManglingContextDecl) {
294 if (
ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
297 if (LexicalDC->isRecord())
298 Kind = DefaultArgument;
299 }
else if (
VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
300 if (Var->getDeclContext()->isRecord())
301 Kind = StaticDataMember;
302 else if (Var->getMostRecentDecl()->isInline())
303 Kind = InlineVariable;
304 else if (Var->getDescribedVarTemplate())
305 Kind = VariableTemplate;
306 else if (
auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
307 if (!VTS->isExplicitSpecialization())
308 Kind = VariableTemplate;
310 }
else if (isa<FieldDecl>(ManglingContextDecl)) {
318 bool IsInNonspecializedTemplate =
319 inTemplateInstantiation() || CurContext->isDependentContext();
324 if ((IsInNonspecializedTemplate &&
325 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
327 while (
auto *CD = dyn_cast<CapturedDecl>(DC))
332 return std::make_tuple(
nullptr,
nullptr);
335 case StaticDataMember:
337 if (!IsInNonspecializedTemplate)
338 return std::make_tuple(
nullptr, ManglingContextDecl);
344 case DefaultArgument:
348 case VariableTemplate:
350 return std::make_tuple(
352 ManglingContextDecl),
353 ManglingContextDecl);
356 llvm_unreachable(
"unexpected context");
365 Expr *TrailingRequiresClause) {
375 if (Result->isUndeducedType()) {
376 Result = SubstAutoType(Result, Context.
DependentTy);
395 Context, Class, EndLoc,
398 MethodType, MethodTypeInfo,
SC_None,
399 true, ConstexprKind, EndLoc, TrailingRequiresClause);
413 if (TemplateMethod) {
416 Class->
addDecl(TemplateMethod);
421 if (!Params.empty()) {
423 CheckParmsForFunctionDef(Params,
427 P->setOwningFunction(Method);
435 Optional<std::tuple<unsigned, bool, Decl *>> Mangling) {
437 unsigned ManglingNumber;
438 bool HasKnownInternalLinkage;
439 Decl *ManglingContextDecl;
440 std::tie(ManglingNumber, HasKnownInternalLinkage, ManglingContextDecl) =
443 HasKnownInternalLinkage);
447 auto getMangleNumberingContext =
451 if (ManglingContextDecl)
456 while (
auto *CD = dyn_cast<CapturedDecl>(DC))
462 Decl *ManglingContextDecl;
463 std::tie(MCtx, ManglingContextDecl) =
465 bool HasKnownInternalLinkage =
false;
466 if (!MCtx && getLangOpts().CUDA) {
471 MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
472 assert(MCtx &&
"Retrieving mangle numbering context failed!");
473 HasKnownInternalLinkage =
true;
478 HasKnownInternalLinkage);
488 bool ExplicitResultType,
492 LSI->
Lambda = LambdaClass;
502 if (ExplicitResultType) {
508 diag::err_lambda_incomplete_result)) {
525 assert(LSI &&
"Expected a lambda scope");
527 "Already acted on explicit template parameters");
529 "Explicit template parameters should come " 530 "before invented (auto) ones");
531 assert(!TParams.empty() &&
532 "No template parameters to act on");
542 for (
unsigned p = 0, NumParams = CallOperator->
getNumParams();
543 p < NumParams; ++p) {
551 for (
const auto &
Capture : Captures) {
555 Diag(
Capture.Loc, diag::note_var_explicitly_captured_here)
560 CheckShadow(CurScope, Param);
562 PushOnScopeChains(Param, CurScope);
582 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
583 return cast<EnumDecl>(D->getDeclContext());
591 if (BO->getOpcode() == BO_Comma)
598 if (
StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
599 if (
Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
620 if (ICE->getCastKind() == CK_IntegralCast)
628 return ET->getDecl();
651 if (!ED)
return nullptr;
654 for (++i; i != e; ++i) {
670 i = returns.begin(), e = returns.end(); i != e; ++i) {
682 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
686 cleanups->setSubExpr(E);
697 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().
CPlusPlus14) &&
698 "lambda expressions use auto deduction in C++14 onwards");
735 assert(!CSI.
ReturnType.
isNull() &&
"We should have a tentative return type.");
740 if (!getLangOpts().CPlusPlus) {
741 assert(isa<BlockScopeInfo>(CSI));
764 (RetE ? RetE->
getType() : Context.
VoidTy).getUnqualifiedType();
770 if (BlockNullability &&
771 (!RetTyNullability ||
780 diag::err_typecheck_missing_return_type_incompatible)
781 << ReturnType << CSI.
ReturnType << isa<LambdaScopeInfo>(CSI);
797 DeductType = BuildReferenceType(DeductType,
true, Loc, Id);
798 assert(!DeductType.
isNull() &&
"can't build reference to auto");
804 ? diag::warn_cxx17_compat_init_capture_pack
805 : diag::ext_init_capture_pack);
855 unsigned InitStyle,
Expr *Init) {
860 PETL.setEllipsisLoc(EllipsisLoc);
867 Loc, Id, InitCaptureType, TSI,
SC_Auto);
871 NewVD->
setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
875 getCurLambda()->LocalPacks.push_back(NewVD);
880 assert(Var->
isInitCapture() &&
"init capture flag should be set");
890 assert(LSI &&
"LambdaScopeInfo should be on stack!");
897 assert(TemplateParamScope &&
898 "Lambda with explicit template param list should establish a " 899 "template param scope");
900 assert(TemplateParamScope->getParent());
901 KnownDependent = TemplateParamScope->getParent()
902 ->getTemplateParamParent() !=
nullptr;
909 bool ExplicitParams =
true;
910 bool ExplicitResultType =
true;
911 bool ContainsUnexpandedParameterPack =
false;
921 EPI.TypeQuals.addConst();
922 LangAS AS = getDefaultCXXMethodAddrSpace();
924 EPI.TypeQuals.addAddressSpace(AS);
932 QualType DefaultTypeForNoTrailingReturn =
938 ExplicitParams =
false;
939 ExplicitResultType =
false;
943 "lambda-declarator is a function");
950 if (!FTI.hasMutableQualifier()) {
955 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
956 assert(MethodTyInfo &&
"no type from lambda-declarator");
959 ExplicitResultType = FTI.hasTrailingReturnType();
962 Params.reserve(FTI.NumParams);
963 for (
unsigned i = 0, e = FTI.NumParams; i != e; ++i)
964 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
969 DiagnoseUnexpandedParameterPack(Intro.
Range.
getBegin(), MethodTyInfo,
970 UPPC_DeclarationType);
974 KnownDependent, Intro.
Default);
976 startLambdaDefinition(Class, Intro.
Range, MethodTyInfo, EndLoc, Params,
980 CheckCXXDefaultArguments(Method);
984 AddRangeBasedOptnone(Method);
987 if (
Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method,
true))
991 ProcessDeclAttributes(CurScope, Method, ParamInfo);
995 if (getLangOpts().
CUDA)
996 CUDASetLambdaAttrs(Method);
999 handleLambdaNumbering(Class, Method);
1002 PushDeclContext(CurScope, Method);
1006 ExplicitParams, ExplicitResultType, !Method->
isConst());
1020 (getCurrentThisType().isNull() ||
1026 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
1032 PrevCaptureLoc = C->Loc, ++C) {
1036 ? diag::ext_star_this_lambda_capture_cxx17
1037 : diag::warn_cxx14_compat_star_this_lambda_capture);
1043 Diag(C->Loc, diag::err_capture_more_than_once)
1046 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1057 ? diag::ext_equals_this_lambda_capture_cxx2a
1058 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1063 QualType ThisCaptureType = getCurrentThisType();
1064 if (ThisCaptureType.
isNull()) {
1065 Diag(C->Loc, diag::err_this_capture) <<
true;
1069 CheckCXXThisCapture(C->Loc,
true,
true,
1077 assert(C->Id &&
"missing identifier for capture");
1079 if (C->Init.isInvalid())
1083 if (C->Init.isUsable()) {
1085 ? diag::warn_cxx11_compat_init_capture
1086 : diag::ext_init_capture);
1093 if (C->InitCaptureType.get().isNull())
1096 if (C->Init.get()->containsUnexpandedParameterPack() &&
1098 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1101 switch (C->InitKind) {
1103 llvm_unreachable(
"not an init-capture?");
1114 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1115 C->EllipsisLoc, C->Id, InitStyle,
1122 PushOnScopeChains(Var, CurScope,
false);
1125 "init capture has valid but null init?");
1133 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1135 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1138 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1140 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1149 LookupName(R, CurScope);
1156 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1161 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1168 if (!CaptureNames.insert(C->Id).second) {
1170 Diag(C->Loc, diag::err_capture_more_than_once)
1173 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1177 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1186 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1195 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1203 if (C->EllipsisLoc.isValid()) {
1205 EllipsisLoc = C->EllipsisLoc;
1207 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1208 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1214 ContainsUnexpandedParameterPack =
true;
1217 if (C->Init.isUsable()) {
1218 addInitCapture(LSI, Var);
1221 TryCapture_ExplicitByVal;
1222 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1227 finishLambdaExplicitCaptures(LSI);
1232 addLambdaParameters(Intro.
Captures, Method, CurScope);
1236 PushExpressionEvaluationContext(
1237 ExpressionEvaluationContext::PotentiallyEvaluated);
1241 bool IsInstantiation) {
1245 DiscardCleanupsInEvaluationContext();
1246 PopExpressionEvaluationContext();
1249 if (!IsInstantiation)
1258 CheckCompletedCXXClass(
nullptr, Class);
1260 PopFunctionScopeInfo();
1276 "Lambda's call operator should not have a reference qualifier");
1289 auto HasPassObjectSizeAttr = [](
const ParmVarDecl *
P) {
1290 return P->hasAttr<PassObjectSizeAttr>();
1292 if (llvm::any_of(CallOperator->
parameters(), HasPassObjectSizeAttr))
1306 ConvExtInfo.TypeQuals.addConst();
1364 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I) {
1374 CallOpConvTL.setParam(I, From);
1375 CallOpConvNameTL.setParam(I, From);
1394 Loc, ConversionName,
1400 Class->
addDecl(ConversionTemplate);
1422 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I)
1423 InvokerParams[I]->setOwningFunction(Invoke);
1431 S.
Context, Class, Loc, InvokerName,
1437 Class->
addDecl(StaticInvokerTemplate);
1455 ConversionEPI.TypeQuals.addConst();
1476 bool IsOpenMPMapping) {
1506 QualType ThisTy = getCurrentThisType();
1507 Expr *
This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.
isValid());
1509 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1515 Name = Var->getIdentifier();
1516 Init = BuildDeclarationNameExpr(
1523 if (IsOpenMPMapping)
1535 return InitSeq.
Perform(*
this, Entity, InitKind, InitExpr);
1542 return BuildLambdaExpr(StartLoc, Body->
getEndLoc(), &LSI);
1556 llvm_unreachable(
"block capture in lambda");
1558 llvm_unreachable(
"Unknown implicit capture style");
1572 ? getCurrentThisType()->getPointeeType()
1580 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1581 !RD->hasTrivialDestructor();
1588 if (CaptureHasSideEffects(From))
1594 auto diag =
Diag(From.
getLocation(), diag::warn_unused_lambda_capture);
1614 if (Var->isInitCapture())
1630 if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
1663 bool ExplicitParams;
1664 bool ExplicitResultType;
1666 bool ContainsUnexpandedParameterPack;
1667 bool IsGenericLambda;
1679 Decl *TemplateOrNonTemplateCallOperatorDecl =
1682 : cast<Decl>(CallOperator);
1688 PopExpressionEvaluationContext();
1691 bool CurHasPreviousCapture = CaptureDefault !=
LCD_None;
1693 CaptureDefaultLoc : IntroducerRange.
getBegin();
1695 for (
unsigned I = 0, N = LSI->
Captures.size(); I != N; ++I) {
1701 assert(!From.
isBlockCapture() &&
"Cannot capture __block variables");
1710 bool IsCaptureUsed =
true;
1711 if (!CurContext->isDependentContext() && !IsImplicit &&
1715 bool NonODRUsedInitCapture =
1717 if (!NonODRUsedInitCapture) {
1721 if (!CurHasPreviousCapture && !IsLast) {
1725 getLocForEndOfToken(CaptureRange.
getEnd()));
1728 FixItRange =
SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1733 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1738 CurHasPreviousCapture |= IsCaptureUsed;
1739 PrevCaptureLoc = CaptureRange.
getEnd();
1748 if (getLangOpts().CPlusPlus2a && IsImplicit &&
1751 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1753 getLocForEndOfToken(CaptureDefaultLoc),
", this");
1770 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1777 BuildCaptureField(Class, From);
1778 Captures.push_back(Capture);
1779 CaptureInits.push_back(Init.get());
1787 if (Captures.empty() && CaptureDefault ==
LCD_None)
1797 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
1804 CheckCompletedCXXClass(
nullptr, Class);
1807 Cleanup.mergeFrom(LambdaCleanup);
1810 CaptureDefault, CaptureDefaultLoc,
1812 ExplicitParams, ExplicitResultType,
1813 CaptureInits, EndLoc,
1814 ContainsUnexpandedParameterPack);
1820 !isa<CoroutineBodyStmt>(CallOperator->
getBody()) &&
1823 CheckConstexprFunctionDefinition(CallOperator,
1824 CheckConstexprKind::CheckValid)
1830 DiagnoseShadowingLambdaDecls(LSI);
1832 if (!CurContext->isDependentContext()) {
1833 switch (ExprEvalContexts.back().Context) {
1837 case ExpressionEvaluationContext::Unevaluated:
1838 case ExpressionEvaluationContext::UnevaluatedList:
1839 case ExpressionEvaluationContext::UnevaluatedAbstract:
1849 case ExpressionEvaluationContext::ConstantEvaluated:
1853 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1856 case ExpressionEvaluationContext::DiscardedStatement:
1857 case ExpressionEvaluationContext::PotentiallyEvaluated:
1858 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1863 return MaybeBindToTemporary(Lambda);
1873 = cast<CXXMethodDecl>(
1882 CurrentLocation, Src);
1884 Init = ActOnFinishFullExpr(Init.
get(),
false);
1899 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I) {
1917 ConvLocation,
nullptr,
1930 ExprCleanupObjects.push_back(Block);
1931 Cleanup.setExprNeedsCleanups(
true);
void setImplicit(bool I=true)
Represents a function declaration or definition.
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
SourceLocation getBeginLoc() const
A class which contains all the information about a particular captured value.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
A (possibly-)qualified type.
bool ExplicitParams
Whether the (empty) parameter list is explicit.
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
bool SetTypeQual(TQ T, SourceLocation Loc)
Stmt - This represents one statement.
An instance of this object exists for each enum constant that is defined.
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Decl - This represents one declaration (or definition), e.g.
bool isVariadic() const
Whether this function prototype is variadic.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool isCopyCapture() const
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
void setParams(ArrayRef< ParmVarDecl *> NewParamInfo)
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
RefQualifierKind RefQualifier
A container of type source information.
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template...
Store information needed for an explicit specifier.
QualType getConversionType() const
Returns the type that this conversion function is converting to.
void setInitStyle(InitializationStyle Style)
Describes the capture of a variable or of this, or of a C++1y init-capture.
This file provides some common utility functions for processing Lambda related AST Constructs...
Represents a variable declaration or definition.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
Information about one declarator, including the parsed type information and the identifier.
QualType getReturnType() const
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
const T * getAs() const
Member-template getAs<specific type>'.
bool This(InterpState &S, CodePtr OpPC)
Extra information about a function prototype.
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
bool isInvalidDecl() const
Stores a list of template parameters for a TemplateDecl and its derived classes.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Represents a parameter to a function.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Defines the clang::Expr interface and subclasses for C++ expressions.
The collection of all-type qualifiers we support.
tok::TokenKind ContextKind
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Represents a struct/union/class.
Scope * getTemplateParamParent()
FunctionType::ExtInfo ExtInfo
One of these records is kept for each identifier that is lexed.
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
ArrayRef< QualType > getParamTypes() const
field_range fields() const
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
LambdaCaptureKind
The different capture forms in a lambda introducer.
Represents a member of a struct/union/class.
bool isReferenceType() const
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
void setParams(ArrayRef< ParmVarDecl *> NewParamInfo)
SourceLocation getBeginLoc() const LLVM_READONLY
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, bool DependentLambda, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
ArrayRef< ParmVarDecl * > parameters() const
DeclClass * getAsSingle() const
bool isThisCapture() const
void setNameLoc(SourceLocation Loc)
Represents the results of name lookup.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
< Capturing the *this object by copy
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
const VariableArrayType * getCapturedVLAType() const
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
A builtin binary operation expression such as "x + y" or "x <= y".
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
void finishedExplicitCaptures()
Note when all explicit captures have been added.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Scope - A scope is a transient data structure that is used while parsing the program.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var)
Add an init-capture to a lambda scope.
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
static EnumDecl * findCommonEnumForBlockReturns(ArrayRef< ReturnStmt *> returns)
Attempt to find a common type T for which all of the returned expressions in a block are enumerator-l...
CXXMethodDecl * startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef< ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause)
Start the definition of a lambda expression.
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Represents a C++ nested-name-specifier or a global scope specifier.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
const LangOptions & getLangOpts() const
bool isLambdaCallOperator(const CXXMethodDecl *MD)
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
StringRef getLambdaStaticInvokerName()
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType)
Get the return type to use for a lambda's conversion function(s) to function pointer type...
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
DeclSpec & getOrCreateMethodQualifiers()
void addLambdaParameters(ArrayRef< LambdaIntroducer::LambdaCapture > Captures, CXXMethodDecl *CallOperator, Scope *CurScope)
Introduce the lambda parameters into scope.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
ExtInfo withCallingConv(CallingConv cc) const
ImplicitCaptureStyle ImpCaptureStyle
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
ConditionalOperator - The ?: ternary operator.
Sema - This implements semantic analysis and AST building for C.
CompoundStmt - This represents a group of statements like { stmt stmt }.
bool Mutable
Whether this is a mutable lambda.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Represents a prototype with parameter type info, e.g.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
DeclarationNameTable DeclarationNames
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
SmallVector< LambdaCapture, 4 > Captures
SourceLocation PotentialThisCaptureLocation
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
bool isVariableCapture() const
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Represents a block literal declaration, which is like an unnamed FunctionDecl.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed...
This represents one expression.
bool isVariadic() const
Whether this function is variadic.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
void setRetValue(Expr *E)
bool isFileContext() const
DeclContext * getDeclContext()
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable)
Endow the lambda scope info with the relevant properties.
bool isCaptured(VarDecl *Var) const
Determine whether the given variable has been captured.
bool isFunctionOrMethod() const
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Direct list-initialization (C++11)
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, ArrayRef< LambdaCapture > Captures, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr *> CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
SourceLocation getEnd() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
struct CXXOpName CXXOperatorName
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Represents a C++ conversion function within a class.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
TypeLoc getReturnLoc() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
SourceLocation getEndLoc() const LLVM_READONLY
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
ConstexprSpecKind getConstexprSpecifier() const
void setIsVariadic(bool value)
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
void setIsConversionFromLambda(bool val=true)
SourceLocation DefaultLoc
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
VarDecl * getVariable() const
ExtProtoInfo getExtProtoInfo() const
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
QualType getReturnType() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
CXXRecordDecl * Lambda
The class that describes the lambda.
static Optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
MutableArrayRef< Expr * > MultiExprArg
void setReferenced(bool R=true)
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user...
void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl, bool HasKnownInternalLinkage=false)
Set the mangling number and context declaration for a lambda class.
Represents a static or instance method of a struct/union/class.
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, Optional< std::tuple< unsigned, bool, Decl *>> Mangling=None)
Number lambda for linkage purposes if necessary.
No ref-qualifier was provided.
C-style initialization with assignment.
const ParmVarDecl * getParamDecl(unsigned i) const
bool isVLATypeCapture() const
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Describes the kind of initialization being performed, along with location information for tokens rela...
SmallVector< Capture, 4 > Captures
Captures - The captures.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise...
Represents a pack expansion of types.
DeclarationNameLoc - Additional source/type location info for a declaration name. ...
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
This file provides some common utility functions for processing Lambdas.
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Dataflow Directional Tag Classes.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
void setBody(CompoundStmt *B)
ConstexprSpecKind
Define the kind of constexpr specifier.
bool isValid() const
Return true if this is a valid SourceLocation object.
LambdaCaptureDefault Default
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body...
Optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
const Expr * getInit() const
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
The name of a declaration.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack...
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef< NamedDecl *> TParams, SourceLocation RAngleLoc)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
void setInitCapture(bool IC)
Capturing variable-length array type.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void setConstexprKind(ConstexprSpecKind CSK)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
TypeSourceInfo * getTypeSourceInfo() const
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
void addDecl(Decl *D)
Add the declaration D into this context.
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Capturing the *this object by reference.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void setSignatureAsWritten(TypeSourceInfo *Sig)
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
bool isInitCapture() const
Determine whether this capture is an init-capture.
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Call-style initialization (C++98)
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
TranslationUnitDecl * getTranslationUnitDecl() const
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Represents a C++ struct/union/class.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Defines the clang::TargetInfo interface.
Represents a complete lambda introducer.
bool HasImplicitReturnType
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
A reference to a declared variable, function, enum, etc.
bool isNonODRUsed() const
bool empty() const
Return true if no decls were found.
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
A trivial tuple used to represent a source range.
void setLexicalDeclContext(DeclContext *DC)
This represents a decl that may have a name.
bool isTranslationUnit() const
void setAccess(AccessSpecifier AS)
void setBlockMissingReturnType(bool val=true)
Describes an entity that is being initialized.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Wrapper for source info for pointers.
SourceLocation getBegin() const
bool isBlockCapture() const
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt *> returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Declaration of a template function.
Attr - This represents one attribute.
SourceLocation getLocation() const
QualType getType() const
Return the type wrapped by this type source info.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...