Index: test/SemaCXX/dynamic-cast.cpp
===================================================================
--- test/SemaCXX/dynamic-cast.cpp	(revision 0)
+++ test/SemaCXX/dynamic-cast.cpp	(revision 0)
@@ -0,0 +1,55 @@
+// RUN: clang -fsyntax-only -verify %s
+
+struct A {};
+struct B : A {};
+struct C : B {};
+
+struct D : private A {};
+struct E : A {};
+struct F : B, E {};
+
+struct Incomplete;
+
+void basic_bad()
+{
+  // ptr -> nonptr
+  (void)dynamic_cast<A>((A*)0); // expected-error {{'struct A' is not a reference or pointer}}
+  // nonptr -> ptr
+  (void)dynamic_cast<A*>(0); // expected-error {{'int' is not a pointer}}
+  // ptr -> noncls
+  (void)dynamic_cast<int*>((A*)0); // expected-error {{'int' is not a class}}
+  // noncls -> ptr
+  (void)dynamic_cast<A*>((int*)0); // expected-error {{'int' is not a class}}
+  // ref -> noncls
+  (void)dynamic_cast<int&>(*((A*)0)); // expected-error {{'int' is not a class}}
+  // noncls -> ref
+  (void)dynamic_cast<A&>(*((int*)0)); // expected-error {{'int' is not a class}}
+  // ptr -> incomplete
+  (void)dynamic_cast<Incomplete*>((A*)0); // expected-error {{'struct Incomplete' is incomplete}}
+  // incomplete -> ptr
+  (void)dynamic_cast<A*>((Incomplete*)0); // expected-error {{'struct Incomplete' is incomplete}}
+}
+
+void same()
+{
+  (void)dynamic_cast<A*>((A*)0);
+  (void)dynamic_cast<A&>(*((A*)0));
+}
+
+void up()
+{
+  (void)dynamic_cast<A*>((B*)0);
+  (void)dynamic_cast<A&>(*((B*)0));
+  (void)dynamic_cast<A*>((C*)0);
+  (void)dynamic_cast<A&>(*((C*)0));
+
+  // Inaccessible
+  //(void)dynamic_cast<A*>((D*)0);
+  //(void)dynamic_cast<A&>(*((D*)0));
+
+  // Ambiguous
+  (void)dynamic_cast<A*>((F*)0); // expected-error {{ambiguous conversion from derived class 'struct F' to base class 'struct A':\n    struct F -> struct B -> struct A\n    struct F -> struct E -> struct A}}
+  (void)dynamic_cast<A&>(*((F*)0)); // expected-error {{ambiguous conversion from derived class 'struct F' to base class 'struct A':\n    struct F -> struct B -> struct A\n    struct F -> struct E -> struct A}}
+}
+
+// FIXME: Other test cases require recognition of polymorphic classes.
Index: test/SemaCXX/const-cast.cpp
===================================================================
--- test/SemaCXX/const-cast.cpp	(revision 58328)
+++ test/SemaCXX/const-cast.cpp	(working copy)
@@ -21,7 +21,7 @@
 {
   // Cast away deep consts and volatiles.
   char ***var2 = const_cast<cppp>(var);
-  char ***const &var3 = static_cast<cpppcr>(var2); // Different bug.
+  char ***const &var3 = *(const cppp*)0; // Different bug.
   // Const reference to reference.
   char ***&var4 = const_cast<cpppr>(var3);
   // Drop reference. Intentionally without qualifier change.
Index: test/SemaCXX/static-cast.cpp
===================================================================
--- test/SemaCXX/static-cast.cpp	(revision 0)
+++ test/SemaCXX/static-cast.cpp	(revision 0)
@@ -0,0 +1,119 @@
+// RUN: clang -fsyntax-only -verify %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 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 };
+
+// Explicit implicits
+void t_529_2()
+{
+  int i = 1;
+  (void)static_cast<float>(i);
+  double d = 1.0;
+  (void)static_cast<float>(d);
+  (void)static_cast<int>(d);
+  (void)static_cast<char>(i);
+  (void)static_cast<unsigned long>(i);
+  (void)static_cast<int>(En1);
+  (void)static_cast<double>(En1);
+  (void)static_cast<int&>(i);
+
+  int ar[1];
+  (void)static_cast<const int*>(ar);
+  (void)static_cast<void (*)()>(t_529_2);
+
+  (void)static_cast<void*>(0);
+  (void)static_cast<void*>((int*)0);
+  (void)static_cast<volatile const void*>((const int*)0);
+  (void)static_cast<A*>((B*)0);
+  // TryCopyInitialization doesn't handle references yet.
+  //(void)static_cast<A&>(*((B*)0));
+  (void)static_cast<const B*>((C1*)0);
+  //(void)static_cast<B&>(*((C1*)0));
+  (void)static_cast<A*>((D*)0);
+  //(void)static_cast<const A&>(*((D*)0));
+
+  // TODO: User-defined conversions
+
+  // Bad code below
+
+  (void)static_cast<void*>((const int*)0); // expected-error {{static_cast from 'int const *' to 'void *' is not allowed}}
+  //(void)static_cast<A*>((E*)0); // {{static_cast from 'struct E *' to 'struct A *' is not allowed}}
+  //(void)static_cast<A*>((H*)0); // {{static_cast from 'struct H *' to 'struct A *' is not allowed}}
+  (void)static_cast<int>((int*)0); // expected-error {{static_cast from 'int *' to 'int' is not allowed}}
+  //(void)static_cast<A**>((B**)0); // {{static_cast from 'struct A * *' to 'struct B * *' is not allowed}}
+  (void)static_cast<char&>(i); // expected-error {{static_cast from 'int' to 'char &' is not allowed}}
+}
+
+// Anything to void
+void t_529_4()
+{
+  static_cast<void>(1);
+  static_cast<void>(t_529_4);
+}
+
+// Static downcasts
+void t_529_5_8()
+{
+  (void)static_cast<B*>((A*)0);
+  (void)static_cast<B&>(*((A*)0));
+  (void)static_cast<const G1*>((A*)0);
+  (void)static_cast<const G1&>(*((A*)0));
+
+  // Bad code below
+
+  (void)static_cast<C1*>((A*)0); // expected-error {{static_cast from 'struct A *' to 'struct C1 *' is not allowed}}
+  (void)static_cast<C1&>(*((A*)0)); // expected-error {{static_cast from 'struct A' to 'struct C1 &' is not allowed}}
+  (void)static_cast<D*>((A*)0); // expected-error {{static_cast from 'struct A *' to 'struct D *' is not allowed}}
+  (void)static_cast<D&>(*((A*)0)); // expected-error {{static_cast from 'struct A' to 'struct D &' is not allowed}}
+  (void)static_cast<B*>((const A*)0); // expected-error {{static_cast from 'struct A const *' to 'struct B *' is not allowed}}
+  (void)static_cast<B&>(*((const A*)0)); // expected-error {{static_cast from 'struct A const' to 'struct B &' is not allowed}}
+  // 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 {{static_cast from 'struct A *' to 'struct H *' is not allowed}}
+  (void)static_cast<H&>(*((A*)0)); // expected-error {{static_cast from 'struct A' to 'struct H &' is not allowed}}
+  (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 {{static_cast from 'struct B' to 'struct E &' is not allowed}}
+
+  // TODO: Test inaccessible base in context where it's accessible, i.e.
+  // member function and friend.
+
+  // TODO: Test DR427. This requires user-defined conversions, though.
+}
+
+// Enum conversions
+void t_529_7()
+{
+  (void)static_cast<Enum>(1);
+  (void)static_cast<Enum>(1.0);
+  (void)static_cast<Onom>(En1);
+
+  // Bad code below
+
+  (void)static_cast<Enum>((int*)0); // expected-error {{static_cast from 'int *' to 'enum Enum' is not allowed}}
+}
+
+// Void pointer to object pointer
+void t_529_10()
+{
+  (void)static_cast<int*>((void*)0);
+  (void)static_cast<const A*>((void*)0);
+
+  // Bad code below
+
+  (void)static_cast<int*>((const void*)0); // expected-error {{static_cast from 'void const *' to 'int *' is not allowed}}
+  (void)static_cast<void (*)()>((void*)0); // expected-error {{static_cast from 'void *' to 'void (*)(void)' is not allowed}}
+}
+
+// TODO: Test member pointers.
Index: test/SemaCXX/condition.cpp
===================================================================
--- test/SemaCXX/condition.cpp	(revision 58328)
+++ test/SemaCXX/condition.cpp	(working copy)
@@ -18,7 +18,7 @@
 
   while (struct S {} x=0) ; // expected-error: {{types may not be defined in conditions}} expected-error: {{incompatible type}} expected-error: {{expression must have bool type}}
   while (struct {} x=0) ; // expected-error: {{types may not be defined in conditions}} expected-error: {{incompatible type}} expected-error: {{expression must have bool type}}
-  switch (enum {E} x=0) ; // expected-error: {{types may not be defined in conditions}}
+  switch (enum {E} x=0) ; // expected-error: {{types may not be defined in conditions}} expected-error: {{incompatible type}}
 
   if (int x=0) { // expected-error: {{previous definition is here}}
     int x;  // expected-error: {{redefinition of 'x'}}
Index: include/clang/Basic/DiagnosticKinds.def
===================================================================
--- include/clang/Basic/DiagnosticKinds.def	(revision 58328)
+++ include/clang/Basic/DiagnosticKinds.def	(working copy)
@@ -1078,6 +1078,8 @@
      "an extension")
 DIAG(err_bad_reinterpret_cast_small_int, ERROR,
      "cast from pointer to smaller type '%0' loses information")
+DIAG(err_bad_dynamic_cast_operand, ERROR,
+     "'%0' is %1")
 
 DIAG(err_invalid_use_of_function_type, ERROR,
      "a function type is not allowed here")
Index: lib/Sema/SemaExprCXX.cpp
===================================================================
--- lib/Sema/SemaExprCXX.cpp	(revision 58328)
+++ lib/Sema/SemaExprCXX.cpp	(working copy)
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "Sema.h"
+#include "SemaInherit.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/Parse/DeclSpec.h"
@@ -40,6 +41,8 @@
                                 DestType, OpLoc);
 
   case tok::kw_dynamic_cast:
+    CheckDynamicCast(OpLoc, Ex, DestType,
+      SourceRange(LAngleBracketLoc, RAngleBracketLoc));
     return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex, 
                                   DestType, OpLoc);
 
