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