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_ObjCProperty:    inappropriate = "property expression"; break;
2093     case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
2094                              break;
2095     }
2096     if (inappropriate) {
2097       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2098           << inappropriate << DestType
2099           << OpRange << SrcExpr.get()->getSourceRange();
2100       msg = 0; SrcExpr = ExprError();
2101       return TC_NotApplicable;
2102     }
2103 
2104     // This code does this transformation for the checked types.
2105     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2106     SrcType = Self.Context.getPointerType(SrcType);
2107 
2108     IsLValueCast = true;
2109   }
2110 
2111   // Canonicalize source for comparison.
2112   SrcType = Self.Context.getCanonicalType(SrcType);
2113 
2114   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2115                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2116   if (DestMemPtr && SrcMemPtr) {
2117     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2118     //   can be explicitly converted to an rvalue of type "pointer to member
2119     //   of Y of type T2" if T1 and T2 are both function types or both object
2120     //   types.
2121     if (DestMemPtr->isMemberFunctionPointer() !=
2122         SrcMemPtr->isMemberFunctionPointer())
2123       return TC_NotApplicable;
2124 
2125     if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2126       // We need to determine the inheritance model that the class will use if
2127       // haven't yet.
2128       (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2129       (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2130     }
2131 
2132     // Don't allow casting between member pointers of different sizes.
2133     if (Self.Context.getTypeSize(DestMemPtr) !=
2134         Self.Context.getTypeSize(SrcMemPtr)) {
2135       msg = diag::err_bad_cxx_cast_member_pointer_size;
2136       return TC_Failed;
2137     }
2138 
2139     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2140     //   constness.
2141     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2142     // we accept it.
2143     if (auto CACK =
2144             CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2145                                /*CheckObjCLifetime=*/CStyle))
2146       return getCastAwayConstnessCastKind(CACK, msg);
2147 
2148     // A valid member pointer cast.
2149     assert(!IsLValueCast);
2150     Kind = CK_ReinterpretMemberPointer;
2151     return TC_Success;
2152   }
2153 
2154   // See below for the enumeral issue.
2155   if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2156     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2157     //   type large enough to hold it. A value of std::nullptr_t can be
2158     //   converted to an integral type; the conversion has the same meaning
2159     //   and validity as a conversion of (void*)0 to the integral type.
2160     if (Self.Context.getTypeSize(SrcType) >
2161         Self.Context.getTypeSize(DestType)) {
2162       msg = diag::err_bad_reinterpret_cast_small_int;
2163       return TC_Failed;
2164     }
2165     Kind = CK_PointerToIntegral;
2166     return TC_Success;
2167   }
2168 
2169   // Allow reinterpret_casts between vectors of the same size and
2170   // between vectors and integers of the same size.
2171   bool destIsVector = DestType->isVectorType();
2172   bool srcIsVector = SrcType->isVectorType();
2173   if (srcIsVector || destIsVector) {
2174     // The non-vector type, if any, must have integral type.  This is
2175     // the same rule that C vector casts use; note, however, that enum
2176     // types are not integral in C++.
2177     if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2178         (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2179       return TC_NotApplicable;
2180 
2181     // The size we want to consider is eltCount * eltSize.
2182     // That's exactly what the lax-conversion rules will check.
2183     if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2184       Kind = CK_BitCast;
2185       return TC_Success;
2186     }
2187 
2188     // Otherwise, pick a reasonable diagnostic.
2189     if (!destIsVector)
2190       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2191     else if (!srcIsVector)
2192       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2193     else
2194       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2195 
2196     return TC_Failed;
2197   }
2198 
2199   if (SrcType == DestType) {
2200     // C++ 5.2.10p2 has a note that mentions that, subject to all other
2201     // restrictions, a cast to the same type is allowed so long as it does not
2202     // cast away constness. In C++98, the intent was not entirely clear here,
2203     // since all other paragraphs explicitly forbid casts to the same type.
2204     // C++11 clarifies this case with p2.
2205     //
2206     // The only allowed types are: integral, enumeration, pointer, or
2207     // pointer-to-member types.  We also won't restrict Obj-C pointers either.
2208     Kind = CK_NoOp;
2209     TryCastResult Result = TC_NotApplicable;
2210     if (SrcType->isIntegralOrEnumerationType() ||
2211         SrcType->isAnyPointerType() ||
2212         SrcType->isMemberPointerType() ||
2213         SrcType->isBlockPointerType()) {
2214       Result = TC_Success;
2215     }
2216     return Result;
2217   }
2218 
2219   bool destIsPtr = DestType->isAnyPointerType() ||
2220                    DestType->isBlockPointerType();
2221   bool srcIsPtr = SrcType->isAnyPointerType() ||
2222                   SrcType->isBlockPointerType();
2223   if (!destIsPtr && !srcIsPtr) {
2224     // Except for std::nullptr_t->integer and lvalue->reference, which are
2225     // handled above, at least one of the two arguments must be a pointer.
2226     return TC_NotApplicable;
2227   }
2228 
2229   if (DestType->isIntegralType(Self.Context)) {
2230     assert(srcIsPtr && "One type must be a pointer");
2231     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2232     //   type large enough to hold it; except in Microsoft mode, where the
2233     //   integral type size doesn't matter (except we don't allow bool).
2234     if ((Self.Context.getTypeSize(SrcType) >
2235          Self.Context.getTypeSize(DestType))) {
2236       bool MicrosoftException =
2237           Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2238       if (MicrosoftException) {
2239         unsigned Diag = SrcType->isVoidPointerType()
2240                             ? diag::warn_void_pointer_to_int_cast
2241                             : diag::warn_pointer_to_int_cast;
2242         Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2243       } else {
2244         msg = diag::err_bad_reinterpret_cast_small_int;
2245         return TC_Failed;
2246       }
2247     }
2248     Kind = CK_PointerToIntegral;
2249     return TC_Success;
2250   }
2251 
2252   if (SrcType->isIntegralOrEnumerationType()) {
2253     assert(destIsPtr && "One type must be a pointer");
2254     checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2255     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2256     //   converted to a pointer.
2257     // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2258     //   necessarily converted to a null pointer value.]
2259     Kind = CK_IntegralToPointer;
2260     return TC_Success;
2261   }
2262 
2263   if (!destIsPtr || !srcIsPtr) {
2264     // With the valid non-pointer conversions out of the way, we can be even
2265     // more stringent.
2266     return TC_NotApplicable;
2267   }
2268 
2269   // Cannot convert between block pointers and Objective-C object pointers.
2270   if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2271       (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2272     return TC_NotApplicable;
2273 
2274   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2275   // The C-style cast operator can.
2276   TryCastResult SuccessResult = TC_Success;
2277   if (auto CACK =
2278           CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2279                              /*CheckObjCLifetime=*/CStyle))
2280     SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2281 
2282   if (IsAddressSpaceConversion(SrcType, DestType)) {
2283     Kind = CK_AddressSpaceConversion;
2284     assert(SrcType->isPointerType() && DestType->isPointerType());
2285     if (!CStyle &&
2286         !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2287             SrcType->getPointeeType().getQualifiers())) {
2288       SuccessResult = TC_Failed;
2289     }
2290   } else if (IsLValueCast) {
2291     Kind = CK_LValueBitCast;
2292   } else if (DestType->isObjCObjectPointerType()) {
2293     Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2294   } else if (DestType->isBlockPointerType()) {
2295     if (!SrcType->isBlockPointerType()) {
2296       Kind = CK_AnyPointerToBlockPointerCast;
2297     } else {
2298       Kind = CK_BitCast;
2299     }
2300   } else {
2301     Kind = CK_BitCast;
2302   }
2303 
2304   // Any pointer can be cast to an Objective-C pointer type with a C-style
2305   // cast.
2306   if (CStyle && DestType->isObjCObjectPointerType()) {
2307     return SuccessResult;
2308   }
2309   if (CStyle)
2310     DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2311 
2312   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2313 
2314   // Not casting away constness, so the only remaining check is for compatible
2315   // pointer categories.
2316 
2317   if (SrcType->isFunctionPointerType()) {
2318     if (DestType->isFunctionPointerType()) {
2319       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2320       // a pointer to a function of a different type.
2321       return SuccessResult;
2322     }
2323 
2324     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2325     //   an object type or vice versa is conditionally-supported.
2326     // Compilers support it in C++03 too, though, because it's necessary for
2327     // casting the return value of dlsym() and GetProcAddress().
2328     // FIXME: Conditionally-supported behavior should be configurable in the
2329     // TargetInfo or similar.
2330     Self.Diag(OpRange.getBegin(),
2331               Self.getLangOpts().CPlusPlus11 ?
2332                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2333       << OpRange;
2334     return SuccessResult;
2335   }
2336 
2337   if (DestType->isFunctionPointerType()) {
2338     // See above.
2339     Self.Diag(OpRange.getBegin(),
2340               Self.getLangOpts().CPlusPlus11 ?
2341                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2342       << OpRange;
2343     return SuccessResult;
2344   }
2345 
2346   // Diagnose address space conversion in nested pointers.
2347   QualType DestPtee = DestType->getPointeeType().isNull()
2348                           ? DestType->getPointeeType()
2349                           : DestType->getPointeeType()->getPointeeType();
2350   QualType SrcPtee = SrcType->getPointeeType().isNull()
2351                          ? SrcType->getPointeeType()
2352                          : SrcType->getPointeeType()->getPointeeType();
2353   while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2354     if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2355       Self.Diag(OpRange.getBegin(),
2356                 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2357           << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2358       break;
2359     }
2360     DestPtee = DestPtee->getPointeeType();
2361     SrcPtee = SrcPtee->getPointeeType();
2362   }
2363 
2364   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2365   //   a pointer to an object of different type.
2366   // Void pointers are not specified, but supported by every compiler out there.
2367   // So we finish by allowing everything that remains - it's got to be two
2368   // object pointers.
2369   return SuccessResult;
2370 }
2371 
2372 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2373                                          QualType DestType, bool CStyle,
2374                                          unsigned &msg, CastKind &Kind) {
2375   if (!Self.getLangOpts().OpenCL)
2376     // FIXME: As compiler doesn't have any information about overlapping addr
2377     // spaces at the moment we have to be permissive here.
2378     return TC_NotApplicable;
2379   // Even though the logic below is general enough and can be applied to
2380   // non-OpenCL mode too, we fast-path above because no other languages
2381   // define overlapping address spaces currently.
2382   auto SrcType = SrcExpr.get()->getType();
2383   // FIXME: Should this be generalized to references? The reference parameter
2384   // however becomes a reference pointee type here and therefore rejected.
2385   // Perhaps this is the right behavior though according to C++.
2386   auto SrcPtrType = SrcType->getAs<PointerType>();
2387   if (!SrcPtrType)
2388     return TC_NotApplicable;
2389   auto DestPtrType = DestType->getAs<PointerType>();
2390   if (!DestPtrType)
2391     return TC_NotApplicable;
2392   auto SrcPointeeType = SrcPtrType->getPointeeType();
2393   auto DestPointeeType = DestPtrType->getPointeeType();
2394   if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
2395     msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2396     return TC_Failed;
2397   }
2398   auto SrcPointeeTypeWithoutAS =
2399       Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2400   auto DestPointeeTypeWithoutAS =
2401       Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2402   if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2403                                DestPointeeTypeWithoutAS)) {
2404     Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2405                ? CK_NoOp
2406                : CK_AddressSpaceConversion;
2407     return TC_Success;
2408   } else {
2409     return TC_NotApplicable;
2410   }
2411 }
2412 
2413 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2414   // In OpenCL only conversions between pointers to objects in overlapping
2415   // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2416   // with any named one, except for constant.
2417 
2418   // Converting the top level pointee addrspace is permitted for compatible
2419   // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2420   // if any of the nested pointee addrspaces differ, we emit a warning
2421   // regardless of addrspace compatibility. This makes
2422   //   local int ** p;
2423   //   return (generic int **) p;
2424   // warn even though local -> generic is permitted.
2425   if (Self.getLangOpts().OpenCL) {
2426     const Type *DestPtr, *SrcPtr;
2427     bool Nested = false;
2428     unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2429     DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2430     SrcPtr  = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2431 
2432     while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2433       const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2434       const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2435       QualType DestPPointee = DestPPtr->getPointeeType();
2436       QualType SrcPPointee = SrcPPtr->getPointeeType();
2437       if (Nested
2438               ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2439               : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
2440         Self.Diag(OpRange.getBegin(), DiagID)
2441             << SrcType << DestType << Sema::AA_Casting
2442             << SrcExpr.get()->getSourceRange();
2443         if (!Nested)
2444           SrcExpr = ExprError();
2445         return;
2446       }
2447 
2448       DestPtr = DestPPtr->getPointeeType().getTypePtr();
2449       SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2450       Nested = true;
2451       DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2452     }
2453   }
2454 }
2455 
2456 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2457                                        bool ListInitialization) {
2458   assert(Self.getLangOpts().CPlusPlus);
2459 
2460   // Handle placeholders.
2461   if (isPlaceholder()) {
2462     // C-style casts can resolve __unknown_any types.
2463     if (claimPlaceholder(BuiltinType::UnknownAny)) {
2464       SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2465                                          SrcExpr.get(), Kind,
2466                                          ValueKind, BasePath);
2467       return;
2468     }
2469 
2470     checkNonOverloadPlaceholders();
2471     if (SrcExpr.isInvalid())
2472       return;
2473   }
2474 
2475   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2476   // This test is outside everything else because it's the only case where
2477   // a non-lvalue-reference target type does not lead to decay.
2478   if (DestType->isVoidType()) {
2479     Kind = CK_ToVoid;
2480 
2481     if (claimPlaceholder(BuiltinType::Overload)) {
2482       Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2483                   SrcExpr, /* Decay Function to ptr */ false,
2484                   /* Complain */ true, DestRange, DestType,
2485                   diag::err_bad_cstyle_cast_overload);
2486       if (SrcExpr.isInvalid())
2487         return;
2488     }
2489 
2490     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2491     return;
2492   }
2493 
2494   // If the type is dependent, we won't do any other semantic analysis now.
2495   if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2496       SrcExpr.get()->isValueDependent()) {
2497     assert(Kind == CK_Dependent);
2498     return;
2499   }
2500 
2501   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2502       !isPlaceholder(BuiltinType::Overload)) {
2503     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2504     if (SrcExpr.isInvalid())
2505       return;
2506   }
2507 
2508   // AltiVec vector initialization with a single literal.
2509   if (const VectorType *vecTy = DestType->getAs<VectorType>())
2510     if (vecTy->getVectorKind() == VectorType::AltiVecVector
2511         && (SrcExpr.get()->getType()->isIntegerType()
2512             || SrcExpr.get()->getType()->isFloatingType())) {
2513       Kind = CK_VectorSplat;
2514       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2515       return;
2516     }
2517 
2518   // C++ [expr.cast]p5: The conversions performed by
2519   //   - a const_cast,
2520   //   - a static_cast,
2521   //   - a static_cast followed by a const_cast,
2522   //   - a reinterpret_cast, or
2523   //   - a reinterpret_cast followed by a const_cast,
2524   //   can be performed using the cast notation of explicit type conversion.
2525   //   [...] If a conversion can be interpreted in more than one of the ways
2526   //   listed above, the interpretation that appears first in the list is used,
2527   //   even if a cast resulting from that interpretation is ill-formed.
2528   // In plain language, this means trying a const_cast ...
2529   // Note that for address space we check compatibility after const_cast.
2530   unsigned msg = diag::err_bad_cxx_cast_generic;
2531   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2532                                    /*CStyle*/ true, msg);
2533   if (SrcExpr.isInvalid())
2534     return;
2535   if (isValidCast(tcr))
2536     Kind = CK_NoOp;
2537 
2538   Sema::CheckedConversionKind CCK =
2539       FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
2540   if (tcr == TC_NotApplicable) {
2541     tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2542                               Kind);
2543     if (SrcExpr.isInvalid())
2544       return;
2545 
2546     if (tcr == TC_NotApplicable) {
2547       // ... or if that is not possible, a static_cast, ignoring const and
2548       // addr space, ...
2549       tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2550                           BasePath, ListInitialization);
2551       if (SrcExpr.isInvalid())
2552         return;
2553 
2554       if (tcr == TC_NotApplicable) {
2555         // ... and finally a reinterpret_cast, ignoring const and addr space.
2556         tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2557                                  OpRange, msg, Kind);
2558         if (SrcExpr.isInvalid())
2559           return;
2560       }
2561     }
2562   }
2563 
2564   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2565       isValidCast(tcr))
2566     checkObjCConversion(CCK);
2567 
2568   if (tcr != TC_Success && msg != 0) {
2569     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2570       DeclAccessPair Found;
2571       FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2572                                 DestType,
2573                                 /*Complain*/ true,
2574                                 Found);
2575       if (Fn) {
2576         // If DestType is a function type (not to be confused with the function
2577         // pointer type), it will be possible to resolve the function address,
2578         // but the type cast should be considered as failure.
2579         OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2580         Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2581           << OE->getName() << DestType << OpRange
2582           << OE->getQualifierLoc().getSourceRange();
2583         Self.NoteAllOverloadCandidates(SrcExpr.get());
2584       }
2585     } else {
2586       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2587                       OpRange, SrcExpr.get(), DestType, ListInitialization);
2588     }
2589   }
2590 
2591   if (isValidCast(tcr)) {
2592     if (Kind == CK_BitCast)
2593       checkCastAlign();
2594   } else {
2595     SrcExpr = ExprError();
2596   }
2597 }
2598 
2599 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2600 ///  non-matching type. Such as enum function call to int, int call to
2601 /// pointer; etc. Cast to 'void' is an exception.
2602 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2603                                   QualType DestType) {
2604   if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2605                            SrcExpr.get()->getExprLoc()))
2606     return;
2607 
2608   if (!isa<CallExpr>(SrcExpr.get()))
2609     return;
2610 
2611   QualType SrcType = SrcExpr.get()->getType();
2612   if (DestType.getUnqualifiedType()->isVoidType())
2613     return;
2614   if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2615       && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2616     return;
2617   if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2618       (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2619       (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2620     return;
2621   if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2622     return;
2623   if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2624     return;
2625   if (SrcType->isComplexType() && DestType->isComplexType())
2626     return;
2627   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2628     return;
2629 
2630   Self.Diag(SrcExpr.get()->getExprLoc(),
2631             diag::warn_bad_function_cast)
2632             << SrcType << DestType << SrcExpr.get()->getSourceRange();
2633 }
2634 
2635 /// Check the semantics of a C-style cast operation, in C.
2636 void CastOperation::CheckCStyleCast() {
2637   assert(!Self.getLangOpts().CPlusPlus);
2638 
2639   // C-style casts can resolve __unknown_any types.
2640   if (claimPlaceholder(BuiltinType::UnknownAny)) {
2641     SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2642                                        SrcExpr.get(), Kind,
2643                                        ValueKind, BasePath);
2644     return;
2645   }
2646 
2647   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2648   // type needs to be scalar.
2649   if (DestType->isVoidType()) {
2650     // We don't necessarily do lvalue-to-rvalue conversions on this.
2651     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2652     if (SrcExpr.isInvalid())
2653       return;
2654 
2655     // Cast to void allows any expr type.
2656     Kind = CK_ToVoid;
2657     return;
2658   }
2659 
2660   // Overloads are allowed with C extensions, so we need to support them.
2661   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2662     DeclAccessPair DAP;
2663     if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2664             SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2665       SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2666     else
2667       return;
2668     assert(SrcExpr.isUsable());
2669   }
2670   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2671   if (SrcExpr.isInvalid())
2672     return;
2673   QualType SrcType = SrcExpr.get()->getType();
2674 
2675   assert(!SrcType->isPlaceholderType());
2676 
2677   checkAddressSpaceCast(SrcType, DestType);
2678   if (SrcExpr.isInvalid())
2679     return;
2680 
2681   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2682                                diag::err_typecheck_cast_to_incomplete)) {
2683     SrcExpr = ExprError();
2684     return;
2685   }
2686 
2687   // Allow casting a sizeless built-in type to itself.
2688   if (DestType->isSizelessBuiltinType() &&
2689       Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
2690     Kind = CK_NoOp;
2691     return;
2692   }
2693 
2694   if (!DestType->isScalarType() && !DestType->isVectorType()) {
2695     const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2696 
2697     if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2698       // GCC struct/union extension: allow cast to self.
2699       Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2700         << DestType << SrcExpr.get()->getSourceRange();
2701       Kind = CK_NoOp;
2702       return;
2703     }
2704 
2705     // GCC's cast to union extension.
2706     if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2707       RecordDecl *RD = DestRecordTy->getDecl();
2708       if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2709         Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2710           << SrcExpr.get()->getSourceRange();
2711         Kind = CK_ToUnion;
2712         return;
2713       } else {
2714         Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2715           << SrcType << SrcExpr.get()->getSourceRange();
2716         SrcExpr = ExprError();
2717         return;
2718       }
2719     }
2720 
2721     // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2722     if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2723       Expr::EvalResult Result;
2724       if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2725         llvm::APSInt CastInt = Result.Val.getInt();
2726         if (0 == CastInt) {
2727           Kind = CK_ZeroToOCLOpaqueType;
2728           return;
2729         }
2730         Self.Diag(OpRange.getBegin(),
2731                   diag::err_opencl_cast_non_zero_to_event_t)
2732                   << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2733         SrcExpr = ExprError();
2734         return;
2735       }
2736     }
2737 
2738     // Reject any other conversions to non-scalar types.
2739     Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2740       << DestType << SrcExpr.get()->getSourceRange();
2741     SrcExpr = ExprError();
2742     return;
2743   }
2744 
2745   // The type we're casting to is known to be a scalar or vector.
2746 
2747   // Require the operand to be a scalar or vector.
2748   if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2749     Self.Diag(SrcExpr.get()->getExprLoc(),
2750               diag::err_typecheck_expect_scalar_operand)
2751       << SrcType << SrcExpr.get()->getSourceRange();
2752     SrcExpr = ExprError();
2753     return;
2754   }
2755 
2756   if (DestType->isExtVectorType()) {
2757     SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2758     return;
2759   }
2760 
2761   if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2762     if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2763           (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2764       Kind = CK_VectorSplat;
2765       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2766     } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2767       SrcExpr = ExprError();
2768     }
2769     return;
2770   }
2771 
2772   if (SrcType->isVectorType()) {
2773     if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2774       SrcExpr = ExprError();
2775     return;
2776   }
2777 
2778   // The source and target types are both scalars, i.e.
2779   //   - arithmetic types (fundamental, enum, and complex)
2780   //   - all kinds of pointers
2781   // Note that member pointers were filtered out with C++, above.
2782 
2783   if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2784     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2785     SrcExpr = ExprError();
2786     return;
2787   }
2788 
2789   // If either type is a pointer, the other type has to be either an
2790   // integer or a pointer.
2791   if (!DestType->isArithmeticType()) {
2792     if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2793       Self.Diag(SrcExpr.get()->getExprLoc(),
2794                 diag::err_cast_pointer_from_non_pointer_int)
2795         << SrcType << SrcExpr.get()->getSourceRange();
2796       SrcExpr = ExprError();
2797       return;
2798     }
2799     checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
2800                           Self);
2801   } else if (!SrcType->isArithmeticType()) {
2802     if (!DestType->isIntegralType(Self.Context) &&
2803         DestType->isArithmeticType()) {
2804       Self.Diag(SrcExpr.get()->getBeginLoc(),
2805                 diag::err_cast_pointer_to_non_pointer_int)
2806           << DestType << SrcExpr.get()->getSourceRange();
2807       SrcExpr = ExprError();
2808       return;
2809     }
2810 
2811     if ((Self.Context.getTypeSize(SrcType) >
2812          Self.Context.getTypeSize(DestType)) &&
2813         !DestType->isBooleanType()) {
2814       // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
2815       // Except as previously specified, the result is implementation-defined.
2816       // If the result cannot be represented in the integer type, the behavior
2817       // is undefined. The result need not be in the range of values of any
2818       // integer type.
2819       unsigned Diag;
2820       if (SrcType->isVoidPointerType())
2821         Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
2822                                           : diag::warn_void_pointer_to_int_cast;
2823       else if (DestType->isEnumeralType())
2824         Diag = diag::warn_pointer_to_enum_cast;
2825       else
2826         Diag = diag::warn_pointer_to_int_cast;
2827       Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2828     }
2829   }
2830 
2831   if (Self.getLangOpts().OpenCL &&
2832       !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
2833     if (DestType->isHalfType()) {
2834       Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
2835           << DestType << SrcExpr.get()->getSourceRange();
2836       SrcExpr = ExprError();
2837       return;
2838     }
2839   }
2840 
2841   // ARC imposes extra restrictions on casts.
2842   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2843     checkObjCConversion(Sema::CCK_CStyleCast);
2844     if (SrcExpr.isInvalid())
2845       return;
2846 
2847     const PointerType *CastPtr = DestType->getAs<PointerType>();
2848     if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
2849       if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2850         Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2851         Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2852         if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2853             ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2854             !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2855           Self.Diag(SrcExpr.get()->getBeginLoc(),
2856                     diag::err_typecheck_incompatible_ownership)
2857               << SrcType << DestType << Sema::AA_Casting
2858               << SrcExpr.get()->getSourceRange();
2859           return;
2860         }
2861       }
2862     }
2863     else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2864       Self.Diag(SrcExpr.get()->getBeginLoc(),
2865                 diag::err_arc_convesion_of_weak_unavailable)
2866           << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2867       SrcExpr = ExprError();
2868       return;
2869     }
2870   }
2871 
2872   DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2873   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2874   DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2875   Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2876   if (SrcExpr.isInvalid())
2877     return;
2878 
2879   if (Kind == CK_BitCast)
2880     checkCastAlign();
2881 }
2882 
2883 void CastOperation::CheckBuiltinBitCast() {
2884   QualType SrcType = SrcExpr.get()->getType();
2885 
2886   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2887                                diag::err_typecheck_cast_to_incomplete) ||
2888       Self.RequireCompleteType(OpRange.getBegin(), SrcType,
2889                                diag::err_incomplete_type)) {
2890     SrcExpr = ExprError();
2891     return;
2892   }
2893 
2894   if (SrcExpr.get()->isRValue())
2895     SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
2896                                                   /*IsLValueReference=*/false);
2897 
2898   CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
2899   CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
2900   if (DestSize != SourceSize) {
2901     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
2902         << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
2903     SrcExpr = ExprError();
2904     return;
2905   }
2906 
2907   if (!DestType.isTriviallyCopyableType(Self.Context)) {
2908     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2909         << 1;
2910     SrcExpr = ExprError();
2911     return;
2912   }
2913 
2914   if (!SrcType.isTriviallyCopyableType(Self.Context)) {
2915     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2916         << 0;
2917     SrcExpr = ExprError();
2918     return;
2919   }
2920 
2921   Kind = CK_LValueToRValueBitCast;
2922 }
2923 
2924 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2925 /// const, volatile or both.
2926 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2927                              QualType DestType) {
2928   if (SrcExpr.isInvalid())
2929     return;
2930 
2931   QualType SrcType = SrcExpr.get()->getType();
2932   if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2933         DestType->isLValueReferenceType()))
2934     return;
2935 
2936   QualType TheOffendingSrcType, TheOffendingDestType;
2937   Qualifiers CastAwayQualifiers;
2938   if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2939                          &TheOffendingSrcType, &TheOffendingDestType,
2940                          &CastAwayQualifiers) !=
2941       CastAwayConstnessKind::CACK_Similar)
2942     return;
2943 
2944   // FIXME: 'restrict' is not properly handled here.
2945   int qualifiers = -1;
2946   if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2947     qualifiers = 0;
2948   } else if (CastAwayQualifiers.hasConst()) {
2949     qualifiers = 1;
2950   } else if (CastAwayQualifiers.hasVolatile()) {
2951     qualifiers = 2;
2952   }
2953   // This is a variant of int **x; const int **y = (const int **)x;
2954   if (qualifiers == -1)
2955     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
2956         << SrcType << DestType;
2957   else
2958     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
2959         << TheOffendingSrcType << TheOffendingDestType << qualifiers;
2960 }
2961 
2962 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2963                                      TypeSourceInfo *CastTypeInfo,
2964                                      SourceLocation RPLoc,
2965                                      Expr *CastExpr) {
2966   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2967   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2968   Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
2969 
2970   if (getLangOpts().CPlusPlus) {
2971     Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
2972                           isa<InitListExpr>(CastExpr));
2973   } else {
2974     Op.CheckCStyleCast();
2975   }
2976 
2977   if (Op.SrcExpr.isInvalid())
2978     return ExprError();
2979 
2980   // -Wcast-qual
2981   DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2982 
2983   return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2984                               Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2985                               &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2986 }
2987 
2988 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2989                                             QualType Type,
2990                                             SourceLocation LPLoc,
2991                                             Expr *CastExpr,
2992                                             SourceLocation RPLoc) {
2993   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2994   CastOperation Op(*this, Type, CastExpr);
2995   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2996   Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
2997 
2998   Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
2999   if (Op.SrcExpr.isInvalid())
3000     return ExprError();
3001 
3002   auto *SubExpr = Op.SrcExpr.get();
3003   if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
3004     SubExpr = BindExpr->getSubExpr();
3005   if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
3006     ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
3007 
3008   return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
3009                          Op.ValueKind, CastTypeInfo, Op.Kind,
3010                          Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
3011 }
3012