[cfe-commits] r77076 - in /cfe/trunk: include/clang/Basic/DiagnosticSemaKinds.td lib/Sema/Sema.h lib/Sema/SemaCXXCast.cpp lib/Sema/SemaExpr.cpp lib/Sema/SemaOverload.cpp test/Parser/cxx-ambig-paren-expr.cpp test/SemaCXX/cstyle-cast.cpp test/SemaCXX/dcl_ambig_res.cpp test/SemaCXX/decl-expr-ambiguity.cpp test/SemaCXX/static-cast.cpp test/SemaTemplate/instantiate-cast.cpp www/cxx_status.html

Sebastian Redl sebastian.redl at getdesigned.at
Sat Jul 25 08:41:42 PDT 2009


Author: cornedbee
Date: Sat Jul 25 10:41:38 2009
New Revision: 77076

URL: http://llvm.org/viewvc/llvm-project?rev=77076&view=rev
Log:
Implement C++ semantics for C-style and functional-style casts. This regresses Clang extension conversions, like vectors, but allows conversions via constructors and conversion operators.
Add custom conversions to static_cast.

Added:
    cfe/trunk/test/SemaCXX/cstyle-cast.cpp
Modified:
    cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
    cfe/trunk/lib/Sema/Sema.h
    cfe/trunk/lib/Sema/SemaCXXCast.cpp
    cfe/trunk/lib/Sema/SemaExpr.cpp
    cfe/trunk/lib/Sema/SemaOverload.cpp
    cfe/trunk/test/Parser/cxx-ambig-paren-expr.cpp
    cfe/trunk/test/SemaCXX/dcl_ambig_res.cpp
    cfe/trunk/test/SemaCXX/decl-expr-ambiguity.cpp
    cfe/trunk/test/SemaCXX/static-cast.cpp
    cfe/trunk/test/SemaTemplate/instantiate-cast.cpp
    cfe/trunk/www/cxx_status.html

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Sat Jul 25 10:41:38 2009
@@ -1395,36 +1395,46 @@
 
 
 // C++ casts
-def err_bad_cxx_cast_generic : Error<"%0 from %2 to %1 is not allowed">;
-def err_bad_cxx_cast_rvalue : Error<"%0 from rvalue to reference type %1">;
+// These messages adhere to the TryCast pattern: %0 is an int specifying the
+// cast type, %1 is the source type, %2 is the destination type.
+def err_bad_cxx_cast_generic : Error<
+  "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
+  "functional-style cast}0 from %1 to %2 is not allowed">;
+def err_bad_cxx_cast_rvalue : Error<
+  "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
+  "functional-style cast}0 from rvalue to reference type %2">;
 def err_bad_cxx_cast_const_away : Error<
-  "%0 from %2 to %1 casts away constness">;
+  "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
+  "functional-style cast}0 from %1 to %2 casts away constness">;
 def err_bad_const_cast_dest : Error<
-  "const_cast to %0, which is not a reference, pointer-to-object, "
-  "or pointer-to-data-member">;
-
-def err_bad_reinterpret_cast_same_type : Error<
-  "source and destination type of reinterpret_cast are not distinct">;
-def ext_reinterpret_cast_fn_obj : Extension<
-  "reinterpret_cast between pointer-to-function and pointer-to-object is "
-  "an extension">;
-
+  "%select{const_cast||||C-style cast|functional-style cast}0 to %2, "
+  "which is not a reference, pointer-to-object, or pointer-to-data-member">;
+def ext_cast_fn_obj : Extension<
+  "cast between pointer-to-function and pointer-to-object is an extension">;
 def err_bad_reinterpret_cast_small_int : Error<
-  "cast from pointer to smaller type %0 loses information">;
+  "cast from pointer to smaller type %2 loses information">;
+def err_bad_lvalue_to_rvalue_cast : Error<
+  "cannot cast from lvalue of type %1 to rvalue reference type %2; types are "
+  "not compatible">;
+def err_bad_static_cast_pointer_nonpointer : Error<
+  "cannot cast from type %1 to pointer type %2">;
+def err_bad_static_cast_member_pointer_nonmp : Error<
+  "cannot cast from type %1 to member pointer type %2">;
+
+// These messages don't adhere to the pattern.
+// FIXME: Display the path somehow better.
+def err_ambiguous_base_to_derived_cast : Error<
+  "ambiguous cast from base %0 to derived %1:%2">;
+def err_static_downcast_via_virtual : Error<
+  "cannot cast %0 to %1 via virtual base %2">;
+def err_downcast_from_inaccessible_base : Error<
+  "cannot cast %1 to %0 due to inaccessible conversion path">;
 def err_bad_dynamic_cast_not_ref_or_ptr : Error<
   "%0 is not a reference or pointer">;
 def err_bad_dynamic_cast_not_class : Error<"%0 is not a class">;
 def err_bad_dynamic_cast_incomplete : Error<"%0 is an incomplete type">;
 def err_bad_dynamic_cast_not_ptr : Error<"%0 is not a pointer">;
 def err_bad_dynamic_cast_not_polymorphic : Error<"%0 is not polymorphic">;
-// FIXME: Display the path somehow better.
-def err_ambiguous_base_to_derived_cast : Error<
-  "ambiguous static_cast from base %0 to derived %1:%2">;
-def err_static_downcast_via_virtual : Error<
-  "cannot cast %0 to %1 via virtual base %2">;
-def err_bad_lvalue_to_rvalue_cast : Error<
-  "cannot cast from lvalue of type %0 to rvalue reference to %1; types are "
-  "not compatible">;
 
 // Other C++ expressions
 def err_need_header_before_typeid : Error<

Modified: cfe/trunk/lib/Sema/Sema.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/Sema.h?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/lib/Sema/Sema.h (original)
+++ cfe/trunk/lib/Sema/Sema.h Sat Jul 25 10:41:38 2009
@@ -3169,9 +3169,10 @@
                           bool AllowExplicit = false,
                           bool ForceRValue = false);
 
-  /// CheckCastTypes - Check type constraints for casting between types.
+  /// CheckCastTypes - Check type constraints for casting between types under
+  /// C semantics.
   bool CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *&CastExpr);
-  
+
   // CheckVectorCast - check type constraints for vectors. 
   // Since vectors are an extension, there are no C standard reference for this.
   // We allow casting between vectors and integer datatypes of the same size.
@@ -3184,7 +3185,11 @@
   // or vectors and the element type of that vector.
   // returns true if the cast is invalid
   bool CheckExtVectorCast(SourceRange R, QualType VectorTy, QualType Ty);
-  
+
+  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
+  /// cast under C++ semantics.
+  bool CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr);
+
   /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 
   /// \param Method - May be null.
   /// \param [out] ReturnType - The return type of the send.
@@ -3196,7 +3201,7 @@
 
   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
   bool CheckCXXBooleanCondition(Expr *&CondExpr);
-                    
+
   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
   /// the specified width and sign.  If an overflow occurs, detect it and emit
   /// the specified diagnostic.

Modified: cfe/trunk/lib/Sema/SemaCXXCast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCXXCast.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/lib/Sema/SemaCXXCast.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCXXCast.cpp Sat Jul 25 10:41:38 2009
@@ -19,11 +19,20 @@
 #include <set>
 using namespace clang;
 
-enum TryStaticCastResult {
-  TSC_NotApplicable, ///< The cast method is not applicable.
-  TSC_Success,       ///< The cast method is appropriate and successful.
-  TSC_Failed         ///< The cast method is appropriate, but failed. A
-                     ///< diagnostic has been emitted.
+enum TryCastResult {
+  TC_NotApplicable, ///< The cast method is not applicable.
+  TC_Success,       ///< The cast method is appropriate and successful.
+  TC_Failed         ///< The cast method is appropriate, but failed. A
+                    ///< diagnostic has been emitted.
+};
+
+enum CastType {
+  CT_Const,       ///< const_cast
+  CT_Static,      ///< static_cast
+  CT_Reinterpret, ///< reinterpret_cast
+  CT_Dynamic,     ///< dynamic_cast
+  CT_CStyle,      ///< (Type)expr
+  CT_Functional   ///< Type(expr)
 };
 
 static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
@@ -39,22 +48,51 @@
                              const SourceRange &DestRange);
 
 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
