From 7cffb63a9d1d7a8d0b75b23ed2f859ede20a06a3 Mon Sep 17 00:00:00 2001 From: Nuno Lopes Date: Mon, 2 Feb 2009 22:57:15 +0000 Subject: [PATCH] emit diagnostic when casting a ptr to a small int when doing static initialization (addresses Eli's comments I believe) llvm-svn: 63562 --- clang/lib/Sema/SemaDecl.cpp | 15 ++++++++++++--- clang/test/Sema/static-init.c | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 21fe6e1ce492..d2140b226757 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -2055,14 +2055,23 @@ bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { } case Expr::ImplicitCastExprClass: case Expr::CStyleCastExprClass: { - const Expr *SubExpr = cast(Init)->getSubExpr(); + const CastExpr *CE = cast(Init); + const Expr *SubExpr = CE->getSubExpr(); + if (SubExpr->getType()->isArithmeticType()) return CheckArithmeticConstantExpression(SubExpr); if (SubExpr->getType()->isPointerType()) { const Expr* Base = FindExpressionBaseAddress(SubExpr); - // If the pointer has a null base, this is an offsetof-like construct - return Base ? false : CheckAddressConstantExpression(SubExpr); + if (Base) { + // the cast is only valid if done to a wide enough type + if (Context.getTypeSize(CE->getType()) >= + Context.getTypeSize(SubExpr->getType())) + return false; + } else { + // If the pointer has a null base, this is an offsetof-like construct + return CheckAddressConstantExpression(SubExpr); + } } InitializerElementNotConstant(Init); diff --git a/clang/test/Sema/static-init.c b/clang/test/Sema/static-init.c index a4035e69df46..b3c8d0f9f181 100644 --- a/clang/test/Sema/static-init.c +++ b/clang/test/Sema/static-init.c @@ -16,4 +16,5 @@ struct foo { }; union bar u[1]; -struct foo x = {(int) u}; // no-error +struct foo x = {(long) u}; // no-error +struct foo y = {(char) u}; // expected-error {{initializer element is not a compile-time constant}}