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