-static TryStaticCastResult TryLValueToRValueCast(
-  Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
-static TryStaticCastResult TryStaticReferenceDowncast(
-  Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
-static TryStaticCastResult TryStaticPointerDowncast(
-  Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
-static TryStaticCastResult TryStaticMemberPointerUpcast(
-  Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
-static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
-                                             QualType DestType,
-                                             const SourceRange &OpRange,
-                                             QualType OrigSrcType,
-                                             QualType OrigDestType);
-static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
-                                                 QualType DestType,
-                                                 const SourceRange &OpRange);
+
+// The Try functions attempt a specific way of casting. If they succeed, they
+// return TC_Success. If their way of casting is not appropriate for the given
+// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
+// to emit if no other way succeeds. If their way of casting is appropriate but
+// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
+// they emit a specialized diagnostic.
+// All diagnostics returned by these functions must expect the same three
+// arguments:
+// %0: Cast Type (a value from the CastType enumeration)
+// %1: Source Type
+// %2: Destination Type
+static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
+                                           QualType DestType, unsigned &msg);
+static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
+                                                QualType DestType, bool CStyle,
+                                                const SourceRange &OpRange,
+                                                unsigned &msg);
+static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
+                                              QualType DestType, bool CStyle,
+                                              const SourceRange &OpRange,
+                                              unsigned &msg);
+static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
+                                       QualType DestType, bool CStyle,
+                                       const SourceRange &OpRange,
+                                       QualType OrigSrcType,
+                                       QualType OrigDestType, unsigned &msg);
+static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
+                                                  QualType DestType,bool CStyle,
+                                                  const SourceRange &OpRange,
+                                                  unsigned &msg);
+static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
+                                           QualType DestType, bool CStyle,
+                                           const SourceRange &OpRange,
+                                           unsigned &msg);
+static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
+                                   QualType DestType, bool CStyle,
+                                   const SourceRange &OpRange,
+                                   unsigned &msg);
+static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
+                                  bool CStyle, unsigned &msg);
+static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
+                                        QualType DestType, bool CStyle,
+                                        const SourceRange &OpRange,
+                                        unsigned &msg);
 
 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
 Action::OwningExprResult
@@ -104,336 +142,208 @@
   return ExprError();
 }
 
-/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
-/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
-/// like this:
-/// const char *str = "literal";
-/// legacy_function(const_cast\<char*\>(str));
-void
-CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
-               const SourceRange &OpRange, const SourceRange &DestRange)
+/// CastsAwayConstness - Check if the pointer conversion from SrcType to
+/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
+/// the cast checkers.  Both arguments must denote pointer (possibly to member)
+/// types.
+bool
+CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
 {
-  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
-
-  DestType = Self.Context.getCanonicalType(DestType);
-  QualType SrcType = SrcExpr->getType();
-  if (const LValueReferenceType *DestTypeTmp =
-        DestType->getAsLValueReferenceType()) {
-    if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
-      // Cannot cast non-lvalue to lvalue reference type.
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
-        << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
-      return;
-    }
-
-    // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
-    //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
-    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
-    SrcType = Self.Context.getPointerType(SrcType);
-  } else {
-    // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
-    //   lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
-    //   conversions are performed on the expression.
-    Self.DefaultFunctionArrayConversion(SrcExpr);
-    SrcType = SrcExpr->getType();
-  }
-
-  // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
-  //   the rules for const_cast are the same as those used for pointers.
+  // Casting away constness is defined in C++ 5.2.11p8 with reference to
+  // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
+  // the rules are non-trivial. So first we construct Tcv *...cv* as described
+  // in C++ 5.2.11p8.
+  assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
+         "Source type is not pointer or pointer to member.");
+  assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
+         "Destination type is not pointer or pointer to member.");
 
-  if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
-    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
-    // was a reference type, we converted it to a pointer above.
-    // The status of rvalue references isn't entirely clear, but it looks like
-    // conversion to them is simply invalid.
-    // C++ 5.2.11p3: For two pointer types [...]
-    Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
-      << OrigDestType << DestRange;
-    return;
-  }
-  if (DestType->isFunctionPointerType() ||
-      DestType->isMemberFunctionPointerType()) {
-    // Cannot cast direct function pointers.
-    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
-    // T is the ultimate pointee of source and target type.
-    Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
-      << OrigDestType << DestRange;
-    return;
-  }
-  SrcType = Self.Context.getCanonicalType(SrcType);
+  QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
+  llvm::SmallVector<unsigned, 8> cv1, cv2;
 
-  // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
-  // completely equal.
-  // FIXME: const_cast should probably not be able to convert between pointers
-  // to different address spaces.
-  // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
-  // in multi-level pointers may change, but the level count must be the same,
-  // as must be the final pointee type.
-  while (SrcType != DestType &&
-         Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
-    SrcType = SrcType.getUnqualifiedType();
-    DestType = DestType.getUnqualifiedType();
+  // Find the qualifications.
+  while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
+    cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
+    cv2.push_back(UnwrappedDestType.getCVRQualifiers());
   }
+  assert(cv1.size() > 0 && "Must have at least one pointer level.");
 
-  // Doug Gregor said to disallow this until users complain.
-#if 0
-  // If we end up with constant arrays of equal size, unwrap those too. A cast
-  // from const int [N] to int (&)[N] is invalid by my reading of the
-  // standard, but g++ accepts it even with -ansi -pedantic.
-  // No more than one level, though, so don't embed this in the unwrap loop
-  // above.
-  const ConstantArrayType *SrcTypeArr, *DestTypeArr;
-  if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
-     (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
+  // Construct void pointers with those qualifiers (in reverse order of
+  // unwrapping, of course).
+  QualType SrcConstruct = Self.Context.VoidTy;
+  QualType DestConstruct = Self.Context.VoidTy;
+  for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
+                                                        i2 = cv2.rbegin();
+       i1 != cv1.rend(); ++i1, ++i2)
   {
-    if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
-      // Different array sizes.
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-        << "const_cast" << OrigDestType << OrigSrcType << OpRange;
-      return;
-    }
-    SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
-    DestType = DestTypeArr->getElementType().getUnqualifiedType();
+    SrcConstruct = Self.Context.getPointerType(
+      SrcConstruct.getQualifiedType(*i1));
+    DestConstruct = Self.Context.getPointerType(
+      DestConstruct.getQualifiedType(*i2));
   }
-#endif
 
-  // Since we're dealing in canonical types, the remainder must be the same.
-  if (SrcType != DestType) {
-    // Cast between unrelated types.
-    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-      << "const_cast" << OrigDestType << OrigSrcType << OpRange;
-    return;
-  }
+  // Test if they're compatible.
+  return SrcConstruct != DestConstruct &&
+    !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
 }
 
-/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
-/// valid.
-/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
-/// like this:
-/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
+/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
+/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
+/// checked downcasts in class hierarchies.
 void
-CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
-                     const SourceRange &OpRange, const SourceRange &DestRange)
+CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+                 const SourceRange &OpRange,
+                 const SourceRange &DestRange)
 {
   QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
-
   DestType = Self.Context.getCanonicalType(DestType);
-  QualType SrcType = SrcExpr->getType();
-  if (const LValueReferenceType *DestTypeTmp =
-        DestType->getAsLValueReferenceType()) {
-    if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
-      // Cannot cast non-lvalue to reference type.
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
-        << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
-      return;
-    }
 
-    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
-    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
-    //   built-in & and * operators.
-    // This code does this transformation for the checked types.
-    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
-    SrcType = Self.Context.getPointerType(SrcType);
-  } else if (const RValueReferenceType *DestTypeTmp =
-               DestType->getAsRValueReferenceType()) {
-    // Both the reference conversion and the rvalue rules apply.
-    Self.DefaultFunctionArrayConversion(SrcExpr);
-    SrcType = SrcExpr->getType();
+  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
+  //   or "pointer to cv void".
 
-    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
-    SrcType = Self.Context.getPointerType(SrcType);
+  QualType DestPointee;
+  const PointerType *DestPointer = DestType->getAsPointerType();
+  const ReferenceType *DestReference = DestType->getAsReferenceType();
+  if (DestPointer) {
+    DestPointee = DestPointer->getPointeeType();
+  } else if (DestReference) {
+    DestPointee = DestReference->getPointeeType();
   } else {
-    // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
-    //   function-to-pointer standard conversions are performed on the
-    //   expression v.
-    Self.DefaultFunctionArrayConversion(SrcExpr);
-    SrcType = SrcExpr->getType();
-  }
-
-  // Canonicalize source for comparison.
-  SrcType = Self.Context.getCanonicalType(SrcType);
-
-  const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
-                          *SrcMemPtr = SrcType->getAsMemberPointerType();
-  if (DestMemPtr && SrcMemPtr) {
-    // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
-    //   can be explicitly converted to an rvalue of type "pointer to member
-    //   of Y of type T2" if T1 and T2 are both function types or both object
-    //   types.
-    if (DestMemPtr->getPointeeType()->isFunctionType() !=
-        SrcMemPtr->getPointeeType()->isFunctionType()) {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-        << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
-      return;
-    }
-
-    // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
-    //   constness.
-    if (CastsAwayConstness(Self, SrcType, DestType)) {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
-        << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
-      return;
-    }
-
-    // A valid member pointer cast.
-    return;
-  }
-
-  // See below for the enumeral issue.
-  if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
-      !DestType->isEnumeralType()) {
-    // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
-    //   type large enough to hold it. A value of std::nullptr_t can be
-    //   converted to an integral type; the conversion has the same meaning
-    //   and validity as a conversion of (void*)0 to the integral type.
-    if (Self.Context.getTypeSize(SrcType) >
-        Self.Context.getTypeSize(DestType)) {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
-        << OrigDestType << DestRange;
-    }
+    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
+      << OrigDestType << DestRange;
     return;
   }
 
