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