[cfe-commits] r58509 - in /cfe/trunk: include/clang/Basic/DiagnosticKinds.def lib/AST/Expr.cpp lib/Sema/Sema.h lib/Sema/SemaExprCXX.cpp lib/Sema/SemaInherit.cpp lib/Sema/SemaInherit.h lib/Sema/SemaOverload.cpp test/SemaCXX/condition.cpp test/SemaCXX/dynamic-cast.cpp test/SemaCXX/static-cast.cpp
Sebastian Redl
sebastian.redl at getdesigned.at
Fri Oct 31 07:43:28 PDT 2008
Author: cornedbee
Date: Fri Oct 31 09:43:28 2008
New Revision: 58509
URL: http://llvm.org/viewvc/llvm-project?rev=58509&view=rev
Log:
Implement semantic checking of static_cast and dynamic_cast.
Added:
cfe/trunk/test/SemaCXX/dynamic-cast.cpp
cfe/trunk/test/SemaCXX/static-cast.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticKinds.def
cfe/trunk/lib/AST/Expr.cpp
cfe/trunk/lib/Sema/Sema.h
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaInherit.cpp
cfe/trunk/lib/Sema/SemaInherit.h
cfe/trunk/lib/Sema/SemaOverload.cpp
cfe/trunk/test/SemaCXX/condition.cpp
Modified: cfe/trunk/include/clang/Basic/DiagnosticKinds.def
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/include/clang/Basic/DiagnosticKinds.def (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticKinds.def Fri Oct 31 09:43:28 2008
@@ -1096,6 +1096,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")
Modified: cfe/trunk/lib/AST/Expr.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Expr.cpp?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/AST/Expr.cpp (original)
+++ cfe/trunk/lib/AST/Expr.cpp Fri Oct 31 09:43:28 2008
@@ -1072,15 +1072,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.
Modified: cfe/trunk/lib/Sema/Sema.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/Sema.h?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/Sema.h (original)
+++ cfe/trunk/lib/Sema/Sema.h Fri Oct 31 09:43:28 2008
@@ -707,13 +707,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);
Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Fri Oct 31 09:43:28 2008
@@ -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,347 @@
}
/// 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<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->isVoidType()) {
+ 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.
+ 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 by
+ // p2 (TryDirectInitialization above).
+ // (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->isComplexType() || SrcType->isVectorType()) {
+ // Fall through - these cannot be converted.
+ } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
+ return;
+ }
+ }
+
+ // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
+ // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
+ 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->isVoidType()) {
+ 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(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
+ /*DetectVirtual=*/true);
+ if (!IsDerivedFrom(DestType, SrcType, Paths)) {
+ return false;
+ }
+
+ if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
+ return false;
+ }
+
+ if (Paths.getDetectedVirtual() != 0) {
+ 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()) {
+ assert(DestPointer && "Reference to void is not possible");
+ } 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.
Modified: cfe/trunk/lib/Sema/SemaInherit.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInherit.cpp?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/SemaInherit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInherit.cpp Fri Oct 31 09:43:28 2008
@@ -42,6 +42,7 @@
Paths.clear();
ClassSubobjects.clear();
ScratchPath.clear();
+ DetectedVirtual = 0;
}
/// IsDerivedFrom - Determine whether the type Derived is derived from
@@ -50,7 +51,8 @@
/// Derived* to a Base* is legal, because it does not account for
/// ambiguous conversions or conversions to private/protected bases.
bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
- BasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false);
+ BasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
+ /*DetectVirtual=*/false);
return IsDerivedFrom(Derived, Base, Paths);
}
@@ -64,10 +66,10 @@
/// information about all of the paths (if @c Paths.isRecordingPaths()).
bool Sema::IsDerivedFrom(QualType Derived, QualType Base, BasePaths &Paths) {
bool FoundPath = false;
-
+
Derived = Context.getCanonicalType(Derived).getUnqualifiedType();
Base = Context.getCanonicalType(Base).getUnqualifiedType();
-
+
if (!Derived->isRecordType() || !Base->isRecordType())
return false;
@@ -87,9 +89,17 @@
// updating the count of subobjects appropriately.
std::pair<bool, unsigned>& Subobjects = Paths.ClassSubobjects[BaseType];
bool VisitBase = true;
+ bool SetVirtual = false;
if (BaseSpec->isVirtual()) {
VisitBase = !Subobjects.first;
Subobjects.first = true;
+ if (Paths.isDetectingVirtual() && Paths.DetectedVirtual == 0) {
+ // If this is the first virtual we find, remember it. If it turns out
+ // there is no base path here, we'll reset it later.
+ Paths.DetectedVirtual = static_cast<const CXXRecordType*>(
+ BaseType->getAsRecordType());
+ SetVirtual = true;
+ }
} else
++Subobjects.second;
@@ -127,6 +137,10 @@
// collecting paths).
if (Paths.isRecordingPaths())
Paths.ScratchPath.pop_back();
+ // If we set a virtual earlier, and this isn't a path, forget it again.
+ if (SetVirtual && !FoundPath) {
+ Paths.DetectedVirtual = 0;
+ }
}
}
@@ -148,7 +162,8 @@
// ambiguous. This is slightly more expensive than checking whether
// the Derived to Base conversion exists, because here we need to
// explore multiple paths to determine if there is an ambiguity.
- BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false);
+ BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
+ /*DetectVirtual=*/false);
bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
assert(DerivationOkay && "Can only be used with a derived-to-base conversion");
if (!DerivationOkay)
Modified: cfe/trunk/lib/Sema/SemaInherit.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInherit.h?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/SemaInherit.h (original)
+++ cfe/trunk/lib/Sema/SemaInherit.h Fri Oct 31 09:43:28 2008
@@ -25,6 +25,7 @@
namespace clang {
class Sema;
class CXXBaseSpecifier;
+ class CXXRecordType;
/// BasePathElement - An element in a path from a derived class to a
/// base class. Each step in the path references the link from a
@@ -97,20 +98,28 @@
std::map<QualType, std::pair<bool, unsigned>, QualTypeOrdering>
ClassSubobjects;
- /// FindAmbiguities - Whether Sema::IsDirectedFrom should try find
+ /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find
/// ambiguous paths while it is looking for a path from a derived
/// type to a base type.
bool FindAmbiguities;
- /// RecordPaths - Whether Sema::IsDirectedFrom should record paths
+ /// RecordPaths - Whether Sema::IsDerivedFrom should record paths
/// while it is determining whether there are paths from a derived
/// type to a base type.
bool RecordPaths;
+ /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search
+ /// if it finds a path that goes across a virtual base. The virtual class
+ /// is also recorded.
+ bool DetectVirtual;
+
/// ScratchPath - A BasePath that is used by Sema::IsDerivedFrom
/// to help build the set of paths.
BasePath ScratchPath;
+ /// DetectedVirtual - The base class that is virtual.
+ const CXXRecordType *DetectedVirtual;
+
friend class Sema;
public:
@@ -118,8 +127,12 @@
/// BasePaths - Construct a new BasePaths structure to record the
/// paths for a derived-to-base search.
- explicit BasePaths(bool FindAmbiguities = true, bool RecordPaths = true)
- : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths) { }
+ explicit BasePaths(bool FindAmbiguities = true,
+ bool RecordPaths = true,
+ bool DetectVirtual = true)
+ : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths),
+ DetectVirtual(DetectVirtual), DetectedVirtual(0)
+ {}
paths_iterator begin() const { return Paths.begin(); }
paths_iterator end() const { return Paths.end(); }
@@ -137,6 +150,14 @@
/// paths or not.
void setRecordingPaths(bool RP) { RecordPaths = RP; }
+ /// isDetectingVirtual - Whether we are detecting virtual bases.
+ bool isDetectingVirtual() const { return DetectVirtual; }
+
+ /// getDetectedVirtual - The virtual base discovered on the path.
+ const CXXRecordType* getDetectedVirtual() const {
+ return DetectedVirtual;
+ }
+
void clear();
};
}
Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Fri Oct 31 09:43:28 2008
@@ -423,8 +423,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();
}
@@ -434,16 +435,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
@@ -502,21 +506,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;
}
@@ -552,7 +560,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();
}
}
@@ -576,13 +584,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;
}
@@ -590,8 +600,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;
}
@@ -630,7 +641,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).
@@ -709,7 +720,8 @@
if (const PointerType *FromPtrType = FromType->getAsPointerType())
if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
- BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false);
+ BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
+ /*DetectVirtual=*/false);
QualType FromPointeeType = FromPtrType->getPointeeType(),
ToPointeeType = ToPtrType->getPointeeType();
if (FromPointeeType->isRecordType() &&
Modified: cfe/trunk/test/SemaCXX/condition.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/condition.cpp?rev=58509&r1=58508&r2=58509&view=diff
==============================================================================
--- cfe/trunk/test/SemaCXX/condition.cpp (original)
+++ cfe/trunk/test/SemaCXX/condition.cpp Fri Oct 31 09:43:28 2008
@@ -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'}}
Added: cfe/trunk/test/SemaCXX/dynamic-cast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/dynamic-cast.cpp?rev=58509&view=auto
==============================================================================
--- cfe/trunk/test/SemaCXX/dynamic-cast.cpp (added)
+++ cfe/trunk/test/SemaCXX/dynamic-cast.cpp Fri Oct 31 09:43:28 2008
@@ -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.
Added: cfe/trunk/test/SemaCXX/static-cast.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/static-cast.cpp?rev=58509&view=auto
==============================================================================
--- cfe/trunk/test/SemaCXX/static-cast.cpp (added)
+++ cfe/trunk/test/SemaCXX/static-cast.cpp Fri Oct 31 09:43:28 2008
@@ -0,0 +1,120 @@
+// 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);
+ (void)static_cast<const 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); // expected-error {{static_cast from 'struct B **' to 'struct A **' 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.
More information about the cfe-commits
mailing list