-  bool destIsPtr = DestType->isPointerType();
-  bool srcIsPtr = SrcType->isPointerType();
-  if (!destIsPtr && !srcIsPtr) {
-    // Except for std::nullptr_t->integer and lvalue->reference, which are
-    // handled above, at least one of the two arguments must be a pointer.
-    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-      << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
+  const RecordType *DestRecord = DestPointee->getAsRecordType();
+  if (DestPointee->isVoidType()) {
+    assert(DestPointer && "Reference to void is not possible");
+  } else if (DestRecord) {
+    if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
+                                    diag::err_bad_dynamic_cast_incomplete,
+                                    DestRange))
+      return;
+  } else {
+    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
+      << DestPointee.getUnqualifiedType() << DestRange;
     return;
   }
 
-  if (SrcType == DestType) {
-    // C++ 5.2.10p2 has a note that mentions that, subject to all other
-    // restrictions, a cast to the same type is allowed. The intent is not
-    // entirely clear here, since all other paragraphs explicitly forbid casts
-    // to the same type. However, the behavior of compilers is pretty consistent
-    // on this point: allow same-type conversion if the involved types are
-    // pointers, disallow otherwise.
-    return;
-  }
+  // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
+  //   complete class type, [...]. If T is an lvalue reference type, v shall be
+  //   an lvalue of a complete class type, [...]. If T is an rvalue reference
+  //   type, v shall be an expression having a complete effective class type,
+  //   [...]
 
-  // Note: Clang treats enumeration types as integral types. If this is ever
-  // changed for C++, the additional check here will be redundant.
-  if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
-    assert(srcIsPtr && "One type must be a pointer");
-    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
-    //   type large enough to hold it.
-    if (Self.Context.getTypeSize(SrcType) >
-        Self.Context.getTypeSize(DestType)) {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
-        << OrigDestType << DestRange;
+  QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
+  QualType SrcPointee;
+  if (DestPointer) {
+    if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
+      SrcPointee = SrcPointer->getPointeeType();
+    } else {
+      Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
+        << OrigSrcType << SrcExpr->getSourceRange();
+      return;
     }
-    return;
+  } else if (DestReference->isLValueReferenceType()) {
+    if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
+      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
+        << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
+    }
+    SrcPointee = SrcType;
+  } else {
+    SrcPointee = SrcType;
   }
 
-  if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
-    assert(destIsPtr && "One type must be a pointer");
-    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
-    //   converted to a pointer.
+  const RecordType *SrcRecord = SrcPointee->getAsRecordType();
+  if (SrcRecord) {
+    if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
+                                    diag::err_bad_dynamic_cast_incomplete,
+                                    SrcExpr->getSourceRange()))
+      return;
+  } else {
+    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
+      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
     return;
   }
 
-  if (!destIsPtr || !srcIsPtr) {
-    // With the valid non-pointer conversions out of the way, we can be even
-    // more stringent.
-    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-      << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
-    return;
-  }
+  assert((DestPointer || DestReference) &&
+    "Bad destination non-ptr/ref slipped through.");
+  assert((DestRecord || DestPointee->isVoidType()) &&
+    "Bad destination pointee slipped through.");
+  assert(SrcRecord && "Bad source pointee slipped through.");
 
-  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
-  if (CastsAwayConstness(Self, SrcType, DestType)) {
+  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
+  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
-      << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
+      << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
     return;
   }
 
-  // Not casting away constness, so the only remaining check is for compatible
-  // pointer categories.
-
-  if (SrcType->isFunctionPointerType()) {
-    if (DestType->isFunctionPointerType()) {
-      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
-      // a pointer to a function of a different type.
-      return;
-    }
-
-    // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
-    //   an object type or vice versa is conditionally-supported.
-    // Compilers support it in C++03 too, though, because it's necessary for
-    // casting the return value of dlsym() and GetProcAddress().
-    // FIXME: Conditionally-supported behavior should be configurable in the
-    // TargetInfo or similar.
-    if (!Self.getLangOptions().CPlusPlus0x) {
-      Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
-        << OpRange;
-    }
+  // C++ 5.2.7p3: If the type of v is the same as the required result type,
+  //   [except for cv].
+  if (DestRecord == SrcRecord) {
     return;
   }
 
-  if (DestType->isFunctionPointerType()) {
-    // See above.
-    if (!Self.getLangOptions().CPlusPlus0x) {
-      Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
-        << OpRange;
-    }
+  // C++ 5.2.7p5
+  // Upcasts are resolved statically.
+  if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
+    Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
+                                      OpRange.getBegin(), OpRange);
+    // Diagnostic already emitted on error.
     return;
   }
 
-  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
-  //   a pointer to an object of different type.
-  // Void pointers are not specified, but supported by every compiler out there.
-  // So we finish by allowing everything that remains - it's got to be two
-  // object pointers.
+  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
+  const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
+  assert(SrcDecl && "Definition missing");
+  if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
+    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
+      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
+  }
+
+  // Done. Everything else is run-time checks.
 }
 
-/// CastsAwayConstness - Check if the pointer conversion from SrcType to
-/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
-/// the cast checkers.  Both arguments must denote pointer (possibly to member)
-/// types.
-bool
-CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
+/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
+/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
+/// like this:
+/// const char *str = "literal";
+/// legacy_function(const_cast\<char*\>(str));
+void
+CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+               const SourceRange &OpRange, const SourceRange &DestRange)
 {
-  // Casting away constness is defined in C++ 5.2.11p8 with reference to
-  // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
-  // the rules are non-trivial. So first we construct Tcv *...cv* as described
-  // in C++ 5.2.11p8.
-  assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
-         "Source type is not pointer or pointer to member.");
-  assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
-         "Destination type is not pointer or pointer to member.");
-
-  QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
-  llvm::SmallVector<unsigned, 8> cv1, cv2;
+  if (!DestType->isLValueReferenceType())
+    Self.DefaultFunctionArrayConversion(SrcExpr);
 
-  // Find the qualifications.
-  while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
-    cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
-    cv2.push_back(UnwrappedDestType.getCVRQualifiers());
-  }
-  assert(cv1.size() > 0 && "Must have at least one pointer level.");
+  unsigned msg = diag::err_bad_cxx_cast_generic;
+  if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
+      && msg != 0)
+    Self.Diag(OpRange.getBegin(), msg) << CT_Const
+      << SrcExpr->getType() << DestType << OpRange;
+}
 
-  // Construct void pointers with those qualifiers (in reverse order of
-  // unwrapping, of course).
-  QualType SrcConstruct = Self.Context.VoidTy;
-  QualType DestConstruct = Self.Context.VoidTy;
-  for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
-                                                        i2 = cv2.rbegin();
-       i1 != cv1.rend(); ++i1, ++i2)
-  {
-    SrcConstruct = Self.Context.getPointerType(
-      SrcConstruct.getQualifiedType(*i1));
-    DestConstruct = Self.Context.getPointerType(
-      DestConstruct.getQualifiedType(*i2));
-  }
+/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
+/// valid.
+/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
+/// like this:
+/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
+void
+CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+                     const SourceRange &OpRange, const SourceRange &DestRange)
+{
+  if (!DestType->isLValueReferenceType())
+    Self.DefaultFunctionArrayConversion(SrcExpr);
 
-  // Test if they're compatible.
-  return SrcConstruct != DestConstruct &&
-    !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
+  unsigned msg = diag::err_bad_cxx_cast_generic;
+  if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
+      != TC_Success && msg != 0)
+    Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
+      << SrcExpr->getType() << DestType << OpRange;
 }
 
+
 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
 /// implicit conversions explicit and getting rid of data loss warnings.
