1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2 //
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 //
10 //  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)'
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Sema/Initialization.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include <set>
27 using namespace clang;
28 
29 
30 
31 enum TryCastResult {
32   TC_NotApplicable, ///< The cast method is not applicable.
33   TC_Success,       ///< The cast method is appropriate and successful.
34   TC_Failed         ///< The cast method is appropriate, but failed. A
35                     ///< diagnostic has been emitted.
36 };
37 
38 enum CastType {
39   CT_Const,       ///< const_cast
40   CT_Static,      ///< static_cast
41   CT_Reinterpret, ///< reinterpret_cast
42   CT_Dynamic,     ///< dynamic_cast
43   CT_CStyle,      ///< (Type)expr
44   CT_Functional   ///< Type(expr)
45 };
46 
47 namespace {
48   struct CastOperation {
49     CastOperation(Sema &S, QualType destType, ExprResult src)
50       : Self(S), SrcExpr(src), DestType(destType),
51         ResultType(destType.getNonLValueExprType(S.Context)),
52         ValueKind(Expr::getValueKindForType(destType)),
53         Kind(CK_Dependent), IsARCUnbridgedCast(false) {
54 
55       if (const BuiltinType *placeholder =
56             src.get()->getType()->getAsPlaceholderType()) {
57         PlaceholderKind = placeholder->getKind();
58       } else {
59         PlaceholderKind = (BuiltinType::Kind) 0;
60       }
61     }
62 
63     Sema &Self;
64     ExprResult SrcExpr;
65     QualType DestType;
66     QualType ResultType;
67     ExprValueKind ValueKind;
68     CastKind Kind;
69     BuiltinType::Kind PlaceholderKind;
70     CXXCastPath BasePath;
71     bool IsARCUnbridgedCast;
72 
73     SourceRange OpRange;
74     SourceRange DestRange;
75 
76     // Top-level semantics-checking routines.
77     void CheckConstCast();
78     void CheckReinterpretCast();
79     void CheckStaticCast();
80     void CheckDynamicCast();
81     void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
82     void CheckCStyleCast();
83 
84     /// Complete an apparently-successful cast operation that yields
85     /// the given expression.
86     ExprResult complete(CastExpr *castExpr) {
87       // If this is an unbridged cast, wrap the result in an implicit
88       // cast that yields the unbridged-cast placeholder type.
89       if (IsARCUnbridgedCast) {
90         castExpr = ImplicitCastExpr::Create(Self.Context,
91                                             Self.Context.ARCUnbridgedCastTy,
92                                             CK_Dependent, castExpr, 0,
93                                             castExpr->getValueKind());
94       }
95       return Self.Owned(castExpr);
96     }
97 
98     // Internal convenience methods.
99 
100     /// Try to handle the given placeholder expression kind.  Return
101     /// true if the source expression has the appropriate placeholder
102     /// kind.  A placeholder can only be claimed once.
103     bool claimPlaceholder(BuiltinType::Kind K) {
104       if (PlaceholderKind != K) return false;
105 
106       PlaceholderKind = (BuiltinType::Kind) 0;
107       return true;
108     }
109 
110     bool isPlaceholder() const {
111       return PlaceholderKind != 0;
112     }
113     bool isPlaceholder(BuiltinType::Kind K) const {
114       return PlaceholderKind == K;
115     }
116 
117     void checkCastAlign() {
118       Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
119     }
120 
121     void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
122       assert(Self.getLangOpts().ObjCAutoRefCount);
123 
124       Expr *src = SrcExpr.get();
125       if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
126             Sema::ACR_unbridged)
127         IsARCUnbridgedCast = true;
128       SrcExpr = src;
129     }
130 
131     /// Check for and handle non-overload placeholder expressions.
132     void checkNonOverloadPlaceholders() {
133       if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
134         return;
135 
136       SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137       if (SrcExpr.isInvalid())
138         return;
139       PlaceholderKind = (BuiltinType::Kind) 0;
140     }
141   };
142 }
143 
144 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145                                bool CheckCVR, bool CheckObjCLifetime);
146 
147 // The Try functions attempt a specific way of casting. If they succeed, they
148 // return TC_Success. If their way of casting is not appropriate for the given
149 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150 // to emit if no other way succeeds. If their way of casting is appropriate but
151 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152 // they emit a specialized diagnostic.
153 // All diagnostics returned by these functions must expect the same three
154 // arguments:
155 // %0: Cast Type (a value from the CastType enumeration)
156 // %1: Source Type
157 // %2: Destination Type
158 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
159                                            QualType DestType, bool CStyle,
160                                            CastKind &Kind,
161                                            CXXCastPath &BasePath,
162                                            unsigned &msg);
163 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
164                                                QualType DestType, bool CStyle,
165                                                const SourceRange &OpRange,
166                                                unsigned &msg,
167                                                CastKind &Kind,
168                                                CXXCastPath &BasePath);
169 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170                                               QualType DestType, bool CStyle,
171                                               const SourceRange &OpRange,
172                                               unsigned &msg,
173                                               CastKind &Kind,
174                                               CXXCastPath &BasePath);
175 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176                                        CanQualType DestType, bool CStyle,
177                                        const SourceRange &OpRange,
178                                        QualType OrigSrcType,
179                                        QualType OrigDestType, unsigned &msg,
180                                        CastKind &Kind,
181                                        CXXCastPath &BasePath);
182 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
183                                                QualType SrcType,
184                                                QualType DestType,bool CStyle,
185                                                const SourceRange &OpRange,
186                                                unsigned &msg,
187                                                CastKind &Kind,
188                                                CXXCastPath &BasePath);
189 
190 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
191                                            QualType DestType,
192                                            Sema::CheckedConversionKind CCK,
193                                            const SourceRange &OpRange,
194                                            unsigned &msg, CastKind &Kind,
195                                            bool ListInitialization);
196 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
197                                    QualType DestType,
198                                    Sema::CheckedConversionKind CCK,
199                                    const SourceRange &OpRange,
200                                    unsigned &msg, CastKind &Kind,
201                                    CXXCastPath &BasePath,
202                                    bool ListInitialization);
203 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
204                                   QualType DestType, bool CStyle,
205                                   unsigned &msg);
206 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
207                                         QualType DestType, bool CStyle,
208                                         const SourceRange &OpRange,
209                                         unsigned &msg,
210                                         CastKind &Kind);
211 
212 
213 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
214 ExprResult
215 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
216                         SourceLocation LAngleBracketLoc, Declarator &D,
217                         SourceLocation RAngleBracketLoc,
218                         SourceLocation LParenLoc, Expr *E,
219                         SourceLocation RParenLoc) {
220 
221   assert(!D.isInvalidType());
222 
223   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
224   if (D.isInvalidType())
225     return ExprError();
226 
227   if (getLangOpts().CPlusPlus) {
228     // Check that there are no default arguments (C++ only).
229     CheckExtraCXXDefaultArguments(D);
230   }
231 
232   return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
233                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
234                            SourceRange(LParenLoc, RParenLoc));
235 }
236 
237 ExprResult
238 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
239                         TypeSourceInfo *DestTInfo, Expr *E,
240                         SourceRange AngleBrackets, SourceRange Parens) {
241   ExprResult Ex = Owned(E);
242   QualType DestType = DestTInfo->getType();
243 
244   // If the type is dependent, we won't do the semantic analysis now.
245   // FIXME: should we check this in a more fine-grained manner?
246   bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
247 
248   CastOperation Op(*this, DestType, E);
249   Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
250   Op.DestRange = AngleBrackets;
251 
252   switch (Kind) {
253   default: llvm_unreachable("Unknown C++ cast!");
254 
255   case tok::kw_const_cast:
256     if (!TypeDependent) {
257       Op.CheckConstCast();
258       if (Op.SrcExpr.isInvalid())
259         return ExprError();
260     }
261     return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
262                                   Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
263                                                 OpLoc, Parens.getEnd(),
264                                                 AngleBrackets));
265 
266   case tok::kw_dynamic_cast: {
267     if (!TypeDependent) {
268       Op.CheckDynamicCast();
269       if (Op.SrcExpr.isInvalid())
270         return ExprError();
271     }
272     return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
273                                     Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
274                                                   &Op.BasePath, DestTInfo,
275                                                   OpLoc, Parens.getEnd(),
276                                                   AngleBrackets));
277   }
278   case tok::kw_reinterpret_cast: {
279     if (!TypeDependent) {
280       Op.CheckReinterpretCast();
281       if (Op.SrcExpr.isInvalid())
282         return ExprError();
283     }
284     return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
285                                     Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
286                                                       0, DestTInfo, OpLoc,
287                                                       Parens.getEnd(),
288                                                       AngleBrackets));
289   }
290   case tok::kw_static_cast: {
291     if (!TypeDependent) {
292       Op.CheckStaticCast();
293       if (Op.SrcExpr.isInvalid())
294         return ExprError();
295     }
296 
297     return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
298                                    Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
299                                                  &Op.BasePath, DestTInfo,
300                                                  OpLoc, Parens.getEnd(),
301                                                  AngleBrackets));
302   }
303   }
304 }
305 
306 /// Try to diagnose a failed overloaded cast.  Returns true if
307 /// diagnostics were emitted.
308 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
309                                       SourceRange range, Expr *src,
310                                       QualType destType,
311                                       bool listInitialization) {
312   switch (CT) {
313   // These cast kinds don't consider user-defined conversions.
314   case CT_Const:
315   case CT_Reinterpret:
316   case CT_Dynamic:
317     return false;
318 
319   // These do.
320   case CT_Static:
321   case CT_CStyle:
322   case CT_Functional:
323     break;
324   }
325 
326   QualType srcType = src->getType();
327   if (!destType->isRecordType() && !srcType->isRecordType())
328     return false;
329 
330   InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
331   InitializationKind initKind
332     = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
333                                                       range, listInitialization)
334     : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
335                                                              listInitialization)
336     : InitializationKind::CreateCast(/*type range?*/ range);
337   InitializationSequence sequence(S, entity, initKind, src);
338 
339   assert(sequence.Failed() && "initialization succeeded on second try?");
340   switch (sequence.getFailureKind()) {
341   default: return false;
342 
343   case InitializationSequence::FK_ConstructorOverloadFailed:
344   case InitializationSequence::FK_UserConversionOverloadFailed:
345     break;
346   }
347 
348   OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
349 
350   unsigned msg = 0;
351   OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
352 
353   switch (sequence.getFailedOverloadResult()) {
354   case OR_Success: llvm_unreachable("successful failed overload");
355   case OR_No_Viable_Function:
356     if (candidates.empty())
357       msg = diag::err_ovl_no_conversion_in_cast;
358     else
359       msg = diag::err_ovl_no_viable_conversion_in_cast;
360     howManyCandidates = OCD_AllCandidates;
361     break;
362 
363   case OR_Ambiguous:
364     msg = diag::err_ovl_ambiguous_conversion_in_cast;
365     howManyCandidates = OCD_ViableCandidates;
366     break;
367 
368   case OR_Deleted:
369     msg = diag::err_ovl_deleted_conversion_in_cast;
370     howManyCandidates = OCD_ViableCandidates;
371     break;
372   }
373 
374   S.Diag(range.getBegin(), msg)
375     << CT << srcType << destType
376     << range << src->getSourceRange();
377 
378   candidates.NoteCandidates(S, howManyCandidates, src);
379 
380   return true;
381 }
382 
383 /// Diagnose a failed cast.
384 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
385                             SourceRange opRange, Expr *src, QualType destType,
386                             bool listInitialization) {
387   if (src->getType() == S.Context.BoundMemberTy) {
388     (void) S.CheckPlaceholderExpr(src); // will always fail
389     return;
390   }
391 
392   if (msg == diag::err_bad_cxx_cast_generic &&
393       tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
394                                 listInitialization))
395     return;
396 
397   S.Diag(opRange.getBegin(), msg) << castType
398     << src->getType() << destType << opRange << src->getSourceRange();
399 }
400 
401 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
402 /// this removes one level of indirection from both types, provided that they're
403 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
404 /// this one doesn't care if the two pointers-to-member don't point into the
405 /// same class. This is because CastsAwayConstness doesn't care.
406 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
407   const PointerType *T1PtrType = T1->getAs<PointerType>(),
408                     *T2PtrType = T2->getAs<PointerType>();
409   if (T1PtrType && T2PtrType) {
410     T1 = T1PtrType->getPointeeType();
411     T2 = T2PtrType->getPointeeType();
412     return true;
413   }
414   const ObjCObjectPointerType *T1ObjCPtrType =
415                                             T1->getAs<ObjCObjectPointerType>(),
416                               *T2ObjCPtrType =
417                                             T2->getAs<ObjCObjectPointerType>();
418   if (T1ObjCPtrType) {
419     if (T2ObjCPtrType) {
420       T1 = T1ObjCPtrType->getPointeeType();
421       T2 = T2ObjCPtrType->getPointeeType();
422       return true;
423     }
424     else if (T2PtrType) {
425       T1 = T1ObjCPtrType->getPointeeType();
426       T2 = T2PtrType->getPointeeType();
427       return true;
428     }
429   }
430   else if (T2ObjCPtrType) {
431     if (T1PtrType) {
432       T2 = T2ObjCPtrType->getPointeeType();
433       T1 = T1PtrType->getPointeeType();
434       return true;
435     }
436   }
437 
438   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
439                           *T2MPType = T2->getAs<MemberPointerType>();
440   if (T1MPType && T2MPType) {
441     T1 = T1MPType->getPointeeType();
442     T2 = T2MPType->getPointeeType();
443     return true;
444   }
445 
446   const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
447                          *T2BPType = T2->getAs<BlockPointerType>();
448   if (T1BPType && T2BPType) {
449     T1 = T1BPType->getPointeeType();
450     T2 = T2BPType->getPointeeType();
451     return true;
452   }
453 
454   return false;
455 }
456 
457 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
458 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
459 /// the cast checkers.  Both arguments must denote pointer (possibly to member)
460 /// types.
461 ///
462 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
463 ///
464 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
465 static bool
466 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
467                    bool CheckCVR, bool CheckObjCLifetime) {
468   // If the only checking we care about is for Objective-C lifetime qualifiers,
469   // and we're not in ARC mode, there's nothing to check.
470   if (!CheckCVR && CheckObjCLifetime &&
471       !Self.Context.getLangOpts().ObjCAutoRefCount)
472     return false;
473 
474   // Casting away constness is defined in C++ 5.2.11p8 with reference to
475   // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
476   // the rules are non-trivial. So first we construct Tcv *...cv* as described
477   // in C++ 5.2.11p8.
478   assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
479           SrcType->isBlockPointerType()) &&
480          "Source type is not pointer or pointer to member.");
481   assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
482           DestType->isBlockPointerType()) &&
483          "Destination type is not pointer or pointer to member.");
484 
485   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
486            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
487   SmallVector<Qualifiers, 8> cv1, cv2;
488 
489   // Find the qualifiers. We only care about cvr-qualifiers for the
490   // purpose of this check, because other qualifiers (address spaces,
491   // Objective-C GC, etc.) are part of the type's identity.
492   while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
493     // Determine the relevant qualifiers at this level.
494     Qualifiers SrcQuals, DestQuals;
495     Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
496     Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
497 
498     Qualifiers RetainedSrcQuals, RetainedDestQuals;
499     if (CheckCVR) {
500       RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
501       RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
502     }
503 
504     if (CheckObjCLifetime &&
505         !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
506       return true;
507 
508     cv1.push_back(RetainedSrcQuals);
509     cv2.push_back(RetainedDestQuals);
510   }
511   if (cv1.empty())
512     return false;
513 
514   // Construct void pointers with those qualifiers (in reverse order of
515   // unwrapping, of course).
516   QualType SrcConstruct = Self.Context.VoidTy;
517   QualType DestConstruct = Self.Context.VoidTy;
518   ASTContext &Context = Self.Context;
519   for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
520                                                           i2 = cv2.rbegin();
521        i1 != cv1.rend(); ++i1, ++i2) {
522     SrcConstruct
523       = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
524     DestConstruct
525       = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
526   }
527 
528   // Test if they're compatible.
529   bool ObjCLifetimeConversion;
530   return SrcConstruct != DestConstruct &&
531     !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
532                                     ObjCLifetimeConversion);
533 }
534 
535 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
536 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
537 /// checked downcasts in class hierarchies.
538 void CastOperation::CheckDynamicCast() {
539   if (ValueKind == VK_RValue)
540     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
541   else if (isPlaceholder())
542     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
543   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
544     return;
545 
546   QualType OrigSrcType = SrcExpr.get()->getType();
547   QualType DestType = Self.Context.getCanonicalType(this->DestType);
548 
549   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
550   //   or "pointer to cv void".
551 
552   QualType DestPointee;
553   const PointerType *DestPointer = DestType->getAs<PointerType>();
554   const ReferenceType *DestReference = 0;
555   if (DestPointer) {
556     DestPointee = DestPointer->getPointeeType();
557   } else if ((DestReference = DestType->getAs<ReferenceType>())) {
558     DestPointee = DestReference->getPointeeType();
559   } else {
560     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
561       << this->DestType << DestRange;
562     return;
563   }
564 
565   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
566   if (DestPointee->isVoidType()) {
567     assert(DestPointer && "Reference to void is not possible");
568   } else if (DestRecord) {
569     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
570                                  diag::err_bad_dynamic_cast_incomplete,
571                                  DestRange))
572       return;
573   } else {
574     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
575       << DestPointee.getUnqualifiedType() << DestRange;
576     return;
577   }
578 
579   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
580   //   complete class type, [...]. If T is an lvalue reference type, v shall be
581   //   an lvalue of a complete class type, [...]. If T is an rvalue reference
582   //   type, v shall be an expression having a complete class type, [...]
583   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
584   QualType SrcPointee;
585   if (DestPointer) {
586     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
587       SrcPointee = SrcPointer->getPointeeType();
588     } else {
589       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
590         << OrigSrcType << SrcExpr.get()->getSourceRange();
591       return;
592     }
593   } else if (DestReference->isLValueReferenceType()) {
594     if (!SrcExpr.get()->isLValue()) {
595       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
596         << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
597     }
598     SrcPointee = SrcType;
599   } else {
600     SrcPointee = SrcType;
601   }
602 
603   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
604   if (SrcRecord) {
605     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
606                                  diag::err_bad_dynamic_cast_incomplete,
607                                  SrcExpr.get()))
608       return;
609   } else {
610     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
611       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
612     return;
613   }
614 
615   assert((DestPointer || DestReference) &&
616     "Bad destination non-ptr/ref slipped through.");
617   assert((DestRecord || DestPointee->isVoidType()) &&
618     "Bad destination pointee slipped through.");
619   assert(SrcRecord && "Bad source pointee slipped through.");
620 
621   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
622   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
623     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
624       << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
625     return;
626   }
627 
628   // C++ 5.2.7p3: If the type of v is the same as the required result type,
629   //   [except for cv].
630   if (DestRecord == SrcRecord) {
631     Kind = CK_NoOp;
632     return;
633   }
634 
635   // C++ 5.2.7p5
636   // Upcasts are resolved statically.
637   if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
638     if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
639                                            OpRange.getBegin(), OpRange,
640                                            &BasePath))
641         return;
642 
643     Kind = CK_DerivedToBase;
644 
645     // If we are casting to or through a virtual base class, we need a
646     // vtable.
647     if (Self.BasePathInvolvesVirtualBase(BasePath))
648       Self.MarkVTableUsed(OpRange.getBegin(),
649                           cast<CXXRecordDecl>(SrcRecord->getDecl()));
650     return;
651   }
652 
653   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
654   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
655   assert(SrcDecl && "Definition missing");
656   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
657     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
658       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
659   }
660   Self.MarkVTableUsed(OpRange.getBegin(),
661                       cast<CXXRecordDecl>(SrcRecord->getDecl()));
662 
663   // Done. Everything else is run-time checks.
664   Kind = CK_Dynamic;
665 }
666 
667 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
668 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
669 /// like this:
670 /// const char *str = "literal";
671 /// legacy_function(const_cast\<char*\>(str));
672 void CastOperation::CheckConstCast() {
673   if (ValueKind == VK_RValue)
674     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
675   else if (isPlaceholder())
676     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
677   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
678     return;
679 
680   unsigned msg = diag::err_bad_cxx_cast_generic;
681   if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
682       && msg != 0)
683     Self.Diag(OpRange.getBegin(), msg) << CT_Const
684       << SrcExpr.get()->getType() << DestType << OpRange;
685 }
686 
687 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
688 /// or downcast between respective pointers or references.
689 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
690                                           QualType DestType,
691                                           SourceRange OpRange) {
692   QualType SrcType = SrcExpr->getType();
693   // When casting from pointer or reference, get pointee type; use original
694   // type otherwise.
695   const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
696   const CXXRecordDecl *SrcRD =
697     SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
698 
699   // Examining subobjects for records is only possible if the complete and
700   // valid definition is available.  Also, template instantiation is not
701   // allowed here.
702   if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
703     return;
704 
705   const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
706 
707   if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
708     return;
709 
710   enum {
711     ReinterpretUpcast,
712     ReinterpretDowncast
713   } ReinterpretKind;
714 
715   CXXBasePaths BasePaths;
716 
717   if (SrcRD->isDerivedFrom(DestRD, BasePaths))
718     ReinterpretKind = ReinterpretUpcast;
719   else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
720     ReinterpretKind = ReinterpretDowncast;
721   else
722     return;
723 
724   bool VirtualBase = true;
725   bool NonZeroOffset = false;
726   for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
727                                           E = BasePaths.end();
728        I != E; ++I) {
729     const CXXBasePath &Path = *I;
730     CharUnits Offset = CharUnits::Zero();
731     bool IsVirtual = false;
732     for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
733          IElem != EElem; ++IElem) {
734       IsVirtual = IElem->Base->isVirtual();
735       if (IsVirtual)
736         break;
737       const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
738       assert(BaseRD && "Base type should be a valid unqualified class type");
739       // Don't check if any base has invalid declaration or has no definition
740       // since it has no layout info.
741       const CXXRecordDecl *Class = IElem->Class,
742                           *ClassDefinition = Class->getDefinition();
743       if (Class->isInvalidDecl() || !ClassDefinition ||
744           !ClassDefinition->isCompleteDefinition())
745         return;
746 
747       const ASTRecordLayout &DerivedLayout =
748           Self.Context.getASTRecordLayout(Class);
749       Offset += DerivedLayout.getBaseClassOffset(BaseRD);
750     }
751     if (!IsVirtual) {
752       // Don't warn if any path is a non-virtually derived base at offset zero.
753       if (Offset.isZero())
754         return;
755       // Offset makes sense only for non-virtual bases.
756       else
757         NonZeroOffset = true;
758     }
759     VirtualBase = VirtualBase && IsVirtual;
760   }
761 
762   assert((VirtualBase || NonZeroOffset) &&
763          "Should have returned if has non-virtual base with zero offset");
764 
765   QualType BaseType =
766       ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
767   QualType DerivedType =
768       ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
769 
770   SourceLocation BeginLoc = OpRange.getBegin();
771   Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
772     << DerivedType << BaseType << !VirtualBase << ReinterpretKind
773     << OpRange;
774   Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
775     << ReinterpretKind
776     << FixItHint::CreateReplacement(BeginLoc, "static_cast");
777 }
778 
779 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
780 /// valid.
781 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
782 /// like this:
783 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
784 void CastOperation::CheckReinterpretCast() {
785   if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
786     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
787   else
788     checkNonOverloadPlaceholders();
789   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
790     return;
791 
792   unsigned msg = diag::err_bad_cxx_cast_generic;
793   TryCastResult tcr =
794     TryReinterpretCast(Self, SrcExpr, DestType,
795                        /*CStyle*/false, OpRange, msg, Kind);
796   if (tcr != TC_Success && msg != 0)
797   {
798     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
799       return;
800     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
801       //FIXME: &f<int>; is overloaded and resolvable
802       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
803         << OverloadExpr::find(SrcExpr.get()).Expression->getName()
804         << DestType << OpRange;
805       Self.NoteAllOverloadCandidates(SrcExpr.get());
806 
807     } else {
808       diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
809                       DestType, /*listInitialization=*/false);
810     }
811   } else if (tcr == TC_Success) {
812     if (Self.getLangOpts().ObjCAutoRefCount)
813       checkObjCARCConversion(Sema::CCK_OtherCast);
814     DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
815   }
816 }
817 
818 
819 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
820 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
821 /// implicit conversions explicit and getting rid of data loss warnings.
822 void CastOperation::CheckStaticCast() {
823   if (isPlaceholder()) {
824     checkNonOverloadPlaceholders();
825     if (SrcExpr.isInvalid())
826       return;
827   }
828 
829   // This test is outside everything else because it's the only case where
830   // a non-lvalue-reference target type does not lead to decay.
831   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
832   if (DestType->isVoidType()) {
833     Kind = CK_ToVoid;
834 
835     if (claimPlaceholder(BuiltinType::Overload)) {
836       Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
837                 false, // Decay Function to ptr
838                 true, // Complain
839                 OpRange, DestType, diag::err_bad_static_cast_overload);
840       if (SrcExpr.isInvalid())
841         return;
842     }
843 
844     SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
845     return;
846   }
847 
848   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
849       !isPlaceholder(BuiltinType::Overload)) {
850     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
851     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
852       return;
853   }
854 
855   unsigned msg = diag::err_bad_cxx_cast_generic;
856   TryCastResult tcr
857     = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
858                     Kind, BasePath, /*ListInitialization=*/false);
859   if (tcr != TC_Success && msg != 0) {
860     if (SrcExpr.isInvalid())
861       return;
862     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
863       OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
864       Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
865         << oe->getName() << DestType << OpRange
866         << oe->getQualifierLoc().getSourceRange();
867       Self.NoteAllOverloadCandidates(SrcExpr.get());
868     } else {
869       diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
870                       /*listInitialization=*/false);
871     }
872   } else if (tcr == TC_Success) {
873     if (Kind == CK_BitCast)
874       checkCastAlign();
875     if (Self.getLangOpts().ObjCAutoRefCount)
876       checkObjCARCConversion(Sema::CCK_OtherCast);
877   } else if (Kind == CK_BitCast) {
878     checkCastAlign();
879   }
880 }
881 
882 /// TryStaticCast - Check if a static cast can be performed, and do so if
883 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
884 /// and casting away constness.
885 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
886                                    QualType DestType,
887                                    Sema::CheckedConversionKind CCK,
888                                    const SourceRange &OpRange, unsigned &msg,
889                                    CastKind &Kind, CXXCastPath &BasePath,
890                                    bool ListInitialization) {
891   // Determine whether we have the semantics of a C-style cast.
892   bool CStyle
893     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
894 
895   // The order the tests is not entirely arbitrary. There is one conversion
896   // that can be handled in two different ways. Given:
897   // struct A {};
898   // struct B : public A {
899   //   B(); B(const A&);
900   // };
901   // const A &a = B();
902   // the cast static_cast<const B&>(a) could be seen as either a static
903   // reference downcast, or an explicit invocation of the user-defined
904   // conversion using B's conversion constructor.
905   // DR 427 specifies that the downcast is to be applied here.
906 
907   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
908   // Done outside this function.
909 
910   TryCastResult tcr;
911 
912   // C++ 5.2.9p5, reference downcast.
913   // See the function for details.
914   // DR 427 specifies that this is to be applied before paragraph 2.
915   tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
916                                    OpRange, msg, Kind, BasePath);
917   if (tcr != TC_NotApplicable)
918     return tcr;
919 
920   // C++0x [expr.static.cast]p3:
921   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
922   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
923   tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
924                               BasePath, msg);
925   if (tcr != TC_NotApplicable)
926     return tcr;
927 
928   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
929   //   [...] if the declaration "T t(e);" is well-formed, [...].
930   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
931                               Kind, ListInitialization);
932   if (SrcExpr.isInvalid())
933     return TC_Failed;
934   if (tcr != TC_NotApplicable)
935     return tcr;
936 
937   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
938   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
939   // conversions, subject to further restrictions.
940   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
941   // of qualification conversions impossible.
942   // In the CStyle case, the earlier attempt to const_cast should have taken
943   // care of reverse qualification conversions.
944 
945   QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
946 
947   // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
948   // converted to an integral type. [...] A value of a scoped enumeration type
949   // can also be explicitly converted to a floating-point type [...].
950   if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
951     if (Enum->getDecl()->isScoped()) {
952       if (DestType->isBooleanType()) {
953         Kind = CK_IntegralToBoolean;
954         return TC_Success;
955       } else if (DestType->isIntegralType(Self.Context)) {
956         Kind = CK_IntegralCast;
957         return TC_Success;
958       } else if (DestType->isRealFloatingType()) {
959         Kind = CK_IntegralToFloating;
960         return TC_Success;
961       }
962     }
963   }
964 
965   // Reverse integral promotion/conversion. All such conversions are themselves
966   // again integral promotions or conversions and are thus already handled by
967   // p2 (TryDirectInitialization above).
968   // (Note: any data loss warnings should be suppressed.)
969   // The exception is the reverse of enum->integer, i.e. integer->enum (and
970   // enum->enum). See also C++ 5.2.9p7.
971   // The same goes for reverse floating point promotion/conversion and
972   // floating-integral conversions. Again, only floating->enum is relevant.
973   if (DestType->isEnumeralType()) {
974     if (SrcType->isIntegralOrEnumerationType()) {
975       Kind = CK_IntegralCast;
976       return TC_Success;
977     } else if (SrcType->isRealFloatingType())   {
978       Kind = CK_FloatingToIntegral;
979       return TC_Success;
980     }
981   }
982 
983   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
984   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
985   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
986                                  Kind, BasePath);
987   if (tcr != TC_NotApplicable)
988     return tcr;
989 
990   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
991   // conversion. C++ 5.2.9p9 has additional information.
992   // DR54's access restrictions apply here also.
993   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
994                                      OpRange, msg, Kind, BasePath);
995   if (tcr != TC_NotApplicable)
996     return tcr;
997 
998   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
999   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1000   // just the usual constness stuff.
1001   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1002     QualType SrcPointee = SrcPointer->getPointeeType();
1003     if (SrcPointee->isVoidType()) {
1004       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1005         QualType DestPointee = DestPointer->getPointeeType();
1006         if (DestPointee->isIncompleteOrObjectType()) {
1007           // This is definitely the intended conversion, but it might fail due
1008           // to a qualifier violation. Note that we permit Objective-C lifetime
1009           // and GC qualifier mismatches here.
1010           if (!CStyle) {
1011             Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1012             Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1013             DestPointeeQuals.removeObjCGCAttr();
1014             DestPointeeQuals.removeObjCLifetime();
1015             SrcPointeeQuals.removeObjCGCAttr();
1016             SrcPointeeQuals.removeObjCLifetime();
1017             if (DestPointeeQuals != SrcPointeeQuals &&
1018                 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1019               msg = diag::err_bad_cxx_cast_qualifiers_away;
1020               return TC_Failed;
1021             }
1022           }
1023           Kind = CK_BitCast;
1024           return TC_Success;
1025         }
1026       }
1027       else if (DestType->isObjCObjectPointerType()) {
1028         // allow both c-style cast and static_cast of objective-c pointers as
1029         // they are pervasive.
1030         Kind = CK_CPointerToObjCPointerCast;
1031         return TC_Success;
1032       }
1033       else if (CStyle && DestType->isBlockPointerType()) {
1034         // allow c-style cast of void * to block pointers.
1035         Kind = CK_AnyPointerToBlockPointerCast;
1036         return TC_Success;
1037       }
1038     }
1039   }
1040   // Allow arbitray objective-c pointer conversion with static casts.
1041   if (SrcType->isObjCObjectPointerType() &&
1042       DestType->isObjCObjectPointerType()) {
1043     Kind = CK_BitCast;
1044     return TC_Success;
1045   }
1046 
1047   // We tried everything. Everything! Nothing works! :-(
1048   return TC_NotApplicable;
1049 }
1050 
1051 /// Tests whether a conversion according to N2844 is valid.
1052 TryCastResult
1053 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1054                       bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1055                       unsigned &msg) {
1056   // C++0x [expr.static.cast]p3:
1057   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1058   //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1059   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1060   if (!R)
1061     return TC_NotApplicable;
1062 
1063   if (!SrcExpr->isGLValue())
1064     return TC_NotApplicable;
1065 
1066   // Because we try the reference downcast before this function, from now on
1067   // this is the only cast possibility, so we issue an error if we fail now.
1068   // FIXME: Should allow casting away constness if CStyle.
1069   bool DerivedToBase;
1070   bool ObjCConversion;
1071   bool ObjCLifetimeConversion;
1072   QualType FromType = SrcExpr->getType();
1073   QualType ToType = R->getPointeeType();
1074   if (CStyle) {
1075     FromType = FromType.getUnqualifiedType();
1076     ToType = ToType.getUnqualifiedType();
1077   }
1078 
1079   if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
1080                                         ToType, FromType,
1081                                         DerivedToBase, ObjCConversion,
1082                                         ObjCLifetimeConversion)
1083         < Sema::Ref_Compatible_With_Added_Qualification) {
1084     msg = diag::err_bad_lvalue_to_rvalue_cast;
1085     return TC_Failed;
1086   }
1087 
1088   if (DerivedToBase) {
1089     Kind = CK_DerivedToBase;
1090     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1091                        /*DetectVirtual=*/true);
1092     if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1093       return TC_NotApplicable;
1094 
1095     Self.BuildBasePathArray(Paths, BasePath);
1096   } else
1097     Kind = CK_NoOp;
1098 
1099   return TC_Success;
1100 }
1101 
1102 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1103 TryCastResult
1104 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1105                            bool CStyle, const SourceRange &OpRange,
1106                            unsigned &msg, CastKind &Kind,
1107                            CXXCastPath &BasePath) {
1108   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1109   //   cast to type "reference to cv2 D", where D is a class derived from B,
1110   //   if a valid standard conversion from "pointer to D" to "pointer to B"
1111   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
1112   // In addition, DR54 clarifies that the base must be accessible in the
1113   // current context. Although the wording of DR54 only applies to the pointer
1114   // variant of this rule, the intent is clearly for it to apply to the this
1115   // conversion as well.
1116 
1117   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1118   if (!DestReference) {
1119     return TC_NotApplicable;
1120   }
1121   bool RValueRef = DestReference->isRValueReferenceType();
1122   if (!RValueRef && !SrcExpr->isLValue()) {
1123     // We know the left side is an lvalue reference, so we can suggest a reason.
1124     msg = diag::err_bad_cxx_cast_rvalue;
1125     return TC_NotApplicable;
1126   }
1127 
1128   QualType DestPointee = DestReference->getPointeeType();
1129 
1130   return TryStaticDowncast(Self,
1131                            Self.Context.getCanonicalType(SrcExpr->getType()),
1132                            Self.Context.getCanonicalType(DestPointee), CStyle,
1133                            OpRange, SrcExpr->getType(), DestType, msg, Kind,
1134                            BasePath);
1135 }
1136 
1137 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1138 TryCastResult
1139 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1140                          bool CStyle, const SourceRange &OpRange,
1141                          unsigned &msg, CastKind &Kind,
1142                          CXXCastPath &BasePath) {
1143   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1144   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
1145   //   is a class derived from B, if a valid standard conversion from "pointer
1146   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1147   //   class of D.
1148   // In addition, DR54 clarifies that the base must be accessible in the
1149   // current context.
1150 
1151   const PointerType *DestPointer = DestType->getAs<PointerType>();
1152   if (!DestPointer) {
1153     return TC_NotApplicable;
1154   }
1155 
1156   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1157   if (!SrcPointer) {
1158     msg = diag::err_bad_static_cast_pointer_nonpointer;
1159     return TC_NotApplicable;
1160   }
1161 
1162   return TryStaticDowncast(Self,
1163                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1164                   Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1165                            CStyle, OpRange, SrcType, DestType, msg, Kind,
1166                            BasePath);
1167 }
1168 
1169 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1170 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1171 /// DestType is possible and allowed.
1172 TryCastResult
1173 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1174                   bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1175                   QualType OrigDestType, unsigned &msg,
1176                   CastKind &Kind, CXXCastPath &BasePath) {
1177   // We can only work with complete types. But don't complain if it doesn't work
1178   if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1179       Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
1180     return TC_NotApplicable;
1181 
1182   // Downcast can only happen in class hierarchies, so we need classes.
1183   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1184     return TC_NotApplicable;
1185   }
1186 
1187   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1188                      /*DetectVirtual=*/true);
1189   if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1190     return TC_NotApplicable;
1191   }
1192 
1193   // Target type does derive from source type. Now we're serious. If an error
1194   // appears now, it's not ignored.
1195   // This may not be entirely in line with the standard. Take for example:
1196   // struct A {};
1197   // struct B : virtual A {
1198   //   B(A&);
1199   // };
1200   //
1201   // void f()
1202   // {
1203   //   (void)static_cast<const B&>(*((A*)0));
1204   // }
1205   // As far as the standard is concerned, p5 does not apply (A is virtual), so
1206   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1207   // However, both GCC and Comeau reject this example, and accepting it would
1208   // mean more complex code if we're to preserve the nice error message.
1209   // FIXME: Being 100% compliant here would be nice to have.
1210 
1211   // Must preserve cv, as always, unless we're in C-style mode.
1212   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1213     msg = diag::err_bad_cxx_cast_qualifiers_away;
1214     return TC_Failed;
1215   }
1216 
1217   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1218     // This code is analoguous to that in CheckDerivedToBaseConversion, except
1219     // that it builds the paths in reverse order.
1220     // To sum up: record all paths to the base and build a nice string from
1221     // them. Use it to spice up the error message.
1222     if (!Paths.isRecordingPaths()) {
1223       Paths.clear();
1224       Paths.setRecordingPaths(true);
1225       Self.IsDerivedFrom(DestType, SrcType, Paths);
1226     }
1227     std::string PathDisplayStr;
1228     std::set<unsigned> DisplayedPaths;
1229     for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1230          PI != PE; ++PI) {
1231       if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1232         // We haven't displayed a path to this particular base
1233         // class subobject yet.
1234         PathDisplayStr += "\n    ";
1235         for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1236                                                  EE = PI->rend();
1237              EI != EE; ++EI)
1238           PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1239         PathDisplayStr += QualType(DestType).getAsString();
1240       }
1241     }
1242 
1243     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1244       << QualType(SrcType).getUnqualifiedType()
1245       << QualType(DestType).getUnqualifiedType()
1246       << PathDisplayStr << OpRange;
1247     msg = 0;
1248     return TC_Failed;
1249   }
1250 
1251   if (Paths.getDetectedVirtual() != 0) {
1252     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1253     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1254       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1255     msg = 0;
1256     return TC_Failed;
1257   }
1258 
1259   if (!CStyle) {
1260     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1261                                       SrcType, DestType,
1262                                       Paths.front(),
1263                                 diag::err_downcast_from_inaccessible_base)) {
1264     case Sema::AR_accessible:
1265     case Sema::AR_delayed:     // be optimistic
1266     case Sema::AR_dependent:   // be optimistic
1267       break;
1268 
1269     case Sema::AR_inaccessible:
1270       msg = 0;
1271       return TC_Failed;
1272     }
1273   }
1274 
1275   Self.BuildBasePathArray(Paths, BasePath);
1276   Kind = CK_BaseToDerived;
1277   return TC_Success;
1278 }
1279 
1280 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1281 /// C++ 5.2.9p9 is valid:
1282 ///
1283 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
1284 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
1285 ///   where B is a base class of D [...].
1286 ///
1287 TryCastResult
1288 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1289                              QualType DestType, bool CStyle,
1290                              const SourceRange &OpRange,
1291                              unsigned &msg, CastKind &Kind,
1292                              CXXCastPath &BasePath) {
1293   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1294   if (!DestMemPtr)
1295     return TC_NotApplicable;
1296 
1297   bool WasOverloadedFunction = false;
1298   DeclAccessPair FoundOverload;
1299   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1300     if (FunctionDecl *Fn
1301           = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1302                                                     FoundOverload)) {
1303       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1304       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1305                       Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1306       WasOverloadedFunction = true;
1307     }
1308   }
1309 
1310   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1311   if (!SrcMemPtr) {
1312     msg = diag::err_bad_static_cast_member_pointer_nonmp;
1313     return TC_NotApplicable;
1314   }
1315 
1316   // T == T, modulo cv
1317   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1318                                            DestMemPtr->getPointeeType()))
1319     return TC_NotApplicable;
1320 
1321   // B base of D
1322   QualType SrcClass(SrcMemPtr->getClass(), 0);
1323   QualType DestClass(DestMemPtr->getClass(), 0);
1324   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1325                   /*DetectVirtual=*/true);
1326   if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1327     return TC_NotApplicable;
1328   }
1329 
1330   // B is a base of D. But is it an allowed base? If not, it's a hard error.
1331   if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1332     Paths.clear();
1333     Paths.setRecordingPaths(true);
1334     bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1335     assert(StillOkay);
1336     (void)StillOkay;
1337     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1338     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1339       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1340     msg = 0;
1341     return TC_Failed;
1342   }
1343 
1344   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1345     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1346       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1347     msg = 0;
1348     return TC_Failed;
1349   }
1350 
1351   if (!CStyle) {
1352     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1353                                       DestClass, SrcClass,
1354                                       Paths.front(),
1355                                       diag::err_upcast_to_inaccessible_base)) {
1356     case Sema::AR_accessible:
1357     case Sema::AR_delayed:
1358     case Sema::AR_dependent:
1359       // Optimistically assume that the delayed and dependent cases
1360       // will work out.
1361       break;
1362 
1363     case Sema::AR_inaccessible:
1364       msg = 0;
1365       return TC_Failed;
1366     }
1367   }
1368 
1369   if (WasOverloadedFunction) {
1370     // Resolve the address of the overloaded function again, this time
1371     // allowing complaints if something goes wrong.
1372     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1373                                                                DestType,
1374                                                                true,
1375                                                                FoundOverload);
1376     if (!Fn) {
1377       msg = 0;
1378       return TC_Failed;
1379     }
1380 
1381     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1382     if (!SrcExpr.isUsable()) {
1383       msg = 0;
1384       return TC_Failed;
1385     }
1386   }
1387 
1388   Self.BuildBasePathArray(Paths, BasePath);
1389   Kind = CK_DerivedToBaseMemberPointer;
1390   return TC_Success;
1391 }
1392 
1393 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1394 /// is valid:
1395 ///
1396 ///   An expression e can be explicitly converted to a type T using a
1397 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
1398 TryCastResult
1399 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1400                       Sema::CheckedConversionKind CCK,
1401                       const SourceRange &OpRange, unsigned &msg,
1402                       CastKind &Kind, bool ListInitialization) {
1403   if (DestType->isRecordType()) {
1404     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1405                                  diag::err_bad_dynamic_cast_incomplete) ||
1406         Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1407                                     diag::err_allocation_of_abstract_type)) {
1408       msg = 0;
1409       return TC_Failed;
1410     }
1411   }
1412 
1413   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1414   InitializationKind InitKind
1415     = (CCK == Sema::CCK_CStyleCast)
1416         ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1417                                                ListInitialization)
1418     : (CCK == Sema::CCK_FunctionalCast)
1419         ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1420     : InitializationKind::CreateCast(OpRange);
1421   Expr *SrcExprRaw = SrcExpr.get();
1422   InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1423 
1424   // At this point of CheckStaticCast, if the destination is a reference,
1425   // or the expression is an overload expression this has to work.
1426   // There is no other way that works.
1427   // On the other hand, if we're checking a C-style cast, we've still got
1428   // the reinterpret_cast way.
1429   bool CStyle
1430     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1431   if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1432     return TC_NotApplicable;
1433 
1434   ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1435   if (Result.isInvalid()) {
1436     msg = 0;
1437     return TC_Failed;
1438   }
1439 
1440   if (InitSeq.isConstructorInitialization())
1441     Kind = CK_ConstructorConversion;
1442   else
1443     Kind = CK_NoOp;
1444 
1445   SrcExpr = Result;
1446   return TC_Success;
1447 }
1448 
1449 /// TryConstCast - See if a const_cast from source to destination is allowed,
1450 /// and perform it if it is.
1451 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1452                                   QualType DestType, bool CStyle,
1453                                   unsigned &msg) {
1454   DestType = Self.Context.getCanonicalType(DestType);
1455   QualType SrcType = SrcExpr.get()->getType();
1456   bool NeedToMaterializeTemporary = false;
1457 
1458   if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1459     // C++11 5.2.11p4:
1460     //   if a pointer to T1 can be explicitly converted to the type "pointer to
1461     //   T2" using a const_cast, then the following conversions can also be
1462     //   made:
1463     //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
1464     //       type T2 using the cast const_cast<T2&>;
1465     //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
1466     //       type T2 using the cast const_cast<T2&&>; and
1467     //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
1468     //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1469 
1470     if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1471       // Cannot const_cast non-lvalue to lvalue reference type. But if this
1472       // is C-style, static_cast might find a way, so we simply suggest a
1473       // message and tell the parent to keep searching.
1474       msg = diag::err_bad_cxx_cast_rvalue;
1475       return TC_NotApplicable;
1476     }
1477 
1478     if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1479       if (!SrcType->isRecordType()) {
1480         // Cannot const_cast non-class prvalue to rvalue reference type. But if
1481         // this is C-style, static_cast can do this.
1482         msg = diag::err_bad_cxx_cast_rvalue;
1483         return TC_NotApplicable;
1484       }
1485 
1486       // Materialize the class prvalue so that the const_cast can bind a
1487       // reference to it.
1488       NeedToMaterializeTemporary = true;
1489     }
1490 
1491     // It's not completely clear under the standard whether we can
1492     // const_cast bit-field gl-values.  Doing so would not be
1493     // intrinsically complicated, but for now, we say no for
1494     // consistency with other compilers and await the word of the
1495     // committee.
1496     if (SrcExpr.get()->refersToBitField()) {
1497       msg = diag::err_bad_cxx_cast_bitfield;
1498       return TC_NotApplicable;
1499     }
1500 
1501     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1502     SrcType = Self.Context.getPointerType(SrcType);
1503   }
1504 
1505   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1506   //   the rules for const_cast are the same as those used for pointers.
1507 
1508   if (!DestType->isPointerType() &&
1509       !DestType->isMemberPointerType() &&
1510       !DestType->isObjCObjectPointerType()) {
1511     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1512     // was a reference type, we converted it to a pointer above.
1513     // The status of rvalue references isn't entirely clear, but it looks like
1514     // conversion to them is simply invalid.
1515     // C++ 5.2.11p3: For two pointer types [...]
1516     if (!CStyle)
1517       msg = diag::err_bad_const_cast_dest;
1518     return TC_NotApplicable;
1519   }
1520   if (DestType->isFunctionPointerType() ||
1521       DestType->isMemberFunctionPointerType()) {
1522     // Cannot cast direct function pointers.
1523     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1524     // T is the ultimate pointee of source and target type.
1525     if (!CStyle)
1526       msg = diag::err_bad_const_cast_dest;
1527     return TC_NotApplicable;
1528   }
1529   SrcType = Self.Context.getCanonicalType(SrcType);
1530 
1531   // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1532   // completely equal.
1533   // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1534   // in multi-level pointers may change, but the level count must be the same,
1535   // as must be the final pointee type.
1536   while (SrcType != DestType &&
1537          Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1538     Qualifiers SrcQuals, DestQuals;
1539     SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1540     DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1541 
1542     // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1543     // the other qualifiers (e.g., address spaces) are identical.
1544     SrcQuals.removeCVRQualifiers();
1545     DestQuals.removeCVRQualifiers();
1546     if (SrcQuals != DestQuals)
1547       return TC_NotApplicable;
1548   }
1549 
1550   // Since we're dealing in canonical types, the remainder must be the same.
1551   if (SrcType != DestType)
1552     return TC_NotApplicable;
1553 
1554   if (NeedToMaterializeTemporary)
1555     // This is a const_cast from a class prvalue to an rvalue reference type.
1556     // Materialize a temporary to store the result of the conversion.
1557     SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1558         SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1559         /*ExtendingDecl*/ 0);
1560 
1561   return TC_Success;
1562 }
1563 
1564 // Checks for undefined behavior in reinterpret_cast.
1565 // The cases that is checked for is:
1566 // *reinterpret_cast<T*>(&a)
1567 // reinterpret_cast<T&>(a)
1568 // where accessing 'a' as type 'T' will result in undefined behavior.
1569 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1570                                           bool IsDereference,
1571                                           SourceRange Range) {
1572   unsigned DiagID = IsDereference ?
1573                         diag::warn_pointer_indirection_from_incompatible_type :
1574                         diag::warn_undefined_reinterpret_cast;
1575 
1576   if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
1577           DiagnosticsEngine::Ignored) {
1578     return;
1579   }
1580 
1581   QualType SrcTy, DestTy;
1582   if (IsDereference) {
1583     if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1584       return;
1585     }
1586     SrcTy = SrcType->getPointeeType();
1587     DestTy = DestType->getPointeeType();
1588   } else {
1589     if (!DestType->getAs<ReferenceType>()) {
1590       return;
1591     }
1592     SrcTy = SrcType;
1593     DestTy = DestType->getPointeeType();
1594   }
1595 
1596   // Cast is compatible if the types are the same.
1597   if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1598     return;
1599   }
1600   // or one of the types is a char or void type
1601   if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1602       SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1603     return;
1604   }
1605   // or one of the types is a tag type.
1606   if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1607     return;
1608   }
1609 
1610   // FIXME: Scoped enums?
1611   if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1612       (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1613     if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1614       return;
1615     }
1616   }
1617 
1618   Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1619 }
1620 
1621 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1622                                   QualType DestType) {
1623   QualType SrcType = SrcExpr.get()->getType();
1624   if (Self.Context.hasSameType(SrcType, DestType))
1625     return;
1626   if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1627     if (SrcPtrTy->isObjCSelType()) {
1628       QualType DT = DestType;
1629       if (isa<PointerType>(DestType))
1630         DT = DestType->getPointeeType();
1631       if (!DT.getUnqualifiedType()->isVoidType())
1632         Self.Diag(SrcExpr.get()->getExprLoc(),
1633                   diag::warn_cast_pointer_from_sel)
1634         << SrcType << DestType << SrcExpr.get()->getSourceRange();
1635     }
1636 }
1637 
1638 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1639                                   const Expr *SrcExpr, QualType DestType,
1640                                   Sema &Self) {
1641   QualType SrcType = SrcExpr->getType();
1642 
1643   // Not warning on reinterpret_cast, boolean, constant expressions, etc
1644   // are not explicit design choices, but consistent with GCC's behavior.
1645   // Feel free to modify them if you've reason/evidence for an alternative.
1646   if (CStyle && SrcType->isIntegralType(Self.Context)
1647       && !SrcType->isBooleanType()
1648       && !SrcType->isEnumeralType()
1649       && !SrcExpr->isIntegerConstantExpr(Self.Context)
1650       && Self.Context.getTypeSize(DestType) >
1651          Self.Context.getTypeSize(SrcType)) {
1652     // Separate between casts to void* and non-void* pointers.
1653     // Some APIs use (abuse) void* for something like a user context,
1654     // and often that value is an integer even if it isn't a pointer itself.
1655     // Having a separate warning flag allows users to control the warning
1656     // for their workflow.
1657     unsigned Diag = DestType->isVoidPointerType() ?
1658                       diag::warn_int_to_void_pointer_cast
1659                     : diag::warn_int_to_pointer_cast;
1660     Self.Diag(Loc, Diag) << SrcType << DestType;
1661   }
1662 }
1663 
1664 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1665                                         QualType DestType, bool CStyle,
1666                                         const SourceRange &OpRange,
1667                                         unsigned &msg,
1668                                         CastKind &Kind) {
1669   bool IsLValueCast = false;
1670 
1671   DestType = Self.Context.getCanonicalType(DestType);
1672   QualType SrcType = SrcExpr.get()->getType();
1673 
1674   // Is the source an overloaded name? (i.e. &foo)
1675   // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1676   if (SrcType == Self.Context.OverloadTy) {
1677     // ... unless foo<int> resolves to an lvalue unambiguously.
1678     // TODO: what if this fails because of DiagnoseUseOfDecl or something
1679     // like it?
1680     ExprResult SingleFunctionExpr = SrcExpr;
1681     if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1682           SingleFunctionExpr,
1683           Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1684         ) && SingleFunctionExpr.isUsable()) {
1685       SrcExpr = SingleFunctionExpr;
1686       SrcType = SrcExpr.get()->getType();
1687     } else {
1688       return TC_NotApplicable;
1689     }
1690   }
1691 
1692   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1693     if (!SrcExpr.get()->isGLValue()) {
1694       // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1695       // similar comment in const_cast.
1696       msg = diag::err_bad_cxx_cast_rvalue;
1697       return TC_NotApplicable;
1698     }
1699 
1700     if (!CStyle) {
1701       Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1702                                           /*isDereference=*/false, OpRange);
1703     }
1704 
1705     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1706     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
1707     //   built-in & and * operators.
1708 
1709     const char *inappropriate = 0;
1710     switch (SrcExpr.get()->getObjectKind()) {
1711     case OK_Ordinary:
1712       break;
1713     case OK_BitField:        inappropriate = "bit-field";           break;
1714     case OK_VectorComponent: inappropriate = "vector element";      break;
1715     case OK_ObjCProperty:    inappropriate = "property expression"; break;
1716     case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
1717                              break;
1718     }
1719     if (inappropriate) {
1720       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1721           << inappropriate << DestType
1722           << OpRange << SrcExpr.get()->getSourceRange();
1723       msg = 0; SrcExpr = ExprError();
1724       return TC_NotApplicable;
1725     }
1726 
1727     // This code does this transformation for the checked types.
1728     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1729     SrcType = Self.Context.getPointerType(SrcType);
1730 
1731     IsLValueCast = true;
1732   }
1733 
1734   // Canonicalize source for comparison.
1735   SrcType = Self.Context.getCanonicalType(SrcType);
1736 
1737   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1738                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1739   if (DestMemPtr && SrcMemPtr) {
1740     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1741     //   can be explicitly converted to an rvalue of type "pointer to member
1742     //   of Y of type T2" if T1 and T2 are both function types or both object
1743     //   types.
1744     if (DestMemPtr->getPointeeType()->isFunctionType() !=
1745         SrcMemPtr->getPointeeType()->isFunctionType())
1746       return TC_NotApplicable;
1747 
1748     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1749     //   constness.
1750     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1751     // we accept it.
1752     if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1753                            /*CheckObjCLifetime=*/CStyle)) {
1754       msg = diag::err_bad_cxx_cast_qualifiers_away;
1755       return TC_Failed;
1756     }
1757 
1758     // Don't allow casting between member pointers of different sizes.
1759     if (Self.Context.getTypeSize(DestMemPtr) !=
1760         Self.Context.getTypeSize(SrcMemPtr)) {
1761       msg = diag::err_bad_cxx_cast_member_pointer_size;
1762       return TC_Failed;
1763     }
1764 
1765     // A valid member pointer cast.
1766     assert(!IsLValueCast);
1767     Kind = CK_ReinterpretMemberPointer;
1768     return TC_Success;
1769   }
1770 
1771   // See below for the enumeral issue.
1772   if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1773     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1774     //   type large enough to hold it. A value of std::nullptr_t can be
1775     //   converted to an integral type; the conversion has the same meaning
1776     //   and validity as a conversion of (void*)0 to the integral type.
1777     if (Self.Context.getTypeSize(SrcType) >
1778         Self.Context.getTypeSize(DestType)) {
1779       msg = diag::err_bad_reinterpret_cast_small_int;
1780       return TC_Failed;
1781     }
1782     Kind = CK_PointerToIntegral;
1783     return TC_Success;
1784   }
1785 
1786   bool destIsVector = DestType->isVectorType();
1787   bool srcIsVector = SrcType->isVectorType();
1788   if (srcIsVector || destIsVector) {
1789     // FIXME: Should this also apply to floating point types?
1790     bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1791     bool destIsScalar = DestType->isIntegralType(Self.Context);
1792 
1793     // Check if this is a cast between a vector and something else.
1794     if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1795         !(srcIsVector && destIsVector))
1796       return TC_NotApplicable;
1797 
1798     // If both types have the same size, we can successfully cast.
1799     if (Self.Context.getTypeSize(SrcType)
1800           == Self.Context.getTypeSize(DestType)) {
1801       Kind = CK_BitCast;
1802       return TC_Success;
1803     }
1804 
1805     if (destIsScalar)
1806       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1807     else if (srcIsScalar)
1808       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1809     else
1810       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1811 
1812     return TC_Failed;
1813   }
1814 
1815   if (SrcType == DestType) {
1816     // C++ 5.2.10p2 has a note that mentions that, subject to all other
1817     // restrictions, a cast to the same type is allowed so long as it does not
1818     // cast away constness. In C++98, the intent was not entirely clear here,
1819     // since all other paragraphs explicitly forbid casts to the same type.
1820     // C++11 clarifies this case with p2.
1821     //
1822     // The only allowed types are: integral, enumeration, pointer, or
1823     // pointer-to-member types.  We also won't restrict Obj-C pointers either.
1824     Kind = CK_NoOp;
1825     TryCastResult Result = TC_NotApplicable;
1826     if (SrcType->isIntegralOrEnumerationType() ||
1827         SrcType->isAnyPointerType() ||
1828         SrcType->isMemberPointerType() ||
1829         SrcType->isBlockPointerType()) {
1830       Result = TC_Success;
1831     }
1832     return Result;
1833   }
1834 
1835   bool destIsPtr = DestType->isAnyPointerType() ||
1836                    DestType->isBlockPointerType();
1837   bool srcIsPtr = SrcType->isAnyPointerType() ||
1838                   SrcType->isBlockPointerType();
1839   if (!destIsPtr && !srcIsPtr) {
1840     // Except for std::nullptr_t->integer and lvalue->reference, which are
1841     // handled above, at least one of the two arguments must be a pointer.
1842     return TC_NotApplicable;
1843   }
1844 
1845   if (DestType->isIntegralType(Self.Context)) {
1846     assert(srcIsPtr && "One type must be a pointer");
1847     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1848     //   type large enough to hold it; except in Microsoft mode, where the
1849     //   integral type size doesn't matter (except we don't allow bool).
1850     bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1851                               !DestType->isBooleanType();
1852     if ((Self.Context.getTypeSize(SrcType) >
1853          Self.Context.getTypeSize(DestType)) &&
1854          !MicrosoftException) {
1855       msg = diag::err_bad_reinterpret_cast_small_int;
1856       return TC_Failed;
1857     }
1858     Kind = CK_PointerToIntegral;
1859     return TC_Success;
1860   }
1861 
1862   if (SrcType->isIntegralOrEnumerationType()) {
1863     assert(destIsPtr && "One type must be a pointer");
1864     checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1865                           Self);
1866     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1867     //   converted to a pointer.
1868     // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1869     //   necessarily converted to a null pointer value.]
1870     Kind = CK_IntegralToPointer;
1871     return TC_Success;
1872   }
1873 
1874   if (!destIsPtr || !srcIsPtr) {
1875     // With the valid non-pointer conversions out of the way, we can be even
1876     // more stringent.
1877     return TC_NotApplicable;
1878   }
1879 
1880   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1881   // The C-style cast operator can.
1882   if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1883                          /*CheckObjCLifetime=*/CStyle)) {
1884     msg = diag::err_bad_cxx_cast_qualifiers_away;
1885     return TC_Failed;
1886   }
1887 
1888   // Cannot convert between block pointers and Objective-C object pointers.
1889   if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1890       (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1891     return TC_NotApplicable;
1892 
1893   if (IsLValueCast) {
1894     Kind = CK_LValueBitCast;
1895   } else if (DestType->isObjCObjectPointerType()) {
1896     Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1897   } else if (DestType->isBlockPointerType()) {
1898     if (!SrcType->isBlockPointerType()) {
1899       Kind = CK_AnyPointerToBlockPointerCast;
1900     } else {
1901       Kind = CK_BitCast;
1902     }
1903   } else {
1904     Kind = CK_BitCast;
1905   }
1906 
1907   // Any pointer can be cast to an Objective-C pointer type with a C-style
1908   // cast.
1909   if (CStyle && DestType->isObjCObjectPointerType()) {
1910     return TC_Success;
1911   }
1912   if (CStyle)
1913     DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1914 
1915   // Not casting away constness, so the only remaining check is for compatible
1916   // pointer categories.
1917 
1918   if (SrcType->isFunctionPointerType()) {
1919     if (DestType->isFunctionPointerType()) {
1920       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1921       // a pointer to a function of a different type.
1922       return TC_Success;
1923     }
1924 
1925     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1926     //   an object type or vice versa is conditionally-supported.
1927     // Compilers support it in C++03 too, though, because it's necessary for
1928     // casting the return value of dlsym() and GetProcAddress().
1929     // FIXME: Conditionally-supported behavior should be configurable in the
1930     // TargetInfo or similar.
1931     Self.Diag(OpRange.getBegin(),
1932               Self.getLangOpts().CPlusPlus11 ?
1933                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1934       << OpRange;
1935     return TC_Success;
1936   }
1937 
1938   if (DestType->isFunctionPointerType()) {
1939     // See above.
1940     Self.Diag(OpRange.getBegin(),
1941               Self.getLangOpts().CPlusPlus11 ?
1942                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1943       << OpRange;
1944     return TC_Success;
1945   }
1946 
1947   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1948   //   a pointer to an object of different type.
1949   // Void pointers are not specified, but supported by every compiler out there.
1950   // So we finish by allowing everything that remains - it's got to be two
1951   // object pointers.
1952   return TC_Success;
1953 }
1954 
1955 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1956                                        bool ListInitialization) {
1957   // Handle placeholders.
1958   if (isPlaceholder()) {
1959     // C-style casts can resolve __unknown_any types.
1960     if (claimPlaceholder(BuiltinType::UnknownAny)) {
1961       SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1962                                          SrcExpr.get(), Kind,
1963                                          ValueKind, BasePath);
1964       return;
1965     }
1966 
1967     checkNonOverloadPlaceholders();
1968     if (SrcExpr.isInvalid())
1969       return;
1970   }
1971 
1972   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1973   // This test is outside everything else because it's the only case where
1974   // a non-lvalue-reference target type does not lead to decay.
1975   if (DestType->isVoidType()) {
1976     Kind = CK_ToVoid;
1977 
1978     if (claimPlaceholder(BuiltinType::Overload)) {
1979       Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1980                   SrcExpr, /* Decay Function to ptr */ false,
1981                   /* Complain */ true, DestRange, DestType,
1982                   diag::err_bad_cstyle_cast_overload);
1983       if (SrcExpr.isInvalid())
1984         return;
1985     }
1986 
1987     SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1988     if (SrcExpr.isInvalid())
1989       return;
1990 
1991     return;
1992   }
1993 
1994   // If the type is dependent, we won't do any other semantic analysis now.
1995   if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1996     assert(Kind == CK_Dependent);
1997     return;
1998   }
1999 
2000   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2001       !isPlaceholder(BuiltinType::Overload)) {
2002     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2003     if (SrcExpr.isInvalid())
2004       return;
2005   }
2006 
2007   // AltiVec vector initialization with a single literal.
2008   if (const VectorType *vecTy = DestType->getAs<VectorType>())
2009     if (vecTy->getVectorKind() == VectorType::AltiVecVector
2010         && (SrcExpr.get()->getType()->isIntegerType()
2011             || SrcExpr.get()->getType()->isFloatingType())) {
2012       Kind = CK_VectorSplat;
2013       return;
2014     }
2015 
2016   // C++ [expr.cast]p5: The conversions performed by
2017   //   - a const_cast,
2018   //   - a static_cast,
2019   //   - a static_cast followed by a const_cast,
2020   //   - a reinterpret_cast, or
2021   //   - a reinterpret_cast followed by a const_cast,
2022   //   can be performed using the cast notation of explicit type conversion.
2023   //   [...] If a conversion can be interpreted in more than one of the ways
2024   //   listed above, the interpretation that appears first in the list is used,
2025   //   even if a cast resulting from that interpretation is ill-formed.
2026   // In plain language, this means trying a const_cast ...
2027   unsigned msg = diag::err_bad_cxx_cast_generic;
2028   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2029                                    /*CStyle*/true, msg);
2030   if (SrcExpr.isInvalid())
2031     return;
2032   if (tcr == TC_Success)
2033     Kind = CK_NoOp;
2034 
2035   Sema::CheckedConversionKind CCK
2036     = FunctionalStyle? Sema::CCK_FunctionalCast
2037                      : Sema::CCK_CStyleCast;
2038   if (tcr == TC_NotApplicable) {
2039     // ... or if that is not possible, a static_cast, ignoring const, ...
2040     tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2041                         msg, Kind, BasePath, ListInitialization);
2042     if (SrcExpr.isInvalid())
2043       return;
2044 
2045     if (tcr == TC_NotApplicable) {
2046       // ... and finally a reinterpret_cast, ignoring const.
2047       tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2048                                OpRange, msg, Kind);
2049       if (SrcExpr.isInvalid())
2050         return;
2051     }
2052   }
2053 
2054   if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
2055     checkObjCARCConversion(CCK);
2056 
2057   if (tcr != TC_Success && msg != 0) {
2058     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2059       DeclAccessPair Found;
2060       FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2061                                 DestType,
2062                                 /*Complain*/ true,
2063                                 Found);
2064 
2065       assert(!Fn && "cast failed but able to resolve overload expression!!");
2066       (void)Fn;
2067 
2068     } else {
2069       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2070                       OpRange, SrcExpr.get(), DestType, ListInitialization);
2071     }
2072   } else if (Kind == CK_BitCast) {
2073     checkCastAlign();
2074   }
2075 
2076   // Clear out SrcExpr if there was a fatal error.
2077   if (tcr != TC_Success)
2078     SrcExpr = ExprError();
2079 }
2080 
2081 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2082 ///  non-matching type. Such as enum function call to int, int call to
2083 /// pointer; etc. Cast to 'void' is an exception.
2084 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2085                                   QualType DestType) {
2086   if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2087                                     SrcExpr.get()->getExprLoc())
2088         == DiagnosticsEngine::Ignored)
2089     return;
2090 
2091   if (!isa<CallExpr>(SrcExpr.get()))
2092     return;
2093 
2094   QualType SrcType = SrcExpr.get()->getType();
2095   if (DestType.getUnqualifiedType()->isVoidType())
2096     return;
2097   if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2098       && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2099     return;
2100   if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2101       (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2102       (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2103     return;
2104   if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2105     return;
2106   if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2107     return;
2108   if (SrcType->isComplexType() && DestType->isComplexType())
2109     return;
2110   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2111     return;
2112 
2113   Self.Diag(SrcExpr.get()->getExprLoc(),
2114             diag::warn_bad_function_cast)
2115             << SrcType << DestType << SrcExpr.get()->getSourceRange();
2116 }
2117 
2118 /// Check the semantics of a C-style cast operation, in C.
2119 void CastOperation::CheckCStyleCast() {
2120   assert(!Self.getLangOpts().CPlusPlus);
2121 
2122   // C-style casts can resolve __unknown_any types.
2123   if (claimPlaceholder(BuiltinType::UnknownAny)) {
2124     SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2125                                        SrcExpr.get(), Kind,
2126                                        ValueKind, BasePath);
2127     return;
2128   }
2129 
2130   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2131   // type needs to be scalar.
2132   if (DestType->isVoidType()) {
2133     // We don't necessarily do lvalue-to-rvalue conversions on this.
2134     SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2135     if (SrcExpr.isInvalid())
2136       return;
2137 
2138     // Cast to void allows any expr type.
2139     Kind = CK_ToVoid;
2140     return;
2141   }
2142 
2143   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2144   if (SrcExpr.isInvalid())
2145     return;
2146   QualType SrcType = SrcExpr.get()->getType();
2147 
2148   assert(!SrcType->isPlaceholderType());
2149 
2150   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2151                                diag::err_typecheck_cast_to_incomplete)) {
2152     SrcExpr = ExprError();
2153     return;
2154   }
2155 
2156   if (!DestType->isScalarType() && !DestType->isVectorType()) {
2157     const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2158 
2159     if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2160       // GCC struct/union extension: allow cast to self.
2161       Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2162         << DestType << SrcExpr.get()->getSourceRange();
2163       Kind = CK_NoOp;
2164       return;
2165     }
2166 
2167     // GCC's cast to union extension.
2168     if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2169       RecordDecl *RD = DestRecordTy->getDecl();
2170       RecordDecl::field_iterator Field, FieldEnd;
2171       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2172            Field != FieldEnd; ++Field) {
2173         if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2174             !Field->isUnnamedBitfield()) {
2175           Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2176             << SrcExpr.get()->getSourceRange();
2177           break;
2178         }
2179       }
2180       if (Field == FieldEnd) {
2181         Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2182           << SrcType << SrcExpr.get()->getSourceRange();
2183         SrcExpr = ExprError();
2184         return;
2185       }
2186       Kind = CK_ToUnion;
2187       return;
2188     }
2189 
2190     // Reject any other conversions to non-scalar types.
2191     Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2192       << DestType << SrcExpr.get()->getSourceRange();
2193     SrcExpr = ExprError();
2194     return;
2195   }
2196 
2197   // The type we're casting to is known to be a scalar or vector.
2198 
2199   // Require the operand to be a scalar or vector.
2200   if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2201     Self.Diag(SrcExpr.get()->getExprLoc(),
2202               diag::err_typecheck_expect_scalar_operand)
2203       << SrcType << SrcExpr.get()->getSourceRange();
2204     SrcExpr = ExprError();
2205     return;
2206   }
2207 
2208   if (DestType->isExtVectorType()) {
2209     SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2210     return;
2211   }
2212 
2213   if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2214     if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2215           (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2216       Kind = CK_VectorSplat;
2217     } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2218       SrcExpr = ExprError();
2219     }
2220     return;
2221   }
2222 
2223   if (SrcType->isVectorType()) {
2224     if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2225       SrcExpr = ExprError();
2226     return;
2227   }
2228 
2229   // The source and target types are both scalars, i.e.
2230   //   - arithmetic types (fundamental, enum, and complex)
2231   //   - all kinds of pointers
2232   // Note that member pointers were filtered out with C++, above.
2233 
2234   if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2235     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2236     SrcExpr = ExprError();
2237     return;
2238   }
2239 
2240   // If either type is a pointer, the other type has to be either an
2241   // integer or a pointer.
2242   if (!DestType->isArithmeticType()) {
2243     if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2244       Self.Diag(SrcExpr.get()->getExprLoc(),
2245                 diag::err_cast_pointer_from_non_pointer_int)
2246         << SrcType << SrcExpr.get()->getSourceRange();
2247       SrcExpr = ExprError();
2248       return;
2249     }
2250     checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2251                           DestType, Self);
2252   } else if (!SrcType->isArithmeticType()) {
2253     if (!DestType->isIntegralType(Self.Context) &&
2254         DestType->isArithmeticType()) {
2255       Self.Diag(SrcExpr.get()->getLocStart(),
2256            diag::err_cast_pointer_to_non_pointer_int)
2257         << DestType << SrcExpr.get()->getSourceRange();
2258       SrcExpr = ExprError();
2259       return;
2260     }
2261   }
2262 
2263   if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2264     if (DestType->isHalfType()) {
2265       Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2266         << DestType << SrcExpr.get()->getSourceRange();
2267       SrcExpr = ExprError();
2268       return;
2269     }
2270   }
2271 
2272   // ARC imposes extra restrictions on casts.
2273   if (Self.getLangOpts().ObjCAutoRefCount) {
2274     checkObjCARCConversion(Sema::CCK_CStyleCast);
2275     if (SrcExpr.isInvalid())
2276       return;
2277 
2278     if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2279       if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2280         Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2281         Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2282         if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2283             ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2284             !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2285           Self.Diag(SrcExpr.get()->getLocStart(),
2286                     diag::err_typecheck_incompatible_ownership)
2287             << SrcType << DestType << Sema::AA_Casting
2288             << SrcExpr.get()->getSourceRange();
2289           return;
2290         }
2291       }
2292     }
2293     else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2294       Self.Diag(SrcExpr.get()->getLocStart(),
2295                 diag::err_arc_convesion_of_weak_unavailable)
2296         << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2297       SrcExpr = ExprError();
2298       return;
2299     }
2300   }
2301   DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2302   DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2303   Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2304   if (SrcExpr.isInvalid())
2305     return;
2306 
2307   if (Kind == CK_BitCast)
2308     checkCastAlign();
2309 }
2310 
2311 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2312                                      TypeSourceInfo *CastTypeInfo,
2313                                      SourceLocation RPLoc,
2314                                      Expr *CastExpr) {
2315   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2316   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2317   Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2318 
2319   if (getLangOpts().CPlusPlus) {
2320     Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2321                           isa<InitListExpr>(CastExpr));
2322   } else {
2323     Op.CheckCStyleCast();
2324   }
2325 
2326   if (Op.SrcExpr.isInvalid())
2327     return ExprError();
2328 
2329   return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2330                               Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2331                               &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2332 }
2333 
2334 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2335                                             SourceLocation LPLoc,
2336                                             Expr *CastExpr,
2337                                             SourceLocation RPLoc) {
2338   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2339   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2340   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2341   Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2342 
2343   Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2344   if (Op.SrcExpr.isInvalid())
2345     return ExprError();
2346 
2347   if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2348     ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
2349 
2350   return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2351                          Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2352                          Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
2353 }
2354