@@ -49,10 +52,11 @@
                                       DestType, OpLoc);
 
   case tok::kw_static_cast:
+    CheckStaticCast(OpLoc, Ex, DestType);
     return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex, 
                                  DestType, OpLoc);
   }
-  
+
   return true;
 }
 
@@ -325,41 +329,360 @@
 }
 
 /// 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.
 void
 Sema::CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
 {
-#if 0
-  // 5.2.9/1 sets the ground rule of disallowing casting away constness.
-  // 5.2.9/2 permits everything allowed for direct-init, deferring to 8.5.
-  //   Note: for class destination, that's overload resolution over dest's
-  //   constructors. Src's conversions are only considered in overload choice.
-  //   For any other destination, that's just the clause 4 standards convs.
-  // 5.2.9/4 permits static_cast&lt;cv void>(anything), which is a no-op.
-  // 5.2.9/5 permits explicit non-dynamic downcasts for lvalue-to-reference.
-  // 5.2.9/6 permits reversing all implicit conversions except lvalue-to-rvalue,
-  //   function-to-pointer, array decay and to-bool, with some further
-  //   restrictions. Defers to 4.
-  // 5.2.9/7 permits integer-to-enum conversion. Interesting note: if the
-  //   integer does not correspond to an enum value, the result is unspecified -
-  //   but it still has to be some value of the enum. I don't think any compiler
-  //   complies with that.
-  // 5.2.9/8 is 5.2.9/5 for pointers.
-  // 5.2.9/9 messes with member pointers. TODO. No need to think about that yet.
-  // 5.2.9/10 permits void* to T*.
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
 
+  // Conversions are tried roughly in the order the standard specifies them.
+  // This is necessary because there are some conversions that can be
+  // interpreted in more than one way, and the order disambiguates.
+  // DR 427 specifies that paragraph 5 is to be applied before paragraph 2.
+
+  // This option is unambiguous and simple, so put it here.
+  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
+  if (DestType.getUnqualifiedType() == Context.VoidTy) {
+    return;
+  }
+
+  DestType = Context.getCanonicalType(DestType);
+
+  // C++ 5.2.9p5, reference downcast.
+  // See the function for details.
+  if (IsStaticReferenceDowncast(SrcExpr, DestType)) {
+    return;
+  }
+
+  // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
+  //   [...] if the declaration "T t(e);" is well-formed, [...].
+  ImplicitConversionSequence ICS = TryDirectInitialization(SrcExpr, DestType);
+  if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
+    if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
+        ICS.Standard.First != ICK_Identity)
+    {
+      DefaultFunctionArrayConversion(SrcExpr);
+    }
+    return;
+  }
+  // FIXME: Missing the validation of the conversion, e.g. for an accessible
+  // base.
+
+  // 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.
+
+  // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
+  // are applied to the expression.
+  // This function also performs the reference hack.
+  DefaultFunctionArrayConversion(SrcExpr);
+
+  QualType SrcType = Context.getCanonicalType(SrcExpr->getType());
+
+  // Reverse integral promotion/conversion. All such conversions are themselves
+  // again integral promotions or conversions and are thus already handled.
+  // (Note: any data loss warnings should be suppressed.)
+  // The exception is the reverse of enum->integer, i.e. integer->enum (and
+  // enum->enum). See also C++ 5.2.9p7.
+  // The same goes for reverse floating point promotion/conversion and
+  // floating-integral conversions. Again, only floating->enum is relevant.
+  if (DestType->isEnumeralType()) {
+    if ((SrcType->isRealType() && !SrcType->isVectorType()) ||
+        SrcType->isEnumeralType())
+    {
+      return;
+    }
+  }
+
+  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
+  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
+  // (This is a practical limitation.)
+  if (IsStaticPointerDowncast(SrcType, DestType)) {
+    return;
+  }
+
+  // Reverse member pointer conversion. C++ 5.11 specifies member pointer
+  // conversion. C++ 5.2.9p9 has additional information.
+  // DR54's access restrictions apply here also.
+  // FIXME: Don't have member pointers yet.
+
+  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
+  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
+  // just the usual constness stuff.
+  if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
+    QualType SrcPointee = SrcPointer->getPointeeType();
+    if (SrcPointee.getUnqualifiedType() == Context.VoidTy) {
+      if (const PointerType *DestPointer = DestType->getAsPointerType()) {
+        QualType DestPointee = DestPointer->getPointeeType();
+        if (DestPointee->isObjectType() &&
+            DestPointee.isAtLeastAsQualifiedAs(SrcPointee))
+        {
+          return;
+        }
+      }
+    }
+  }
+
+  // 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.
+  Diag(OpLoc, diag::err_bad_cxx_cast_generic, "static_cast",
+    OrigDestType.getAsString(), OrigSrcType.getAsString());
+}
+
+/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
+bool
+Sema::IsStaticReferenceDowncast(Expr *SrcExpr, QualType DestType)
+{
+  // 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,
+  //   if a valid standard conversion from "pointer to D" to "pointer to B"
+  //   exists, cv2 >= cv1, and B is not a virtual base class of D.
+  // In addition, DR54 clarifies that the base must be accessible in the
+  // current context. Although the wording of DR54 only applies to the pointer
+  // variant of this rule, the intent is clearly for it to apply to the this
+  // conversion as well.
+
+  if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
+    return false;
+  }
+
+  DestType = Context.getCanonicalType(DestType);
+  const ReferenceType *DestReference = DestType->getAsReferenceType();
+  if (!DestReference) {
+    return false;
+  }
+  QualType DestPointee = DestReference->getPointeeType();
+
+  QualType SrcType = Context.getCanonicalType(SrcExpr->getType());
+
+  return IsStaticDowncast(SrcType, DestPointee);
+}
+
+/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
+bool
+Sema::IsStaticPointerDowncast(QualType SrcType, QualType DestType)
+{
+  // 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
+  //   is a class derived from B, if a valid standard conversion from "pointer
+  //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
+  //   class of D.
+  // In addition, DR54 clarifies that the base must be accessible in the
+  // current context.
+
+  SrcType = Context.getCanonicalType(SrcType);
+  const PointerType *SrcPointer = SrcType->getAsPointerType();
+  if (!SrcPointer) {
+    return false;
+  }
+
+  DestType = Context.getCanonicalType(DestType);
+  const PointerType *DestPointer = DestType->getAsPointerType();
+  if (!DestPointer) {
+    return false;
+  }
+
+  return IsStaticDowncast(SrcPointer->getPointeeType(),
+                          DestPointer->getPointeeType());
+}
+
+/// IsStaticDowncast - Common functionality of IsStaticReferenceDowncast and
+/// IsStaticPointerDowncast. Tests whether a static downcast from SrcType to
+/// DestType, both of which must be canonical, is possible and allowed.
+bool
+Sema::IsStaticDowncast(QualType SrcType, QualType DestType)
+{
+  assert(SrcType->isCanonical());
+  assert(DestType->isCanonical());
+
+  if (!DestType->isRecordType()) {
+    return false;
+  }
+
+  if (!SrcType->isRecordType()) {
+    return false;
+  }
+
+  // Comparing cv is cheaper, so do it first.
+  if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
+    return false;
+  }
+
+  BasePaths Paths; // Finds ambiguities and records.
+  if (!IsDerivedFrom(DestType, SrcType, Paths)) {
+    return false;
+  }
+
+  if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
+    return false;
+  }
+
+  BasePaths::paths_iterator Path = Paths.begin(), Path2 = Path;
+  ++Path2;
+  if (Path2 != Paths.end()) {
+    // If there is more than one path, but there's no ambiguity, there's got
+    // to be a virtual inheritance in the paths.
+    return false;
+  }
+
+  for (BasePath::const_iterator PElem = Path->begin();
+       PElem != Path->end(); ++PElem)
+  {
+    if (PElem->Base->isVirtual()) {
+      return false;
+    }
+  }
+
+  // FIXME: Test accessibility.
+
+  return true;
+}
+
+/// TryDirectInitialization - Attempt to direct-initialize a value of the
+/// given type (DestType) from the given expression (SrcExpr), as one would
+/// do when creating an object with new with parameters. This function returns
+/// an implicit conversion sequence that can be used to perform the
+/// initialization.
+/// This routine is very similar to TryCopyInitialization; the differences
+/// between the two (C++ 8.5p12 and C++ 8.5p14) are:
+/// 1) In direct-initialization, all constructors of the target type are
+///    considered, including those marked as explicit.
+/// 2) In direct-initialization, overload resolution is performed over the
+///    constructors of the target type. In copy-initialization, overload
+///    resolution is performed over all conversion functions that result in
+///    the target type. This can lead to different functions used.
+ImplicitConversionSequence
+Sema::TryDirectInitialization(Expr *SrcExpr, QualType DestType)
+{
+  if (!DestType->isRecordType()) {
+    // For non-class types, copy and direct initialization are identical.
+    // C++ 8.5p11
+    // FIXME: Those parts should be in a common function, actually.
+    return TryCopyInitialization(SrcExpr, DestType);
+  }
+
+  // Not enough support for the rest yet, actually.
+  ImplicitConversionSequence ICS;
+  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
+  return ICS;
+}
+
+/// 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
+Sema::CheckDynamicCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType,
+  const SourceRange &DestRange)
+{
   QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
   DestType = Context.getCanonicalType(DestType);
-  // Tests are ordered by simplicity and a wild guess at commonness.
 
-  if (const BuiltinType *BuiltinDest = DestType->getAsBuiltinType()) {
-    // 5.2.9/4
-    if (BuiltinDest->getKind() == BuiltinType::Void) {
+  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
+  //   or "pointer to cv void".
+
+  QualType DestPointee;
+  const PointerType *DestPointer = DestType->getAsPointerType();
+  const ReferenceType *DestReference = DestType->getAsReferenceType();
+  if (DestPointer) {
+    DestPointee = DestPointer->getPointeeType();
+  } else if (DestReference) {
+    DestPointee = DestReference->getPointeeType();
+  } else {
+    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+      OrigDestType.getAsString(), "not a reference or pointer", DestRange);
+    return;
+  }
+
+  const RecordType *DestRecord = DestPointee->getAsRecordType();
+  if (DestPointee->isVoidType()) {
+    // Reference to void should be impossible.
+    assert(DestPointer);
+  } else if (DestRecord) {
+    if (!DestRecord->getDecl()->isDefinition()) {
+      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+        DestPointee.getUnqualifiedType().getAsString(),
+        "incomplete", DestRange);
       return;
     }
+  } else {
+    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+      DestPointee.getUnqualifiedType().getAsString(),
+      "not a class", DestRange);
+    return;
+  }
 
