blob: df9ef4f5bccdd1b15db5f1a8d217a1656b6b1bb6 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCall9776e432011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregore81f58e2010-11-08 03:40:48 +000028
Douglas Gregore81f58e2010-11-08 03:40:48 +000029
Sebastian Redl9f831db2009-07-25 15:41:38 +000030enum TryCastResult {
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
35};
36
37enum CastType {
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000044};
45
John McCallb50451a2011-10-05 07:41:44 +000046namespace {
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
John McCall9776e432011-10-06 23:25:11 +000052 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
53
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
57 } else {
58 PlaceholderKind = (BuiltinType::Kind) 0;
59 }
60 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000061
John McCallb50451a2011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
68 bool IsARCUnbridgedCast;
John McCall9776e432011-10-06 23:25:11 +000069 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000070 CXXCastPath BasePath;
Douglas Gregore81f58e2010-11-08 03:40:48 +000071
John McCallb50451a2011-10-05 07:41:44 +000072 SourceRange OpRange;
73 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000074
John McCall9776e432011-10-06 23:25:11 +000075 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000076 void CheckConstCast();
77 void CheckReinterpretCast();
78 void CheckStaticCast();
79 void CheckDynamicCast();
John McCall9776e432011-10-06 23:25:11 +000080 void CheckCXXCStyleCast(bool FunctionalCast);
81 void CheckCStyleCast();
82
83 // Internal convenience methods.
84
85 /// Try to handle the given placeholder expression kind. Return
86 /// true if the source expression has the appropriate placeholder
87 /// kind. A placeholder can only be claimed once.
88 bool claimPlaceholder(BuiltinType::Kind K) {
89 if (PlaceholderKind != K) return false;
90
91 PlaceholderKind = (BuiltinType::Kind) 0;
92 return true;
93 }
94
95 bool isPlaceholder() const {
96 return PlaceholderKind != 0;
97 }
98 bool isPlaceholder(BuiltinType::Kind K) const {
99 return PlaceholderKind == K;
100 }
John McCallb50451a2011-10-05 07:41:44 +0000101
102 void checkCastAlign() {
103 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
104 }
105
106 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
107 Expr *src = SrcExpr.get();
108 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
109 SrcExpr = src;
110 }
John McCall9776e432011-10-06 23:25:11 +0000111
112 /// Check for and handle non-overload placeholder expressions.
113 void checkNonOverloadPlaceholders() {
114 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
115 return;
116
117 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
118 if (SrcExpr.isInvalid())
119 return;
120 PlaceholderKind = (BuiltinType::Kind) 0;
121 }
John McCallb50451a2011-10-05 07:41:44 +0000122 };
123}
Sebastian Redl842ef522008-11-08 13:00:26 +0000124
John McCall31168b02011-06-15 23:02:42 +0000125static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
126 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000127
128// The Try functions attempt a specific way of casting. If they succeed, they
129// return TC_Success. If their way of casting is not appropriate for the given
130// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
131// to emit if no other way succeeds. If their way of casting is appropriate but
132// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
133// they emit a specialized diagnostic.
134// All diagnostics returned by these functions must expect the same three
135// arguments:
136// %0: Cast Type (a value from the CastType enumeration)
137// %1: Source Type
138// %2: Destination Type
139static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000140 QualType DestType, bool CStyle,
141 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000142 CXXCastPath &BasePath,
143 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000144static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000145 QualType DestType, bool CStyle,
146 const SourceRange &OpRange,
147 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000148 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000149 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000150static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
151 QualType DestType, bool CStyle,
152 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000153 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000154 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000155 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000156static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
157 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000158 const SourceRange &OpRange,
159 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000160 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000161 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000162 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000163static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000164 QualType SrcType,
165 QualType DestType,bool CStyle,
166 const SourceRange &OpRange,
167 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000168 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000169 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000170
John Wiegley01296292011-04-08 18:41:53 +0000171static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000172 QualType DestType,
173 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000174 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000175 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000176 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000177static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000178 QualType DestType,
179 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000180 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000181 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000182 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000183 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000184static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
185 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000186static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000187 QualType DestType, bool CStyle,
188 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000189 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000190 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000191
Douglas Gregorb491ed32011-02-19 21:32:49 +0000192
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000193/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000194ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000195Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000196 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000197 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000198 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000199 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000200
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000201 assert(!D.isInvalidType());
202
203 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
204 if (D.isInvalidType())
205 return ExprError();
206
207 if (getLangOptions().CPlusPlus) {
208 // Check that there are no default arguments (C++ only).
209 CheckExtraCXXDefaultArguments(D);
210 }
211
212 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCalld377e042010-01-15 19:13:16 +0000213 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
214 SourceRange(LParenLoc, RParenLoc));
215}
216
John McCalldadc5752010-08-24 06:29:42 +0000217ExprResult
John McCalld377e042010-01-15 19:13:16 +0000218Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000219 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000220 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000221 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000222 QualType DestType = DestTInfo->getType();
223
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000224 // If the type is dependent, we won't do the semantic analysis now.
225 // FIXME: should we check this in a more fine-grained manner?
John Wiegley01296292011-04-08 18:41:53 +0000226 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000227
John McCallb50451a2011-10-05 07:41:44 +0000228 CastOperation Op(*this, DestType, E);
229 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
230 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000231
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000232 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000233 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000234
235 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000236 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000237 Op.CheckConstCast();
238 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000239 return ExprError();
240 }
John McCallb50451a2011-10-05 07:41:44 +0000241 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
242 Op.SrcExpr.take(), DestTInfo, OpLoc,
Douglas Gregor4478f852011-01-12 22:41:29 +0000243 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000244
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000245 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000246 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000247 Op.CheckDynamicCast();
248 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000249 return ExprError();
250 }
John McCallb50451a2011-10-05 07:41:44 +0000251 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
252 Op.ValueKind, Op.Kind,
253 Op.SrcExpr.take(), &Op.BasePath,
254 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000255 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000256 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000257 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000258 Op.CheckReinterpretCast();
259 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000260 return ExprError();
261 }
John McCallb50451a2011-10-05 07:41:44 +0000262 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
263 Op.ValueKind, Op.Kind,
264 Op.SrcExpr.take(), 0,
265 DestTInfo, OpLoc,
266 Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000267 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000268 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000269 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000270 Op.CheckStaticCast();
271 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000272 return ExprError();
273 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000274
John McCallb50451a2011-10-05 07:41:44 +0000275 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
276 Op.Kind, Op.SrcExpr.take(),
277 &Op.BasePath, DestTInfo, OpLoc,
278 Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000279 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000280 }
281
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000282 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000283}
284
John McCall909acf82011-02-14 18:34:10 +0000285/// Try to diagnose a failed overloaded cast. Returns true if
286/// diagnostics were emitted.
287static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
288 SourceRange range, Expr *src,
289 QualType destType) {
290 switch (CT) {
291 // These cast kinds don't consider user-defined conversions.
292 case CT_Const:
293 case CT_Reinterpret:
294 case CT_Dynamic:
295 return false;
296
297 // These do.
298 case CT_Static:
299 case CT_CStyle:
300 case CT_Functional:
301 break;
302 }
303
304 QualType srcType = src->getType();
305 if (!destType->isRecordType() && !srcType->isRecordType())
306 return false;
307
308 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
309 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000310 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
311 range)
312 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
313 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall909acf82011-02-14 18:34:10 +0000314 InitializationSequence sequence(S, entity, initKind, &src, 1);
315
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000316 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000317 switch (sequence.getFailureKind()) {
318 default: return false;
319
320 case InitializationSequence::FK_ConstructorOverloadFailed:
321 case InitializationSequence::FK_UserConversionOverloadFailed:
322 break;
323 }
324
325 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
326
327 unsigned msg = 0;
328 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
329
330 switch (sequence.getFailedOverloadResult()) {
331 case OR_Success: llvm_unreachable("successful failed overload");
332 return false;
333 case OR_No_Viable_Function:
334 if (candidates.empty())
335 msg = diag::err_ovl_no_conversion_in_cast;
336 else
337 msg = diag::err_ovl_no_viable_conversion_in_cast;
338 howManyCandidates = OCD_AllCandidates;
339 break;
340
341 case OR_Ambiguous:
342 msg = diag::err_ovl_ambiguous_conversion_in_cast;
343 howManyCandidates = OCD_ViableCandidates;
344 break;
345
346 case OR_Deleted:
347 msg = diag::err_ovl_deleted_conversion_in_cast;
348 howManyCandidates = OCD_ViableCandidates;
349 break;
350 }
351
352 S.Diag(range.getBegin(), msg)
353 << CT << srcType << destType
354 << range << src->getSourceRange();
355
356 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
357
358 return true;
359}
360
361/// Diagnose a failed cast.
362static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
363 SourceRange opRange, Expr *src, QualType destType) {
John McCall0009fcc2011-04-26 20:42:42 +0000364 if (src->getType() == S.Context.BoundMemberTy) {
365 (void) S.CheckPlaceholderExpr(src); // will always fail
366 return;
367 }
368
John McCall909acf82011-02-14 18:34:10 +0000369 if (msg == diag::err_bad_cxx_cast_generic &&
370 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
371 return;
372
373 S.Diag(opRange.getBegin(), msg) << castType
374 << src->getType() << destType << opRange << src->getSourceRange();
375}
376
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000377/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
378/// this removes one level of indirection from both types, provided that they're
379/// the same kind of pointer (plain or to-member). Unlike the Sema function,
380/// this one doesn't care if the two pointers-to-member don't point into the
381/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000382static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000383 const PointerType *T1PtrType = T1->getAs<PointerType>(),
384 *T2PtrType = T2->getAs<PointerType>();
385 if (T1PtrType && T2PtrType) {
386 T1 = T1PtrType->getPointeeType();
387 T2 = T2PtrType->getPointeeType();
388 return true;
389 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000390 const ObjCObjectPointerType *T1ObjCPtrType =
391 T1->getAs<ObjCObjectPointerType>(),
392 *T2ObjCPtrType =
393 T2->getAs<ObjCObjectPointerType>();
394 if (T1ObjCPtrType) {
395 if (T2ObjCPtrType) {
396 T1 = T1ObjCPtrType->getPointeeType();
397 T2 = T2ObjCPtrType->getPointeeType();
398 return true;
399 }
400 else if (T2PtrType) {
401 T1 = T1ObjCPtrType->getPointeeType();
402 T2 = T2PtrType->getPointeeType();
403 return true;
404 }
405 }
406 else if (T2ObjCPtrType) {
407 if (T1PtrType) {
408 T2 = T2ObjCPtrType->getPointeeType();
409 T1 = T1PtrType->getPointeeType();
410 return true;
411 }
412 }
413
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000414 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
415 *T2MPType = T2->getAs<MemberPointerType>();
416 if (T1MPType && T2MPType) {
417 T1 = T1MPType->getPointeeType();
418 T2 = T2MPType->getPointeeType();
419 return true;
420 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000421
422 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
423 *T2BPType = T2->getAs<BlockPointerType>();
424 if (T1BPType && T2BPType) {
425 T1 = T1BPType->getPointeeType();
426 T2 = T2BPType->getPointeeType();
427 return true;
428 }
429
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000430 return false;
431}
432
Sebastian Redla5a77a62009-01-27 23:18:31 +0000433/// CastsAwayConstness - Check if the pointer conversion from SrcType to
434/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
435/// the cast checkers. Both arguments must denote pointer (possibly to member)
436/// types.
John McCall31168b02011-06-15 23:02:42 +0000437///
438/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
439///
440/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000441static bool
John McCall31168b02011-06-15 23:02:42 +0000442CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
443 bool CheckCVR, bool CheckObjCLifetime) {
444 // If the only checking we care about is for Objective-C lifetime qualifiers,
445 // and we're not in ARC mode, there's nothing to check.
446 if (!CheckCVR && CheckObjCLifetime &&
447 !Self.Context.getLangOptions().ObjCAutoRefCount)
448 return false;
449
Sebastian Redla5a77a62009-01-27 23:18:31 +0000450 // Casting away constness is defined in C++ 5.2.11p8 with reference to
451 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
452 // the rules are non-trivial. So first we construct Tcv *...cv* as described
453 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000454 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
455 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000456 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000457 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
458 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000459 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000460
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000461 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
462 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000463 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000464
Douglas Gregorb472e932011-04-15 17:59:54 +0000465 // Find the qualifiers. We only care about cvr-qualifiers for the
466 // purpose of this check, because other qualifiers (address spaces,
467 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000468 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000469 // Determine the relevant qualifiers at this level.
470 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000471 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000472 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000473
474 Qualifiers RetainedSrcQuals, RetainedDestQuals;
475 if (CheckCVR) {
476 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
477 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
478 }
479
480 if (CheckObjCLifetime &&
481 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
482 return true;
483
484 cv1.push_back(RetainedSrcQuals);
485 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000487 if (cv1.empty())
488 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000489
490 // Construct void pointers with those qualifiers (in reverse order of
491 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000492 QualType SrcConstruct = Self.Context.VoidTy;
493 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000494 ASTContext &Context = Self.Context;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall8ccfcb52009-09-24 19:53:00 +0000496 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000497 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000498 SrcConstruct
499 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
500 DestConstruct
501 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000502 }
503
504 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000505 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000506 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000507 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
508 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000509}
510
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000511/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
512/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
513/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000514void CastOperation::CheckDynamicCast() {
515 QualType OrigSrcType = SrcExpr.get()->getType();
516 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000517
518 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
519 // or "pointer to cv void".
520
521 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000522 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000523 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000524 if (DestPointer) {
525 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000526 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000527 DestPointee = DestReference->getPointeeType();
528 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000529 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000530 << this->DestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000531 return;
532 }
533
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000534 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000535 if (DestPointee->isVoidType()) {
536 assert(DestPointer && "Reference to void is not possible");
537 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000538 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000539 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000540 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000541 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000542 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000543 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000544 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000545 return;
546 }
547
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000548 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
549 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000550 // an lvalue of a complete class type, [...]. If T is an rvalue reference
551 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000552 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000553 QualType SrcPointee;
554 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000555 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000556 SrcPointee = SrcPointer->getPointeeType();
557 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000558 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000559 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000560 return;
561 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000562 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000563 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000564 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000565 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000566 }
567 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000568 } else {
569 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000570 }
571
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000572 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000573 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000574 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000575 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000576 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000578 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000579 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000580 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000581 return;
582 }
583
584 assert((DestPointer || DestReference) &&
585 "Bad destination non-ptr/ref slipped through.");
586 assert((DestRecord || DestPointee->isVoidType()) &&
587 "Bad destination pointee slipped through.");
588 assert(SrcRecord && "Bad source pointee slipped through.");
589
590 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
591 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000592 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000593 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000594 return;
595 }
596
597 // C++ 5.2.7p3: If the type of v is the same as the required result type,
598 // [except for cv].
599 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000600 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000601 return;
602 }
603
604 // C++ 5.2.7p5
605 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000606 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000607 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
608 OpRange.getBegin(), OpRange,
609 &BasePath))
610 return;
611
John McCalle3027922010-08-25 11:45:40 +0000612 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000613
614 // If we are casting to or through a virtual base class, we need a
615 // vtable.
616 if (Self.BasePathInvolvesVirtualBase(BasePath))
617 Self.MarkVTableUsed(OpRange.getBegin(),
618 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000619 return;
620 }
621
622 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000623 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000624 assert(SrcDecl && "Definition missing");
625 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000626 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000627 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000628 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000629 Self.MarkVTableUsed(OpRange.getBegin(),
630 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000631
632 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000633 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000634}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000635
636/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
637/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
638/// like this:
639/// const char *str = "literal";
640/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000641void CastOperation::CheckConstCast() {
642 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000643 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
644 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
645 return;
646 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000647
648 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000649 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000650 && msg != 0)
651 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000652 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000653}
654
655/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
656/// valid.
657/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
658/// like this:
659/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000660void CastOperation::CheckReinterpretCast() {
661 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000662 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
663 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
664 return;
665 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000666
667 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000668 TryCastResult tcr =
669 TryReinterpretCast(Self, SrcExpr, DestType,
670 /*CStyle*/false, OpRange, msg, Kind);
671 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000672 {
John Wiegley01296292011-04-08 18:41:53 +0000673 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
674 return;
675 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000676 //FIXME: &f<int>; is overloaded and resolvable
677 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000678 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000679 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000680 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000681
John McCall909acf82011-02-14 18:34:10 +0000682 } else {
John Wiegley01296292011-04-08 18:41:53 +0000683 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000684 }
John McCall31168b02011-06-15 23:02:42 +0000685 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +0000686 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCall31168b02011-06-15 23:02:42 +0000687 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000688}
689
690
691/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
692/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
693/// implicit conversions explicit and getting rid of data loss warnings.
John McCallb50451a2011-10-05 07:41:44 +0000694void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000695 if (isPlaceholder()) {
696 checkNonOverloadPlaceholders();
697 if (SrcExpr.isInvalid())
698 return;
699 }
700
Sebastian Redl9f831db2009-07-25 15:41:38 +0000701 // This test is outside everything else because it's the only case where
702 // a non-lvalue-reference target type does not lead to decay.
703 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000704 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000705 Kind = CK_ToVoid;
706
707 if (claimPlaceholder(BuiltinType::Overload)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +0000708 ExprResult SingleFunctionExpression =
John McCall9776e432011-10-06 23:25:11 +0000709 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +0000710 false, // Decay Function to ptr
711 true, // Complain
712 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall9776e432011-10-06 23:25:11 +0000713 if (SingleFunctionExpression.isUsable())
714 SrcExpr = SingleFunctionExpression;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000715 }
John McCall9776e432011-10-06 23:25:11 +0000716
717 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000718 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000719 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000720
John McCallb50451a2011-10-05 07:41:44 +0000721 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
John Wiegley01296292011-04-08 18:41:53 +0000722 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
723 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
724 return;
725 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000726
727 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000728 TryCastResult tcr
729 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
730 Kind, BasePath);
731 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000732 if (SrcExpr.isInvalid())
733 return;
734 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
735 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000736 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000737 << oe->getName() << DestType << OpRange
738 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000739 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000740 } else {
John Wiegley01296292011-04-08 18:41:53 +0000741 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000742 }
John McCall31168b02011-06-15 23:02:42 +0000743 } else if (tcr == TC_Success) {
744 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000745 checkCastAlign();
746 if (Self.getLangOptions().ObjCAutoRefCount)
747 checkObjCARCConversion(Sema::CCK_OtherCast);
748 } else if (Kind == CK_BitCast) {
749 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000750 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000751}
752
753/// TryStaticCast - Check if a static cast can be performed, and do so if
754/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
755/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000756static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000757 QualType DestType,
758 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000759 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000760 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000761 CXXCastPath &BasePath) {
John McCall31168b02011-06-15 23:02:42 +0000762 // Determine whether we have the semantics of a C-style cast.
763 bool CStyle
764 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
765
Sebastian Redl9f831db2009-07-25 15:41:38 +0000766 // The order the tests is not entirely arbitrary. There is one conversion
767 // that can be handled in two different ways. Given:
768 // struct A {};
769 // struct B : public A {
770 // B(); B(const A&);
771 // };
772 // const A &a = B();
773 // the cast static_cast<const B&>(a) could be seen as either a static
774 // reference downcast, or an explicit invocation of the user-defined
775 // conversion using B's conversion constructor.
776 // DR 427 specifies that the downcast is to be applied here.
777
778 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
779 // Done outside this function.
780
781 TryCastResult tcr;
782
783 // C++ 5.2.9p5, reference downcast.
784 // See the function for details.
785 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000786 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000787 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000788 if (tcr != TC_NotApplicable)
789 return tcr;
790
Douglas Gregor465184a2011-01-22 00:06:57 +0000791 // C++0x [expr.static.cast]p3:
792 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
793 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000794 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000795 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000796 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000797 return tcr;
798
799 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
800 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000801 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000802 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000803 if (SrcExpr.isInvalid())
804 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000805 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000806 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000807
Sebastian Redl9f831db2009-07-25 15:41:38 +0000808 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
809 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
810 // conversions, subject to further restrictions.
811 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
812 // of qualification conversions impossible.
813 // In the CStyle case, the earlier attempt to const_cast should have taken
814 // care of reverse qualification conversions.
815
John Wiegley01296292011-04-08 18:41:53 +0000816 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000817
Douglas Gregor0bf31402010-10-08 23:50:27 +0000818 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000819 // converted to an integral type. [...] A value of a scoped enumeration type
820 // can also be explicitly converted to a floating-point type [...].
821 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
822 if (Enum->getDecl()->isScoped()) {
823 if (DestType->isBooleanType()) {
824 Kind = CK_IntegralToBoolean;
825 return TC_Success;
826 } else if (DestType->isIntegralType(Self.Context)) {
827 Kind = CK_IntegralCast;
828 return TC_Success;
829 } else if (DestType->isRealFloatingType()) {
830 Kind = CK_IntegralToFloating;
831 return TC_Success;
832 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000833 }
834 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000835
Sebastian Redl9f831db2009-07-25 15:41:38 +0000836 // Reverse integral promotion/conversion. All such conversions are themselves
837 // again integral promotions or conversions and are thus already handled by
838 // p2 (TryDirectInitialization above).
839 // (Note: any data loss warnings should be suppressed.)
840 // The exception is the reverse of enum->integer, i.e. integer->enum (and
841 // enum->enum). See also C++ 5.2.9p7.
842 // The same goes for reverse floating point promotion/conversion and
843 // floating-integral conversions. Again, only floating->enum is relevant.
844 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000845 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000846 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000847 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +0000848 } else if (SrcType->isRealFloatingType()) {
849 Kind = CK_FloatingToIntegral;
850 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000851 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000852 }
853
854 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
855 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000856 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000857 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000858 if (tcr != TC_NotApplicable)
859 return tcr;
860
861 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
862 // conversion. C++ 5.2.9p9 has additional information.
863 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000864 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000865 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000866 if (tcr != TC_NotApplicable)
867 return tcr;
868
869 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
870 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
871 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000872 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000873 QualType SrcPointee = SrcPointer->getPointeeType();
874 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000875 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000876 QualType DestPointee = DestPointer->getPointeeType();
877 if (DestPointee->isIncompleteOrObjectType()) {
878 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +0000879 // to a qualifier violation. Note that we permit Objective-C lifetime
880 // and GC qualifier mismatches here.
881 if (!CStyle) {
882 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
883 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
884 DestPointeeQuals.removeObjCGCAttr();
885 DestPointeeQuals.removeObjCLifetime();
886 SrcPointeeQuals.removeObjCGCAttr();
887 SrcPointeeQuals.removeObjCLifetime();
888 if (DestPointeeQuals != SrcPointeeQuals &&
889 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
890 msg = diag::err_bad_cxx_cast_qualifiers_away;
891 return TC_Failed;
892 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000893 }
John McCalle3027922010-08-25 11:45:40 +0000894 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000895 return TC_Success;
896 }
897 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000898 else if (DestType->isObjCObjectPointerType()) {
899 // allow both c-style cast and static_cast of objective-c pointers as
900 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +0000901 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000902 return TC_Success;
903 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000904 else if (CStyle && DestType->isBlockPointerType()) {
905 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000906 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000907 return TC_Success;
908 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000909 }
910 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000911 // Allow arbitray objective-c pointer conversion with static casts.
912 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000913 DestType->isObjCObjectPointerType()) {
914 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000915 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000916 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000917
Sebastian Redl9f831db2009-07-25 15:41:38 +0000918 // We tried everything. Everything! Nothing works! :-(
919 return TC_NotApplicable;
920}
921
922/// Tests whether a conversion according to N2844 is valid.
923TryCastResult
924TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000925 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
926 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000927 // C++0x [expr.static.cast]p3:
928 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
929 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000930 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000931 if (!R)
932 return TC_NotApplicable;
933
Douglas Gregor465184a2011-01-22 00:06:57 +0000934 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000935 return TC_NotApplicable;
936
937 // Because we try the reference downcast before this function, from now on
938 // this is the only cast possibility, so we issue an error if we fail now.
939 // FIXME: Should allow casting away constness if CStyle.
940 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000941 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +0000942 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000943 QualType FromType = SrcExpr->getType();
944 QualType ToType = R->getPointeeType();
945 if (CStyle) {
946 FromType = FromType.getUnqualifiedType();
947 ToType = ToType.getUnqualifiedType();
948 }
949
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000950 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000951 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +0000952 DerivedToBase, ObjCConversion,
953 ObjCLifetimeConversion)
954 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000955 msg = diag::err_bad_lvalue_to_rvalue_cast;
956 return TC_Failed;
957 }
958
Douglas Gregorba278e22011-01-25 16:13:26 +0000959 if (DerivedToBase) {
960 Kind = CK_DerivedToBase;
961 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
962 /*DetectVirtual=*/true);
963 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
964 return TC_NotApplicable;
965
966 Self.BuildBasePathArray(Paths, BasePath);
967 } else
968 Kind = CK_NoOp;
969
Sebastian Redl9f831db2009-07-25 15:41:38 +0000970 return TC_Success;
971}
972
973/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
974TryCastResult
975TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
976 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000977 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000978 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000979 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
980 // cast to type "reference to cv2 D", where D is a class derived from B,
981 // if a valid standard conversion from "pointer to D" to "pointer to B"
982 // exists, cv2 >= cv1, and B is not a virtual base class of D.
983 // In addition, DR54 clarifies that the base must be accessible in the
984 // current context. Although the wording of DR54 only applies to the pointer
985 // variant of this rule, the intent is clearly for it to apply to the this
986 // conversion as well.
987
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000988 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000989 if (!DestReference) {
990 return TC_NotApplicable;
991 }
992 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000993 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 // We know the left side is an lvalue reference, so we can suggest a reason.
995 msg = diag::err_bad_cxx_cast_rvalue;
996 return TC_NotApplicable;
997 }
998
999 QualType DestPointee = DestReference->getPointeeType();
1000
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001001 return TryStaticDowncast(Self,
1002 Self.Context.getCanonicalType(SrcExpr->getType()),
1003 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001004 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1005 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001006}
1007
1008/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1009TryCastResult
1010TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001011 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001012 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001013 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001014 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1015 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1016 // is a class derived from B, if a valid standard conversion from "pointer
1017 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1018 // class of D.
1019 // In addition, DR54 clarifies that the base must be accessible in the
1020 // current context.
1021
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001022 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001023 if (!DestPointer) {
1024 return TC_NotApplicable;
1025 }
1026
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001027 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001028 if (!SrcPointer) {
1029 msg = diag::err_bad_static_cast_pointer_nonpointer;
1030 return TC_NotApplicable;
1031 }
1032
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001033 return TryStaticDowncast(Self,
1034 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1035 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001036 CStyle, OpRange, SrcType, DestType, msg, Kind,
1037 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001038}
1039
1040/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1041/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001042/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001043TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001044TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001046 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001047 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001048 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +00001049 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1050 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001051 return TC_NotApplicable;
1052
Sebastian Redl9f831db2009-07-25 15:41:38 +00001053 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001054 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001055 return TC_NotApplicable;
1056 }
1057
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001058 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001059 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001060 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1061 return TC_NotApplicable;
1062 }
1063
1064 // Target type does derive from source type. Now we're serious. If an error
1065 // appears now, it's not ignored.
1066 // This may not be entirely in line with the standard. Take for example:
1067 // struct A {};
1068 // struct B : virtual A {
1069 // B(A&);
1070 // };
Mike Stump11289f42009-09-09 15:08:12 +00001071 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001072 // void f()
1073 // {
1074 // (void)static_cast<const B&>(*((A*)0));
1075 // }
1076 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1077 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1078 // However, both GCC and Comeau reject this example, and accepting it would
1079 // mean more complex code if we're to preserve the nice error message.
1080 // FIXME: Being 100% compliant here would be nice to have.
1081
1082 // Must preserve cv, as always, unless we're in C-style mode.
1083 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001084 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001085 return TC_Failed;
1086 }
1087
1088 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1089 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1090 // that it builds the paths in reverse order.
1091 // To sum up: record all paths to the base and build a nice string from
1092 // them. Use it to spice up the error message.
1093 if (!Paths.isRecordingPaths()) {
1094 Paths.clear();
1095 Paths.setRecordingPaths(true);
1096 Self.IsDerivedFrom(DestType, SrcType, Paths);
1097 }
1098 std::string PathDisplayStr;
1099 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001100 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001101 PI != PE; ++PI) {
1102 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1103 // We haven't displayed a path to this particular base
1104 // class subobject yet.
1105 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001106 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1107 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001108 EI != EE; ++EI)
1109 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001110 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001111 }
1112 }
1113
1114 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001115 << QualType(SrcType).getUnqualifiedType()
1116 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001117 << PathDisplayStr << OpRange;
1118 msg = 0;
1119 return TC_Failed;
1120 }
1121
1122 if (Paths.getDetectedVirtual() != 0) {
1123 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1124 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1125 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1126 msg = 0;
1127 return TC_Failed;
1128 }
1129
John McCallfe9cf0a2011-02-14 23:21:33 +00001130 if (!CStyle) {
1131 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1132 SrcType, DestType,
1133 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001134 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001135 case Sema::AR_accessible:
1136 case Sema::AR_delayed: // be optimistic
1137 case Sema::AR_dependent: // be optimistic
1138 break;
1139
1140 case Sema::AR_inaccessible:
1141 msg = 0;
1142 return TC_Failed;
1143 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001144 }
1145
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001146 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001147 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001148 return TC_Success;
1149}
1150
1151/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1152/// C++ 5.2.9p9 is valid:
1153///
1154/// An rvalue of type "pointer to member of D of type cv1 T" can be
1155/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1156/// where B is a base class of D [...].
1157///
1158TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001159TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001160 QualType DestType, bool CStyle,
1161 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001162 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001163 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001164 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001165 if (!DestMemPtr)
1166 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001167
1168 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001169 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001170 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001171 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001172 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001173 FoundOverload)) {
1174 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1175 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1176 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1177 WasOverloadedFunction = true;
1178 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001179 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001180
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001181 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001182 if (!SrcMemPtr) {
1183 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1184 return TC_NotApplicable;
1185 }
1186
1187 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001188 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1189 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001190 return TC_NotApplicable;
1191
1192 // B base of D
1193 QualType SrcClass(SrcMemPtr->getClass(), 0);
1194 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001195 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001196 /*DetectVirtual=*/true);
1197 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1198 return TC_NotApplicable;
1199 }
1200
1201 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001202 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001203 Paths.clear();
1204 Paths.setRecordingPaths(true);
1205 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1206 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001207 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001208 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1209 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1210 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1211 msg = 0;
1212 return TC_Failed;
1213 }
1214
1215 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1216 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1217 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1218 msg = 0;
1219 return TC_Failed;
1220 }
1221
John McCallfe9cf0a2011-02-14 23:21:33 +00001222 if (!CStyle) {
1223 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1224 DestClass, SrcClass,
1225 Paths.front(),
1226 diag::err_upcast_to_inaccessible_base)) {
1227 case Sema::AR_accessible:
1228 case Sema::AR_delayed:
1229 case Sema::AR_dependent:
1230 // Optimistically assume that the delayed and dependent cases
1231 // will work out.
1232 break;
1233
1234 case Sema::AR_inaccessible:
1235 msg = 0;
1236 return TC_Failed;
1237 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001238 }
1239
Douglas Gregorc934bc82010-03-07 23:24:59 +00001240 if (WasOverloadedFunction) {
1241 // Resolve the address of the overloaded function again, this time
1242 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001243 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001244 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001245 true,
1246 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001247 if (!Fn) {
1248 msg = 0;
1249 return TC_Failed;
1250 }
1251
John McCall16df1e52010-03-30 21:47:33 +00001252 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001253 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001254 msg = 0;
1255 return TC_Failed;
1256 }
1257 }
1258
Anders Carlssonb78feca2010-04-24 19:22:20 +00001259 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001260 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001261 return TC_Success;
1262}
1263
1264/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1265/// is valid:
1266///
1267/// An expression e can be explicitly converted to a type T using a
1268/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1269TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001270TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001271 Sema::CheckedConversionKind CCK,
1272 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001273 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001274 if (DestType->isRecordType()) {
1275 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1276 diag::err_bad_dynamic_cast_incomplete)) {
1277 msg = 0;
1278 return TC_Failed;
1279 }
1280 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001281
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001282 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1283 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001284 = (CCK == Sema::CCK_CStyleCast)
1285 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1286 : (CCK == Sema::CCK_FunctionalCast)
1287 ? InitializationKind::CreateFunctionalCast(OpRange)
1288 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001289 Expr *SrcExprRaw = SrcExpr.get();
1290 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001291
1292 // At this point of CheckStaticCast, if the destination is a reference,
1293 // or the expression is an overload expression this has to work.
1294 // There is no other way that works.
1295 // On the other hand, if we're checking a C-style cast, we've still got
1296 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001297 bool CStyle
1298 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001299 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001300 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001301
John McCalldadc5752010-08-24 06:29:42 +00001302 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001303 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001304 if (Result.isInvalid()) {
1305 msg = 0;
1306 return TC_Failed;
1307 }
1308
Douglas Gregorb33eed02010-04-16 22:09:46 +00001309 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001310 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001311 else
John McCalle3027922010-08-25 11:45:40 +00001312 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001313
John Wiegley01296292011-04-08 18:41:53 +00001314 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001315 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001316}
1317
1318/// TryConstCast - See if a const_cast from source to destination is allowed,
1319/// and perform it if it is.
1320static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1321 bool CStyle, unsigned &msg) {
1322 DestType = Self.Context.getCanonicalType(DestType);
1323 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001324 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1325 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001326 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1327 // is C-style, static_cast might find a way, so we simply suggest a
1328 // message and tell the parent to keep searching.
1329 msg = diag::err_bad_cxx_cast_rvalue;
1330 return TC_NotApplicable;
1331 }
1332
1333 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1334 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1335 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1336 SrcType = Self.Context.getPointerType(SrcType);
1337 }
1338
1339 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1340 // the rules for const_cast are the same as those used for pointers.
1341
John McCall0e704f72010-05-18 09:35:29 +00001342 if (!DestType->isPointerType() &&
1343 !DestType->isMemberPointerType() &&
1344 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001345 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1346 // was a reference type, we converted it to a pointer above.
1347 // The status of rvalue references isn't entirely clear, but it looks like
1348 // conversion to them is simply invalid.
1349 // C++ 5.2.11p3: For two pointer types [...]
1350 if (!CStyle)
1351 msg = diag::err_bad_const_cast_dest;
1352 return TC_NotApplicable;
1353 }
1354 if (DestType->isFunctionPointerType() ||
1355 DestType->isMemberFunctionPointerType()) {
1356 // Cannot cast direct function pointers.
1357 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1358 // T is the ultimate pointee of source and target type.
1359 if (!CStyle)
1360 msg = diag::err_bad_const_cast_dest;
1361 return TC_NotApplicable;
1362 }
1363 SrcType = Self.Context.getCanonicalType(SrcType);
1364
1365 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1366 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001367 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1368 // in multi-level pointers may change, but the level count must be the same,
1369 // as must be the final pointee type.
1370 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001371 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001372 Qualifiers SrcQuals, DestQuals;
1373 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1374 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1375
1376 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1377 // the other qualifiers (e.g., address spaces) are identical.
1378 SrcQuals.removeCVRQualifiers();
1379 DestQuals.removeCVRQualifiers();
1380 if (SrcQuals != DestQuals)
1381 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001382 }
1383
1384 // Since we're dealing in canonical types, the remainder must be the same.
1385 if (SrcType != DestType)
1386 return TC_NotApplicable;
1387
1388 return TC_Success;
1389}
1390
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001391// Checks for undefined behavior in reinterpret_cast.
1392// The cases that is checked for is:
1393// *reinterpret_cast<T*>(&a)
1394// reinterpret_cast<T&>(a)
1395// where accessing 'a' as type 'T' will result in undefined behavior.
1396void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1397 bool IsDereference,
1398 SourceRange Range) {
1399 unsigned DiagID = IsDereference ?
1400 diag::warn_pointer_indirection_from_incompatible_type :
1401 diag::warn_undefined_reinterpret_cast;
1402
1403 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001404 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001405 return;
1406 }
1407
1408 QualType SrcTy, DestTy;
1409 if (IsDereference) {
1410 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1411 return;
1412 }
1413 SrcTy = SrcType->getPointeeType();
1414 DestTy = DestType->getPointeeType();
1415 } else {
1416 if (!DestType->getAs<ReferenceType>()) {
1417 return;
1418 }
1419 SrcTy = SrcType;
1420 DestTy = DestType->getPointeeType();
1421 }
1422
1423 // Cast is compatible if the types are the same.
1424 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1425 return;
1426 }
1427 // or one of the types is a char or void type
1428 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1429 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1430 return;
1431 }
1432 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001433 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001434 return;
1435 }
1436
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001437 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001438 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1439 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1440 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1441 return;
1442 }
1443 }
1444
1445 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1446}
Douglas Gregor1beec452011-03-12 01:48:56 +00001447
John Wiegley01296292011-04-08 18:41:53 +00001448static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001449 QualType DestType, bool CStyle,
1450 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001451 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001452 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001453 bool IsLValueCast = false;
1454
Sebastian Redl9f831db2009-07-25 15:41:38 +00001455 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001456 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001457
1458 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001459 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1460 if (SrcType == Self.Context.OverloadTy) {
1461 // ... unless foo<int> resolves to an lvalue unambiguously
1462 ExprResult SingleFunctionExpr =
John Wiegley01296292011-04-08 18:41:53 +00001463 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +00001464 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1465 );
1466 if (SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001467 SrcExpr = move(SingleFunctionExpr);
1468 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001469 }
1470 else
1471 return TC_NotApplicable;
1472 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001473
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001474 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001475 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001476 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001477 // Cannot cast non-lvalue to lvalue reference type. See the similar
1478 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001479 msg = diag::err_bad_cxx_cast_rvalue;
1480 return TC_NotApplicable;
1481 }
1482
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001483 if (!CStyle) {
1484 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1485 /*isDereference=*/false, OpRange);
1486 }
1487
Sebastian Redl9f831db2009-07-25 15:41:38 +00001488 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1489 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1490 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001491
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001492 const char *inappropriate = 0;
1493 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001494 case OK_Ordinary:
1495 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001496 case OK_BitField: inappropriate = "bit-field"; break;
1497 case OK_VectorComponent: inappropriate = "vector element"; break;
1498 case OK_ObjCProperty: inappropriate = "property expression"; break;
1499 }
1500 if (inappropriate) {
1501 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1502 << inappropriate << DestType
1503 << OpRange << SrcExpr.get()->getSourceRange();
1504 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001505 return TC_NotApplicable;
1506 }
1507
Sebastian Redl9f831db2009-07-25 15:41:38 +00001508 // This code does this transformation for the checked types.
1509 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1510 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001511
Douglas Gregor51954272010-07-13 23:17:26 +00001512 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001513 }
1514
1515 // Canonicalize source for comparison.
1516 SrcType = Self.Context.getCanonicalType(SrcType);
1517
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001518 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1519 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001520 if (DestMemPtr && SrcMemPtr) {
1521 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1522 // can be explicitly converted to an rvalue of type "pointer to member
1523 // of Y of type T2" if T1 and T2 are both function types or both object
1524 // types.
1525 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1526 SrcMemPtr->getPointeeType()->isFunctionType())
1527 return TC_NotApplicable;
1528
1529 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1530 // constness.
1531 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1532 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001533 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1534 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001535 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001536 return TC_Failed;
1537 }
1538
Charles Davisebab1ed2010-08-16 05:30:44 +00001539 // Don't allow casting between member pointers of different sizes.
1540 if (Self.Context.getTypeSize(DestMemPtr) !=
1541 Self.Context.getTypeSize(SrcMemPtr)) {
1542 msg = diag::err_bad_cxx_cast_member_pointer_size;
1543 return TC_Failed;
1544 }
1545
Sebastian Redl9f831db2009-07-25 15:41:38 +00001546 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001547 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001548 return TC_Success;
1549 }
1550
1551 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001552 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001553 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1554 // type large enough to hold it. A value of std::nullptr_t can be
1555 // converted to an integral type; the conversion has the same meaning
1556 // and validity as a conversion of (void*)0 to the integral type.
1557 if (Self.Context.getTypeSize(SrcType) >
1558 Self.Context.getTypeSize(DestType)) {
1559 msg = diag::err_bad_reinterpret_cast_small_int;
1560 return TC_Failed;
1561 }
John McCalle3027922010-08-25 11:45:40 +00001562 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001563 return TC_Success;
1564 }
1565
Anders Carlsson570af5d2009-09-16 19:19:43 +00001566 bool destIsVector = DestType->isVectorType();
1567 bool srcIsVector = SrcType->isVectorType();
1568 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001569 // FIXME: Should this also apply to floating point types?
1570 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1571 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001572
1573 // Check if this is a cast between a vector and something else.
1574 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1575 !(srcIsVector && destIsVector))
1576 return TC_NotApplicable;
1577
1578 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001579 if (Self.Context.getTypeSize(SrcType)
1580 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001581 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001582 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001583 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001584
1585 if (destIsScalar)
1586 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1587 else if (srcIsScalar)
1588 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1589 else
1590 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1591
1592 return TC_Failed;
1593 }
1594
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001595 bool destIsPtr = DestType->isAnyPointerType() ||
1596 DestType->isBlockPointerType();
1597 bool srcIsPtr = SrcType->isAnyPointerType() ||
1598 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001599 if (!destIsPtr && !srcIsPtr) {
1600 // Except for std::nullptr_t->integer and lvalue->reference, which are
1601 // handled above, at least one of the two arguments must be a pointer.
1602 return TC_NotApplicable;
1603 }
1604
1605 if (SrcType == DestType) {
1606 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1607 // restrictions, a cast to the same type is allowed. The intent is not
1608 // entirely clear here, since all other paragraphs explicitly forbid casts
1609 // to the same type. However, the behavior of compilers is pretty consistent
1610 // on this point: allow same-type conversion if the involved types are
1611 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001612 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001613 return TC_Success;
1614 }
1615
Douglas Gregor6972a622010-06-16 00:35:25 +00001616 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001617 assert(srcIsPtr && "One type must be a pointer");
1618 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001619 // type large enough to hold it; except in Microsoft mode, where the
1620 // integral type size doesn't matter.
1621 if ((Self.Context.getTypeSize(SrcType) >
1622 Self.Context.getTypeSize(DestType)) &&
Francois Pichet0706d202011-09-17 17:15:52 +00001623 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001624 msg = diag::err_bad_reinterpret_cast_small_int;
1625 return TC_Failed;
1626 }
John McCalle3027922010-08-25 11:45:40 +00001627 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001628 return TC_Success;
1629 }
1630
Douglas Gregorb90df602010-06-16 00:17:44 +00001631 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001632 assert(destIsPtr && "One type must be a pointer");
1633 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1634 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001635 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1636 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001637 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001638 return TC_Success;
1639 }
1640
1641 if (!destIsPtr || !srcIsPtr) {
1642 // With the valid non-pointer conversions out of the way, we can be even
1643 // more stringent.
1644 return TC_NotApplicable;
1645 }
1646
1647 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1648 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001649 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1650 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001651 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001652 return TC_Failed;
1653 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001654
1655 // Cannot convert between block pointers and Objective-C object pointers.
1656 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1657 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1658 return TC_NotApplicable;
1659
John McCall9320b872011-09-09 05:25:32 +00001660 if (IsLValueCast) {
1661 Kind = CK_LValueBitCast;
1662 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001663 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001664 } else if (DestType->isBlockPointerType()) {
1665 if (!SrcType->isBlockPointerType()) {
1666 Kind = CK_AnyPointerToBlockPointerCast;
1667 } else {
1668 Kind = CK_BitCast;
1669 }
1670 } else {
1671 Kind = CK_BitCast;
1672 }
1673
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001674 // Any pointer can be cast to an Objective-C pointer type with a C-style
1675 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001676 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001677 return TC_Success;
1678 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001679
Sebastian Redl9f831db2009-07-25 15:41:38 +00001680 // Not casting away constness, so the only remaining check is for compatible
1681 // pointer categories.
1682
1683 if (SrcType->isFunctionPointerType()) {
1684 if (DestType->isFunctionPointerType()) {
1685 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1686 // a pointer to a function of a different type.
1687 return TC_Success;
1688 }
1689
1690 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1691 // an object type or vice versa is conditionally-supported.
1692 // Compilers support it in C++03 too, though, because it's necessary for
1693 // casting the return value of dlsym() and GetProcAddress().
1694 // FIXME: Conditionally-supported behavior should be configurable in the
1695 // TargetInfo or similar.
1696 if (!Self.getLangOptions().CPlusPlus0x)
1697 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1698 return TC_Success;
1699 }
1700
1701 if (DestType->isFunctionPointerType()) {
1702 // See above.
1703 if (!Self.getLangOptions().CPlusPlus0x)
1704 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1705 return TC_Success;
1706 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001707
Sebastian Redl9f831db2009-07-25 15:41:38 +00001708 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1709 // a pointer to an object of different type.
1710 // Void pointers are not specified, but supported by every compiler out there.
1711 // So we finish by allowing everything that remains - it's got to be two
1712 // object pointers.
1713 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001714}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001715
John McCall9776e432011-10-06 23:25:11 +00001716void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
1717 // Handle placeholders.
1718 if (isPlaceholder()) {
1719 // C-style casts can resolve __unknown_any types.
1720 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1721 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1722 SrcExpr.get(), Kind,
1723 ValueKind, BasePath);
1724 return;
1725 }
John McCallb50451a2011-10-05 07:41:44 +00001726
John McCall9776e432011-10-06 23:25:11 +00001727 checkNonOverloadPlaceholders();
1728 if (SrcExpr.isInvalid())
1729 return;
1730 }
1731
1732 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00001733 // This test is outside everything else because it's the only case where
1734 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00001735 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00001736 Kind = CK_ToVoid;
1737
John McCall9776e432011-10-06 23:25:11 +00001738 if (claimPlaceholder(BuiltinType::Overload)) {
John McCallb50451a2011-10-05 07:41:44 +00001739 SrcExpr = Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1740 SrcExpr.take(), /* Decay Function to ptr */ false,
1741 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00001742 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00001743 if (SrcExpr.isInvalid())
1744 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001745 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001746
John McCall9776e432011-10-06 23:25:11 +00001747 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1748 if (SrcExpr.isInvalid())
John McCallb50451a2011-10-05 07:41:44 +00001749 return;
John McCallb50451a2011-10-05 07:41:44 +00001750
1751 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00001752 }
1753
Sebastian Redl9f831db2009-07-25 15:41:38 +00001754 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb50451a2011-10-05 07:41:44 +00001755 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1756 assert(Kind == CK_Dependent);
1757 return;
John McCall8cb679e2010-11-15 09:13:47 +00001758 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00001759
John McCallb50451a2011-10-05 07:41:44 +00001760 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
1761 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1762 if (SrcExpr.isInvalid())
1763 return;
John Wiegley01296292011-04-08 18:41:53 +00001764 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001765
John McCall3aef3d82011-04-10 19:13:55 +00001766 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00001767 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00001768 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00001769 && (SrcExpr.get()->getType()->isIntegerType()
1770 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00001771 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00001772 return;
John McCall3aef3d82011-04-10 19:13:55 +00001773 }
1774
Sebastian Redl9f831db2009-07-25 15:41:38 +00001775 // C++ [expr.cast]p5: The conversions performed by
1776 // - a const_cast,
1777 // - a static_cast,
1778 // - a static_cast followed by a const_cast,
1779 // - a reinterpret_cast, or
1780 // - a reinterpret_cast followed by a const_cast,
1781 // can be performed using the cast notation of explicit type conversion.
1782 // [...] If a conversion can be interpreted in more than one of the ways
1783 // listed above, the interpretation that appears first in the list is used,
1784 // even if a cast resulting from that interpretation is ill-formed.
1785 // In plain language, this means trying a const_cast ...
1786 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb50451a2011-10-05 07:41:44 +00001787 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1788 /*CStyle*/true, msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001789 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001790 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001791
John McCall31168b02011-06-15 23:02:42 +00001792 Sema::CheckedConversionKind CCK
1793 = FunctionalStyle? Sema::CCK_FunctionalCast
1794 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001795 if (tcr == TC_NotApplicable) {
1796 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00001797 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1798 msg, Kind, BasePath);
1799 if (SrcExpr.isInvalid())
1800 return;
1801
Sebastian Redl9f831db2009-07-25 15:41:38 +00001802 if (tcr == TC_NotApplicable) {
1803 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00001804 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1805 OpRange, msg, Kind);
1806 if (SrcExpr.isInvalid())
1807 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001808 }
1809 }
1810
John McCallb50451a2011-10-05 07:41:44 +00001811 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1812 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00001813
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001814 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00001815 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001816 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00001817 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1818 DestType,
1819 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001820 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001821
Richard Trieu70d14f52011-04-16 01:09:30 +00001822 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001823 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001824
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001825 } else {
John McCallb50451a2011-10-05 07:41:44 +00001826 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1827 OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001828 }
John McCallb50451a2011-10-05 07:41:44 +00001829 } else if (Kind == CK_BitCast) {
1830 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001831 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001832
John McCallb50451a2011-10-05 07:41:44 +00001833 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00001834 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00001835 SrcExpr = ExprError();
1836}
1837
John McCall9776e432011-10-06 23:25:11 +00001838/// Check the semantics of a C-style cast operation, in C.
1839void CastOperation::CheckCStyleCast() {
1840 assert(!Self.getLangOptions().CPlusPlus);
1841
1842 // Handle placeholders.
1843 if (isPlaceholder()) {
1844 // C-style casts can resolve __unknown_any types.
1845 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1846 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1847 SrcExpr.get(), Kind,
1848 ValueKind, BasePath);
1849 return;
1850 }
1851
1852 checkNonOverloadPlaceholders();
1853 if (SrcExpr.isInvalid())
1854 return;
1855 }
1856
1857 assert(!isPlaceholder());
1858
1859 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1860 // type needs to be scalar.
1861 if (DestType->isVoidType()) {
1862 // We don't necessarily do lvalue-to-rvalue conversions on this.
1863 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1864 if (SrcExpr.isInvalid())
1865 return;
1866
1867 // Cast to void allows any expr type.
1868 Kind = CK_ToVoid;
1869 return;
1870 }
1871
1872 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1873 if (SrcExpr.isInvalid())
1874 return;
1875 QualType SrcType = SrcExpr.get()->getType();
1876
1877 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1878 diag::err_typecheck_cast_to_incomplete)) {
1879 SrcExpr = ExprError();
1880 return;
1881 }
1882
1883 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1884 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1885
1886 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1887 // GCC struct/union extension: allow cast to self.
1888 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1889 << DestType << SrcExpr.get()->getSourceRange();
1890 Kind = CK_NoOp;
1891 return;
1892 }
1893
1894 // GCC's cast to union extension.
1895 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1896 RecordDecl *RD = DestRecordTy->getDecl();
1897 RecordDecl::field_iterator Field, FieldEnd;
1898 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1899 Field != FieldEnd; ++Field) {
1900 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1901 !Field->isUnnamedBitfield()) {
1902 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1903 << SrcExpr.get()->getSourceRange();
1904 break;
1905 }
1906 }
1907 if (Field == FieldEnd) {
1908 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1909 << SrcType << SrcExpr.get()->getSourceRange();
1910 SrcExpr = ExprError();
1911 return;
1912 }
1913 Kind = CK_ToUnion;
1914 return;
1915 }
1916
1917 // Reject any other conversions to non-scalar types.
1918 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1919 << DestType << SrcExpr.get()->getSourceRange();
1920 SrcExpr = ExprError();
1921 return;
1922 }
1923
1924 // The type we're casting to is known to be a scalar or vector.
1925
1926 // Require the operand to be a scalar or vector.
1927 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1928 Self.Diag(SrcExpr.get()->getExprLoc(),
1929 diag::err_typecheck_expect_scalar_operand)
1930 << SrcType << SrcExpr.get()->getSourceRange();
1931 SrcExpr = ExprError();
1932 return;
1933 }
1934
1935 if (DestType->isExtVectorType()) {
1936 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1937 return;
1938 }
1939
1940 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1941 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1942 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1943 Kind = CK_VectorSplat;
1944 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1945 SrcExpr = ExprError();
1946 }
1947 return;
1948 }
1949
1950 if (SrcType->isVectorType()) {
1951 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1952 SrcExpr = ExprError();
1953 return;
1954 }
1955
1956 // The source and target types are both scalars, i.e.
1957 // - arithmetic types (fundamental, enum, and complex)
1958 // - all kinds of pointers
1959 // Note that member pointers were filtered out with C++, above.
1960
1961 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
1962 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
1963 SrcExpr = ExprError();
1964 return;
1965 }
1966
1967 // If either type is a pointer, the other type has to be either an
1968 // integer or a pointer.
1969 if (!DestType->isArithmeticType()) {
1970 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
1971 Self.Diag(SrcExpr.get()->getExprLoc(),
1972 diag::err_cast_pointer_from_non_pointer_int)
1973 << SrcType << SrcExpr.get()->getSourceRange();
1974 SrcExpr = ExprError();
1975 return;
1976 }
1977 } else if (!SrcType->isArithmeticType()) {
1978 if (!DestType->isIntegralType(Self.Context) &&
1979 DestType->isArithmeticType()) {
1980 Self.Diag(SrcExpr.get()->getLocStart(),
1981 diag::err_cast_pointer_to_non_pointer_int)
1982 << SrcType << SrcExpr.get()->getSourceRange();
1983 SrcExpr = ExprError();
1984 return;
1985 }
1986 }
1987
1988 // ARC imposes extra restrictions on casts.
1989 if (Self.getLangOptions().ObjCAutoRefCount) {
1990 checkObjCARCConversion(Sema::CCK_CStyleCast);
1991 if (SrcExpr.isInvalid())
1992 return;
1993
1994 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
1995 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
1996 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
1997 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
1998 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
1999 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2000 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2001 Self.Diag(SrcExpr.get()->getLocStart(),
2002 diag::err_typecheck_incompatible_ownership)
2003 << SrcType << DestType << Sema::AA_Casting
2004 << SrcExpr.get()->getSourceRange();
2005 return;
2006 }
2007 }
2008 }
2009 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2010 Self.Diag(SrcExpr.get()->getLocStart(),
2011 diag::err_arc_convesion_of_weak_unavailable)
2012 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2013 SrcExpr = ExprError();
2014 return;
2015 }
2016 }
2017
2018 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2019 if (SrcExpr.isInvalid())
2020 return;
2021
2022 if (Kind == CK_BitCast)
2023 checkCastAlign();
2024}
2025
2026ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2027 TypeSourceInfo *CastTypeInfo,
2028 SourceLocation RPLoc,
2029 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002030 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2031 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2032 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2033
John McCall9776e432011-10-06 23:25:11 +00002034 if (getLangOptions().CPlusPlus) {
2035 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
2036 } else {
2037 Op.CheckCStyleCast();
2038 }
2039
John McCallb50451a2011-10-05 07:41:44 +00002040 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002041 return ExprError();
2042
John McCallb50451a2011-10-05 07:41:44 +00002043 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
2044 Op.Kind, Op.SrcExpr.take(), &Op.BasePath,
2045 CastTypeInfo, LPLoc, RPLoc));
2046}
2047
2048ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2049 SourceLocation LPLoc,
2050 Expr *CastExpr,
2051 SourceLocation RPLoc) {
2052 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2053 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2054 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2055
John McCall9776e432011-10-06 23:25:11 +00002056 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
John McCallb50451a2011-10-05 07:41:44 +00002057 if (Op.SrcExpr.isInvalid())
2058 return ExprError();
2059
2060 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2061 Op.ValueKind, CastTypeInfo,
2062 Op.DestRange.getBegin(),
2063 Op.Kind, Op.SrcExpr.take(),
2064 &Op.BasePath, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002065}