@@ -441,6 +351,31 @@
 CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
                 const SourceRange &OpRange)
 {
+  // This test is outside everything else because it's the only case where
+  // a non-lvalue-reference target type does not lead to decay.
+  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
+  if (DestType->isVoidType()) {
+    return;
+  }
+
+  if (!DestType->isLValueReferenceType())
+    Self.DefaultFunctionArrayConversion(SrcExpr);
+
+  unsigned msg = diag::err_bad_cxx_cast_generic;
+  if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
+      != TC_Success && msg != 0)
+    Self.Diag(OpRange.getBegin(), msg) << CT_Static
+      << SrcExpr->getType() << DestType << OpRange;
+}
+
+/// TryStaticCast - Check if a static cast can be performed, and do so if
+/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
+/// and casting away constness.
+static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
+                                   QualType DestType, bool CStyle,
+                                   const SourceRange &OpRange,
+                                   unsigned &msg)
+{
   // The order the tests is not entirely arbitrary. There is one conversion
   // that can be handled in two different ways. Given:
   // struct A {};
@@ -453,45 +388,39 @@
   // conversion using B's conversion constructor.
   // DR 427 specifies that the downcast is to be applied here.
 
-  // FIXME: With N2812, casts to rvalue refs will change.
-
   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
-  if (DestType->isVoidType()) {
-    return;
-  }
+  // Done outside this function.
+
+  TryCastResult tcr;
 
   // C++ 5.2.9p5, reference downcast.
   // See the function for details.
   // DR 427 specifies that this is to be applied before paragraph 2.
-  if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
-      > TSC_NotApplicable) {
-    return;
-  }
+  tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
+  if (tcr != TC_NotApplicable)
+    return tcr;
 
   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
-  if (TryLValueToRValueCast(Self, SrcExpr, DestType, OpRange) >
-      TSC_NotApplicable) {
-    return;
-  }
+  tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
+  if (tcr != TC_NotApplicable)
+    return tcr;
 
   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
   //   [...] if the declaration "T t(e);" is well-formed, [...].
-  if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
-      TSC_NotApplicable) {
-    return;
-  }
+  tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg);
+  if (tcr != TC_NotApplicable)
+    return tcr;
 
   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
   // conversions, subject to further restrictions.
   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
   // of qualification conversions impossible.
+  // In the CStyle case, the earlier attempt to const_cast should have taken
+  // care of reverse qualification conversions.
 
-  // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
-  // are applied to the expression.
   QualType OrigSrcType = SrcExpr->getType();
-  Self.DefaultFunctionArrayConversion(SrcExpr);
 
   QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
 
@@ -506,25 +435,23 @@
   if (DestType->isEnumeralType()) {
     if (SrcType->isComplexType() || SrcType->isVectorType()) {
       // Fall through - these cannot be converted.
-    } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
-      return;
-    }
+    } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
+      return TC_Success;
   }
 
   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
-  if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
-      > TSC_NotApplicable) {
-    return;
-  }
+  tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
+  if (tcr != TC_NotApplicable)
+    return tcr;
 
   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
   // conversion. C++ 5.2.9p9 has additional information.
   // DR54's access restrictions apply here also.
-  if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
-      > TSC_NotApplicable) {
-    return;
-  }
+  tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
+                                     OpRange, msg);
+  if (tcr != TC_NotApplicable)
+    return tcr;
 
   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
@@ -537,59 +464,55 @@
         if (DestPointee->isIncompleteOrObjectType()) {
           // This is definitely the intended conversion, but it might fail due
           // to a const violation.
-          if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
-            Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
-              << "static_cast" << DestType << OrigSrcType << OpRange;
+          if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
+            msg = diag::err_bad_cxx_cast_const_away;
+            return TC_Failed;
           }
-          return;
+          return TC_Success;
         }
       }
     }
   }
 
   // We tried everything. Everything! Nothing works! :-(
-  // FIXME: Error reporting could be a lot better. Should store the reason why
-  // every substep failed and, at the end, select the most specific and report
-  // that.
-  Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
-    << "static_cast" << DestType << OrigSrcType
-    << OpRange;
+  return TC_NotApplicable;
 }
 
 /// Tests whether a conversion according to N2844 is valid.
-TryStaticCastResult
+TryCastResult
 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
-                      const SourceRange &OpRange)
+                      unsigned &msg)
 {
   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
   const RValueReferenceType *R = DestType->getAsRValueReferenceType();
   if (!R)
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
 
   if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
 
   // Because we try the reference downcast before this function, from now on
   // this is the only cast possibility, so we issue an error if we fail now.
+  // FIXME: Should allow casting away constness if CStyle.
   bool DerivedToBase;
   if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
                                         DerivedToBase) <
         Sema::Ref_Compatible_With_Added_Qualification) {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_lvalue_to_rvalue_cast)
-      << SrcExpr->getType() << R->getPointeeType() << OpRange;
-    return TSC_Failed;
+    msg = diag::err_bad_lvalue_to_rvalue_cast;
+    return TC_Failed;
   }
 
   // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
   // than nothing.
-  return TSC_Success;
+  return TC_Success;
 }
 
 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
-TryStaticCastResult
+TryCastResult
 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
-                           const SourceRange &OpRange)
+                           bool CStyle, const SourceRange &OpRange,
+                           unsigned &msg)
 {
   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
   //   cast to type "reference to cv2 D", where D is a class derived from B,
@@ -600,24 +523,27 @@
   // variant of this rule, the intent is clearly for it to apply to the this
   // conversion as well.
 
-  if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
-    return TSC_NotApplicable;
-  }
-
   const ReferenceType *DestReference = DestType->getAsReferenceType();
   if (!DestReference) {
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
   }
+  bool RValueRef = DestReference->isRValueReferenceType();
+  if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
+    // We know the left side is an lvalue reference, so we can suggest a reason.
+    msg = diag::err_bad_cxx_cast_rvalue;
+    return TC_NotApplicable;
+  }
+
   QualType DestPointee = DestReference->getPointeeType();
 
-  return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
-                          SrcExpr->getType(), DestType);
+  return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
+                           OpRange, SrcExpr->getType(), DestType, msg);
 }
 
 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
-TryStaticCastResult
+TryCastResult
 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
-                         const SourceRange &OpRange)
+                         bool CStyle, const SourceRange &OpRange, unsigned &msg)
 {
   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
@@ -627,38 +553,39 @@
   // In addition, DR54 clarifies that the base must be accessible in the
   // current context.
 
-  const PointerType *SrcPointer = SrcType->getAsPointerType();
-  if (!SrcPointer) {
-    return TSC_NotApplicable;
-  }
-
   const PointerType *DestPointer = DestType->getAsPointerType();
   if (!DestPointer) {
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
+  }
+
+  const PointerType *SrcPointer = SrcType->getAsPointerType();
+  if (!SrcPointer) {
+    msg = diag::err_bad_static_cast_pointer_nonpointer;
+    return TC_NotApplicable;
   }
 
   return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
-                          DestPointer->getPointeeType(),
-                          OpRange, SrcType, DestType);
+                          DestPointer->getPointeeType(), CStyle,
+                          OpRange, SrcType, DestType, msg);
 }
 
 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
 /// DestType, both of which must be canonical, is possible and allowed.
-TryStaticCastResult
+TryCastResult
 TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
-                  const SourceRange &OpRange, QualType OrigSrcType,
-                  QualType OrigDestType)
+                  bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
+                  QualType OrigDestType, unsigned &msg)
 {
   // Downcast can only happen in class hierarchies, so we need classes.
   if (!DestType->isRecordType() || !SrcType->isRecordType()) {
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
   }
 
-  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
+  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
                   /*DetectVirtual=*/true);
   if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
   }
 
   // Target type does derive from source type. Now we're serious. If an error
@@ -679,11 +606,10 @@
   // mean more complex code if we're to preserve the nice error message.
   // FIXME: Being 100% compliant here would be nice to have.
 
-  // Must preserve cv, as always.
-  if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
-      << "static_cast" << OrigDestType << OrigSrcType << OpRange;
-    return TSC_Failed;
+  // Must preserve cv, as always, unless we're in C-style mode.
+  if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
+    msg = diag::err_bad_cxx_cast_const_away;
+    return TC_Failed;
   }
 
   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
@@ -691,20 +617,22 @@
     // that it builds the paths in reverse order.
     // To sum up: record all paths to the base and build a nice string from
     // them. Use it to spice up the error message.
-    Paths.clear();
-    Paths.setRecordingPaths(true);
-    Self.IsDerivedFrom(DestType, SrcType, Paths);
+    if (!Paths.isRecordingPaths()) {
+      Paths.clear();
+      Paths.setRecordingPaths(true);
+      Self.IsDerivedFrom(DestType, SrcType, Paths);
+    }
     std::string PathDisplayStr;
     std::set<unsigned> DisplayedPaths;
-    for (BasePaths::paths_iterator Path = Paths.begin();
-         Path != Paths.end(); ++Path) {
-      if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
+    for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
+         PI != PE; ++PI) {
+      if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
         // We haven't displayed a path to this particular base
         // class subobject yet.
         PathDisplayStr += "\n    ";
-        for (BasePath::const_reverse_iterator Element = Path->rbegin();
-             Element != Path->rend(); ++Element)
-          PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
+        for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
+             EI != EE; ++EI)
+          PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
         PathDisplayStr += DestType.getAsString();
       }
     }