-    // Primitive conversions for 5.2.9/2 and 6.
+  // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
+  //   complete class type, [...]. If T is a reference type, v shall be an
+  //   lvalue of a complete class type, [...].
+
+  QualType SrcType = Context.getCanonicalType(OrigSrcType);
+  QualType SrcPointee;
+  if (DestPointer) {
+    if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
+      SrcPointee = SrcPointer->getPointeeType();
+    } else {
+      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+        OrigSrcType.getAsString(), "not a pointer", SrcExpr->getSourceRange());
+      return;
+    }
+  } else {
+    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
+      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+        OrigDestType.getAsString(), "not an lvalue", SrcExpr->getSourceRange());
+    }
+    SrcPointee = SrcType;
   }
-#endif
+
+  const RecordType *SrcRecord = SrcPointee->getAsRecordType();
+  if (SrcRecord) {
+    if (!SrcRecord->getDecl()->isDefinition()) {
+      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+        SrcPointee.getUnqualifiedType().getAsString(), "incomplete",
+        SrcExpr->getSourceRange());
+      return;
+    }
+  } else {
+    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
+      SrcPointee.getUnqualifiedType().getAsString(), "not a class",
+      SrcExpr->getSourceRange());
+    return;
+  }
+
+  // Assumptions to this point.
+  assert(DestPointer || DestReference);
+  assert(DestRecord || DestPointee->isVoidType());
+  assert(SrcRecord);
+
+  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
+  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
+    Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "dynamic_cast",
+      OrigDestType.getAsString(), OrigSrcType.getAsString());
+    return;
+  }
+
+  // C++ 5.2.7p3: If the type of v is the same as the required result type,
+  //   [except for cv].
+  if (DestRecord == SrcRecord) {
+    return;
+  }
+
+  // C++ 5.2.7p5
+  // Upcasts are resolved statically.
+  if (DestRecord && IsDerivedFrom(SrcPointee, DestPointee)) {
+    CheckDerivedToBaseConversion(SrcPointee, DestPointee, OpLoc, SourceRange());
+    // Diagnostic already emitted on error.
+    return;
+  }
+
+  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
+  // FIXME: Information not yet available.
+
+  // Done. Everything else is run-time checks.
 }
 
 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
