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