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