Index: lib/Sema/SemaOverload.cpp
===================================================================
--- lib/Sema/SemaOverload.cpp	(revision 58328)
+++ lib/Sema/SemaOverload.cpp	(working copy)
@@ -447,8 +447,9 @@
     FromType = ToType.getUnqualifiedType();
   } 
   // Integral conversions (C++ 4.7).
+  // FIXME: isIntegralType shouldn't be true for enums in C++.
   else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
-           (ToType->isIntegralType() || ToType->isEnumeralType())) {
+           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
     ICS.Standard.Second = ICK_Integral_Conversion;
     FromType = ToType.getUnqualifiedType();
   }
@@ -458,16 +459,19 @@
     FromType = ToType.getUnqualifiedType();
   }
   // Floating-integral conversions (C++ 4.9).
+  // FIXME: isIntegralType shouldn't be true for enums in C++.
   else if ((FromType->isFloatingType() &&
-            ToType->isIntegralType() && !ToType->isBooleanType()) ||
+            ToType->isIntegralType() && !ToType->isBooleanType() &&
+                                        !ToType->isEnumeralType()) ||
            ((FromType->isIntegralType() || FromType->isEnumeralType()) && 
             ToType->isFloatingType())) {
     ICS.Standard.Second = ICK_Floating_Integral;
     FromType = ToType.getUnqualifiedType();
   }
   // Pointer conversions (C++ 4.10).