@@ -712,19 +640,26 @@
     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
       << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
       << PathDisplayStr << OpRange;
-    return TSC_Failed;
+    msg = 0;
+    return TC_Failed;
   }
 
   if (Paths.getDetectedVirtual() != 0) {
     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
-    return TSC_Failed;
+    msg = 0;
+    return TC_Failed;
   }
 
-  // FIXME: Test accessibility.
+  if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
+                          diag::err_downcast_from_inaccessible_base, Paths,
+                          OpRange.getBegin(), DeclarationName())) {
+    msg = 0;
+    return TC_Failed;
+  }
 
-  return TSC_Success;
+  return TC_Success;
 }
 
 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
@@ -734,31 +669,34 @@
 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
 ///   where B is a base class of D [...].
 ///
-TryStaticCastResult
+TryCastResult
 TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
-                             const SourceRange &OpRange)
+                             bool CStyle, const SourceRange &OpRange,
+                             unsigned &msg)
 {
-  const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
-  if (!SrcMemPtr)
-    return TSC_NotApplicable;
   const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType();
   if (!DestMemPtr)
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
+  const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
+  if (!SrcMemPtr) {
+    msg = diag::err_bad_static_cast_member_pointer_nonmp;
+    return TC_NotApplicable;
+  }
 
   // T == T, modulo cv
   if (Self.Context.getCanonicalType(
         SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
       Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
                                     getUnqualifiedType()))
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
 
   // B base of D
   QualType SrcClass(SrcMemPtr->getClass(), 0);
   QualType DestClass(DestMemPtr->getClass(), 0);
-  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
+  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
                   /*DetectVirtual=*/true);
   if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
-    return TSC_NotApplicable;
+    return TC_NotApplicable;
   }
 
   // B is a base of D. But is it an allowed base? If not, it's a hard error.
@@ -771,18 +709,25 @@
     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
-    return TSC_Failed;
+    msg = 0;
+    return TC_Failed;
   }
 
   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
-    return TSC_Failed;
+    msg = 0;
+    return TC_Failed;
   }
 
-  // FIXME: Test accessibility.
+  if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
+                          diag::err_downcast_from_inaccessible_base, Paths,
+                          OpRange.getBegin(), DeclarationName())) {
+    msg = 0;
+    return TC_Failed;
+  }
 
-  return TSC_Success;
+  return TC_Success;
 }
 
 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
@@ -790,143 +735,311 @@
 ///
 ///   An expression e can be explicitly converted to a type T using a
 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
-TryStaticCastResult
+TryCastResult
 TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
-                      const SourceRange &OpRange)
+                      bool CStyle, const SourceRange &OpRange, unsigned &msg)
 {
   if (DestType->isReferenceType()) {
     // At this point of CheckStaticCast, if the destination is a reference,
     // this has to work. There is no other way that works.
-    return Self.CheckReferenceInit(SrcExpr, DestType) ?
-      TSC_Failed : TSC_Success;
+    // On the other hand, if we're checking a C-style cast, we've still got
+    // the reinterpret_cast way. In that case, we pass an ICS so we don't
+    // get error messages.
+    ImplicitConversionSequence ICS;
+    bool failed = Self.CheckReferenceInit(SrcExpr, DestType, CStyle ? &ICS : 0);
+    if (!failed)
+      return TC_Success;
+    if (CStyle)
+      return TC_NotApplicable;
+    // If we didn't pass the ICS, we already got an error message.
+    msg = 0;
+    return TC_Failed;
   }
   if (DestType->isRecordType()) {
-    // FIXME: Use an implementation of C++ [over.match.ctor] for this.
-    return TSC_NotApplicable;
+    // There are no further possibilities for the target type being a class,
+    // neither in static_cast nor in a C-style cast. So we can fail here.
+    // FIXME: We need to store this constructor in the AST.
+    if (Self.PerformInitializationByConstructor(DestType, &SrcExpr, 1,
+          OpRange.getBegin(), OpRange, DeclarationName(), Sema::IK_Direct))
+      return TC_Success;
+    // The function already emitted an error.
+    msg = 0;
+    return TC_Failed;
   }
 
   // FIXME: To get a proper error from invalid conversions here, we need to
   // reimplement more of this.
+  // FIXME: This does not actually perform the conversion, and thus does not
+  // check for ambiguity or access.
   ImplicitConversionSequence ICS = Self.TryImplicitConversion(
     SrcExpr, DestType);
   return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
-    TSC_NotApplicable : TSC_Success;
+    TC_NotApplicable : TC_Success;
 }
 
-/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
-/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
-/// checked downcasts in class hierarchies.
-void
-CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
-                 const SourceRange &OpRange,
-                 const SourceRange &DestRange)
-{
-  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+/// TryConstCast - See if a const_cast from source to destination is allowed,
+/// and perform it if it is.
+static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
+                                  bool CStyle, unsigned &msg) {
   DestType = Self.Context.getCanonicalType(DestType);
+  QualType SrcType = SrcExpr->getType();
+  if (const LValueReferenceType *DestTypeTmp =
+        DestType->getAsLValueReferenceType()) {
+    if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
+      // Cannot const_cast non-lvalue to lvalue reference type. But if this
+      // is C-style, static_cast might find a way, so we simply suggest a
+      // message and tell the parent to keep searching.
+      msg = diag::err_bad_cxx_cast_rvalue;
+      return TC_NotApplicable;
+    }
 
-  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
-  //   or "pointer to cv void".
+    // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
+    //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
+    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
+    SrcType = Self.Context.getPointerType(SrcType);
+  }
 
-  QualType DestPointee;
-  const PointerType *DestPointer = DestType->getAsPointerType();
-  const ReferenceType *DestReference = DestType->getAsReferenceType();
-  if (DestPointer) {
-    DestPointee = DestPointer->getPointeeType();
-  } else if (DestReference) {
-    DestPointee = DestReference->getPointeeType();
-  } else {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
-      << OrigDestType << DestRange;
-    return;
+  // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
+  //   the rules for const_cast are the same as those used for pointers.
+
+  if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
+    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
+    // was a reference type, we converted it to a pointer above.
+    // The status of rvalue references isn't entirely clear, but it looks like
+    // conversion to them is simply invalid.
+    // C++ 5.2.11p3: For two pointer types [...]
+    if (!CStyle)
+      msg = diag::err_bad_const_cast_dest;
+    return TC_NotApplicable;
+  }
+  if (DestType->isFunctionPointerType() ||
+      DestType->isMemberFunctionPointerType()) {
+    // Cannot cast direct function pointers.
+    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
+    // T is the ultimate pointee of source and target type.
+    if (!CStyle)
+      msg = diag::err_bad_const_cast_dest;
+    return TC_NotApplicable;
   }
+  SrcType = Self.Context.getCanonicalType(SrcType);
 
-  const RecordType *DestRecord = DestPointee->getAsRecordType();
-  if (DestPointee->isVoidType()) {
-    assert(DestPointer && "Reference to void is not possible");
-  } else if (DestRecord) {
-    if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 
-                                    diag::err_bad_dynamic_cast_incomplete,
-                                    DestRange))
-      return;
-  } else {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
-      << DestPointee.getUnqualifiedType() << DestRange;
-    return;
+  // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
+  // completely equal.
+  // FIXME: const_cast should probably not be able to convert between pointers
+  // to different address spaces.
+  // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
+  // in multi-level pointers may change, but the level count must be the same,
+  // as must be the final pointee type.
+  while (SrcType != DestType &&
+         Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
+    SrcType = SrcType.getUnqualifiedType();
+    DestType = DestType.getUnqualifiedType();
   }
 
-  // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
-  //   complete class type, [...]. If T is an lvalue reference type, v shall be
-  //   an lvalue of a complete class type, [...]. If T is an rvalue reference
-  //   type, v shall be an expression having a complete effective class type,
-  //   [...]
+  // Since we're dealing in canonical types, the remainder must be the same.
+  if (SrcType != DestType)
+    return TC_NotApplicable;
 
-  QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
-  QualType SrcPointee;
-  if (DestPointer) {
-    if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
-      SrcPointee = SrcPointer->getPointeeType();
-    } else {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
-        << OrigSrcType << SrcExpr->getSourceRange();
-      return;
+  return TC_Success;
+}
+
+static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
+                                        QualType DestType, bool CStyle,
+                                        const SourceRange &OpRange,
+                                        unsigned &msg) {
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+
+  DestType = Self.Context.getCanonicalType(DestType);
+  QualType SrcType = SrcExpr->getType();
+  if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
+    bool LValue = DestTypeTmp->isLValueReferenceType();
+    if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
+      // Cannot cast non-lvalue to reference type. See the similar comment in
+      // const_cast.
+      msg = diag::err_bad_cxx_cast_rvalue;
+      return TC_NotApplicable;
     }
