clang API Documentation

SemaCXXCast.cpp

Go to the documentation of this file.
00001 //===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ named casts.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "clang/AST/ExprCXX.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/CXXInheritance.h"
00019 #include "clang/Basic/PartialDiagnostic.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include <set>
00022 using namespace clang;
00023 
00024 enum TryCastResult {
00025   TC_NotApplicable, ///< The cast method is not applicable.
00026   TC_Success,       ///< The cast method is appropriate and successful.
00027   TC_Failed         ///< The cast method is appropriate, but failed. A
00028                     ///< diagnostic has been emitted.
00029 };
00030 
00031 enum CastType {
00032   CT_Const,       ///< const_cast
00033   CT_Static,      ///< static_cast
00034   CT_Reinterpret, ///< reinterpret_cast
00035   CT_Dynamic,     ///< dynamic_cast
00036   CT_CStyle,      ///< (Type)expr
00037   CT_Functional   ///< Type(expr)
00038 };
00039 
00040 static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00041                            const SourceRange &OpRange,
00042                            const SourceRange &DestRange);
00043 static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00044                                  const SourceRange &OpRange,
00045                                  const SourceRange &DestRange,
00046                                  CastExpr::CastKind &Kind);
00047 static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00048                             const SourceRange &OpRange,
00049                             CastExpr::CastKind &Kind,
00050                             CXXMethodDecl *&ConversionDecl);
00051 static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00052                              const SourceRange &OpRange,
00053                              const SourceRange &DestRange,
00054                              CastExpr::CastKind &Kind);
00055 
00056 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
00057 
00058 // The Try functions attempt a specific way of casting. If they succeed, they
00059 // return TC_Success. If their way of casting is not appropriate for the given
00060 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
00061 // to emit if no other way succeeds. If their way of casting is appropriate but
00062 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
00063 // they emit a specialized diagnostic.
00064 // All diagnostics returned by these functions must expect the same three
00065 // arguments:
00066 // %0: Cast Type (a value from the CastType enumeration)
00067 // %1: Source Type
00068 // %2: Destination Type
00069 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
00070                                            QualType DestType, unsigned &msg);
00071 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
00072                                                 QualType DestType, bool CStyle,
00073                                                 const SourceRange &OpRange,
00074                                                 unsigned &msg,
00075                                                 CastExpr::CastKind &Kind);
00076 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
00077                                               QualType DestType, bool CStyle,
00078                                               const SourceRange &OpRange,
00079                                               unsigned &msg,
00080                                               CastExpr::CastKind &Kind);
00081 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
00082                                        CanQualType DestType, bool CStyle,
00083                                        const SourceRange &OpRange,
00084                                        QualType OrigSrcType,
00085                                        QualType OrigDestType, unsigned &msg,
00086                                        CastExpr::CastKind &Kind);
00087 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
00088                                                   QualType SrcType,
00089                                                   QualType DestType,bool CStyle,
00090                                                   const SourceRange &OpRange,
00091                                                   unsigned &msg,
00092                                                   CastExpr::CastKind &Kind);
00093 static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
00094                                            QualType DestType, bool CStyle,
00095                                            const SourceRange &OpRange,
00096                                            unsigned &msg,
00097                                            CastExpr::CastKind &Kind,
00098                                            CXXMethodDecl *&ConversionDecl);
00099 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
00100                                    QualType DestType, bool CStyle,
00101                                    const SourceRange &OpRange,
00102                                    unsigned &msg,
00103                                    CastExpr::CastKind &Kind,
00104                                    CXXMethodDecl *&ConversionDecl);
00105 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00106                                   bool CStyle, unsigned &msg);
00107 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
00108                                         QualType DestType, bool CStyle,
00109                                         const SourceRange &OpRange,
00110                                         unsigned &msg,
00111                                         CastExpr::CastKind &Kind);
00112 
00113 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
00114 Action::OwningExprResult
00115 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00116                         SourceLocation LAngleBracketLoc, TypeTy *Ty,
00117                         SourceLocation RAngleBracketLoc,
00118                         SourceLocation LParenLoc, ExprArg E,
00119                         SourceLocation RParenLoc) {
00120   
00121   TypeSourceInfo *DestTInfo;
00122   QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
00123   if (!DestTInfo)
00124     DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
00125 
00126   return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
00127                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
00128                            SourceRange(LParenLoc, RParenLoc));
00129 }
00130 
00131 Action::OwningExprResult
00132 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00133                         TypeSourceInfo *DestTInfo, ExprArg E,
00134                         SourceRange AngleBrackets, SourceRange Parens) {
00135   Expr *Ex = E.takeAs<Expr>();
00136   QualType DestType = DestTInfo->getType();
00137 
00138   SourceRange OpRange(OpLoc, Parens.getEnd());
00139   SourceRange DestRange = AngleBrackets;
00140 
00141   // If the type is dependent, we won't do the semantic analysis now.
00142   // FIXME: should we check this in a more fine-grained manner?
00143   bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
00144 
00145   switch (Kind) {
00146   default: assert(0 && "Unknown C++ cast!");
00147 
00148   case tok::kw_const_cast:
00149     if (!TypeDependent)
00150       CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
00151     return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
00152                                                 Ex, DestTInfo, OpLoc));
00153 
00154   case tok::kw_dynamic_cast: {
00155     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00156     if (!TypeDependent)
00157       CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
00158     return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
00159                                                  Kind, Ex, DestTInfo, OpLoc));
00160   }
00161   case tok::kw_reinterpret_cast: {
00162     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00163     if (!TypeDependent)
00164       CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
00165     return Owned(new (Context) CXXReinterpretCastExpr(
00166                                   DestType.getNonReferenceType(),
00167                                   Kind, Ex, DestTInfo, OpLoc));
00168   }
00169   case tok::kw_static_cast: {
00170     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00171     if (!TypeDependent) {
00172       CXXMethodDecl *Method = 0;
00173       
00174       CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
00175       
00176       if (Method) {
00177         OwningExprResult CastArg 
00178           = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(), 
00179                                  Kind, Method, Owned(Ex));
00180           if (CastArg.isInvalid())
00181             return ExprError();
00182           
00183           Ex = CastArg.takeAs<Expr>();
00184       }
00185     }
00186     
00187     return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
00188                                                  Kind, Ex, DestTInfo, OpLoc));
00189   }
00190   }
00191 
00192   return ExprError();
00193 }
00194 
00195 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
00196 /// this removes one level of indirection from both types, provided that they're
00197 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
00198 /// this one doesn't care if the two pointers-to-member don't point into the
00199 /// same class. This is because CastsAwayConstness doesn't care.
00200 bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
00201   const PointerType *T1PtrType = T1->getAs<PointerType>(),
00202                     *T2PtrType = T2->getAs<PointerType>();
00203   if (T1PtrType && T2PtrType) {
00204     T1 = T1PtrType->getPointeeType();
00205     T2 = T2PtrType->getPointeeType();
00206     return true;
00207   }
00208   const ObjCObjectPointerType *T1ObjCPtrType = 
00209                                             T1->getAs<ObjCObjectPointerType>(),
00210                               *T2ObjCPtrType = 
00211                                             T2->getAs<ObjCObjectPointerType>();
00212   if (T1ObjCPtrType) {
00213     if (T2ObjCPtrType) {
00214       T1 = T1ObjCPtrType->getPointeeType();
00215       T2 = T2ObjCPtrType->getPointeeType();
00216       return true;
00217     }
00218     else if (T2PtrType) {
00219       T1 = T1ObjCPtrType->getPointeeType();
00220       T2 = T2PtrType->getPointeeType();
00221       return true;
00222     }
00223   }
00224   else if (T2ObjCPtrType) {
00225     if (T1PtrType) {
00226       T2 = T2ObjCPtrType->getPointeeType();
00227       T1 = T1PtrType->getPointeeType();
00228       return true;
00229     }
00230   }
00231   
00232   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
00233                           *T2MPType = T2->getAs<MemberPointerType>();
00234   if (T1MPType && T2MPType) {
00235     T1 = T1MPType->getPointeeType();
00236     T2 = T2MPType->getPointeeType();
00237     return true;
00238   }
00239   return false;
00240 }
00241 
00242 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
00243 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
00244 /// the cast checkers.  Both arguments must denote pointer (possibly to member)
00245 /// types.
00246 static bool
00247 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
00248   // Casting away constness is defined in C++ 5.2.11p8 with reference to
00249   // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
00250   // the rules are non-trivial. So first we construct Tcv *...cv* as described
00251   // in C++ 5.2.11p8.
00252   assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
00253          "Source type is not pointer or pointer to member.");
00254   assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
00255          "Destination type is not pointer or pointer to member.");
00256 
00257   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 
00258            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
00259   llvm::SmallVector<Qualifiers, 8> cv1, cv2;
00260 
00261   // Find the qualifications.
00262   while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
00263     cv1.push_back(UnwrappedSrcType.getQualifiers());
00264     cv2.push_back(UnwrappedDestType.getQualifiers());
00265   }
00266   assert(cv1.size() > 0 && "Must have at least one pointer level.");
00267 
00268   // Construct void pointers with those qualifiers (in reverse order of
00269   // unwrapping, of course).
00270   QualType SrcConstruct = Self.Context.VoidTy;
00271   QualType DestConstruct = Self.Context.VoidTy;
00272   ASTContext &Context = Self.Context;
00273   for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
00274                                                           i2 = cv2.rbegin();
00275        i1 != cv1.rend(); ++i1, ++i2) {
00276     SrcConstruct
00277       = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
00278     DestConstruct
00279       = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
00280   }
00281 
00282   // Test if they're compatible.
00283   return SrcConstruct != DestConstruct &&
00284     !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
00285 }
00286 
00287 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid.
00288 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
00289 /// checked downcasts in class hierarchies.
00290 static void
00291 CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00292                  const SourceRange &OpRange,
00293                  const SourceRange &DestRange, CastExpr::CastKind &Kind) {
00294   QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
00295   DestType = Self.Context.getCanonicalType(DestType);
00296 
00297   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
00298   //   or "pointer to cv void".
00299 
00300   QualType DestPointee;
00301   const PointerType *DestPointer = DestType->getAs<PointerType>();
00302   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
00303   if (DestPointer) {
00304     DestPointee = DestPointer->getPointeeType();
00305   } else if (DestReference) {
00306     DestPointee = DestReference->getPointeeType();
00307   } else {
00308     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
00309       << OrigDestType << DestRange;
00310     return;
00311   }
00312 
00313   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
00314   if (DestPointee->isVoidType()) {
00315     assert(DestPointer && "Reference to void is not possible");
00316   } else if (DestRecord) {
00317     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
00318                                  PDiag(diag::err_bad_dynamic_cast_incomplete)
00319                                    << DestRange))
00320       return;
00321   } else {
00322     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00323       << DestPointee.getUnqualifiedType() << DestRange;
00324     return;
00325   }
00326 
00327   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
00328   //   complete class type, [...]. If T is an lvalue reference type, v shall be
00329   //   an lvalue of a complete class type, [...]. If T is an rvalue reference
00330   //   type, v shall be an expression having a complete effective class type,
00331   //   [...]
00332 
00333   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
00334   QualType SrcPointee;
00335   if (DestPointer) {
00336     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
00337       SrcPointee = SrcPointer->getPointeeType();
00338     } else {
00339       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
00340         << OrigSrcType << SrcExpr->getSourceRange();
00341       return;
00342     }
00343   } else if (DestReference->isLValueReferenceType()) {
00344     if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00345       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
00346         << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
00347     }
00348     SrcPointee = SrcType;
00349   } else {
00350     SrcPointee = SrcType;
00351   }
00352 
00353   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
00354   if (SrcRecord) {
00355     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
00356                                  PDiag(diag::err_bad_dynamic_cast_incomplete)
00357                                    << SrcExpr->getSourceRange()))
00358       return;
00359   } else {
00360     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00361       << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
00362     return;
00363   }
00364 
00365   assert((DestPointer || DestReference) &&
00366     "Bad destination non-ptr/ref slipped through.");
00367   assert((DestRecord || DestPointee->isVoidType()) &&
00368     "Bad destination pointee slipped through.");
00369   assert(SrcRecord && "Bad source pointee slipped through.");
00370 
00371   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
00372   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
00373     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
00374       << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
00375     return;
00376   }
00377 
00378   // C++ 5.2.7p3: If the type of v is the same as the required result type,
00379   //   [except for cv].
00380   if (DestRecord == SrcRecord) {
00381     return;
00382   }
00383 
00384   // C++ 5.2.7p5
00385   // Upcasts are resolved statically.
00386   if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
00387     Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
00388                                       OpRange.getBegin(), OpRange);
00389     Kind = CastExpr::CK_DerivedToBase;
00390     // Diagnostic already emitted on error.
00391     return;
00392   }
00393 
00394   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
00395   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
00396   assert(SrcDecl && "Definition missing");
00397   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
00398     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
00399       << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
00400   }
00401 
00402   // Done. Everything else is run-time checks.
00403   Kind = CastExpr::CK_Dynamic;
00404 }
00405 
00406 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid.
00407 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
00408 /// like this:
00409 /// const char *str = "literal";
00410 /// legacy_function(const_cast<char*>(str));
00411 void
00412 CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00413                const SourceRange &OpRange, const SourceRange &DestRange) {
00414   if (!DestType->isLValueReferenceType())
00415     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00416 
00417   unsigned msg = diag::err_bad_cxx_cast_generic;
00418   if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
00419       && msg != 0)
00420     Self.Diag(OpRange.getBegin(), msg) << CT_Const
00421       << SrcExpr->getType() << DestType << OpRange;
00422 }
00423 
00424 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is
00425 /// valid.
00426 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
00427 /// like this:
00428 /// char *bytes = reinterpret_cast<char*>(int_ptr);
00429 void
00430 CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00431                      const SourceRange &OpRange, const SourceRange &DestRange,
00432                      CastExpr::CastKind &Kind) {
00433   if (!DestType->isLValueReferenceType())
00434     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00435 
00436   unsigned msg = diag::err_bad_cxx_cast_generic;
00437   if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
00438                          msg, Kind)
00439       != TC_Success && msg != 0)
00440     Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
00441       << SrcExpr->getType() << DestType << OpRange;
00442 }
00443 
00444 
00445 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid.
00446 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
00447 /// implicit conversions explicit and getting rid of data loss warnings.
00448 void
00449 CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00450                 const SourceRange &OpRange, CastExpr::CastKind &Kind,
00451                 CXXMethodDecl *&ConversionDecl) {
00452   // This test is outside everything else because it's the only case where
00453   // a non-lvalue-reference target type does not lead to decay.
00454   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00455   if (DestType->isVoidType()) {
00456     Kind = CastExpr::CK_ToVoid;
00457     return;
00458   }
00459 
00460   if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
00461     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00462 
00463   unsigned msg = diag::err_bad_cxx_cast_generic;
00464   if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
00465                     Kind, ConversionDecl)
00466       != TC_Success && msg != 0)
00467     Self.Diag(OpRange.getBegin(), msg) << CT_Static
00468       << SrcExpr->getType() << DestType << OpRange;
00469 }
00470 
00471 /// TryStaticCast - Check if a static cast can be performed, and do so if
00472 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
00473 /// and casting away constness.
00474 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
00475                                    QualType DestType, bool CStyle,
00476                                    const SourceRange &OpRange, unsigned &msg,
00477                                    CastExpr::CastKind &Kind,
00478                                    CXXMethodDecl *&ConversionDecl) {
00479   // The order the tests is not entirely arbitrary. There is one conversion
00480   // that can be handled in two different ways. Given:
00481   // struct A {};
00482   // struct B : public A {
00483   //   B(); B(const A&);
00484   // };
00485   // const A &a = B();
00486   // the cast static_cast<const B&>(a) could be seen as either a static
00487   // reference downcast, or an explicit invocation of the user-defined
00488   // conversion using B's conversion constructor.
00489   // DR 427 specifies that the downcast is to be applied here.
00490 
00491   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00492   // Done outside this function.
00493 
00494   TryCastResult tcr;
00495 
00496   // C++ 5.2.9p5, reference downcast.
00497   // See the function for details.
00498   // DR 427 specifies that this is to be applied before paragraph 2.
00499   tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
00500                                    msg, Kind);
00501   if (tcr != TC_NotApplicable)
00502     return tcr;
00503 
00504   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
00505   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
00506   tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
00507   if (tcr != TC_NotApplicable) {
00508     Kind = CastExpr::CK_NoOp;
00509     return tcr;
00510   }
00511 
00512   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
00513   //   [...] if the declaration "T t(e);" is well-formed, [...].
00514   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
00515                               Kind, ConversionDecl);
00516   if (tcr != TC_NotApplicable)
00517     return tcr;
00518   
00519   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
00520   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
00521   // conversions, subject to further restrictions.
00522   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
00523   // of qualification conversions impossible.
00524   // In the CStyle case, the earlier attempt to const_cast should have taken
00525   // care of reverse qualification conversions.
00526 
00527   QualType OrigSrcType = SrcExpr->getType();
00528 
00529   QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
00530 
00531   // Reverse integral promotion/conversion. All such conversions are themselves
00532   // again integral promotions or conversions and are thus already handled by
00533   // p2 (TryDirectInitialization above).
00534   // (Note: any data loss warnings should be suppressed.)
00535   // The exception is the reverse of enum->integer, i.e. integer->enum (and
00536   // enum->enum). See also C++ 5.2.9p7.
00537   // The same goes for reverse floating point promotion/conversion and
00538   // floating-integral conversions. Again, only floating->enum is relevant.
00539   if (DestType->isEnumeralType()) {
00540     if (SrcType->isComplexType() || SrcType->isVectorType()) {
00541       // Fall through - these cannot be converted.
00542     } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
00543       Kind = CastExpr::CK_IntegralCast;
00544       return TC_Success;
00545     }
00546   }
00547 
00548   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
00549   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
00550   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
00551                                  Kind);
00552   if (tcr != TC_NotApplicable)
00553     return tcr;
00554 
00555   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
00556   // conversion. C++ 5.2.9p9 has additional information.
00557   // DR54's access restrictions apply here also.
00558   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
00559                                      OpRange, msg, Kind);
00560   if (tcr != TC_NotApplicable)
00561     return tcr;
00562 
00563   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
00564   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
00565   // just the usual constness stuff.
00566   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
00567     QualType SrcPointee = SrcPointer->getPointeeType();
00568     if (SrcPointee->isVoidType()) {
00569       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
00570         QualType DestPointee = DestPointer->getPointeeType();
00571         if (DestPointee->isIncompleteOrObjectType()) {
00572           // This is definitely the intended conversion, but it might fail due
00573           // to a const violation.
00574           if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
00575             msg = diag::err_bad_cxx_cast_const_away;
00576             return TC_Failed;
00577           }
00578           Kind = CastExpr::CK_BitCast;
00579           return TC_Success;
00580         }
00581       }
00582       else if (CStyle && DestType->isObjCObjectPointerType()) {
00583         // allow c-style cast of objective-c pointers as they are pervasive.
00584         Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
00585         return TC_Success;
00586       }
00587       else if (CStyle && DestType->isBlockPointerType()) {
00588         // allow c-style cast of void * to block pointers.
00589         Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
00590         return TC_Success;
00591       }
00592     }
00593   }
00594 
00595   // We tried everything. Everything! Nothing works! :-(
00596   return TC_NotApplicable;
00597 }
00598 
00599 /// Tests whether a conversion according to N2844 is valid.
00600 TryCastResult
00601 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00602                       unsigned &msg) {
00603   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
00604   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
00605   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
00606   if (!R)
00607     return TC_NotApplicable;
00608 
00609   if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
00610     return TC_NotApplicable;
00611 
00612   // Because we try the reference downcast before this function, from now on
00613   // this is the only cast possibility, so we issue an error if we fail now.
00614   // FIXME: Should allow casting away constness if CStyle.
00615   bool DerivedToBase;
00616   if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
00617                                         SrcExpr->getType(), R->getPointeeType(),
00618                                         DerivedToBase) <
00619         Sema::Ref_Compatible_With_Added_Qualification) {
00620     msg = diag::err_bad_lvalue_to_rvalue_cast;
00621     return TC_Failed;
00622   }
00623 
00624   // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
00625   // than nothing.
00626   return TC_Success;
00627 }
00628 
00629 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
00630 TryCastResult
00631 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
00632                            bool CStyle, const SourceRange &OpRange,
00633                            unsigned &msg, CastExpr::CastKind &Kind) {
00634   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
00635   //   cast to type "reference to cv2 D", where D is a class derived from B,
00636   //   if a valid standard conversion from "pointer to D" to "pointer to B"
00637   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
00638   // In addition, DR54 clarifies that the base must be accessible in the
00639   // current context. Although the wording of DR54 only applies to the pointer
00640   // variant of this rule, the intent is clearly for it to apply to the this
00641   // conversion as well.
00642 
00643   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
00644   if (!DestReference) {
00645     return TC_NotApplicable;
00646   }
00647   bool RValueRef = DestReference->isRValueReferenceType();
00648   if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00649     // We know the left side is an lvalue reference, so we can suggest a reason.
00650     msg = diag::err_bad_cxx_cast_rvalue;
00651     return TC_NotApplicable;
00652   }
00653 
00654   QualType DestPointee = DestReference->getPointeeType();
00655 
00656   return TryStaticDowncast(Self, 
00657                            Self.Context.getCanonicalType(SrcExpr->getType()), 
00658                            Self.Context.getCanonicalType(DestPointee), CStyle,
00659                            OpRange, SrcExpr->getType(), DestType, msg, Kind);
00660 }
00661 
00662 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
00663 TryCastResult
00664 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
00665                          bool CStyle, const SourceRange &OpRange,
00666                          unsigned &msg, CastExpr::CastKind &Kind) {
00667   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
00668   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
00669   //   is a class derived from B, if a valid standard conversion from "pointer
00670   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
00671   //   class of D.
00672   // In addition, DR54 clarifies that the base must be accessible in the
00673   // current context.
00674 
00675   const PointerType *DestPointer = DestType->getAs<PointerType>();
00676   if (!DestPointer) {
00677     return TC_NotApplicable;
00678   }
00679 
00680   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
00681   if (!SrcPointer) {
00682     msg = diag::err_bad_static_cast_pointer_nonpointer;
00683     return TC_NotApplicable;
00684   }
00685 
00686   return TryStaticDowncast(Self, 
00687                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
00688                   Self.Context.getCanonicalType(DestPointer->getPointeeType()), 
00689                            CStyle, OpRange, SrcType, DestType, msg, Kind);
00690 }
00691 
00692 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
00693 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
00694 /// DestType is possible and allowed.
00695 TryCastResult
00696 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
00697                   bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
00698                   QualType OrigDestType, unsigned &msg, 
00699                   CastExpr::CastKind &Kind) {
00700   // We can only work with complete types. But don't complain if it doesn't work
00701   if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
00702       Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
00703     return TC_NotApplicable;
00704 
00705   // Downcast can only happen in class hierarchies, so we need classes.
00706   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
00707     return TC_NotApplicable;
00708   }
00709 
00710   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
00711                      /*DetectVirtual=*/true);
00712   if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
00713     return TC_NotApplicable;
00714   }
00715 
00716   // Target type does derive from source type. Now we're serious. If an error
00717   // appears now, it's not ignored.
00718   // This may not be entirely in line with the standard. Take for example:
00719   // struct A {};
00720   // struct B : virtual A {
00721   //   B(A&);
00722   // };
00723   //
00724   // void f()
00725   // {
00726   //   (void)static_cast<const B&>(*((A*)0));
00727   // }
00728   // As far as the standard is concerned, p5 does not apply (A is virtual), so
00729   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
00730   // However, both GCC and Comeau reject this example, and accepting it would
00731   // mean more complex code if we're to preserve the nice error message.
00732   // FIXME: Being 100% compliant here would be nice to have.
00733 
00734   // Must preserve cv, as always, unless we're in C-style mode.
00735   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
00736     msg = diag::err_bad_cxx_cast_const_away;
00737     return TC_Failed;
00738   }
00739 
00740   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
00741     // This code is analoguous to that in CheckDerivedToBaseConversion, except
00742     // that it builds the paths in reverse order.
00743     // To sum up: record all paths to the base and build a nice string from
00744     // them. Use it to spice up the error message.
00745     if (!Paths.isRecordingPaths()) {
00746       Paths.clear();
00747       Paths.setRecordingPaths(true);
00748       Self.IsDerivedFrom(DestType, SrcType, Paths);
00749     }
00750     std::string PathDisplayStr;
00751     std::set<unsigned> DisplayedPaths;
00752     for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
00753          PI != PE; ++PI) {
00754       if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
00755         // We haven't displayed a path to this particular base
00756         // class subobject yet.
00757         PathDisplayStr += "\n    ";
00758         for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
00759                                                  EE = PI->rend();
00760              EI != EE; ++EI)
00761           PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
00762         PathDisplayStr += QualType(DestType).getAsString();
00763       }
00764     }
00765 
00766     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
00767       << QualType(SrcType).getUnqualifiedType() 
00768       << QualType(DestType).getUnqualifiedType()
00769       << PathDisplayStr << OpRange;
00770     msg = 0;
00771     return TC_Failed;
00772   }
00773 
00774   if (Paths.getDetectedVirtual() != 0) {
00775     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
00776     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
00777       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
00778     msg = 0;
00779     return TC_Failed;
00780   }
00781 
00782   if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
00783                                            /*IsBaseToDerived*/ true,
00784                                            SrcType, DestType,
00785                                            Paths.front())) {
00786     msg = 0;
00787     return TC_Failed;
00788   }
00789 
00790   Kind = CastExpr::CK_BaseToDerived;
00791   return TC_Success;
00792 }
00793 
00794 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
00795 /// C++ 5.2.9p9 is valid:
00796 ///
00797 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
00798 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
00799 ///   where B is a base class of D [...].
00800 ///
00801 TryCastResult
00802 TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType, 
00803                              QualType DestType, bool CStyle, 
00804                              const SourceRange &OpRange,
00805                              unsigned &msg, CastExpr::CastKind &Kind) {
00806   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
00807   if (!DestMemPtr)
00808     return TC_NotApplicable;
00809 
00810   bool WasOverloadedFunction = false;
00811   if (FunctionDecl *Fn
00812           = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false)) {
00813     CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
00814     SrcType = Self.Context.getMemberPointerType(Fn->getType(),
00815                     Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
00816     WasOverloadedFunction = true;
00817   }
00818 
00819   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
00820   if (!SrcMemPtr) {
00821     msg = diag::err_bad_static_cast_member_pointer_nonmp;
00822     return TC_NotApplicable;
00823   }
00824 
00825   // T == T, modulo cv
00826   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
00827                                            DestMemPtr->getPointeeType()))
00828     return TC_NotApplicable;
00829 
00830   // B base of D
00831   QualType SrcClass(SrcMemPtr->getClass(), 0);
00832   QualType DestClass(DestMemPtr->getClass(), 0);
00833   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
00834                   /*DetectVirtual=*/true);
00835   if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
00836     return TC_NotApplicable;
00837   }
00838 
00839   // B is a base of D. But is it an allowed base? If not, it's a hard error.
00840   if (Paths.isAmbiguous(DestClass)) {
00841     Paths.clear();
00842     Paths.setRecordingPaths(true);
00843     bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
00844     assert(StillOkay);
00845     StillOkay = StillOkay;
00846     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
00847     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
00848       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
00849     msg = 0;
00850     return TC_Failed;
00851   }
00852 
00853   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
00854     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
00855       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
00856     msg = 0;
00857     return TC_Failed;
00858   }
00859 
00860   if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
00861                                            /*IsBaseToDerived*/ false,
00862                                            DestType, SrcType,
00863                                            Paths.front())) {
00864     msg = 0;
00865     return TC_Failed;
00866   }
00867 
00868   if (WasOverloadedFunction) {
00869     // Resolve the address of the overloaded function again, this time
00870     // allowing complaints if something goes wrong.
00871     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr, 
00872                                                                DestType, 
00873                                                                true);
00874     if (!Fn) {
00875       msg = 0;
00876       return TC_Failed;
00877     }
00878 
00879     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, Fn);
00880     if (!SrcExpr) {
00881       msg = 0;
00882       return TC_Failed;
00883     }
00884   }
00885 
00886   Kind = CastExpr::CK_DerivedToBaseMemberPointer;
00887   return TC_Success;
00888 }
00889 
00890 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
00891 /// is valid:
00892 ///
00893 ///   An expression e can be explicitly converted to a type T using a
00894 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
00895 TryCastResult
00896 TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00897                       bool CStyle, const SourceRange &OpRange, unsigned &msg,
00898                       CastExpr::CastKind &Kind, 
00899                       CXXMethodDecl *&ConversionDecl) {
00900   if (DestType->isRecordType()) {
00901     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
00902                                  diag::err_bad_dynamic_cast_incomplete)) {
00903       msg = 0;
00904       return TC_Failed;
00905     }
00906   }
00907 
00908   if (DestType->isReferenceType()) {
00909     // All reference bindings insert implicit casts above that do the actual
00910     // casting.
00911     Kind = CastExpr::CK_NoOp;
00912 
00913     // At this point of CheckStaticCast, if the destination is a reference,
00914     // this has to work. There is no other way that works.
00915     // On the other hand, if we're checking a C-style cast, we've still got
00916     // the reinterpret_cast way. So in C-style mode, we first try the call
00917     // with an ICS to suppress errors.
00918     if (CStyle) {
00919       ImplicitConversionSequence ICS;
00920       if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
00921                                  /*SuppressUserConversions=*/false,
00922                                  /*AllowExplicit=*/false, /*ForceRValue=*/false,
00923                                  &ICS))
00924         return TC_NotApplicable;
00925     }
00926     // Now we're committed either way.
00927     if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
00928                                 /*SuppressUserConversions=*/false,
00929                                 /*AllowExplicit=*/false,
00930                                 /*ForceRValue=*/false, 0,
00931                                 /*IgnoreBaseAccess=*/CStyle))
00932       return TC_Success;
00933 
00934     // We already got an error message.
00935     msg = 0;
00936     return TC_Failed;
00937   }
00938 
00939   if (DestType->isRecordType()) {
00940     if (CXXConstructorDecl *Constructor
00941           = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
00942                                                 OpRange.getBegin(),
00943               InitializationKind::CreateDirect(OpRange.getBegin(),
00944                                                OpRange.getBegin(), 
00945                                                OpRange.getEnd()))) {
00946       ConversionDecl = Constructor;
00947       Kind = CastExpr::CK_ConstructorConversion;
00948       return TC_Success;
00949     }
00950     
00951     return TC_NotApplicable;
00952   }
00953 
00954   // FIXME: To get a proper error from invalid conversions here, we need to
00955   // reimplement more of this.
00956   // FIXME: This does not actually perform the conversion, and thus does not
00957   // check for ambiguity or access.
00958   ImplicitConversionSequence ICS =
00959     Self.TryImplicitConversion(SrcExpr, DestType,
00960                                /*SuppressUserConversions=*/false,
00961                                /*AllowExplicit=*/true,
00962                                /*ForceRValue=*/false,
00963                                /*InOverloadResolution=*/false,
00964                                /*one of user provided casts*/true);
00965 
00966   if (ICS.isBad())
00967     return TC_NotApplicable;
00968 
00969   // The conversion is possible, so commit to it.
00970   Kind = CastExpr::CK_NoOp;
00971   msg = 0;
00972   return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
00973                                         /*IgnoreBaseAccess*/CStyle) ?
00974       TC_Failed : TC_Success;
00975 }
00976 
00977 /// TryConstCast - See if a const_cast from source to destination is allowed,
00978 /// and perform it if it is.
00979 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00980                                   bool CStyle, unsigned &msg) {
00981   DestType = Self.Context.getCanonicalType(DestType);
00982   QualType SrcType = SrcExpr->getType();
00983   if (const LValueReferenceType *DestTypeTmp =
00984         DestType->getAs<LValueReferenceType>()) {
00985     if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00986       // Cannot const_cast non-lvalue to lvalue reference type. But if this
00987       // is C-style, static_cast might find a way, so we simply suggest a
00988       // message and tell the parent to keep searching.
00989       msg = diag::err_bad_cxx_cast_rvalue;
00990       return TC_NotApplicable;
00991     }
00992 
00993     // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
00994     //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
00995     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
00996     SrcType = Self.Context.getPointerType(SrcType);
00997   }
00998 
00999   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
01000   //   the rules for const_cast are the same as those used for pointers.
01001 
01002   if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
01003     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
01004     // was a reference type, we converted it to a pointer above.
01005     // The status of rvalue references isn't entirely clear, but it looks like
01006     // conversion to them is simply invalid.
01007     // C++ 5.2.11p3: For two pointer types [...]
01008     if (!CStyle)
01009       msg = diag::err_bad_const_cast_dest;
01010     return TC_NotApplicable;
01011   }
01012   if (DestType->isFunctionPointerType() ||
01013       DestType->isMemberFunctionPointerType()) {
01014     // Cannot cast direct function pointers.
01015     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
01016     // T is the ultimate pointee of source and target type.
01017     if (!CStyle)
01018       msg = diag::err_bad_const_cast_dest;
01019     return TC_NotApplicable;
01020   }
01021   SrcType = Self.Context.getCanonicalType(SrcType);
01022 
01023   // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
01024   // completely equal.
01025   // FIXME: const_cast should probably not be able to convert between pointers
01026   // to different address spaces.
01027   // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
01028   // in multi-level pointers may change, but the level count must be the same,
01029   // as must be the final pointee type.
01030   while (SrcType != DestType &&
01031          Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
01032     Qualifiers Quals;
01033     SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
01034     DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
01035   }
01036 
01037   // Since we're dealing in canonical types, the remainder must be the same.
01038   if (SrcType != DestType)
01039     return TC_NotApplicable;
01040 
01041   return TC_Success;
01042 }
01043 
01044 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
01045                                         QualType DestType, bool CStyle,
01046                                         const SourceRange &OpRange,
01047                                         unsigned &msg,
01048                                         CastExpr::CastKind &Kind) {
01049   DestType = Self.Context.getCanonicalType(DestType);
01050   QualType SrcType = SrcExpr->getType();
01051   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
01052     bool LValue = DestTypeTmp->isLValueReferenceType();
01053     if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
01054       // Cannot cast non-lvalue to reference type. See the similar comment in
01055       // const_cast.
01056       msg = diag::err_bad_cxx_cast_rvalue;
01057       return TC_NotApplicable;
01058     }
01059 
01060     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
01061     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
01062     //   built-in & and * operators.
01063     // This code does this transformation for the checked types.
01064     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
01065     SrcType = Self.Context.getPointerType(SrcType);
01066   }
01067 
01068   // Canonicalize source for comparison.
01069   SrcType = Self.Context.getCanonicalType(SrcType);
01070 
01071   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
01072                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
01073   if (DestMemPtr && SrcMemPtr) {
01074     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
01075     //   can be explicitly converted to an rvalue of type "pointer to member
01076     //   of Y of type T2" if T1 and T2 are both function types or both object
01077     //   types.
01078     if (DestMemPtr->getPointeeType()->isFunctionType() !=
01079         SrcMemPtr->getPointeeType()->isFunctionType())
01080       return TC_NotApplicable;
01081 
01082     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
01083     //   constness.
01084     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
01085     // we accept it.
01086     if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
01087       msg = diag::err_bad_cxx_cast_const_away;
01088       return TC_Failed;
01089     }
01090 
01091     // A valid member pointer cast.
01092     Kind = CastExpr::CK_BitCast;
01093     return TC_Success;
01094   }
01095 
01096   // See below for the enumeral issue.
01097   if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
01098       !DestType->isEnumeralType()) {
01099     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
01100     //   type large enough to hold it. A value of std::nullptr_t can be
01101     //   converted to an integral type; the conversion has the same meaning
01102     //   and validity as a conversion of (void*)0 to the integral type.
01103     if (Self.Context.getTypeSize(SrcType) >
01104         Self.Context.getTypeSize(DestType)) {
01105       msg = diag::err_bad_reinterpret_cast_small_int;
01106       return TC_Failed;
01107     }
01108     Kind = CastExpr::CK_PointerToIntegral;
01109     return TC_Success;
01110   }
01111 
01112   bool destIsVector = DestType->isVectorType();
01113   bool srcIsVector = SrcType->isVectorType();
01114   if (srcIsVector || destIsVector) {
01115     bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
01116     bool destIsScalar = 
01117       DestType->isIntegralType() && !DestType->isEnumeralType();
01118     
01119     // Check if this is a cast between a vector and something else.
01120     if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
01121         !(srcIsVector && destIsVector))
01122       return TC_NotApplicable;
01123 
01124     // If both types have the same size, we can successfully cast.
01125     if (Self.Context.getTypeSize(SrcType)
01126           == Self.Context.getTypeSize(DestType)) {
01127       Kind = CastExpr::CK_BitCast;
01128       return TC_Success;
01129     }
01130     
01131     if (destIsScalar)
01132       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
01133     else if (srcIsScalar)
01134       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
01135     else
01136       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
01137     
01138     return TC_Failed;
01139   }
01140   
01141   bool destIsPtr = DestType->isAnyPointerType();
01142   bool srcIsPtr = SrcType->isAnyPointerType();
01143   if (!destIsPtr && !srcIsPtr) {
01144     // Except for std::nullptr_t->integer and lvalue->reference, which are
01145     // handled above, at least one of the two arguments must be a pointer.
01146     return TC_NotApplicable;
01147   }
01148 
01149   if (SrcType == DestType) {
01150     // C++ 5.2.10p2 has a note that mentions that, subject to all other
01151     // restrictions, a cast to the same type is allowed. The intent is not
01152     // entirely clear here, since all other paragraphs explicitly forbid casts
01153     // to the same type. However, the behavior of compilers is pretty consistent
01154     // on this point: allow same-type conversion if the involved types are
01155     // pointers, disallow otherwise.
01156     Kind = CastExpr::CK_NoOp;
01157     return TC_Success;
01158   }
01159 
01160   // Note: Clang treats enumeration types as integral types. If this is ever
01161   // changed for C++, the additional check here will be redundant.
01162   if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
01163     assert(srcIsPtr && "One type must be a pointer");
01164     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
01165     //   type large enough to hold it.
01166     if (Self.Context.getTypeSize(SrcType) >
01167         Self.Context.getTypeSize(DestType)) {
01168       msg = diag::err_bad_reinterpret_cast_small_int;
01169       return TC_Failed;
01170     }
01171     Kind = CastExpr::CK_PointerToIntegral;
01172     return TC_Success;
01173   }
01174 
01175   if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
01176     assert(destIsPtr && "One type must be a pointer");
01177     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
01178     //   converted to a pointer.
01179     Kind = CastExpr::CK_IntegralToPointer;
01180     return TC_Success;
01181   }
01182 
01183   if (!destIsPtr || !srcIsPtr) {
01184     // With the valid non-pointer conversions out of the way, we can be even
01185     // more stringent.
01186     return TC_NotApplicable;
01187   }
01188 
01189   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
01190   // The C-style cast operator can.
01191   if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
01192     msg = diag::err_bad_cxx_cast_const_away;
01193     return TC_Failed;
01194   }
01195   if (CStyle && DestType->isObjCObjectPointerType()) {
01196     Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
01197     return TC_Success;
01198   }
01199   
01200   // Not casting away constness, so the only remaining check is for compatible
01201   // pointer categories.
01202   Kind = CastExpr::CK_BitCast;
01203 
01204   if (SrcType->isFunctionPointerType()) {
01205     if (DestType->isFunctionPointerType()) {
01206       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
01207       // a pointer to a function of a different type.
01208       return TC_Success;
01209     }
01210 
01211     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
01212     //   an object type or vice versa is conditionally-supported.
01213     // Compilers support it in C++03 too, though, because it's necessary for
01214     // casting the return value of dlsym() and GetProcAddress().
01215     // FIXME: Conditionally-supported behavior should be configurable in the
01216     // TargetInfo or similar.
01217     if (!Self.getLangOptions().CPlusPlus0x)
01218       Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
01219     return TC_Success;
01220   }
01221 
01222   if (DestType->isFunctionPointerType()) {
01223     // See above.
01224     if (!Self.getLangOptions().CPlusPlus0x)
01225       Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
01226     return TC_Success;
01227   }
01228 
01229   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
01230   //   a pointer to an object of different type.
01231   // Void pointers are not specified, but supported by every compiler out there.
01232   // So we finish by allowing everything that remains - it's got to be two
01233   // object pointers.
01234   return TC_Success;
01235 }
01236 
01237 bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
01238                               CastExpr::CastKind &Kind, bool FunctionalStyle,
01239                               CXXMethodDecl *&ConversionDecl) {
01240   // This test is outside everything else because it's the only case where
01241   // a non-lvalue-reference target type does not lead to decay.
01242   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
01243   if (CastTy->isVoidType()) {
01244     Kind = CastExpr::CK_ToVoid;
01245     return false;
01246   }
01247 
01248   // If the type is dependent, we won't do any other semantic analysis now.
01249   if (CastTy->isDependentType() || CastExpr->isTypeDependent())
01250     return false;
01251 
01252   if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
01253     DefaultFunctionArrayLvalueConversion(CastExpr);
01254 
01255   // C++ [expr.cast]p5: The conversions performed by
01256   //   - a const_cast,
01257   //   - a static_cast,
01258   //   - a static_cast followed by a const_cast,
01259   //   - a reinterpret_cast, or
01260   //   - a reinterpret_cast followed by a const_cast,
01261   //   can be performed using the cast notation of explicit type conversion.
01262   //   [...] If a conversion can be interpreted in more than one of the ways
01263   //   listed above, the interpretation that appears first in the list is used,
01264   //   even if a cast resulting from that interpretation is ill-formed.
01265   // In plain language, this means trying a const_cast ...
01266   unsigned msg = diag::err_bad_cxx_cast_generic;
01267   TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
01268                                    msg);
01269   if (tcr == TC_Success)
01270     Kind = CastExpr::CK_NoOp;
01271 
01272   if (tcr == TC_NotApplicable) {
01273     // ... or if that is not possible, a static_cast, ignoring const, ...
01274     tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
01275                         Kind, ConversionDecl);
01276     if (tcr == TC_NotApplicable) {
01277       // ... and finally a reinterpret_cast, ignoring const.
01278       tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
01279                                Kind);
01280     }
01281   }
01282 
01283   if (tcr != TC_Success && msg != 0)
01284     Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
01285       << CastExpr->getType() << CastTy << R;
01286 
01287   return tcr != TC_Success;
01288 }