]> granicus.if.org Git - clang/commitdiff
emit diagnostic when casting a ptr to a small int when doing static initialization...
authorNuno Lopes <nunoplopes@sapo.pt>
Mon, 2 Feb 2009 22:57:15 +0000 (22:57 +0000)
committerNuno Lopes <nunoplopes@sapo.pt>
Mon, 2 Feb 2009 22:57:15 +0000 (22:57 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@63562 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Sema/SemaDecl.cpp
test/Sema/static-init.c

index 21fe6e1ce4924e0538c6388041980d0cbfe72d47..d2140b22675780adad4ec6ba7b23c9739b5f4df7 100644 (file)
@@ -2055,14 +2055,23 @@ bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
   }
   case Expr::ImplicitCastExprClass:
   case Expr::CStyleCastExprClass: {
-    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
+    const CastExpr *CE = cast<CastExpr>(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);
index a4035e69df466f14dbc343169aede19ae68bf93e..b3c8d0f9f1819cd67106dbc53b016f2c58ce765f 100644 (file)
@@ -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}}