-  else if (IsPointerConversion(From, FromType, ToType, FromType))
+  else if (IsPointerConversion(From, FromType, ToType, FromType)) {
     ICS.Standard.Second = ICK_Pointer_Conversion;
+  }
   // FIXME: Pointer to member conversions (4.11).
   // Boolean conversions (C++ 4.12).
   // FIXME: pointer-to-member type
@@ -507,21 +511,25 @@
 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
 {
   const BuiltinType *To = ToType->getAsBuiltinType();
+  if (!To) {
+    return false;
+  }
 
   // An rvalue of type char, signed char, unsigned char, short int, or
   // unsigned short int can be converted to an rvalue of type int if
   // int can represent all the values of the source type; otherwise,
   // the source rvalue can be converted to an rvalue of type unsigned
   // int (C++ 4.5p1).
-  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && To) {
+  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
     if (// We can promote any signed, promotable integer type to an int
         (FromType->isSignedIntegerType() ||
          // We can promote any unsigned integer type whose size is
          // less than int to an int.
          (!FromType->isSignedIntegerType() && 
-          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))))
+          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
       return To->getKind() == BuiltinType::Int;
-        
+    }
+
     return To->getKind() == BuiltinType::UInt;
   }
 
@@ -557,7 +565,7 @@
         // We found the type that we can promote to. If this is the
         // type we wanted, we have a promotion. Otherwise, no
         // promotion.
