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