-  } else if (DestReference->isLValueReferenceType()) {
-    if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
-      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
-        << "dynamic_cast" << OrigDestType << OpRange;
+
+    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
+    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
+    //   built-in & and * operators.
+    // This code does this transformation for the checked types.
+    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
+    SrcType = Self.Context.getPointerType(SrcType);
+  }
+
+  // Canonicalize source for comparison.
+  SrcType = Self.Context.getCanonicalType(SrcType);
+
+  const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
+                          *SrcMemPtr = SrcType->getAsMemberPointerType();
+  if (DestMemPtr && SrcMemPtr) {
+    // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
+    //   can be explicitly converted to an rvalue of type "pointer to member
+    //   of Y of type T2" if T1 and T2 are both function types or both object
+    //   types.
+    if (DestMemPtr->getPointeeType()->isFunctionType() !=
+        SrcMemPtr->getPointeeType()->isFunctionType())
+      return TC_NotApplicable;
+
+    // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
+    //   constness.
+    // A reinterpret_cast followed by a const_cast can, though, so in C-style,
+    // we accept it.
+    if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
+      msg = diag::err_bad_cxx_cast_const_away;
+      return TC_Failed;
     }
-    SrcPointee = SrcType;
-  } else {
-    SrcPointee = SrcType;
+
+    // A valid member pointer cast.
+    return TC_Success;
   }
 
-  const RecordType *SrcRecord = SrcPointee->getAsRecordType();
-  if (SrcRecord) {
-    if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
-                                    diag::err_bad_dynamic_cast_incomplete,
-                                    SrcExpr->getSourceRange()))
-      return;
-  } else {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
-      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
-    return;
+  // See below for the enumeral issue.
+  if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
+      !DestType->isEnumeralType()) {
+    // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
+    //   type large enough to hold it. A value of std::nullptr_t can be
+    //   converted to an integral type; the conversion has the same meaning
+    //   and validity as a conversion of (void*)0 to the integral type.
+    if (Self.Context.getTypeSize(SrcType) >
+        Self.Context.getTypeSize(DestType)) {
+      msg = diag::err_bad_reinterpret_cast_small_int;
+      return TC_Failed;
+    }
+    return TC_Success;
   }
 
-  assert((DestPointer || DestReference) &&
-    "Bad destination non-ptr/ref slipped through.");
-  assert((DestRecord || DestPointee->isVoidType()) &&
-    "Bad destination pointee slipped through.");
-  assert(SrcRecord && "Bad source pointee slipped through.");
+  bool destIsPtr = DestType->isPointerType();
+  bool srcIsPtr = SrcType->isPointerType();
+  if (!destIsPtr && !srcIsPtr) {
+    // Except for std::nullptr_t->integer and lvalue->reference, which are
+    // handled above, at least one of the two arguments must be a pointer.
+    return TC_NotApplicable;
+  }
 
-  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
-  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
-      << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
-    return;
+  if (SrcType == DestType) {
+    // C++ 5.2.10p2 has a note that mentions that, subject to all other
+    // restrictions, a cast to the same type is allowed. The intent is not
+    // entirely clear here, since all other paragraphs explicitly forbid casts
+    // to the same type. However, the behavior of compilers is pretty consistent
+    // on this point: allow same-type conversion if the involved types are
+    // pointers, disallow otherwise.
+    return TC_Success;
   }
 
-  // C++ 5.2.7p3: If the type of v is the same as the required result type,
-  //   [except for cv].
-  if (DestRecord == SrcRecord) {
-    return;
+  // Note: Clang treats enumeration types as integral types. If this is ever
+  // changed for C++, the additional check here will be redundant.
+  if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
+    assert(srcIsPtr && "One type must be a pointer");
+    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
+    //   type large enough to hold it.
+    if (Self.Context.getTypeSize(SrcType) >
+        Self.Context.getTypeSize(DestType)) {
+      msg = diag::err_bad_reinterpret_cast_small_int;
+      return TC_Failed;
+    }
+    return TC_Success;
   }
 
-  // C++ 5.2.7p5
-  // Upcasts are resolved statically.
-  if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
-    Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
-                                      OpRange.getBegin(), OpRange);
-    // Diagnostic already emitted on error.
-    return;
+  if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
+    assert(destIsPtr && "One type must be a pointer");
+    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
+    //   converted to a pointer.
+    return TC_Success;
   }
 
-  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
-  const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
-  assert(SrcDecl && "Definition missing");
-  if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
-    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
-      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
+  if (!destIsPtr || !srcIsPtr) {
+    // With the valid non-pointer conversions out of the way, we can be even
+    // more stringent.
+    return TC_NotApplicable;
   }
 
-  // Done. Everything else is run-time checks.
+  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
+  // The C-style cast operator can.
+  if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
+    msg = diag::err_bad_cxx_cast_const_away;
+    return TC_Failed;
+  }
+
+  // Not casting away constness, so the only remaining check is for compatible
+  // pointer categories.
+
+  if (SrcType->isFunctionPointerType()) {
+    if (DestType->isFunctionPointerType()) {
+      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
+      // a pointer to a function of a different type.
+      return TC_Success;
+    }
+
+    // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
+    //   an object type or vice versa is conditionally-supported.
+    // Compilers support it in C++03 too, though, because it's necessary for
+    // casting the return value of dlsym() and GetProcAddress().
+    // FIXME: Conditionally-supported behavior should be configurable in the
+    // TargetInfo or similar.
+    if (!Self.getLangOptions().CPlusPlus0x)
+      Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
+    return TC_Success;
+  }
+
+  if (DestType->isFunctionPointerType()) {
+    // See above.
+    if (!Self.getLangOptions().CPlusPlus0x)
+      Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
+    return TC_Success;
+  }
+
+  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
+  //   a pointer to an object of different type.
+  // Void pointers are not specified, but supported by every compiler out there.
+  // So we finish by allowing everything that remains - it's got to be two
+  // object pointers.
+  return TC_Success;
+}
+
+
+bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr)
+{
+  // This test is outside everything else because it's the only case where
+  // a non-lvalue-reference target type does not lead to decay.
+  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
+  if (CastTy->isVoidType())
+    return false;
+
+  // If the type is dependent, we won't do any other semantic analysis now.
+  if (CastTy->isDependentType() || CastExpr->isTypeDependent())
+    return false;
+
+  if (!CastTy->isLValueReferenceType())
+    DefaultFunctionArrayConversion(CastExpr);
+
+  // C++ [expr.cast]p5: The conversions performed by
+  //   - a const_cast,
+  //   - a static_cast,
+  //   - a static_cast followed by a const_cast,
+  //   - a reinterpret_cast, or
+  //   - a reinterpret_cast followed by a const_cast,
+  //   can be performed using the cast notation of explicit type conversion.
+  //   [...] If a conversion can be interpreted in more than one of the ways
+  //   listed above, the interpretation that appears first in the list is used,
+  //   even if a cast resulting from that interpretation is ill-formed.
+  // In plain language, this means trying a const_cast ...
+  unsigned msg = diag::err_bad_cxx_cast_generic;
+  TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,msg);
+  if (tcr == TC_NotApplicable) {
+    // ... or if that is not possible, a static_cast, ignoring const, ...
+    tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
+    if (tcr == TC_NotApplicable) {
+      // ... and finally a reinterpret_cast, ignoring const.
+      tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
+    }
+  }
+
+  // FIXME: Differentiate functional-style and C-style cast.
+  if (tcr != TC_Success && msg != 0)
+    Diag(R.getBegin(), msg) << CT_CStyle
+      << CastExpr->getType() << CastTy << R;
+
+  return tcr != TC_Success;
 }

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Sat Jul 25 10:41:38 2009
@@ -2919,14 +2919,15 @@
 
 /// CheckCastTypes - Check type constraints for casting between types.
 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
+  if (getLangOptions().CPlusPlus)
+    return CXXCheckCStyleCast(TyR, castType, castExpr);
+
   UsualUnaryConversions(castExpr);
 
   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
   // type needs to be scalar.
   if (castType->isVoidType()) {
     // Cast to void allows any expr type.
-  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
-    // We can't check any more until template instantiation time.
   } else if (!castType->isScalarType() && !castType->isVectorType()) {
     if (Context.getCanonicalType(castType).getUnqualifiedType() ==
         Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
@@ -3040,7 +3041,8 @@
 
   if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
     return ExprError();
-  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
+  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
+                                            castExpr, castType,
                                             LParenLoc, RParenLoc));
 }
 

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Sat Jul 25 10:41:38 2009
@@ -1136,7 +1136,7 @@
 
 /// CheckPointerConversion - Check the pointer conversion from the
 /// expression From to the type ToType. This routine checks for