-        return Context.getCanonicalType(FromType).getUnqualifiedType()
+        return Context.getCanonicalType(ToType).getUnqualifiedType()
           == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
       }
     }
@@ -581,13 +589,15 @@
 
       // Are we promoting to an int from a bitfield that fits in an int?
       if (BitWidth < ToSize ||
-          (FromType->isSignedIntegerType() && BitWidth <= ToSize))
+          (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
         return To->getKind() == BuiltinType::Int;
-        
+      }
+
       // Are we promoting to an unsigned int from an unsigned bitfield
       // that fits into an unsigned int?
-      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize)
+      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
         return To->getKind() == BuiltinType::UInt;
+      }
 
       return false;
     }
@@ -595,8 +605,9 @@
 
   // An rvalue of type bool can be converted to an rvalue of type int,
   // with false becoming zero and true becoming one (C++ 4.5p4).
-  if (FromType->isBooleanType() && To && To->getKind() == BuiltinType::Int)
+  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
     return true;
+  }
 
   return false;
 }
@@ -635,7 +646,7 @@
     ConvertedType = ToType;
     return true;
   }
-  
+
   // An rvalue of type "pointer to cv T," where T is an object type,
   // can be converted to an rvalue of type "pointer to cv void" (C++
   // 4.10p2).
