Author: Ivan Ugryumov Date: 2026-11-19T00:13:38Z New Revision: 91d101b4e7a406b0494ff98c2825277dd193f467
URL: https://github.com/llvm/llvm-project/commit/91d101b4e7a406b0494ff98c2825277dd193f467 DIFF: https://github.com/llvm/llvm-project/commit/91d101b4e7a406b0494ff98c2825277dd193f467.diff LOG: [clang] Diagnose VLA types from an enclosing function in local classes and blocks (#229697) A variably modified type whose array bound is evaluated in an enclosing function cannot be used in a member function of a local class or in a block: the size is only computed in the enclosing function, so CodeGen crashed when emitting such a declaration. Record the context in which each VLA bound is evaluated, and diagnose uses of such a type (variable, parameter and typedef declarations, casts, sizeof) across a local class or block boundary: ``` error: variably modified type 'X' (aka 'int[foo()]') cannot be used in a local class because its size is evaluated in an enclosing function note: size expression is evaluated here ``` Such a declaration is now rejected even in a member function that is never used, the same way a reference to a local variable of the enclosing function already is. This also fixes a crash when a variable of such a type was declared in a lambda, and replaces the typedef-based capture code in sizeof and array subscripts. Not handled yet: - bounds in a function prototype (FIXME test) - default arguments - va_arg Fixes #55686 Assisted-by: Claude Opus 5.5 Added: clang/test/CodeGenCXX/vla-lambda-enclosing-function.cpp clang/test/Sema/vla-enclosing-function-blocks.c clang/test/SemaCXX/vla-enclosing-function.cpp Modified: clang/docs/ReleaseNotes.md clang/include/clang/Basic/DiagnosticSemaKinds.td clang/include/clang/Sema/Sema.h clang/lib/Sema/SemaCast.cpp clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaType.cpp clang/lib/Sema/TreeTransform.h Removed: ################################################################################ diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index aab88904167ab..060c9a2c91749 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -912,6 +912,7 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and - Fixed a bug where a stray closing curley brace in an OpenMP/OpenACC pragma could cause pragma parsing issues when inside of a member function. (#GH214195) - Fixed a bug where preprocessor directives following comments were not correctly recognized when using -C. (#GH48361) - Fixed a crash when declaring a member template within a local class inside an OpenMP region. (#GH216052) +- Fixed a crash when a variably modified type whose size is evaluated in an enclosing function was used in a local class or a block. Such uses are now diagnosed, and a lambda now captures the size of such a type. (#GH55686) - Fixed a crash when an OpenMP `copyprivate` clause names a non-static data member that is not private in the enclosing context, which is now diagnosed, a data member inside a member function template, or a structured binding. (#GH217893) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 56929fb4f89ce..1ebfb40114c4b 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -8341,6 +8341,12 @@ def err_unexpected_interface : Error< def err_ref_non_value : Error<"%0 does not refer to a value">; def err_ref_vm_type : Error< "cannot refer to declaration with a variably modified type inside block">; +def err_vm_type_from_enclosing_function : Error< + "variably modified type %0 cannot be used in a " + "%select{local class|block}1 because its size is evaluated in an " + "enclosing function">; +def note_vm_type_size_evaluated_here : Note< + "size expression is evaluated here">; def err_ref_flexarray_type : Error< "cannot refer to declaration of structure variable with flexible array member " "inside block">; diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 8e9e7e7dd1242..0d13ea4c74ebf 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -7318,6 +7318,12 @@ class Sema final : public SemaBase { /// variable will have in the given scope. QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc); + /// Handle a use of the variably modified type \p T in the current context. + /// Array bounds evaluated in an enclosing context are captured by the + /// lambdas in between; if a local class or a block is in between instead, + /// the use is diagnosed. Returns false if the use is invalid. + bool CheckVariablyModifiedTypeUse(QualType T, SourceLocation Loc); + /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. @@ -8534,6 +8540,10 @@ class Sema final : public SemaBase { private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); + /// Maps the size expression of each VLA type created inside a function, + /// block or lambda to the context in which that size is evaluated. + llvm::DenseMap<const Expr *, const DeclContext *> VLASizeExprOwners; + /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp index cb169c3fc65f7..ff260fcddac65 100644 --- a/clang/lib/Sema/SemaCast.cpp +++ b/clang/lib/Sema/SemaCast.cpp @@ -342,6 +342,9 @@ Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceRange AngleBrackets, SourceRange Parens) { ExprResult Ex = E; QualType DestType = DestTInfo->getType(); + if (!CheckVariablyModifiedTypeUse(DestType, + DestTInfo->getTypeLoc().getBeginLoc())) + return ExprError(); // If the type is dependent, we won't do the semantic analysis now. bool TypeDependent = @@ -3493,6 +3496,10 @@ ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, TypeSourceInfo *CastTypeInfo, SourceLocation RPLoc, Expr *CastExpr) { + if (!CheckVariablyModifiedTypeUse(CastTypeInfo->getType(), + CastTypeInfo->getTypeLoc().getBeginLoc())) + return ExprError(); + CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = CastOperation::OpRangeType(LPLoc, LPLoc, CastExpr->getEndLoc()); @@ -3523,6 +3530,10 @@ ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, Expr *CastExpr, SourceLocation RPLoc) { assert(LPLoc.isValid() && "List-initialization shouldn't get here."); + if (!CheckVariablyModifiedTypeUse(Type, + CastTypeInfo->getTypeLoc().getBeginLoc())) + return ExprError(); + CastOperation Op(*this, Type, CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index e0fb824c1e14d..a0bd7f524db1c 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -7035,6 +7035,12 @@ Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { // that redeclarations will match. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); QualType T = TInfo->getType(); + + if (!CheckVariablyModifiedTypeUse(T, TInfo->getTypeLoc().getBeginLoc())) { + NewTD->setInvalidDecl(); + return; + } + if (T->isVariablyModifiedType()) { setFunctionHasBranchProtectedScope(); @@ -9041,6 +9047,14 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { if (NewVD->isInvalidDecl()) return; + SourceLocation VMLoc = NewVD->getLocation(); + if (TypeSourceInfo *TSI = NewVD->getTypeSourceInfo()) + VMLoc = TSI->getTypeLoc().getBeginLoc(); + if (!CheckVariablyModifiedTypeUse(NewVD->getType(), VMLoc)) { + NewVD->setInvalidDecl(); + return; + } + QualType T = NewVD->getType(); // Defer checking an 'auto' type until its initializer is attached. @@ -16192,6 +16206,10 @@ ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, Context.getAdjustedParameterType(T), TSInfo, SC, nullptr); + SourceLocation VMLoc = TSInfo ? TSInfo->getTypeLoc().getBeginLoc() : NameLoc; + if (!CheckVariablyModifiedTypeUse(T, VMLoc)) + New->setInvalidDecl(); + // Make a note if we created a new pack in the scope of a lambda, so that // we know that references to that pack must also be expanded within the // lambda scope. diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 45cc932c3eb93..5b63964b48daa 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -4661,10 +4661,12 @@ bool Sema::CheckVecStepExpr(Expr *E) { return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); } -static void captureVariablyModifiedType(ASTContext &Context, QualType T, - CapturingScopeInfo *CSI) { +/// Walk down into the variably modified type \p T and call \p Fn for each +/// variable length array type in it. +static void forEachVariableArrayType( + ASTContext &Context, QualType T, + llvm::function_ref<void(const VariableArrayType *)> Fn) { assert(T->isVariablyModifiedType()); - assert(CSI != nullptr); // We're going to walk down into the type and look for VLA expressions. do { @@ -4725,14 +4727,7 @@ static void captureVariablyModifiedType(ASTContext &Context, QualType T, case Type::VariableArray: { // Losing element qualification here is fine. const VariableArrayType *VAT = cast<VariableArrayType>(Ty); - - // Unknown size indication requires no size computation. - // Otherwise, evaluate and record it. - auto Size = VAT->getSizeExpr(); - if (Size && !CSI->isVLATypeCaptured(VAT) && - (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) - CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); - + Fn(VAT); T = VAT->getElementType(); break; } @@ -4783,6 +4778,106 @@ static void captureVariablyModifiedType(ASTContext &Context, QualType T, } while (!T.isNull() && T->isVariablyModifiedType()); } +static void captureVariablyModifiedType(ASTContext &Context, QualType T, + CapturingScopeInfo *CSI) { + assert(CSI != nullptr); + forEachVariableArrayType(Context, T, [&](const VariableArrayType *VAT) { + // Unknown size indication requires no size computation. + // Otherwise, evaluate and record it. + auto Size = VAT->getSizeExpr(); + if (Size && !CSI->isVLATypeCaptured(VAT) && + (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) + CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); + }); +} + +/// Find the capturing scope that is being built for the lambda call operator +/// or captured declaration \p DC, if any. +static CapturingScopeInfo * +findCapturingScope(ArrayRef<FunctionScopeInfo *> Scopes, + const DeclContext *DC) { + for (FunctionScopeInfo *FSI : llvm::reverse(Scopes)) { + if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI); + LSI && LSI->CallOperator == DC) + return LSI; + if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(FSI); + CRSI && CRSI->TheCapturedDecl == DC) + return CRSI; + } + return nullptr; +} + +bool Sema::CheckVariablyModifiedTypeUse(QualType T, SourceLocation Loc) { + if (VLASizeExprOwners.empty() || T.isNull()) + return true; + // Default arguments and default member initializers are evaluated where + // they are used, and unevaluated operands are not evaluated at all. + if (isUnevaluatedContext() || isCheckingDefaultArgumentOrInitializer()) + return true; + // FIXME: DeducedType drops the variably modified bit of the deduced type + // (auto, __auto_type), so look at the canonical type. + QualType CanonT = T.getCanonicalType(); + if (!CanonT->isVariablyModifiedType()) + return true; + + const Expr *BadSize = nullptr; + unsigned BadKind = 0; + forEachVariableArrayType(Context, CanonT, [&](const VariableArrayType *VAT) { + const Expr *Size = VAT->getSizeExpr(); + if (BadSize || !Size) + return; + auto It = VLASizeExprOwners.find(Size); + if (It == VLASizeExprOwners.end()) + return; + + // Walk from the use to the context in which the bound is evaluated. + // Lambdas and captured regions on the way capture the bound; a local + // class or a block cannot see it. + SmallVector<CapturingScopeInfo *, 2> Capturers; + std::optional<unsigned> Barrier; + const DeclContext *DC = CurContext; + for (; DC && DC != It->second; DC = DC->getParent()) { + if (isLambdaCallOperator(DC) || isa<CapturedDecl>(DC)) { + if (CapturingScopeInfo *CSI = findCapturingScope(FunctionScopes, DC)) + Capturers.push_back(CSI); + } else if (isa<BlockDecl>(DC)) { + Barrier = Barrier.value_or(1); + } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) { + if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD); + !CRD || !CRD->isLambda()) + Barrier = Barrier.value_or(0); + } + } + // Nothing to do if the bound is not evaluated in an enclosing context. + if (!DC) + return; + if (Barrier) { + BadSize = Size; + BadKind = *Barrier; + return; + } + // VAT is a canonical type; the bound may already have been captured + // through a diff erent type node with the same size expression. + for (CapturingScopeInfo *CSI : Capturers) + if (llvm::none_of(CSI->Captures, [&](const Capture &C) { + return C.isVLATypeCapture() && + C.getCapturedVLAType()->getSizeExpr() == Size; + })) + CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); + }); + if (!BadSize) + return true; + + // A typedef naming such a type has already been diagnosed. + if (const auto *TT = T->getAs<TypedefType>(); + TT && TT->getDecl()->isInvalidDecl()) + return false; + + Diag(Loc, diag::err_vm_type_from_enclosing_function) << T << BadKind; + Diag(BadSize->getBeginLoc(), diag::note_vm_type_size_evaluated_here); + return false; +} + bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, @@ -4861,30 +4956,6 @@ bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, ExprKind)) return true; - if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) { - if (auto *TT = ExprType->getAs<TypedefType>()) { - for (auto I = FunctionScopes.rbegin(), - E = std::prev(FunctionScopes.rend()); - I != E; ++I) { - auto *CSI = dyn_cast<CapturingScopeInfo>(*I); - if (CSI == nullptr) - break; - DeclContext *DC = nullptr; - if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) - DC = LSI->CallOperator; - else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) - DC = CRSI->TheCapturedDecl; - else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) - DC = BSI->TheDecl; - if (DC) { - if (DC->containsDecl(TT->getDecl())) - break; - captureVariablyModifiedType(Context, ExprType, CSI); - } - } - } - } - return false; } @@ -4914,6 +4985,20 @@ ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, if (!TInfo) return ExprError(); + if (!TInfo->getType()->isDependentType()) { + // The operand of sizeof is parsed in an unevaluated context, but a + // variably modified operand is evaluated if the sizeof itself is. + // FIXME: TransformToPotentiallyEvaluated() above should take care of this, + // but it only runs if an array bound is written inside the sizeof, not + // whenever the sizeof is potentially evaluated. + std::optional<EnterExpressionEvaluationContext> Evaluated; + if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && + isUnevaluatedContext()) + Evaluated.emplace(*this, parentEvaluationContext().Context); + if (!CheckVariablyModifiedTypeUse(TInfo->getType(), OpLoc)) + return ExprError(); + } + // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. return new (Context) UnaryExprOrTypeTraitExpr( ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); @@ -5655,33 +5740,6 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, assert(VK == VK_PRValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()); - if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && - FunctionScopes.size() > 1) { - if (auto *TT = - LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { - for (auto I = FunctionScopes.rbegin(), - E = std::prev(FunctionScopes.rend()); - I != E; ++I) { - auto *CSI = dyn_cast<CapturingScopeInfo>(*I); - if (CSI == nullptr) - break; - DeclContext *DC = nullptr; - if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) - DC = LSI->CallOperator; - else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) - DC = CRSI->TheCapturedDecl; - else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) - DC = BSI->TheDecl; - if (DC) { - if (DC->containsDecl(TT->getDecl())) - break; - captureVariablyModifiedType( - Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); - } - } - } - } - return new (Context) ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); } diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 19d39b5861485..0e49975e4bed0 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -2400,6 +2400,15 @@ QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM, } } + // Remember where the bound of a VLA is evaluated. Bounds in a function + // prototype are evaluated in that function, which doesn't exist yet, so they + // are not recorded and their uses are not diagnosed. + if (const VariableArrayType *VAT = Context.getAsVariableArrayType(T)) + if (CurContext->isFunctionOrMethod() && + !(getCurScope() && getCurScope()->isFunctionPrototypeScope())) + if (const Expr *Size = VAT->getSizeExpr()) + VLASizeExprOwners.try_emplace(Size, CurContext); + return T; } diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 2b6348b7ec8a6..87a0f40584384 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -14041,6 +14041,13 @@ template<typename Derived> ExprResult TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr( UnaryExprOrTypeTraitExpr *E) { + // C++0x [expr.sizeof]p1: + // The operand is either an expression, which is an unevaluated operand + // [...] + EnterExpressionEvaluationContext Unevaluated( + SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, + Sema::ReuseLambdaContextDecl); + if (E->isArgumentType()) { TypeSourceInfo *OldT = E->getArgumentTypeInfo(); @@ -14056,13 +14063,6 @@ TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr( E->getSourceRange()); } - // C++0x [expr.sizeof]p1: - // The operand is either an expression, which is an unevaluated operand - // [...] - EnterExpressionEvaluationContext Unevaluated( - SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, - Sema::ReuseLambdaContextDecl); - // Try to recover if we have something like sizeof(T::X) where X is a type. // Notably, there must be *exactly* one set of parens if X is a type. TypeSourceInfo *RecoveryTSI = nullptr; diff --git a/clang/test/CodeGenCXX/vla-lambda-enclosing-function.cpp b/clang/test/CodeGenCXX/vla-lambda-enclosing-function.cpp new file mode 100644 index 0000000000000..3b8043eb3c311 --- /dev/null +++ b/clang/test/CodeGenCXX/vla-lambda-enclosing-function.cpp @@ -0,0 +1,56 @@ +// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -Wno-vla-cxx-extension -emit-llvm -o - %s | FileCheck %s + +// A lambda that declares a variable of a VLA type from the enclosing function +// captures the array bound. + +int foo(); + +// CHECK-LABEL: define {{.*}} @_Z9by_copy_tv( +// CHECK: [[SIZE:%.*]] = call noundef i32 @_Z3foov() +// CHECK: [[EXT:%.*]] = zext i32 [[SIZE]] to i64 +// CHECK: store i64 [[EXT]], ptr {{%.*}} +// CHECK-LABEL: define internal {{.*}} @"_ZZ9by_copy_tvENK3$_0clEv"( +// CHECK: [[BOUND:%[0-9]+]] = load i64, ptr {{%[0-9]+}} +// CHECK: alloca i32, i64 [[BOUND]] +int by_copy_t() { + using X = int[foo()]; + return [] { X x; return (int)sizeof(x); }(); +} + +// An explicit cast to such a type captures the bound as well. +// CHECK-LABEL: define {{.*}} @_Z14cast_in_lambdav( +// CHECK: store i64 {{%.*}}, ptr {{%.*}} +// CHECK-LABEL: define internal {{.*}} @"_ZZ14cast_in_lambdavENK3$_0clEv"( +// CHECK: [[BOUND:%[0-9]+]] = load i64, ptr {{%[0-9]+}} +// CHECK: mul nuw i64 4, [[BOUND]] +unsigned long cast_in_lambda() { + using P = int (*)[foo()]; + return [] { return sizeof(((P)0)[1]); }(); +} + +// So does sizeof of such a type. +// CHECK-LABEL: define {{.*}} @_Z13sizeof_lambdav( +// CHECK: store i64 {{%.*}}, ptr {{%.*}} +// CHECK-LABEL: define internal {{.*}} @"_ZZ13sizeof_lambdavENK3$_0clEv"( +// CHECK: [[BOUND:%[0-9]+]] = load i64, ptr {{%[0-9]+}} +// CHECK: mul nuw i64 4, [[BOUND]] +unsigned long sizeof_lambda() { + using X = int[foo()]; + return [] { return sizeof(X); }(); +} + +// The bound of the lambda's own parameter is not captured. +// CHECK-LABEL: define {{.*}} @_Z15own_param_boundv( +// CHECK-LABEL: define internal {{.*}} @"_ZZ15own_param_boundvENK3$_0clEiPA_i"(ptr noundef nonnull align 1 dereferenceable(1) %this, +int own_param_bound() { + return [](int m, int (*p)[m]) { decltype(p) q = p; return (int)sizeof(*q); }(1, nullptr); +} + +// CHECK-LABEL: define {{.*}} @_Z8nested_tv( +// CHECK-LABEL: define internal {{.*}} @"_ZZZ8nested_tvENK3$_0clEvENKUlvE_clEv"( +// CHECK: [[BOUND:%[0-9]+]] = load i64, ptr {{%[0-9]+}} +// CHECK: alloca i32, i64 [[BOUND]] +int nested_t() { + using X = int[foo()]; + return [&] { return [&] { X x; return (int)sizeof(x); }(); }(); +} diff --git a/clang/test/Sema/vla-enclosing-function-blocks.c b/clang/test/Sema/vla-enclosing-function-blocks.c new file mode 100644 index 0000000000000..2e420efabd77b --- /dev/null +++ b/clang/test/Sema/vla-enclosing-function-blocks.c @@ -0,0 +1,39 @@ +// RUN: %clang_cc1 -fsyntax-only -fblocks -verify %s + +// GH55686 +int size_tab(void); +int main(void) { + __auto_type tab = (int(*)[size_tab()])0; // expected-note {{size expression is evaluated here}} + (^ int(__typeof(tab) arr) { return sizeof(*arr); })(tab); // expected-error {{cannot be used in a block}} +} + +void var_in_block(void) { + typedef int X[size_tab()]; // expected-note {{size expression is evaluated here}} + ^{ X x; }(); // expected-error {{cannot be used in a block}} +} + +void typedef_in_block(void) { + typedef int X[size_tab()]; // expected-note {{size expression is evaluated here}} + ^{ typedef X Y; }(); // expected-error {{cannot be used in a block}} +} + +void cast_in_block(void) { + typedef int (*P)[size_tab()]; // expected-note {{size expression is evaluated here}} + ^{ (void)(P)0; }(); // expected-error {{cannot be used in a block}} +} + +void sizeof_in_block(void) { + typedef int X[size_tab()]; // expected-note 2 {{size expression is evaluated here}} + ^{ (void)sizeof(X); }(); // expected-error {{cannot be used in a block}} + ^{ (void)_Countof(X); }(); // expected-error {{cannot be used in a block}} +} + +// Valid: VLA parameter of the block itself. +int own_vla_param_in_block(void) { + return (^ int(int m, int (*p)[m]) { __typeof(p) q = p; return sizeof(*q); })(1, 0); +} + +// Valid: VLA declared inside the block itself. +int own_vla_in_block(void) { + return (^ int(void) { int a[size_tab()]; return sizeof(a); })(); +} diff --git a/clang/test/SemaCXX/vla-enclosing-function.cpp b/clang/test/SemaCXX/vla-enclosing-function.cpp new file mode 100644 index 0000000000000..cbb722aa2b6df --- /dev/null +++ b/clang/test/SemaCXX/vla-enclosing-function.cpp @@ -0,0 +1,124 @@ +// RUN: %clang_cc1 -fsyntax-only -Wno-vla-cxx-extension -verify %s + +// GH55686 +int foo(); + +void ctor() { + using X = int[foo()]; // expected-note {{size expression is evaluated here}} + struct S { S() { X x; } }; // expected-error {{cannot be used in a local class because its size is evaluated in an enclosing function}} +} + +void sizeof_enclosing_vla_var() { + int a[foo()]; // expected-note {{'a' declared here}} + struct S { unsigned long f() { return sizeof(a); } }; // expected-error {{reference to local variable 'a' declared in enclosing function}} +} + +void decltype_var() { + int a[foo()]; // expected-note {{size expression is evaluated here}} + struct S { void f() { decltype(a) b; } }; // expected-error {{cannot be used in a local class}} +} + +void nested_local_class() { + using X = int[foo()]; // expected-note {{size expression is evaluated here}} + struct S { + void f() { struct T { T() { X x; } }; } // expected-error {{cannot be used in a local class}} + }; +} + +void pointer_to_vla() { + using P = int (*)[foo()]; // expected-note {{size expression is evaluated here}} + struct S { unsigned long f(P p) { return sizeof(*p); } }; // expected-error {{cannot be used in a local class}} +} + +void casts() { + using P = int (*)[foo()]; // expected-note 3 {{size expression is evaluated here}} + struct S { + void f() { + (void)(P)0; // expected-error {{cannot be used in a local class}} + (void)static_cast<P>(nullptr); // expected-error {{cannot be used in a local class}} + (void)P(nullptr); // expected-error {{cannot be used in a local class}} + } + }; +} + +void typedef_in_member_function() { + using X = int[foo()]; // expected-note {{size expression is evaluated here}} + struct S { void f() { typedef X Y; } }; // expected-error {{cannot be used in a local class}} +} + +// FIXME: Bounds in a function prototype are not recorded, so this is not +// diagnosed. +void param_bound(int n, int (*p)[n]) { + struct S { void f() { decltype(p) q; } }; +} + +void sizeof_type() { + using X = int[foo()]; // expected-note {{size expression is evaluated here}} + int a[foo()]; // expected-note {{size expression is evaluated here}} + struct S { + unsigned long f() { return sizeof(X); } // expected-error {{cannot be used in a local class}} + unsigned long g() { return sizeof(decltype(a)); } // expected-error {{cannot be used in a local class}} + }; +} + +template <typename T> void in_template() { + using X = int[foo()]; // expected-note {{size expression is evaluated here}} + struct S { S() { X x; } }; // expected-error {{cannot be used in a local class}} +} + +template <typename T> void sizeof_in_template() { + using X = T[foo()]; // expected-note {{size expression is evaluated here}} + struct S { // expected-note {{in instantiation of member function}} + unsigned long f() { return sizeof(X); } // expected-error {{cannot be used in a local class}} + void g() { decltype(sizeof(X)) n = 0; (void)n; } + }; +} +template void sizeof_in_template<int>(); // expected-note {{in instantiation of}} + +namespace GH55686 { +void f(int n) { + using T = int[n]; // expected-note 2 {{size expression is evaluated here}} + struct A { + using U = T; // expected-error {{cannot be used in a local class}} + void f() { U u; } + void g() { T t; } // expected-error {{cannot be used in a local class}} + }; + A::U u; + A a; + a.f(); + a.g(); +} +} // namespace GH55686 + +// Valid: no diagnostics. +int same_function() { + using X = int[foo()]; + X x; + return sizeof(X) + sizeof(x); +} + +// The bound is not evaluated here. +void sizeof_not_evaluated() { + using X = int[foo()]; + struct S { + void f() { decltype(sizeof(X)) n = 0; (void)n; } + unsigned long g() { return alignof(X); } + }; +} + +void own_vla_in_local_class() { + struct S { void f() { int a[foo()]; (void)sizeof(a); } }; +} + +void param_vla_in_local_class() { + struct S { unsigned long f(int n, int (*p)[n]) { return sizeof(*p); } }; +} + +unsigned long lambda_own_vla_param() { + return [](int m, int (*p)[m]) { decltype(p) q = p; return sizeof(*q); }(1, nullptr); +} + +int lambda_sizeof() { + using X = int[foo()]; + return [&] { return (int)sizeof(X); }(); +} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