-/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
+/// ambiguous or inaccessible derived-to-base pointer
 /// conversions for which IsPointerConversion has already returned
 /// true. It returns true and produces a diagnostic if there was an
 /// error, or returns false otherwise.

Modified: cfe/trunk/test/Parser/cxx-ambig-paren-expr.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/cxx-ambig-paren-expr.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/test/Parser/cxx-ambig-paren-expr.cpp (original)
+++ cfe/trunk/test/Parser/cxx-ambig-paren-expr.cpp Sat Jul 25 10:41:38 2009
@@ -5,9 +5,9 @@
   int x, *px;
   
   // Type id.
-  (T())x;    // expected-error {{used type 'T ()'}}
-  (T())+x;   // expected-error {{used type 'T ()'}}
-  (T())*px;  // expected-error {{used type 'T ()'}}
+  (T())x;    // expected-error {{cast from 'int' to 'T ()'}}
+  (T())+x;   // expected-error {{cast from 'int' to 'T ()'}}
+  (T())*px;  // expected-error {{cast from 'int' to 'T ()'}}
   
   // Expression.
   x = (T());

Added: cfe/trunk/test/SemaCXX/cstyle-cast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/cstyle-cast.cpp?rev=77076&view=auto

==============================================================================
--- cfe/trunk/test/SemaCXX/cstyle-cast.cpp (added)
+++ cfe/trunk/test/SemaCXX/cstyle-cast.cpp Sat Jul 25 10:41:38 2009
@@ -0,0 +1,231 @@
+// RUN: clang-cc -fsyntax-only -verify -faccess-control %s
+
+struct A {};
+
+// ----------- const_cast --------------
+
+typedef char c;
+typedef c *cp;
+typedef cp *cpp;
+typedef cpp *cppp;
+typedef cppp &cpppr;
+typedef const cppp &cpppcr;
+typedef const char cc;
+typedef cc *ccp;
+typedef volatile ccp ccvp;
+typedef ccvp *ccvpp;
+typedef const volatile ccvpp ccvpcvp;
+typedef ccvpcvp *ccvpcvpp;
+typedef int iar[100];
+typedef iar &iarr;
+typedef int (*f)(int);
+
+void t_cc()
+{
+  ccvpcvpp var = 0;
+  // Cast away deep consts and volatiles.
+  char ***var2 = (cppp)(var);
+  char ***const &var3 = var2;
+  // Const reference to reference.
+  char ***&var4 = (cpppr)(var3);
+  // Drop reference. Intentionally without qualifier change.
+  char *** var5 = (cppp)(var4);
+  const int ar[100] = {0};
+  // Array decay. Intentionally without qualifier change.
+  int *pi = (int*)(ar);
+  f fp = 0;
+  // Don't misidentify fn** as a function pointer.
+  f *fpp = (f*)(&fp);
+  int const A::* const A::*icapcap = 0;
+  int A::* A::* iapap = (int A::* A::*)(icapcap);
+}
+
+// ----------- static_cast -------------
+
+struct B : public A {};             // Single public base.
+struct C1 : public virtual B {};    // Single virtual base.
+struct C2 : public virtual B {};
+struct D : public C1, public C2 {}; // Diamond
+struct E : private A {};            // Single private base.
+struct F : public C1 {};            // Single path to B with virtual.
+struct G1 : public B {};
+struct G2 : public B {};
+struct H : public G1, public G2 {}; // Ambiguous path to B.
+
+enum Enum { En1, En2 };
+enum Onom { On1, On2 };
+
+struct Co1 { operator int(); };
+struct Co2 { Co2(int); };
+struct Co3 { };
+struct Co4 { Co4(Co3); operator Co3(); };
+
+// Explicit implicits
+void t_529_2()
+{
+  int i = 1;
+  (void)(float)(i);
+  double d = 1.0;
+  (void)(float)(d);
+  (void)(int)(d);
+  (void)(char)(i);
+  (void)(unsigned long)(i);
+  (void)(int)(En1);
+  (void)(double)(En1);
+  (void)(int&)(i);
+  (void)(const int&)(i);
+
+  int ar[1];
+  (void)(const int*)(ar);
+  (void)(void (*)())(t_529_2);
+
+  (void)(void*)(0);
+  (void)(void*)((int*)0);
+  (void)(volatile const void*)((const int*)0);
+  (void)(A*)((B*)0);
+  (void)(A&)(*((B*)0));
+  (void)(const B*)((C1*)0);
+  (void)(B&)(*((C1*)0));
+  (void)(A*)((D*)0);
+  (void)(const A&)(*((D*)0));
+  (void)(int B::*)((int A::*)0);
+  (void)(void (B::*)())((void (A::*)())0);
+  (void)(A*)((E*)0); // C-style cast ignores access control
+  (void)(void*)((const int*)0); // const_cast appended
+
+  (void)(int)(Co1());
+  (void)(Co2)(1);
+  (void)(Co3)((Co4)(Co3()));
+
+  // Bad code below
+  //(void)(A*)((H*)0); // {{static_cast from 'struct H *' to 'struct A *' is not allowed}}
+}
+
+// Anything to void
+void t_529_4()
+{
+  (void)(1);
+  (void)(t_529_4);
+}
+
+// Static downcasts
+void t_529_5_8()
+{
+  (void)(B*)((A*)0);
+  (void)(B&)(*((A*)0));
+  (void)(const G1*)((A*)0);
+  (void)(const G1&)(*((A*)0));
+  (void)(B*)((const A*)0); // const_cast appended
+  (void)(B&)(*((const A*)0)); // const_cast appended
+  (void)(E*)((A*)0); // access control ignored
+  (void)(E&)(*((A*)0)); // access control ignored
+
+  // Bad code below
+
+  (void)(C1*)((A*)0); // expected-error {{cannot cast 'struct A *' to 'struct C1 *' via virtual base 'struct B'}}
+  (void)(C1&)(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct C1 &' via virtual base 'struct B'}}
+  (void)(D*)((A*)0); // expected-error {{cannot cast 'struct A *' to 'struct D *' via virtual base 'struct B'}}
+  (void)(D&)(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct D &' via virtual base 'struct B'}}
+  (void)(H*)((A*)0); // expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
+  (void)(H&)(*((A*)0)); // expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
+
+  // TODO: Test DR427. This requires user-defined conversions, though.
+}
+
+// Enum conversions
+void t_529_7()
+{
+  (void)(Enum)(1);
+  (void)(Enum)(1.0);
+  (void)(Onom)(En1);
+
+  // Bad code below
+
+  (void)(Enum)((int*)0); // expected-error {{C-style cast from 'int *' to 'enum Enum' is not allowed}}
+}
+
+// Void pointer to object pointer
+void t_529_10()
+{
+  (void)(int*)((void*)0);
+  (void)(const A*)((void*)0);
+  (void)(int*)((const void*)0); // const_cast appended
+}
+
+// Member pointer upcast.
+void t_529_9()
+{
+  (void)(int A::*)((int B::*)0);
+
+  // Bad code below
+  (void)(int A::*)((int H::*)0); // expected-error {{ambiguous conversion from pointer to member of derived class 'struct H'}}
+  (void)(int A::*)((int F::*)0); // expected-error {{conversion from pointer to member of class 'struct F'}}
+}
+
+// -------- reinterpret_cast -----------
+
+enum test { testval = 1 };
+struct structure { int m; };
+typedef void (*fnptr)();
+
+// Test conversion between pointer and integral types, as in p3 and p4.
+void integral_conversion()
+{
+  void *vp = (void*)(testval);
+  long l = (long)(vp);
+  (void)(float*)(l);
+  fnptr fnp = (fnptr)(l);
+  (void)(char)(fnp); // expected-error {{cast from pointer to smaller type 'char' loses information}}
+  (void)(long)(fnp);
+}
+
+void pointer_conversion()
+{
+  int *p1 = 0;
+  float *p2 = (float*)(p1);
+  structure *p3 = (structure*)(p2);
+  typedef int **ppint;
+  ppint *deep = (ppint*)(p3);
+  (void)(fnptr*)(deep);
+}
+
+void constness()
+{
+  int ***const ipppc = 0;
+  int const *icp = (int const*)(ipppc);
+  (void)(int*)(icp); // const_cast appended
+  int const *const **icpcpp = (int const* const**)(ipppc); // const_cast appended
+  int *ip = (int*)(icpcpp);
+  (void)(int const*)(ip);
+  (void)(int const* const* const*)(ipppc);
+}
+
+void fnptrs()
+{
+  typedef int (*fnptr2)(int);
+  fnptr fp = 0;
+  (void)(fnptr2)(fp);
+  void *vp = (void*)(fp);
+  (void)(fnptr)(vp);
+}
+
+void refs()
+{
+  long l = 0;
+  char &c = (char&)(l);
+  // Bad: from rvalue
+  (void)(int&)(&c); // expected-error {{C-style cast from rvalue to reference type 'int &'}}
+}
+
+void memptrs()
+{
+  const int structure::*psi = 0;
+  (void)(const float structure::*)(psi);
+  (void)(int structure::*)(psi); // const_cast appended
+
+  void (structure::*psf)() = 0;
+  (void)(int (structure::*)())(psf);
+
+  (void)(void (structure::*)())(psi); // expected-error {{C-style cast from 'int const struct structure::*' to 'void (struct structure::*)()' is not allowed}}
+  (void)(int structure::*)(psf); // expected-error {{C-style cast from 'void (struct structure::*)()' to 'int struct structure::*' is not allowed}}
+}

Modified: cfe/trunk/test/SemaCXX/dcl_ambig_res.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/dcl_ambig_res.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/test/SemaCXX/dcl_ambig_res.cpp (original)
+++ cfe/trunk/test/SemaCXX/dcl_ambig_res.cpp Sat Jul 25 10:41:38 2009
@@ -50,7 +50,7 @@
 void foo6() 
 { 
   (void)(int(1)); //expression 
-  (void)(int())1; // expected-error{{used type}}
+  (void)(int())1; // expected-error{{to 'int ()'}}
 } 
 
 // [dcl.ambig.res]p7:

Modified: cfe/trunk/test/SemaCXX/decl-expr-ambiguity.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/decl-expr-ambiguity.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/test/SemaCXX/decl-expr-ambiguity.cpp (original)
+++ cfe/trunk/test/SemaCXX/decl-expr-ambiguity.cpp Sat Jul 25 10:41:38 2009
@@ -19,7 +19,7 @@
   (int(1)); // expected-warning {{expression result unused}}
 
   // type-id
-  (int())1; // expected-error {{used type 'int ()' where arithmetic or pointer type is required}}
+  (int())1; // expected-error {{C-style cast from 'int' to 'int ()' is not allowed}}
 
   // Declarations.
   int fd(T(a)); // expected-warning {{parentheses were disambiguated as a function declarator}}

Modified: cfe/trunk/test/SemaCXX/static-cast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/static-cast.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/test/SemaCXX/static-cast.cpp (original)
+++ cfe/trunk/test/SemaCXX/static-cast.cpp Sat Jul 25 10:41:38 2009
@@ -1,11 +1,11 @@
-// RUN: clang-cc -fsyntax-only -verify %s
+// RUN: clang-cc -fsyntax-only -verify -faccess-control %s
 
 struct A {};
 struct B : public A {};             // Single public base.
 struct C1 : public virtual B {};    // Single virtual base.
 struct C2 : public virtual B {};
 struct D : public C1, public C2 {}; // Diamond
-struct E : private A {};            // Single private base.
+struct E : private A {};            // Single private base. expected-note 2 {{'private' inheritance specifier here}}
 struct F : public C1 {};            // Single path to B with virtual.
 struct G1 : public B {};
 struct G2 : public B {};
@@ -14,6 +14,11 @@
 enum Enum { En1, En2 };
 enum Onom { On1, On2 };
 
+struct Co1 { operator int(); };
+struct Co2 { Co2(int); };
+struct Co3 { };
+struct Co4 { Co4(Co3); operator Co3(); };
+
 // Explicit implicits
 void t_529_2()
 {
@@ -45,7 +50,9 @@
   (void)static_cast<int B::*>((int A::*)0);
   (void)static_cast<void (B::*)()>((void (A::*)())0);
 
-  // TODO: User-defined conversions
+  (void)static_cast<int>(Co1());
+  (void)static_cast<Co2>(1);
+  (void)static_cast<Co3>(static_cast<Co4>(Co3()));
 
   // Bad code below
 
@@ -80,11 +87,10 @@
   (void)static_cast<D&>(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct D &' via virtual base 'struct B'}}
   (void)static_cast<B*>((const A*)0); // expected-error {{static_cast from 'struct A const *' to 'struct B *' casts away constness}}
   (void)static_cast<B&>(*((const A*)0)); // expected-error {{static_cast from 'struct A const' to 'struct B &' casts away constness}}
-  // Accessibility is not yet tested
-  //(void)static_cast<E*>((A*)0); // {{static_cast from 'struct A *' to 'struct E *' is not allowed}}
-  //(void)static_cast<E&>(*((A*)0)); // {{static_cast from 'struct A' to 'struct E &' is not allowed}}
-  (void)static_cast<H*>((A*)0); // expected-error {{ambiguous static_cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
-  (void)static_cast<H&>(*((A*)0)); // expected-error {{ambiguous static_cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
+  (void)static_cast<E*>((A*)0); // expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}
+  (void)static_cast<E&>(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}
+  (void)static_cast<H*>((A*)0); // expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
+  (void)static_cast<H&>(*((A*)0)); // expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
   (void)static_cast<E*>((B*)0); // expected-error {{static_cast from 'struct B *' to 'struct E *' is not allowed}}
   (void)static_cast<E&>(*((B*)0)); // expected-error {{non-const lvalue reference to type 'struct E' cannot be initialized with a value of type 'struct B'}}
 

Modified: cfe/trunk/test/SemaTemplate/instantiate-cast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/instantiate-cast.cpp?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/test/SemaTemplate/instantiate-cast.cpp (original)
+++ cfe/trunk/test/SemaTemplate/instantiate-cast.cpp Sat Jul 25 10:41:38 2009
@@ -1,6 +1,6 @@
 // RUN: clang-cc -fsyntax-only -verify %s
 
-struct A { int x; };
+struct A { int x; }; // expected-note 2 {{candidate}}
 
 class Base { 
 public:
@@ -23,7 +23,7 @@
 template<typename T, typename U>
 struct CStyleCast0 {
   void f(T t) {
-    (void)((U)t); // FIXME:ugly expected-error{{operand}}
+    (void)((U)t); // expected-error{{C-style cast from 'struct A' to 'int'}}
   }
 };
 
@@ -36,7 +36,7 @@
 template<typename T, typename U>
 struct StaticCast0 {
   void f(T t) {
-    (void)static_cast<U>(t); // expected-error{{static_cast}}
+    (void)static_cast<U>(t); // expected-error{{initialization of 'struct A'}}
   }
 };
 
@@ -89,7 +89,7 @@
 template<typename T, typename U>
 struct FunctionalCast1 {
   void f(T t) {
-    (void)U(t); // FIXME:ugly expected-error{{operand}}
+    (void)U(t); // expected-error{{C-style cast from 'struct A' to 'int'}}
   }
 };
 

Modified: cfe/trunk/www/cxx_status.html
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/www/cxx_status.html?rev=77076&r1=77075&r2=77076&view=diff

==============================================================================
--- cfe/trunk/www/cxx_status.html (original)
+++ cfe/trunk/www/cxx_status.html Sat Jul 25 10:41:38 2009
@@ -540,10 +540,10 @@
 <tr>
   <td>    5.2.3 [expr.type.conv]</td>
   <td class="complete" align="center"></td>
-  <td class="complete" align="center"></td>
-  <td class="basic"></td>
+  <td class="medium" align="center"></td>
+  <td class="advanced"></td>
   <td></td>
-  <td>Only between non-class types</td>
+  <td>Allows some invalid pointer conversions, AST has little information</td>
 </tr>
 <tr>
   <td>    5.2.4 [expr.pseudo]</td>
@@ -588,10 +588,10 @@
 <tr>
   <td>    5.2.9 [expr.static.cast]</td>
   <td class="complete" align="center"></td>
-  <td class="complete" align="center"></td>
+  <td class="medium" align="center"></td>
   <td class="advanced" align="center"></td>
   <td></td>
-  <td>Some custom conversions don't work.</td>
+  <td>Allows some invalid pointer conversions, AST has little information</td>
 </tr>
 <tr>
   <td>    5.2.10 [expr.reinterpret.cast]</td>
@@ -694,10 +694,10 @@
 <tr>
   <td>  5.4 [expr.cast]</td>
   <td class="complete" align="center"></td>
-  <td class="complete" align="center"></td>
-  <td class="medium"></td>
+  <td class="medium" align="center"></td>
+  <td class="advanced"></td>
   <td></td>
-  <td>Too lenient, and may not always have correct semantics</td>
+  <td>Allows some invalid pointer conversions, AST has little information</td>
 </tr>
 <tr>
   <td>  5.5 [expr.mptr.oper]</td>





More information about the cfe-commits mailing list