Index: lib/Sema/Sema.h
===================================================================
--- lib/Sema/Sema.h	(revision 58328)
+++ lib/Sema/Sema.h	(working copy)
@@ -702,13 +702,22 @@
                                        SourceLocation LParenLoc, ExprTy *E,
                                        SourceLocation RParenLoc);
 
+private:
   // Helpers for ActOnCXXCasts
-  bool CastsAwayConstness(QualType SrcType, QualType DestType);
   void CheckConstCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType);
   void CheckReinterpretCast(SourceLocation OpLoc, Expr *&SrcExpr,
                             QualType DestType);
   void CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType);
+  void CheckDynamicCast(SourceLocation OpLoc, Expr *&SrcExpr,
+                        QualType DestType, const SourceRange &DestRange);
+  bool CastsAwayConstness(QualType SrcType, QualType DestType);
+  bool IsStaticReferenceDowncast(Expr *SrcExpr, QualType DestType);
+  bool IsStaticPointerDowncast(QualType SrcType, QualType DestType);
+  bool IsStaticDowncast(QualType SrcType, QualType DestType);
+  ImplicitConversionSequence TryDirectInitialization(Expr *SrcExpr,
+                                                     QualType DestType);
 
+public:
   //// ActOnCXXThis -  Parse 'this' pointer.
   virtual ExprResult ActOnCXXThis(SourceLocation ThisLoc);
 
Index: lib/AST/Expr.cpp
===================================================================
--- lib/AST/Expr.cpp	(revision 58328)
+++ lib/AST/Expr.cpp	(working copy)
@@ -1073,15 +1073,17 @@
 /// integer constant expression with the value zero, or if this is one that is
 /// cast to void*.
 bool Expr::isNullPointerConstant(ASTContext &Ctx) const {
-  // Strip off a cast to void*, if it exists.
+  // Strip off a cast to void*, if it exists. Except in C++.
   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
-    // Check that it is a cast to void*.
-    if (const PointerType *PT = CE->getType()->getAsPointerType()) {
-      QualType Pointee = PT->getPointeeType();
-      if (Pointee.getCVRQualifiers() == 0 && 
-          Pointee->isVoidType() &&                                 // to void*
-          CE->getSubExpr()->getType()->isIntegerType())            // from int.
-        return CE->getSubExpr()->isNullPointerConstant(Ctx);
+    if(!Ctx.getLangOptions().CPlusPlus) {
+      // Check that it is a cast to void*.
+      if (const PointerType *PT = CE->getType()->getAsPointerType()) {
+        QualType Pointee = PT->getPointeeType();
+        if (Pointee.getCVRQualifiers() == 0 && 
+            Pointee->isVoidType() &&                              // to void*
+            CE->getSubExpr()->getType()->isIntegerType())         // from int.
+          return CE->getSubExpr()->isNullPointerConstant(Ctx);
+      }
     }
   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
     // Ignore the ImplicitCastExpr type entirely.
