SemaCast.cpp revision 280031
1//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for cast expressions, including
11//  1) C-style casts like '(int) x'
12//  2) C++ functional casts like 'int(x)'
13//  3) C++ named casts like 'static_cast<int>(x)'
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/Sema/SemaInternal.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/Initialization.h"
26#include "llvm/ADT/SmallVector.h"
27#include <set>
28using namespace clang;
29
30
31
32enum TryCastResult {
33  TC_NotApplicable, ///< The cast method is not applicable.
34  TC_Success,       ///< The cast method is appropriate and successful.
35  TC_Failed         ///< The cast method is appropriate, but failed. A
36                    ///< diagnostic has been emitted.
37};
38
39enum CastType {
40  CT_Const,       ///< const_cast
41  CT_Static,      ///< static_cast
42  CT_Reinterpret, ///< reinterpret_cast
43  CT_Dynamic,     ///< dynamic_cast
44  CT_CStyle,      ///< (Type)expr
45  CT_Functional   ///< Type(expr)
46};
47
48namespace {
49  struct CastOperation {
50    CastOperation(Sema &S, QualType destType, ExprResult src)
51      : Self(S), SrcExpr(src), DestType(destType),
52        ResultType(destType.getNonLValueExprType(S.Context)),
53        ValueKind(Expr::getValueKindForType(destType)),
54        Kind(CK_Dependent), IsARCUnbridgedCast(false) {
55
56      if (const BuiltinType *placeholder =
57            src.get()->getType()->getAsPlaceholderType()) {
58        PlaceholderKind = placeholder->getKind();
59      } else {
60        PlaceholderKind = (BuiltinType::Kind) 0;
61      }
62    }
63
64    Sema &Self;
65    ExprResult SrcExpr;
66    QualType DestType;
67    QualType ResultType;
68    ExprValueKind ValueKind;
69    CastKind Kind;
70    BuiltinType::Kind PlaceholderKind;
71    CXXCastPath BasePath;
72    bool IsARCUnbridgedCast;
73
74    SourceRange OpRange;
75    SourceRange DestRange;
76
77    // Top-level semantics-checking routines.
78    void CheckConstCast();
79    void CheckReinterpretCast();
80    void CheckStaticCast();
81    void CheckDynamicCast();
82    void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
83    void CheckCStyleCast();
84
85    /// Complete an apparently-successful cast operation that yields
86    /// the given expression.
87    ExprResult complete(CastExpr *castExpr) {
88      // If this is an unbridged cast, wrap the result in an implicit
89      // cast that yields the unbridged-cast placeholder type.
90      if (IsARCUnbridgedCast) {
91        castExpr = ImplicitCastExpr::Create(Self.Context,
92                                            Self.Context.ARCUnbridgedCastTy,
93                                            CK_Dependent, castExpr, nullptr,
94                                            castExpr->getValueKind());
95      }
96      return castExpr;
97    }
98
99    // Internal convenience methods.
100
101    /// Try to handle the given placeholder expression kind.  Return
102    /// true if the source expression has the appropriate placeholder
103    /// kind.  A placeholder can only be claimed once.
104    bool claimPlaceholder(BuiltinType::Kind K) {
105      if (PlaceholderKind != K) return false;
106
107      PlaceholderKind = (BuiltinType::Kind) 0;
108      return true;
109    }
110
111    bool isPlaceholder() const {
112      return PlaceholderKind != 0;
113    }
114    bool isPlaceholder(BuiltinType::Kind K) const {
115      return PlaceholderKind == K;
116    }
117
118    void checkCastAlign() {
119      Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
120    }
121
122    void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
123      assert(Self.getLangOpts().ObjCAutoRefCount);
124
125      Expr *src = SrcExpr.get();
126      if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127            Sema::ACR_unbridged)
128        IsARCUnbridgedCast = true;
129      SrcExpr = src;
130    }
131
132    /// Check for and handle non-overload placeholder expressions.
133    void checkNonOverloadPlaceholders() {
134      if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
135        return;
136
137      SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
138      if (SrcExpr.isInvalid())
139        return;
140      PlaceholderKind = (BuiltinType::Kind) 0;
141    }
142  };
143}
144
145// The Try functions attempt a specific way of casting. If they succeed, they
146// return TC_Success. If their way of casting is not appropriate for the given
147// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
148// to emit if no other way succeeds. If their way of casting is appropriate but
149// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
150// they emit a specialized diagnostic.
151// All diagnostics returned by these functions must expect the same three
152// arguments:
153// %0: Cast Type (a value from the CastType enumeration)
154// %1: Source Type
155// %2: Destination Type
156static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
157                                           QualType DestType, bool CStyle,
158                                           CastKind &Kind,
159                                           CXXCastPath &BasePath,
160                                           unsigned &msg);
161static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
162                                               QualType DestType, bool CStyle,
163                                               const SourceRange &OpRange,
164                                               unsigned &msg,
165                                               CastKind &Kind,
166                                               CXXCastPath &BasePath);
167static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
168                                              QualType DestType, bool CStyle,
169                                              const SourceRange &OpRange,
170                                              unsigned &msg,
171                                              CastKind &Kind,
172                                              CXXCastPath &BasePath);
173static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
174                                       CanQualType DestType, bool CStyle,
175                                       const SourceRange &OpRange,
176                                       QualType OrigSrcType,
177                                       QualType OrigDestType, unsigned &msg,
178                                       CastKind &Kind,
179                                       CXXCastPath &BasePath);
180static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
181                                               QualType SrcType,
182                                               QualType DestType,bool CStyle,
183                                               const SourceRange &OpRange,
184                                               unsigned &msg,
185                                               CastKind &Kind,
186                                               CXXCastPath &BasePath);
187
188static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
189                                           QualType DestType,
190                                           Sema::CheckedConversionKind CCK,
191                                           const SourceRange &OpRange,
192                                           unsigned &msg, CastKind &Kind,
193                                           bool ListInitialization);
194static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
195                                   QualType DestType,
196                                   Sema::CheckedConversionKind CCK,
197                                   const SourceRange &OpRange,
198                                   unsigned &msg, CastKind &Kind,
199                                   CXXCastPath &BasePath,
200                                   bool ListInitialization);
201static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
202                                  QualType DestType, bool CStyle,
203                                  unsigned &msg);
204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
205                                        QualType DestType, bool CStyle,
206                                        const SourceRange &OpRange,
207                                        unsigned &msg,
208                                        CastKind &Kind);
209
210
211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
212ExprResult
213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
214                        SourceLocation LAngleBracketLoc, Declarator &D,
215                        SourceLocation RAngleBracketLoc,
216                        SourceLocation LParenLoc, Expr *E,
217                        SourceLocation RParenLoc) {
218
219  assert(!D.isInvalidType());
220
221  TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222  if (D.isInvalidType())
223    return ExprError();
224
225  if (getLangOpts().CPlusPlus) {
226    // Check that there are no default arguments (C++ only).
227    CheckExtraCXXDefaultArguments(D);
228  }
229
230  return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
231                           SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232                           SourceRange(LParenLoc, RParenLoc));
233}
234
235ExprResult
236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
237                        TypeSourceInfo *DestTInfo, Expr *E,
238                        SourceRange AngleBrackets, SourceRange Parens) {
239  ExprResult Ex = E;
240  QualType DestType = DestTInfo->getType();
241
242  // If the type is dependent, we won't do the semantic analysis now.
243  bool TypeDependent =
244      DestType->isDependentType() || Ex.get()->isTypeDependent();
245
246  CastOperation Op(*this, DestType, E);
247  Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248  Op.DestRange = AngleBrackets;
249
250  switch (Kind) {
251  default: llvm_unreachable("Unknown C++ cast!");
252
253  case tok::kw_const_cast:
254    if (!TypeDependent) {
255      Op.CheckConstCast();
256      if (Op.SrcExpr.isInvalid())
257        return ExprError();
258    }
259    return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
260                                  Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
261                                                OpLoc, Parens.getEnd(),
262                                                AngleBrackets));
263
264  case tok::kw_dynamic_cast: {
265    if (!TypeDependent) {
266      Op.CheckDynamicCast();
267      if (Op.SrcExpr.isInvalid())
268        return ExprError();
269    }
270    return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
271                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
272                                                  &Op.BasePath, DestTInfo,
273                                                  OpLoc, Parens.getEnd(),
274                                                  AngleBrackets));
275  }
276  case tok::kw_reinterpret_cast: {
277    if (!TypeDependent) {
278      Op.CheckReinterpretCast();
279      if (Op.SrcExpr.isInvalid())
280        return ExprError();
281    }
282    return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
283                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
284                                                      nullptr, DestTInfo, OpLoc,
285                                                      Parens.getEnd(),
286                                                      AngleBrackets));
287  }
288  case tok::kw_static_cast: {
289    if (!TypeDependent) {
290      Op.CheckStaticCast();
291      if (Op.SrcExpr.isInvalid())
292        return ExprError();
293    }
294
295    return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
296                                   Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
297                                                 &Op.BasePath, DestTInfo,
298                                                 OpLoc, Parens.getEnd(),
299                                                 AngleBrackets));
300  }
301  }
302}
303
304/// Try to diagnose a failed overloaded cast.  Returns true if
305/// diagnostics were emitted.
306static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
307                                      SourceRange range, Expr *src,
308                                      QualType destType,
309                                      bool listInitialization) {
310  switch (CT) {
311  // These cast kinds don't consider user-defined conversions.
312  case CT_Const:
313  case CT_Reinterpret:
314  case CT_Dynamic:
315    return false;
316
317  // These do.
318  case CT_Static:
319  case CT_CStyle:
320  case CT_Functional:
321    break;
322  }
323
324  QualType srcType = src->getType();
325  if (!destType->isRecordType() && !srcType->isRecordType())
326    return false;
327
328  InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
329  InitializationKind initKind
330    = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
331                                                      range, listInitialization)
332    : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
333                                                             listInitialization)
334    : InitializationKind::CreateCast(/*type range?*/ range);
335  InitializationSequence sequence(S, entity, initKind, src);
336
337  assert(sequence.Failed() && "initialization succeeded on second try?");
338  switch (sequence.getFailureKind()) {
339  default: return false;
340
341  case InitializationSequence::FK_ConstructorOverloadFailed:
342  case InitializationSequence::FK_UserConversionOverloadFailed:
343    break;
344  }
345
346  OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
347
348  unsigned msg = 0;
349  OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
350
351  switch (sequence.getFailedOverloadResult()) {
352  case OR_Success: llvm_unreachable("successful failed overload");
353  case OR_No_Viable_Function:
354    if (candidates.empty())
355      msg = diag::err_ovl_no_conversion_in_cast;
356    else
357      msg = diag::err_ovl_no_viable_conversion_in_cast;
358    howManyCandidates = OCD_AllCandidates;
359    break;
360
361  case OR_Ambiguous:
362    msg = diag::err_ovl_ambiguous_conversion_in_cast;
363    howManyCandidates = OCD_ViableCandidates;
364    break;
365
366  case OR_Deleted:
367    msg = diag::err_ovl_deleted_conversion_in_cast;
368    howManyCandidates = OCD_ViableCandidates;
369    break;
370  }
371
372  S.Diag(range.getBegin(), msg)
373    << CT << srcType << destType
374    << range << src->getSourceRange();
375
376  candidates.NoteCandidates(S, howManyCandidates, src);
377
378  return true;
379}
380
381/// Diagnose a failed cast.
382static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
383                            SourceRange opRange, Expr *src, QualType destType,
384                            bool listInitialization) {
385  if (msg == diag::err_bad_cxx_cast_generic &&
386      tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
387                                listInitialization))
388    return;
389
390  S.Diag(opRange.getBegin(), msg) << castType
391    << src->getType() << destType << opRange << src->getSourceRange();
392}
393
394/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
395/// this removes one level of indirection from both types, provided that they're
396/// the same kind of pointer (plain or to-member). Unlike the Sema function,
397/// this one doesn't care if the two pointers-to-member don't point into the
398/// same class. This is because CastsAwayConstness doesn't care.
399static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
400  const PointerType *T1PtrType = T1->getAs<PointerType>(),
401                    *T2PtrType = T2->getAs<PointerType>();
402  if (T1PtrType && T2PtrType) {
403    T1 = T1PtrType->getPointeeType();
404    T2 = T2PtrType->getPointeeType();
405    return true;
406  }
407  const ObjCObjectPointerType *T1ObjCPtrType =
408                                            T1->getAs<ObjCObjectPointerType>(),
409                              *T2ObjCPtrType =
410                                            T2->getAs<ObjCObjectPointerType>();
411  if (T1ObjCPtrType) {
412    if (T2ObjCPtrType) {
413      T1 = T1ObjCPtrType->getPointeeType();
414      T2 = T2ObjCPtrType->getPointeeType();
415      return true;
416    }
417    else if (T2PtrType) {
418      T1 = T1ObjCPtrType->getPointeeType();
419      T2 = T2PtrType->getPointeeType();
420      return true;
421    }
422  }
423  else if (T2ObjCPtrType) {
424    if (T1PtrType) {
425      T2 = T2ObjCPtrType->getPointeeType();
426      T1 = T1PtrType->getPointeeType();
427      return true;
428    }
429  }
430
431  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
432                          *T2MPType = T2->getAs<MemberPointerType>();
433  if (T1MPType && T2MPType) {
434    T1 = T1MPType->getPointeeType();
435    T2 = T2MPType->getPointeeType();
436    return true;
437  }
438
439  const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
440                         *T2BPType = T2->getAs<BlockPointerType>();
441  if (T1BPType && T2BPType) {
442    T1 = T1BPType->getPointeeType();
443    T2 = T2BPType->getPointeeType();
444    return true;
445  }
446
447  return false;
448}
449
450/// CastsAwayConstness - Check if the pointer conversion from SrcType to
451/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
452/// the cast checkers.  Both arguments must denote pointer (possibly to member)
453/// types.
454///
455/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
456///
457/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
458static bool
459CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
460                   bool CheckCVR, bool CheckObjCLifetime,
461                   QualType *TheOffendingSrcType = nullptr,
462                   QualType *TheOffendingDestType = nullptr,
463                   Qualifiers *CastAwayQualifiers = nullptr) {
464  // If the only checking we care about is for Objective-C lifetime qualifiers,
465  // and we're not in ARC mode, there's nothing to check.
466  if (!CheckCVR && CheckObjCLifetime &&
467      !Self.Context.getLangOpts().ObjCAutoRefCount)
468    return false;
469
470  // Casting away constness is defined in C++ 5.2.11p8 with reference to
471  // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
472  // the rules are non-trivial. So first we construct Tcv *...cv* as described
473  // in C++ 5.2.11p8.
474  assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
475          SrcType->isBlockPointerType()) &&
476         "Source type is not pointer or pointer to member.");
477  assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
478          DestType->isBlockPointerType()) &&
479         "Destination type is not pointer or pointer to member.");
480
481  QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
482           UnwrappedDestType = Self.Context.getCanonicalType(DestType);
483  SmallVector<Qualifiers, 8> cv1, cv2;
484
485  // Find the qualifiers. We only care about cvr-qualifiers for the
486  // purpose of this check, because other qualifiers (address spaces,
487  // Objective-C GC, etc.) are part of the type's identity.
488  QualType PrevUnwrappedSrcType = UnwrappedSrcType;
489  QualType PrevUnwrappedDestType = UnwrappedDestType;
490  while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
491    // Determine the relevant qualifiers at this level.
492    Qualifiers SrcQuals, DestQuals;
493    Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
494    Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
495
496    Qualifiers RetainedSrcQuals, RetainedDestQuals;
497    if (CheckCVR) {
498      RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
499      RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
500
501      if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
502          TheOffendingDestType && CastAwayQualifiers) {
503        *TheOffendingSrcType = PrevUnwrappedSrcType;
504        *TheOffendingDestType = PrevUnwrappedDestType;
505        *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
506      }
507    }
508
509    if (CheckObjCLifetime &&
510        !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
511      return true;
512
513    cv1.push_back(RetainedSrcQuals);
514    cv2.push_back(RetainedDestQuals);
515
516    PrevUnwrappedSrcType = UnwrappedSrcType;
517    PrevUnwrappedDestType = UnwrappedDestType;
518  }
519  if (cv1.empty())
520    return false;
521
522  // Construct void pointers with those qualifiers (in reverse order of
523  // unwrapping, of course).
524  QualType SrcConstruct = Self.Context.VoidTy;
525  QualType DestConstruct = Self.Context.VoidTy;
526  ASTContext &Context = Self.Context;
527  for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
528                                                     i2 = cv2.rbegin();
529       i1 != cv1.rend(); ++i1, ++i2) {
530    SrcConstruct
531      = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
532    DestConstruct
533      = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
534  }
535
536  // Test if they're compatible.
537  bool ObjCLifetimeConversion;
538  return SrcConstruct != DestConstruct &&
539    !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
540                                    ObjCLifetimeConversion);
541}
542
543/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
544/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
545/// checked downcasts in class hierarchies.
546void CastOperation::CheckDynamicCast() {
547  if (ValueKind == VK_RValue)
548    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
549  else if (isPlaceholder())
550    SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
551  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
552    return;
553
554  QualType OrigSrcType = SrcExpr.get()->getType();
555  QualType DestType = Self.Context.getCanonicalType(this->DestType);
556
557  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
558  //   or "pointer to cv void".
559
560  QualType DestPointee;
561  const PointerType *DestPointer = DestType->getAs<PointerType>();
562  const ReferenceType *DestReference = nullptr;
563  if (DestPointer) {
564    DestPointee = DestPointer->getPointeeType();
565  } else if ((DestReference = DestType->getAs<ReferenceType>())) {
566    DestPointee = DestReference->getPointeeType();
567  } else {
568    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
569      << this->DestType << DestRange;
570    SrcExpr = ExprError();
571    return;
572  }
573
574  const RecordType *DestRecord = DestPointee->getAs<RecordType>();
575  if (DestPointee->isVoidType()) {
576    assert(DestPointer && "Reference to void is not possible");
577  } else if (DestRecord) {
578    if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
579                                 diag::err_bad_dynamic_cast_incomplete,
580                                 DestRange)) {
581      SrcExpr = ExprError();
582      return;
583    }
584  } else {
585    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
586      << DestPointee.getUnqualifiedType() << DestRange;
587    SrcExpr = ExprError();
588    return;
589  }
590
591  // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
592  //   complete class type, [...]. If T is an lvalue reference type, v shall be
593  //   an lvalue of a complete class type, [...]. If T is an rvalue reference
594  //   type, v shall be an expression having a complete class type, [...]
595  QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
596  QualType SrcPointee;
597  if (DestPointer) {
598    if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
599      SrcPointee = SrcPointer->getPointeeType();
600    } else {
601      Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
602        << OrigSrcType << SrcExpr.get()->getSourceRange();
603      SrcExpr = ExprError();
604      return;
605    }
606  } else if (DestReference->isLValueReferenceType()) {
607    if (!SrcExpr.get()->isLValue()) {
608      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
609        << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
610    }
611    SrcPointee = SrcType;
612  } else {
613    // If we're dynamic_casting from a prvalue to an rvalue reference, we need
614    // to materialize the prvalue before we bind the reference to it.
615    if (SrcExpr.get()->isRValue())
616      SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
617          SrcType, SrcExpr.get(), /*IsLValueReference*/false);
618    SrcPointee = SrcType;
619  }
620
621  const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
622  if (SrcRecord) {
623    if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
624                                 diag::err_bad_dynamic_cast_incomplete,
625                                 SrcExpr.get())) {
626      SrcExpr = ExprError();
627      return;
628    }
629  } else {
630    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
631      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
632    SrcExpr = ExprError();
633    return;
634  }
635
636  assert((DestPointer || DestReference) &&
637    "Bad destination non-ptr/ref slipped through.");
638  assert((DestRecord || DestPointee->isVoidType()) &&
639    "Bad destination pointee slipped through.");
640  assert(SrcRecord && "Bad source pointee slipped through.");
641
642  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
643  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
644    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
645      << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
646    SrcExpr = ExprError();
647    return;
648  }
649
650  // C++ 5.2.7p3: If the type of v is the same as the required result type,
651  //   [except for cv].
652  if (DestRecord == SrcRecord) {
653    Kind = CK_NoOp;
654    return;
655  }
656
657  // C++ 5.2.7p5
658  // Upcasts are resolved statically.
659  if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
660    if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
661                                           OpRange.getBegin(), OpRange,
662                                           &BasePath)) {
663      SrcExpr = ExprError();
664      return;
665    }
666
667    Kind = CK_DerivedToBase;
668
669    // If we are casting to or through a virtual base class, we need a
670    // vtable.
671    if (Self.BasePathInvolvesVirtualBase(BasePath))
672      Self.MarkVTableUsed(OpRange.getBegin(),
673                          cast<CXXRecordDecl>(SrcRecord->getDecl()));
674    return;
675  }
676
677  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
678  const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
679  assert(SrcDecl && "Definition missing");
680  if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
681    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
682      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
683    SrcExpr = ExprError();
684  }
685  Self.MarkVTableUsed(OpRange.getBegin(),
686                      cast<CXXRecordDecl>(SrcRecord->getDecl()));
687
688  // dynamic_cast is not available with -fno-rtti.
689  // As an exception, dynamic_cast to void* is available because it doesn't
690  // use RTTI.
691  if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
692    Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
693    SrcExpr = ExprError();
694    return;
695  }
696
697  // Done. Everything else is run-time checks.
698  Kind = CK_Dynamic;
699}
700
701/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
702/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
703/// like this:
704/// const char *str = "literal";
705/// legacy_function(const_cast\<char*\>(str));
706void CastOperation::CheckConstCast() {
707  if (ValueKind == VK_RValue)
708    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
709  else if (isPlaceholder())
710    SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
711  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
712    return;
713
714  unsigned msg = diag::err_bad_cxx_cast_generic;
715  if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
716      && msg != 0) {
717    Self.Diag(OpRange.getBegin(), msg) << CT_Const
718      << SrcExpr.get()->getType() << DestType << OpRange;
719    SrcExpr = ExprError();
720  }
721}
722
723/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
724/// or downcast between respective pointers or references.
725static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
726                                          QualType DestType,
727                                          SourceRange OpRange) {
728  QualType SrcType = SrcExpr->getType();
729  // When casting from pointer or reference, get pointee type; use original
730  // type otherwise.
731  const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
732  const CXXRecordDecl *SrcRD =
733    SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
734
735  // Examining subobjects for records is only possible if the complete and
736  // valid definition is available.  Also, template instantiation is not
737  // allowed here.
738  if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
739    return;
740
741  const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
742
743  if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
744    return;
745
746  enum {
747    ReinterpretUpcast,
748    ReinterpretDowncast
749  } ReinterpretKind;
750
751  CXXBasePaths BasePaths;
752
753  if (SrcRD->isDerivedFrom(DestRD, BasePaths))
754    ReinterpretKind = ReinterpretUpcast;
755  else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
756    ReinterpretKind = ReinterpretDowncast;
757  else
758    return;
759
760  bool VirtualBase = true;
761  bool NonZeroOffset = false;
762  for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
763                                          E = BasePaths.end();
764       I != E; ++I) {
765    const CXXBasePath &Path = *I;
766    CharUnits Offset = CharUnits::Zero();
767    bool IsVirtual = false;
768    for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
769         IElem != EElem; ++IElem) {
770      IsVirtual = IElem->Base->isVirtual();
771      if (IsVirtual)
772        break;
773      const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
774      assert(BaseRD && "Base type should be a valid unqualified class type");
775      // Don't check if any base has invalid declaration or has no definition
776      // since it has no layout info.
777      const CXXRecordDecl *Class = IElem->Class,
778                          *ClassDefinition = Class->getDefinition();
779      if (Class->isInvalidDecl() || !ClassDefinition ||
780          !ClassDefinition->isCompleteDefinition())
781        return;
782
783      const ASTRecordLayout &DerivedLayout =
784          Self.Context.getASTRecordLayout(Class);
785      Offset += DerivedLayout.getBaseClassOffset(BaseRD);
786    }
787    if (!IsVirtual) {
788      // Don't warn if any path is a non-virtually derived base at offset zero.
789      if (Offset.isZero())
790        return;
791      // Offset makes sense only for non-virtual bases.
792      else
793        NonZeroOffset = true;
794    }
795    VirtualBase = VirtualBase && IsVirtual;
796  }
797
798  (void) NonZeroOffset; // Silence set but not used warning.
799  assert((VirtualBase || NonZeroOffset) &&
800         "Should have returned if has non-virtual base with zero offset");
801
802  QualType BaseType =
803      ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
804  QualType DerivedType =
805      ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
806
807  SourceLocation BeginLoc = OpRange.getBegin();
808  Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
809    << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
810    << OpRange;
811  Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
812    << int(ReinterpretKind)
813    << FixItHint::CreateReplacement(BeginLoc, "static_cast");
814}
815
816/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
817/// valid.
818/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
819/// like this:
820/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
821void CastOperation::CheckReinterpretCast() {
822  if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
823    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
824  else
825    checkNonOverloadPlaceholders();
826  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
827    return;
828
829  unsigned msg = diag::err_bad_cxx_cast_generic;
830  TryCastResult tcr =
831    TryReinterpretCast(Self, SrcExpr, DestType,
832                       /*CStyle*/false, OpRange, msg, Kind);
833  if (tcr != TC_Success && msg != 0)
834  {
835    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
836      return;
837    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
838      //FIXME: &f<int>; is overloaded and resolvable
839      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
840        << OverloadExpr::find(SrcExpr.get()).Expression->getName()
841        << DestType << OpRange;
842      Self.NoteAllOverloadCandidates(SrcExpr.get());
843
844    } else {
845      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
846                      DestType, /*listInitialization=*/false);
847    }
848    SrcExpr = ExprError();
849  } else if (tcr == TC_Success) {
850    if (Self.getLangOpts().ObjCAutoRefCount)
851      checkObjCARCConversion(Sema::CCK_OtherCast);
852    DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
853  }
854}
855
856
857/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
858/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
859/// implicit conversions explicit and getting rid of data loss warnings.
860void CastOperation::CheckStaticCast() {
861  if (isPlaceholder()) {
862    checkNonOverloadPlaceholders();
863    if (SrcExpr.isInvalid())
864      return;
865  }
866
867  // This test is outside everything else because it's the only case where
868  // a non-lvalue-reference target type does not lead to decay.
869  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
870  if (DestType->isVoidType()) {
871    Kind = CK_ToVoid;
872
873    if (claimPlaceholder(BuiltinType::Overload)) {
874      Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
875                false, // Decay Function to ptr
876                true, // Complain
877                OpRange, DestType, diag::err_bad_static_cast_overload);
878      if (SrcExpr.isInvalid())
879        return;
880    }
881
882    SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
883    return;
884  }
885
886  if (ValueKind == VK_RValue && !DestType->isRecordType() &&
887      !isPlaceholder(BuiltinType::Overload)) {
888    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
889    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
890      return;
891  }
892
893  unsigned msg = diag::err_bad_cxx_cast_generic;
894  TryCastResult tcr
895    = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
896                    Kind, BasePath, /*ListInitialization=*/false);
897  if (tcr != TC_Success && msg != 0) {
898    if (SrcExpr.isInvalid())
899      return;
900    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
901      OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
902      Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
903        << oe->getName() << DestType << OpRange
904        << oe->getQualifierLoc().getSourceRange();
905      Self.NoteAllOverloadCandidates(SrcExpr.get());
906    } else {
907      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
908                      /*listInitialization=*/false);
909    }
910    SrcExpr = ExprError();
911  } else if (tcr == TC_Success) {
912    if (Kind == CK_BitCast)
913      checkCastAlign();
914    if (Self.getLangOpts().ObjCAutoRefCount)
915      checkObjCARCConversion(Sema::CCK_OtherCast);
916  } else if (Kind == CK_BitCast) {
917    checkCastAlign();
918  }
919}
920
921/// TryStaticCast - Check if a static cast can be performed, and do so if
922/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
923/// and casting away constness.
924static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
925                                   QualType DestType,
926                                   Sema::CheckedConversionKind CCK,
927                                   const SourceRange &OpRange, unsigned &msg,
928                                   CastKind &Kind, CXXCastPath &BasePath,
929                                   bool ListInitialization) {
930  // Determine whether we have the semantics of a C-style cast.
931  bool CStyle
932    = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
933
934  // The order the tests is not entirely arbitrary. There is one conversion
935  // that can be handled in two different ways. Given:
936  // struct A {};
937  // struct B : public A {
938  //   B(); B(const A&);
939  // };
940  // const A &a = B();
941  // the cast static_cast<const B&>(a) could be seen as either a static
942  // reference downcast, or an explicit invocation of the user-defined
943  // conversion using B's conversion constructor.
944  // DR 427 specifies that the downcast is to be applied here.
945
946  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
947  // Done outside this function.
948
949  TryCastResult tcr;
950
951  // C++ 5.2.9p5, reference downcast.
952  // See the function for details.
953  // DR 427 specifies that this is to be applied before paragraph 2.
954  tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
955                                   OpRange, msg, Kind, BasePath);
956  if (tcr != TC_NotApplicable)
957    return tcr;
958
959  // C++0x [expr.static.cast]p3:
960  //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
961  //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
962  tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
963                              BasePath, msg);
964  if (tcr != TC_NotApplicable)
965    return tcr;
966
967  // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
968  //   [...] if the declaration "T t(e);" is well-formed, [...].
969  tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
970                              Kind, ListInitialization);
971  if (SrcExpr.isInvalid())
972    return TC_Failed;
973  if (tcr != TC_NotApplicable)
974    return tcr;
975
976  // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
977  // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
978  // conversions, subject to further restrictions.
979  // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
980  // of qualification conversions impossible.
981  // In the CStyle case, the earlier attempt to const_cast should have taken
982  // care of reverse qualification conversions.
983
984  QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
985
986  // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
987  // converted to an integral type. [...] A value of a scoped enumeration type
988  // can also be explicitly converted to a floating-point type [...].
989  if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
990    if (Enum->getDecl()->isScoped()) {
991      if (DestType->isBooleanType()) {
992        Kind = CK_IntegralToBoolean;
993        return TC_Success;
994      } else if (DestType->isIntegralType(Self.Context)) {
995        Kind = CK_IntegralCast;
996        return TC_Success;
997      } else if (DestType->isRealFloatingType()) {
998        Kind = CK_IntegralToFloating;
999        return TC_Success;
1000      }
1001    }
1002  }
1003
1004  // Reverse integral promotion/conversion. All such conversions are themselves
1005  // again integral promotions or conversions and are thus already handled by
1006  // p2 (TryDirectInitialization above).
1007  // (Note: any data loss warnings should be suppressed.)
1008  // The exception is the reverse of enum->integer, i.e. integer->enum (and
1009  // enum->enum). See also C++ 5.2.9p7.
1010  // The same goes for reverse floating point promotion/conversion and
1011  // floating-integral conversions. Again, only floating->enum is relevant.
1012  if (DestType->isEnumeralType()) {
1013    if (SrcType->isIntegralOrEnumerationType()) {
1014      Kind = CK_IntegralCast;
1015      return TC_Success;
1016    } else if (SrcType->isRealFloatingType())   {
1017      Kind = CK_FloatingToIntegral;
1018      return TC_Success;
1019    }
1020  }
1021
1022  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1023  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1024  tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1025                                 Kind, BasePath);
1026  if (tcr != TC_NotApplicable)
1027    return tcr;
1028
1029  // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1030  // conversion. C++ 5.2.9p9 has additional information.
1031  // DR54's access restrictions apply here also.
1032  tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1033                                     OpRange, msg, Kind, BasePath);
1034  if (tcr != TC_NotApplicable)
1035    return tcr;
1036
1037  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1038  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1039  // just the usual constness stuff.
1040  if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1041    QualType SrcPointee = SrcPointer->getPointeeType();
1042    if (SrcPointee->isVoidType()) {
1043      if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1044        QualType DestPointee = DestPointer->getPointeeType();
1045        if (DestPointee->isIncompleteOrObjectType()) {
1046          // This is definitely the intended conversion, but it might fail due
1047          // to a qualifier violation. Note that we permit Objective-C lifetime
1048          // and GC qualifier mismatches here.
1049          if (!CStyle) {
1050            Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1051            Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1052            DestPointeeQuals.removeObjCGCAttr();
1053            DestPointeeQuals.removeObjCLifetime();
1054            SrcPointeeQuals.removeObjCGCAttr();
1055            SrcPointeeQuals.removeObjCLifetime();
1056            if (DestPointeeQuals != SrcPointeeQuals &&
1057                !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1058              msg = diag::err_bad_cxx_cast_qualifiers_away;
1059              return TC_Failed;
1060            }
1061          }
1062          Kind = CK_BitCast;
1063          return TC_Success;
1064        }
1065      }
1066      else if (DestType->isObjCObjectPointerType()) {
1067        // allow both c-style cast and static_cast of objective-c pointers as
1068        // they are pervasive.
1069        Kind = CK_CPointerToObjCPointerCast;
1070        return TC_Success;
1071      }
1072      else if (CStyle && DestType->isBlockPointerType()) {
1073        // allow c-style cast of void * to block pointers.
1074        Kind = CK_AnyPointerToBlockPointerCast;
1075        return TC_Success;
1076      }
1077    }
1078  }
1079  // Allow arbitray objective-c pointer conversion with static casts.
1080  if (SrcType->isObjCObjectPointerType() &&
1081      DestType->isObjCObjectPointerType()) {
1082    Kind = CK_BitCast;
1083    return TC_Success;
1084  }
1085  // Allow ns-pointer to cf-pointer conversion in either direction
1086  // with static casts.
1087  if (!CStyle &&
1088      Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1089    return TC_Success;
1090
1091  // We tried everything. Everything! Nothing works! :-(
1092  return TC_NotApplicable;
1093}
1094
1095/// Tests whether a conversion according to N2844 is valid.
1096TryCastResult
1097TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1098                      bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1099                      unsigned &msg) {
1100  // C++0x [expr.static.cast]p3:
1101  //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1102  //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1103  const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1104  if (!R)
1105    return TC_NotApplicable;
1106
1107  if (!SrcExpr->isGLValue())
1108    return TC_NotApplicable;
1109
1110  // Because we try the reference downcast before this function, from now on
1111  // this is the only cast possibility, so we issue an error if we fail now.
1112  // FIXME: Should allow casting away constness if CStyle.
1113  bool DerivedToBase;
1114  bool ObjCConversion;
1115  bool ObjCLifetimeConversion;
1116  QualType FromType = SrcExpr->getType();
1117  QualType ToType = R->getPointeeType();
1118  if (CStyle) {
1119    FromType = FromType.getUnqualifiedType();
1120    ToType = ToType.getUnqualifiedType();
1121  }
1122
1123  if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
1124                                        ToType, FromType,
1125                                        DerivedToBase, ObjCConversion,
1126                                        ObjCLifetimeConversion)
1127        < Sema::Ref_Compatible_With_Added_Qualification) {
1128    msg = diag::err_bad_lvalue_to_rvalue_cast;
1129    return TC_Failed;
1130  }
1131
1132  if (DerivedToBase) {
1133    Kind = CK_DerivedToBase;
1134    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1135                       /*DetectVirtual=*/true);
1136    if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1137      return TC_NotApplicable;
1138
1139    Self.BuildBasePathArray(Paths, BasePath);
1140  } else
1141    Kind = CK_NoOp;
1142
1143  return TC_Success;
1144}
1145
1146/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1147TryCastResult
1148TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1149                           bool CStyle, const SourceRange &OpRange,
1150                           unsigned &msg, CastKind &Kind,
1151                           CXXCastPath &BasePath) {
1152  // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1153  //   cast to type "reference to cv2 D", where D is a class derived from B,
1154  //   if a valid standard conversion from "pointer to D" to "pointer to B"
1155  //   exists, cv2 >= cv1, and B is not a virtual base class of D.
1156  // In addition, DR54 clarifies that the base must be accessible in the
1157  // current context. Although the wording of DR54 only applies to the pointer
1158  // variant of this rule, the intent is clearly for it to apply to the this
1159  // conversion as well.
1160
1161  const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1162  if (!DestReference) {
1163    return TC_NotApplicable;
1164  }
1165  bool RValueRef = DestReference->isRValueReferenceType();
1166  if (!RValueRef && !SrcExpr->isLValue()) {
1167    // We know the left side is an lvalue reference, so we can suggest a reason.
1168    msg = diag::err_bad_cxx_cast_rvalue;
1169    return TC_NotApplicable;
1170  }
1171
1172  QualType DestPointee = DestReference->getPointeeType();
1173
1174  // FIXME: If the source is a prvalue, we should issue a warning (because the
1175  // cast always has undefined behavior), and for AST consistency, we should
1176  // materialize a temporary.
1177  return TryStaticDowncast(Self,
1178                           Self.Context.getCanonicalType(SrcExpr->getType()),
1179                           Self.Context.getCanonicalType(DestPointee), CStyle,
1180                           OpRange, SrcExpr->getType(), DestType, msg, Kind,
1181                           BasePath);
1182}
1183
1184/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1185TryCastResult
1186TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1187                         bool CStyle, const SourceRange &OpRange,
1188                         unsigned &msg, CastKind &Kind,
1189                         CXXCastPath &BasePath) {
1190  // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1191  //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
1192  //   is a class derived from B, if a valid standard conversion from "pointer
1193  //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1194  //   class of D.
1195  // In addition, DR54 clarifies that the base must be accessible in the
1196  // current context.
1197
1198  const PointerType *DestPointer = DestType->getAs<PointerType>();
1199  if (!DestPointer) {
1200    return TC_NotApplicable;
1201  }
1202
1203  const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1204  if (!SrcPointer) {
1205    msg = diag::err_bad_static_cast_pointer_nonpointer;
1206    return TC_NotApplicable;
1207  }
1208
1209  return TryStaticDowncast(Self,
1210                   Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1211                  Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1212                           CStyle, OpRange, SrcType, DestType, msg, Kind,
1213                           BasePath);
1214}
1215
1216/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1217/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1218/// DestType is possible and allowed.
1219TryCastResult
1220TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1221                  bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1222                  QualType OrigDestType, unsigned &msg,
1223                  CastKind &Kind, CXXCastPath &BasePath) {
1224  // We can only work with complete types. But don't complain if it doesn't work
1225  if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1226      Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
1227    return TC_NotApplicable;
1228
1229  // Downcast can only happen in class hierarchies, so we need classes.
1230  if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1231    return TC_NotApplicable;
1232  }
1233
1234  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1235                     /*DetectVirtual=*/true);
1236  if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1237    return TC_NotApplicable;
1238  }
1239
1240  // Target type does derive from source type. Now we're serious. If an error
1241  // appears now, it's not ignored.
1242  // This may not be entirely in line with the standard. Take for example:
1243  // struct A {};
1244  // struct B : virtual A {
1245  //   B(A&);
1246  // };
1247  //
1248  // void f()
1249  // {
1250  //   (void)static_cast<const B&>(*((A*)0));
1251  // }
1252  // As far as the standard is concerned, p5 does not apply (A is virtual), so
1253  // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1254  // However, both GCC and Comeau reject this example, and accepting it would
1255  // mean more complex code if we're to preserve the nice error message.
1256  // FIXME: Being 100% compliant here would be nice to have.
1257
1258  // Must preserve cv, as always, unless we're in C-style mode.
1259  if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1260    msg = diag::err_bad_cxx_cast_qualifiers_away;
1261    return TC_Failed;
1262  }
1263
1264  if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1265    // This code is analoguous to that in CheckDerivedToBaseConversion, except
1266    // that it builds the paths in reverse order.
1267    // To sum up: record all paths to the base and build a nice string from
1268    // them. Use it to spice up the error message.
1269    if (!Paths.isRecordingPaths()) {
1270      Paths.clear();
1271      Paths.setRecordingPaths(true);
1272      Self.IsDerivedFrom(DestType, SrcType, Paths);
1273    }
1274    std::string PathDisplayStr;
1275    std::set<unsigned> DisplayedPaths;
1276    for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1277         PI != PE; ++PI) {
1278      if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1279        // We haven't displayed a path to this particular base
1280        // class subobject yet.
1281        PathDisplayStr += "\n    ";
1282        for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1283                                                 EE = PI->rend();
1284             EI != EE; ++EI)
1285          PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1286        PathDisplayStr += QualType(DestType).getAsString();
1287      }
1288    }
1289
1290    Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1291      << QualType(SrcType).getUnqualifiedType()
1292      << QualType(DestType).getUnqualifiedType()
1293      << PathDisplayStr << OpRange;
1294    msg = 0;
1295    return TC_Failed;
1296  }
1297
1298  if (Paths.getDetectedVirtual() != nullptr) {
1299    QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1300    Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1301      << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1302    msg = 0;
1303    return TC_Failed;
1304  }
1305
1306  if (!CStyle) {
1307    switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1308                                      SrcType, DestType,
1309                                      Paths.front(),
1310                                diag::err_downcast_from_inaccessible_base)) {
1311    case Sema::AR_accessible:
1312    case Sema::AR_delayed:     // be optimistic
1313    case Sema::AR_dependent:   // be optimistic
1314      break;
1315
1316    case Sema::AR_inaccessible:
1317      msg = 0;
1318      return TC_Failed;
1319    }
1320  }
1321
1322  Self.BuildBasePathArray(Paths, BasePath);
1323  Kind = CK_BaseToDerived;
1324  return TC_Success;
1325}
1326
1327/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1328/// C++ 5.2.9p9 is valid:
1329///
1330///   An rvalue of type "pointer to member of D of type cv1 T" can be
1331///   converted to an rvalue of type "pointer to member of B of type cv2 T",
1332///   where B is a base class of D [...].
1333///
1334TryCastResult
1335TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1336                             QualType DestType, bool CStyle,
1337                             const SourceRange &OpRange,
1338                             unsigned &msg, CastKind &Kind,
1339                             CXXCastPath &BasePath) {
1340  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1341  if (!DestMemPtr)
1342    return TC_NotApplicable;
1343
1344  bool WasOverloadedFunction = false;
1345  DeclAccessPair FoundOverload;
1346  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1347    if (FunctionDecl *Fn
1348          = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1349                                                    FoundOverload)) {
1350      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1351      SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1352                      Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1353      WasOverloadedFunction = true;
1354    }
1355  }
1356
1357  const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1358  if (!SrcMemPtr) {
1359    msg = diag::err_bad_static_cast_member_pointer_nonmp;
1360    return TC_NotApplicable;
1361  }
1362
1363  // T == T, modulo cv
1364  if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1365                                           DestMemPtr->getPointeeType()))
1366    return TC_NotApplicable;
1367
1368  // B base of D
1369  QualType SrcClass(SrcMemPtr->getClass(), 0);
1370  QualType DestClass(DestMemPtr->getClass(), 0);
1371  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1372                  /*DetectVirtual=*/true);
1373  if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1374      !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1375    return TC_NotApplicable;
1376  }
1377
1378  // B is a base of D. But is it an allowed base? If not, it's a hard error.
1379  if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1380    Paths.clear();
1381    Paths.setRecordingPaths(true);
1382    bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1383    assert(StillOkay);
1384    (void)StillOkay;
1385    std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1386    Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1387      << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1388    msg = 0;
1389    return TC_Failed;
1390  }
1391
1392  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1393    Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1394      << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1395    msg = 0;
1396    return TC_Failed;
1397  }
1398
1399  if (!CStyle) {
1400    switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1401                                      DestClass, SrcClass,
1402                                      Paths.front(),
1403                                      diag::err_upcast_to_inaccessible_base)) {
1404    case Sema::AR_accessible:
1405    case Sema::AR_delayed:
1406    case Sema::AR_dependent:
1407      // Optimistically assume that the delayed and dependent cases
1408      // will work out.
1409      break;
1410
1411    case Sema::AR_inaccessible:
1412      msg = 0;
1413      return TC_Failed;
1414    }
1415  }
1416
1417  if (WasOverloadedFunction) {
1418    // Resolve the address of the overloaded function again, this time
1419    // allowing complaints if something goes wrong.
1420    FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1421                                                               DestType,
1422                                                               true,
1423                                                               FoundOverload);
1424    if (!Fn) {
1425      msg = 0;
1426      return TC_Failed;
1427    }
1428
1429    SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1430    if (!SrcExpr.isUsable()) {
1431      msg = 0;
1432      return TC_Failed;
1433    }
1434  }
1435
1436  Self.BuildBasePathArray(Paths, BasePath);
1437  Kind = CK_DerivedToBaseMemberPointer;
1438  return TC_Success;
1439}
1440
1441/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1442/// is valid:
1443///
1444///   An expression e can be explicitly converted to a type T using a
1445///   @c static_cast if the declaration "T t(e);" is well-formed [...].
1446TryCastResult
1447TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1448                      Sema::CheckedConversionKind CCK,
1449                      const SourceRange &OpRange, unsigned &msg,
1450                      CastKind &Kind, bool ListInitialization) {
1451  if (DestType->isRecordType()) {
1452    if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1453                                 diag::err_bad_dynamic_cast_incomplete) ||
1454        Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1455                                    diag::err_allocation_of_abstract_type)) {
1456      msg = 0;
1457      return TC_Failed;
1458    }
1459  } else if (DestType->isMemberPointerType()) {
1460    if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1461      Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1462    }
1463  }
1464
1465  InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1466  InitializationKind InitKind
1467    = (CCK == Sema::CCK_CStyleCast)
1468        ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1469                                               ListInitialization)
1470    : (CCK == Sema::CCK_FunctionalCast)
1471        ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1472    : InitializationKind::CreateCast(OpRange);
1473  Expr *SrcExprRaw = SrcExpr.get();
1474  InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1475
1476  // At this point of CheckStaticCast, if the destination is a reference,
1477  // or the expression is an overload expression this has to work.
1478  // There is no other way that works.
1479  // On the other hand, if we're checking a C-style cast, we've still got
1480  // the reinterpret_cast way.
1481  bool CStyle
1482    = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1483  if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1484    return TC_NotApplicable;
1485
1486  ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1487  if (Result.isInvalid()) {
1488    msg = 0;
1489    return TC_Failed;
1490  }
1491
1492  if (InitSeq.isConstructorInitialization())
1493    Kind = CK_ConstructorConversion;
1494  else
1495    Kind = CK_NoOp;
1496
1497  SrcExpr = Result;
1498  return TC_Success;
1499}
1500
1501/// TryConstCast - See if a const_cast from source to destination is allowed,
1502/// and perform it if it is.
1503static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1504                                  QualType DestType, bool CStyle,
1505                                  unsigned &msg) {
1506  DestType = Self.Context.getCanonicalType(DestType);
1507  QualType SrcType = SrcExpr.get()->getType();
1508  bool NeedToMaterializeTemporary = false;
1509
1510  if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1511    // C++11 5.2.11p4:
1512    //   if a pointer to T1 can be explicitly converted to the type "pointer to
1513    //   T2" using a const_cast, then the following conversions can also be
1514    //   made:
1515    //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
1516    //       type T2 using the cast const_cast<T2&>;
1517    //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
1518    //       type T2 using the cast const_cast<T2&&>; and
1519    //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
1520    //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1521
1522    if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1523      // Cannot const_cast non-lvalue to lvalue reference type. But if this
1524      // is C-style, static_cast might find a way, so we simply suggest a
1525      // message and tell the parent to keep searching.
1526      msg = diag::err_bad_cxx_cast_rvalue;
1527      return TC_NotApplicable;
1528    }
1529
1530    if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1531      if (!SrcType->isRecordType()) {
1532        // Cannot const_cast non-class prvalue to rvalue reference type. But if
1533        // this is C-style, static_cast can do this.
1534        msg = diag::err_bad_cxx_cast_rvalue;
1535        return TC_NotApplicable;
1536      }
1537
1538      // Materialize the class prvalue so that the const_cast can bind a
1539      // reference to it.
1540      NeedToMaterializeTemporary = true;
1541    }
1542
1543    // It's not completely clear under the standard whether we can
1544    // const_cast bit-field gl-values.  Doing so would not be
1545    // intrinsically complicated, but for now, we say no for
1546    // consistency with other compilers and await the word of the
1547    // committee.
1548    if (SrcExpr.get()->refersToBitField()) {
1549      msg = diag::err_bad_cxx_cast_bitfield;
1550      return TC_NotApplicable;
1551    }
1552
1553    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1554    SrcType = Self.Context.getPointerType(SrcType);
1555  }
1556
1557  // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1558  //   the rules for const_cast are the same as those used for pointers.
1559
1560  if (!DestType->isPointerType() &&
1561      !DestType->isMemberPointerType() &&
1562      !DestType->isObjCObjectPointerType()) {
1563    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1564    // was a reference type, we converted it to a pointer above.
1565    // The status of rvalue references isn't entirely clear, but it looks like
1566    // conversion to them is simply invalid.
1567    // C++ 5.2.11p3: For two pointer types [...]
1568    if (!CStyle)
1569      msg = diag::err_bad_const_cast_dest;
1570    return TC_NotApplicable;
1571  }
1572  if (DestType->isFunctionPointerType() ||
1573      DestType->isMemberFunctionPointerType()) {
1574    // Cannot cast direct function pointers.
1575    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1576    // T is the ultimate pointee of source and target type.
1577    if (!CStyle)
1578      msg = diag::err_bad_const_cast_dest;
1579    return TC_NotApplicable;
1580  }
1581  SrcType = Self.Context.getCanonicalType(SrcType);
1582
1583  // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1584  // completely equal.
1585  // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1586  // in multi-level pointers may change, but the level count must be the same,
1587  // as must be the final pointee type.
1588  while (SrcType != DestType &&
1589         Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1590    Qualifiers SrcQuals, DestQuals;
1591    SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1592    DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1593
1594    // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1595    // the other qualifiers (e.g., address spaces) are identical.
1596    SrcQuals.removeCVRQualifiers();
1597    DestQuals.removeCVRQualifiers();
1598    if (SrcQuals != DestQuals)
1599      return TC_NotApplicable;
1600  }
1601
1602  // Since we're dealing in canonical types, the remainder must be the same.
1603  if (SrcType != DestType)
1604    return TC_NotApplicable;
1605
1606  if (NeedToMaterializeTemporary)
1607    // This is a const_cast from a class prvalue to an rvalue reference type.
1608    // Materialize a temporary to store the result of the conversion.
1609    SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1610        SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
1611
1612  return TC_Success;
1613}
1614
1615// Checks for undefined behavior in reinterpret_cast.
1616// The cases that is checked for is:
1617// *reinterpret_cast<T*>(&a)
1618// reinterpret_cast<T&>(a)
1619// where accessing 'a' as type 'T' will result in undefined behavior.
1620void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1621                                          bool IsDereference,
1622                                          SourceRange Range) {
1623  unsigned DiagID = IsDereference ?
1624                        diag::warn_pointer_indirection_from_incompatible_type :
1625                        diag::warn_undefined_reinterpret_cast;
1626
1627  if (Diags.isIgnored(DiagID, Range.getBegin()))
1628    return;
1629
1630  QualType SrcTy, DestTy;
1631  if (IsDereference) {
1632    if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1633      return;
1634    }
1635    SrcTy = SrcType->getPointeeType();
1636    DestTy = DestType->getPointeeType();
1637  } else {
1638    if (!DestType->getAs<ReferenceType>()) {
1639      return;
1640    }
1641    SrcTy = SrcType;
1642    DestTy = DestType->getPointeeType();
1643  }
1644
1645  // Cast is compatible if the types are the same.
1646  if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1647    return;
1648  }
1649  // or one of the types is a char or void type
1650  if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1651      SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1652    return;
1653  }
1654  // or one of the types is a tag type.
1655  if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1656    return;
1657  }
1658
1659  // FIXME: Scoped enums?
1660  if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1661      (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1662    if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1663      return;
1664    }
1665  }
1666
1667  Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1668}
1669
1670static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1671                                  QualType DestType) {
1672  QualType SrcType = SrcExpr.get()->getType();
1673  if (Self.Context.hasSameType(SrcType, DestType))
1674    return;
1675  if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1676    if (SrcPtrTy->isObjCSelType()) {
1677      QualType DT = DestType;
1678      if (isa<PointerType>(DestType))
1679        DT = DestType->getPointeeType();
1680      if (!DT.getUnqualifiedType()->isVoidType())
1681        Self.Diag(SrcExpr.get()->getExprLoc(),
1682                  diag::warn_cast_pointer_from_sel)
1683        << SrcType << DestType << SrcExpr.get()->getSourceRange();
1684    }
1685}
1686
1687static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1688                                  const Expr *SrcExpr, QualType DestType,
1689                                  Sema &Self) {
1690  QualType SrcType = SrcExpr->getType();
1691
1692  // Not warning on reinterpret_cast, boolean, constant expressions, etc
1693  // are not explicit design choices, but consistent with GCC's behavior.
1694  // Feel free to modify them if you've reason/evidence for an alternative.
1695  if (CStyle && SrcType->isIntegralType(Self.Context)
1696      && !SrcType->isBooleanType()
1697      && !SrcType->isEnumeralType()
1698      && !SrcExpr->isIntegerConstantExpr(Self.Context)
1699      && Self.Context.getTypeSize(DestType) >
1700         Self.Context.getTypeSize(SrcType)) {
1701    // Separate between casts to void* and non-void* pointers.
1702    // Some APIs use (abuse) void* for something like a user context,
1703    // and often that value is an integer even if it isn't a pointer itself.
1704    // Having a separate warning flag allows users to control the warning
1705    // for their workflow.
1706    unsigned Diag = DestType->isVoidPointerType() ?
1707                      diag::warn_int_to_void_pointer_cast
1708                    : diag::warn_int_to_pointer_cast;
1709    Self.Diag(Loc, Diag) << SrcType << DestType;
1710  }
1711}
1712
1713static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1714                                        QualType DestType, bool CStyle,
1715                                        const SourceRange &OpRange,
1716                                        unsigned &msg,
1717                                        CastKind &Kind) {
1718  bool IsLValueCast = false;
1719
1720  DestType = Self.Context.getCanonicalType(DestType);
1721  QualType SrcType = SrcExpr.get()->getType();
1722
1723  // Is the source an overloaded name? (i.e. &foo)
1724  // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1725  if (SrcType == Self.Context.OverloadTy) {
1726    // ... unless foo<int> resolves to an lvalue unambiguously.
1727    // TODO: what if this fails because of DiagnoseUseOfDecl or something
1728    // like it?
1729    ExprResult SingleFunctionExpr = SrcExpr;
1730    if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1731          SingleFunctionExpr,
1732          Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1733        ) && SingleFunctionExpr.isUsable()) {
1734      SrcExpr = SingleFunctionExpr;
1735      SrcType = SrcExpr.get()->getType();
1736    } else {
1737      return TC_NotApplicable;
1738    }
1739  }
1740
1741  if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1742    if (!SrcExpr.get()->isGLValue()) {
1743      // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1744      // similar comment in const_cast.
1745      msg = diag::err_bad_cxx_cast_rvalue;
1746      return TC_NotApplicable;
1747    }
1748
1749    if (!CStyle) {
1750      Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1751                                          /*isDereference=*/false, OpRange);
1752    }
1753
1754    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1755    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
1756    //   built-in & and * operators.
1757
1758    const char *inappropriate = nullptr;
1759    switch (SrcExpr.get()->getObjectKind()) {
1760    case OK_Ordinary:
1761      break;
1762    case OK_BitField:        inappropriate = "bit-field";           break;
1763    case OK_VectorComponent: inappropriate = "vector element";      break;
1764    case OK_ObjCProperty:    inappropriate = "property expression"; break;
1765    case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
1766                             break;
1767    }
1768    if (inappropriate) {
1769      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1770          << inappropriate << DestType
1771          << OpRange << SrcExpr.get()->getSourceRange();
1772      msg = 0; SrcExpr = ExprError();
1773      return TC_NotApplicable;
1774    }
1775
1776    // This code does this transformation for the checked types.
1777    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1778    SrcType = Self.Context.getPointerType(SrcType);
1779
1780    IsLValueCast = true;
1781  }
1782
1783  // Canonicalize source for comparison.
1784  SrcType = Self.Context.getCanonicalType(SrcType);
1785
1786  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1787                          *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1788  if (DestMemPtr && SrcMemPtr) {
1789    // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1790    //   can be explicitly converted to an rvalue of type "pointer to member
1791    //   of Y of type T2" if T1 and T2 are both function types or both object
1792    //   types.
1793    if (DestMemPtr->getPointeeType()->isFunctionType() !=
1794        SrcMemPtr->getPointeeType()->isFunctionType())
1795      return TC_NotApplicable;
1796
1797    // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1798    //   constness.
1799    // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1800    // we accept it.
1801    if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1802                           /*CheckObjCLifetime=*/CStyle)) {
1803      msg = diag::err_bad_cxx_cast_qualifiers_away;
1804      return TC_Failed;
1805    }
1806
1807    if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1808      // We need to determine the inheritance model that the class will use if
1809      // haven't yet.
1810      Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
1811      Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1812    }
1813
1814    // Don't allow casting between member pointers of different sizes.
1815    if (Self.Context.getTypeSize(DestMemPtr) !=
1816        Self.Context.getTypeSize(SrcMemPtr)) {
1817      msg = diag::err_bad_cxx_cast_member_pointer_size;
1818      return TC_Failed;
1819    }
1820
1821    // A valid member pointer cast.
1822    assert(!IsLValueCast);
1823    Kind = CK_ReinterpretMemberPointer;
1824    return TC_Success;
1825  }
1826
1827  // See below for the enumeral issue.
1828  if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1829    // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1830    //   type large enough to hold it. A value of std::nullptr_t can be
1831    //   converted to an integral type; the conversion has the same meaning
1832    //   and validity as a conversion of (void*)0 to the integral type.
1833    if (Self.Context.getTypeSize(SrcType) >
1834        Self.Context.getTypeSize(DestType)) {
1835      msg = diag::err_bad_reinterpret_cast_small_int;
1836      return TC_Failed;
1837    }
1838    Kind = CK_PointerToIntegral;
1839    return TC_Success;
1840  }
1841
1842  bool destIsVector = DestType->isVectorType();
1843  bool srcIsVector = SrcType->isVectorType();
1844  if (srcIsVector || destIsVector) {
1845    // FIXME: Should this also apply to floating point types?
1846    bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1847    bool destIsScalar = DestType->isIntegralType(Self.Context);
1848
1849    // Check if this is a cast between a vector and something else.
1850    if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1851        !(srcIsVector && destIsVector))
1852      return TC_NotApplicable;
1853
1854    // If both types have the same size, we can successfully cast.
1855    if (Self.Context.getTypeSize(SrcType)
1856          == Self.Context.getTypeSize(DestType)) {
1857      Kind = CK_BitCast;
1858      return TC_Success;
1859    }
1860
1861    if (destIsScalar)
1862      msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1863    else if (srcIsScalar)
1864      msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1865    else
1866      msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1867
1868    return TC_Failed;
1869  }
1870
1871  if (SrcType == DestType) {
1872    // C++ 5.2.10p2 has a note that mentions that, subject to all other
1873    // restrictions, a cast to the same type is allowed so long as it does not
1874    // cast away constness. In C++98, the intent was not entirely clear here,
1875    // since all other paragraphs explicitly forbid casts to the same type.
1876    // C++11 clarifies this case with p2.
1877    //
1878    // The only allowed types are: integral, enumeration, pointer, or
1879    // pointer-to-member types.  We also won't restrict Obj-C pointers either.
1880    Kind = CK_NoOp;
1881    TryCastResult Result = TC_NotApplicable;
1882    if (SrcType->isIntegralOrEnumerationType() ||
1883        SrcType->isAnyPointerType() ||
1884        SrcType->isMemberPointerType() ||
1885        SrcType->isBlockPointerType()) {
1886      Result = TC_Success;
1887    }
1888    return Result;
1889  }
1890
1891  bool destIsPtr = DestType->isAnyPointerType() ||
1892                   DestType->isBlockPointerType();
1893  bool srcIsPtr = SrcType->isAnyPointerType() ||
1894                  SrcType->isBlockPointerType();
1895  if (!destIsPtr && !srcIsPtr) {
1896    // Except for std::nullptr_t->integer and lvalue->reference, which are
1897    // handled above, at least one of the two arguments must be a pointer.
1898    return TC_NotApplicable;
1899  }
1900
1901  if (DestType->isIntegralType(Self.Context)) {
1902    assert(srcIsPtr && "One type must be a pointer");
1903    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1904    //   type large enough to hold it; except in Microsoft mode, where the
1905    //   integral type size doesn't matter (except we don't allow bool).
1906    bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1907                              !DestType->isBooleanType();
1908    if ((Self.Context.getTypeSize(SrcType) >
1909         Self.Context.getTypeSize(DestType)) &&
1910         !MicrosoftException) {
1911      msg = diag::err_bad_reinterpret_cast_small_int;
1912      return TC_Failed;
1913    }
1914    Kind = CK_PointerToIntegral;
1915    return TC_Success;
1916  }
1917
1918  if (SrcType->isIntegralOrEnumerationType()) {
1919    assert(destIsPtr && "One type must be a pointer");
1920    checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1921                          Self);
1922    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1923    //   converted to a pointer.
1924    // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1925    //   necessarily converted to a null pointer value.]
1926    Kind = CK_IntegralToPointer;
1927    return TC_Success;
1928  }
1929
1930  if (!destIsPtr || !srcIsPtr) {
1931    // With the valid non-pointer conversions out of the way, we can be even
1932    // more stringent.
1933    return TC_NotApplicable;
1934  }
1935
1936  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1937  // The C-style cast operator can.
1938  if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1939                         /*CheckObjCLifetime=*/CStyle)) {
1940    msg = diag::err_bad_cxx_cast_qualifiers_away;
1941    return TC_Failed;
1942  }
1943
1944  // Cannot convert between block pointers and Objective-C object pointers.
1945  if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1946      (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1947    return TC_NotApplicable;
1948
1949  if (IsLValueCast) {
1950    Kind = CK_LValueBitCast;
1951  } else if (DestType->isObjCObjectPointerType()) {
1952    Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1953  } else if (DestType->isBlockPointerType()) {
1954    if (!SrcType->isBlockPointerType()) {
1955      Kind = CK_AnyPointerToBlockPointerCast;
1956    } else {
1957      Kind = CK_BitCast;
1958    }
1959  } else {
1960    Kind = CK_BitCast;
1961  }
1962
1963  // Any pointer can be cast to an Objective-C pointer type with a C-style
1964  // cast.
1965  if (CStyle && DestType->isObjCObjectPointerType()) {
1966    return TC_Success;
1967  }
1968  if (CStyle)
1969    DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1970
1971  // Not casting away constness, so the only remaining check is for compatible
1972  // pointer categories.
1973
1974  if (SrcType->isFunctionPointerType()) {
1975    if (DestType->isFunctionPointerType()) {
1976      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1977      // a pointer to a function of a different type.
1978      return TC_Success;
1979    }
1980
1981    // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1982    //   an object type or vice versa is conditionally-supported.
1983    // Compilers support it in C++03 too, though, because it's necessary for
1984    // casting the return value of dlsym() and GetProcAddress().
1985    // FIXME: Conditionally-supported behavior should be configurable in the
1986    // TargetInfo or similar.
1987    Self.Diag(OpRange.getBegin(),
1988              Self.getLangOpts().CPlusPlus11 ?
1989                diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1990      << OpRange;
1991    return TC_Success;
1992  }
1993
1994  if (DestType->isFunctionPointerType()) {
1995    // See above.
1996    Self.Diag(OpRange.getBegin(),
1997              Self.getLangOpts().CPlusPlus11 ?
1998                diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1999      << OpRange;
2000    return TC_Success;
2001  }
2002
2003  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2004  //   a pointer to an object of different type.
2005  // Void pointers are not specified, but supported by every compiler out there.
2006  // So we finish by allowing everything that remains - it's got to be two
2007  // object pointers.
2008  return TC_Success;
2009}
2010
2011void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2012                                       bool ListInitialization) {
2013  // Handle placeholders.
2014  if (isPlaceholder()) {
2015    // C-style casts can resolve __unknown_any types.
2016    if (claimPlaceholder(BuiltinType::UnknownAny)) {
2017      SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2018                                         SrcExpr.get(), Kind,
2019                                         ValueKind, BasePath);
2020      return;
2021    }
2022
2023    checkNonOverloadPlaceholders();
2024    if (SrcExpr.isInvalid())
2025      return;
2026  }
2027
2028  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2029  // This test is outside everything else because it's the only case where
2030  // a non-lvalue-reference target type does not lead to decay.
2031  if (DestType->isVoidType()) {
2032    Kind = CK_ToVoid;
2033
2034    if (claimPlaceholder(BuiltinType::Overload)) {
2035      Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2036                  SrcExpr, /* Decay Function to ptr */ false,
2037                  /* Complain */ true, DestRange, DestType,
2038                  diag::err_bad_cstyle_cast_overload);
2039      if (SrcExpr.isInvalid())
2040        return;
2041    }
2042
2043    SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2044    return;
2045  }
2046
2047  // If the type is dependent, we won't do any other semantic analysis now.
2048  if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2049      SrcExpr.get()->isValueDependent()) {
2050    assert(Kind == CK_Dependent);
2051    return;
2052  }
2053
2054  if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2055      !isPlaceholder(BuiltinType::Overload)) {
2056    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2057    if (SrcExpr.isInvalid())
2058      return;
2059  }
2060
2061  // AltiVec vector initialization with a single literal.
2062  if (const VectorType *vecTy = DestType->getAs<VectorType>())
2063    if (vecTy->getVectorKind() == VectorType::AltiVecVector
2064        && (SrcExpr.get()->getType()->isIntegerType()
2065            || SrcExpr.get()->getType()->isFloatingType())) {
2066      Kind = CK_VectorSplat;
2067      return;
2068    }
2069
2070  // C++ [expr.cast]p5: The conversions performed by
2071  //   - a const_cast,
2072  //   - a static_cast,
2073  //   - a static_cast followed by a const_cast,
2074  //   - a reinterpret_cast, or
2075  //   - a reinterpret_cast followed by a const_cast,
2076  //   can be performed using the cast notation of explicit type conversion.
2077  //   [...] If a conversion can be interpreted in more than one of the ways
2078  //   listed above, the interpretation that appears first in the list is used,
2079  //   even if a cast resulting from that interpretation is ill-formed.
2080  // In plain language, this means trying a const_cast ...
2081  unsigned msg = diag::err_bad_cxx_cast_generic;
2082  TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2083                                   /*CStyle*/true, msg);
2084  if (SrcExpr.isInvalid())
2085    return;
2086  if (tcr == TC_Success)
2087    Kind = CK_NoOp;
2088
2089  Sema::CheckedConversionKind CCK
2090    = FunctionalStyle? Sema::CCK_FunctionalCast
2091                     : Sema::CCK_CStyleCast;
2092  if (tcr == TC_NotApplicable) {
2093    // ... or if that is not possible, a static_cast, ignoring const, ...
2094    tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2095                        msg, Kind, BasePath, ListInitialization);
2096    if (SrcExpr.isInvalid())
2097      return;
2098
2099    if (tcr == TC_NotApplicable) {
2100      // ... and finally a reinterpret_cast, ignoring const.
2101      tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2102                               OpRange, msg, Kind);
2103      if (SrcExpr.isInvalid())
2104        return;
2105    }
2106  }
2107
2108  if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
2109    checkObjCARCConversion(CCK);
2110
2111  if (tcr != TC_Success && msg != 0) {
2112    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2113      DeclAccessPair Found;
2114      FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2115                                DestType,
2116                                /*Complain*/ true,
2117                                Found);
2118      if (Fn) {
2119        // If DestType is a function type (not to be confused with the function
2120        // pointer type), it will be possible to resolve the function address,
2121        // but the type cast should be considered as failure.
2122        OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2123        Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2124          << OE->getName() << DestType << OpRange
2125          << OE->getQualifierLoc().getSourceRange();
2126        Self.NoteAllOverloadCandidates(SrcExpr.get());
2127      }
2128    } else {
2129      diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2130                      OpRange, SrcExpr.get(), DestType, ListInitialization);
2131    }
2132  } else if (Kind == CK_BitCast) {
2133    checkCastAlign();
2134  }
2135
2136  // Clear out SrcExpr if there was a fatal error.
2137  if (tcr != TC_Success)
2138    SrcExpr = ExprError();
2139}
2140
2141/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2142///  non-matching type. Such as enum function call to int, int call to
2143/// pointer; etc. Cast to 'void' is an exception.
2144static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2145                                  QualType DestType) {
2146  if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2147                           SrcExpr.get()->getExprLoc()))
2148    return;
2149
2150  if (!isa<CallExpr>(SrcExpr.get()))
2151    return;
2152
2153  QualType SrcType = SrcExpr.get()->getType();
2154  if (DestType.getUnqualifiedType()->isVoidType())
2155    return;
2156  if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2157      && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2158    return;
2159  if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2160      (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2161      (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2162    return;
2163  if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2164    return;
2165  if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2166    return;
2167  if (SrcType->isComplexType() && DestType->isComplexType())
2168    return;
2169  if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2170    return;
2171
2172  Self.Diag(SrcExpr.get()->getExprLoc(),
2173            diag::warn_bad_function_cast)
2174            << SrcType << DestType << SrcExpr.get()->getSourceRange();
2175}
2176
2177/// Check the semantics of a C-style cast operation, in C.
2178void CastOperation::CheckCStyleCast() {
2179  assert(!Self.getLangOpts().CPlusPlus);
2180
2181  // C-style casts can resolve __unknown_any types.
2182  if (claimPlaceholder(BuiltinType::UnknownAny)) {
2183    SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2184                                       SrcExpr.get(), Kind,
2185                                       ValueKind, BasePath);
2186    return;
2187  }
2188
2189  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2190  // type needs to be scalar.
2191  if (DestType->isVoidType()) {
2192    // We don't necessarily do lvalue-to-rvalue conversions on this.
2193    SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2194    if (SrcExpr.isInvalid())
2195      return;
2196
2197    // Cast to void allows any expr type.
2198    Kind = CK_ToVoid;
2199    return;
2200  }
2201
2202  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2203  if (SrcExpr.isInvalid())
2204    return;
2205  QualType SrcType = SrcExpr.get()->getType();
2206
2207  assert(!SrcType->isPlaceholderType());
2208
2209  // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2210  // address space B is illegal.
2211  if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2212      SrcType->isPointerType()) {
2213    const PointerType *DestPtr = DestType->getAs<PointerType>();
2214    if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
2215      Self.Diag(OpRange.getBegin(),
2216                diag::err_typecheck_incompatible_address_space)
2217          << SrcType << DestType << Sema::AA_Casting
2218          << SrcExpr.get()->getSourceRange();
2219      SrcExpr = ExprError();
2220      return;
2221    }
2222  }
2223
2224  if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2225                               diag::err_typecheck_cast_to_incomplete)) {
2226    SrcExpr = ExprError();
2227    return;
2228  }
2229
2230  if (!DestType->isScalarType() && !DestType->isVectorType()) {
2231    const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2232
2233    if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2234      // GCC struct/union extension: allow cast to self.
2235      Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2236        << DestType << SrcExpr.get()->getSourceRange();
2237      Kind = CK_NoOp;
2238      return;
2239    }
2240
2241    // GCC's cast to union extension.
2242    if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2243      RecordDecl *RD = DestRecordTy->getDecl();
2244      RecordDecl::field_iterator Field, FieldEnd;
2245      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2246           Field != FieldEnd; ++Field) {
2247        if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2248            !Field->isUnnamedBitfield()) {
2249          Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2250            << SrcExpr.get()->getSourceRange();
2251          break;
2252        }
2253      }
2254      if (Field == FieldEnd) {
2255        Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2256          << SrcType << SrcExpr.get()->getSourceRange();
2257        SrcExpr = ExprError();
2258        return;
2259      }
2260      Kind = CK_ToUnion;
2261      return;
2262    }
2263
2264    // Reject any other conversions to non-scalar types.
2265    Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2266      << DestType << SrcExpr.get()->getSourceRange();
2267    SrcExpr = ExprError();
2268    return;
2269  }
2270
2271  // The type we're casting to is known to be a scalar or vector.
2272
2273  // Require the operand to be a scalar or vector.
2274  if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2275    Self.Diag(SrcExpr.get()->getExprLoc(),
2276              diag::err_typecheck_expect_scalar_operand)
2277      << SrcType << SrcExpr.get()->getSourceRange();
2278    SrcExpr = ExprError();
2279    return;
2280  }
2281
2282  if (DestType->isExtVectorType()) {
2283    SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2284    return;
2285  }
2286
2287  if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2288    if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2289          (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2290      Kind = CK_VectorSplat;
2291    } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2292      SrcExpr = ExprError();
2293    }
2294    return;
2295  }
2296
2297  if (SrcType->isVectorType()) {
2298    if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2299      SrcExpr = ExprError();
2300    return;
2301  }
2302
2303  // The source and target types are both scalars, i.e.
2304  //   - arithmetic types (fundamental, enum, and complex)
2305  //   - all kinds of pointers
2306  // Note that member pointers were filtered out with C++, above.
2307
2308  if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2309    Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2310    SrcExpr = ExprError();
2311    return;
2312  }
2313
2314  // If either type is a pointer, the other type has to be either an
2315  // integer or a pointer.
2316  if (!DestType->isArithmeticType()) {
2317    if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2318      Self.Diag(SrcExpr.get()->getExprLoc(),
2319                diag::err_cast_pointer_from_non_pointer_int)
2320        << SrcType << SrcExpr.get()->getSourceRange();
2321      SrcExpr = ExprError();
2322      return;
2323    }
2324    checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2325                          DestType, Self);
2326  } else if (!SrcType->isArithmeticType()) {
2327    if (!DestType->isIntegralType(Self.Context) &&
2328        DestType->isArithmeticType()) {
2329      Self.Diag(SrcExpr.get()->getLocStart(),
2330           diag::err_cast_pointer_to_non_pointer_int)
2331        << DestType << SrcExpr.get()->getSourceRange();
2332      SrcExpr = ExprError();
2333      return;
2334    }
2335  }
2336
2337  if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2338    if (DestType->isHalfType()) {
2339      Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2340        << DestType << SrcExpr.get()->getSourceRange();
2341      SrcExpr = ExprError();
2342      return;
2343    }
2344  }
2345
2346  // ARC imposes extra restrictions on casts.
2347  if (Self.getLangOpts().ObjCAutoRefCount) {
2348    checkObjCARCConversion(Sema::CCK_CStyleCast);
2349    if (SrcExpr.isInvalid())
2350      return;
2351
2352    if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2353      if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2354        Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2355        Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2356        if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2357            ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2358            !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2359          Self.Diag(SrcExpr.get()->getLocStart(),
2360                    diag::err_typecheck_incompatible_ownership)
2361            << SrcType << DestType << Sema::AA_Casting
2362            << SrcExpr.get()->getSourceRange();
2363          return;
2364        }
2365      }
2366    }
2367    else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2368      Self.Diag(SrcExpr.get()->getLocStart(),
2369                diag::err_arc_convesion_of_weak_unavailable)
2370        << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2371      SrcExpr = ExprError();
2372      return;
2373    }
2374  }
2375
2376  DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2377  DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2378  Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2379  if (SrcExpr.isInvalid())
2380    return;
2381
2382  if (Kind == CK_BitCast)
2383    checkCastAlign();
2384
2385  // -Wcast-qual
2386  QualType TheOffendingSrcType, TheOffendingDestType;
2387  Qualifiers CastAwayQualifiers;
2388  if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2389      CastsAwayConstness(Self, SrcType, DestType, true, false,
2390                         &TheOffendingSrcType, &TheOffendingDestType,
2391                         &CastAwayQualifiers)) {
2392    int qualifiers = -1;
2393    if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2394      qualifiers = 0;
2395    } else if (CastAwayQualifiers.hasConst()) {
2396      qualifiers = 1;
2397    } else if (CastAwayQualifiers.hasVolatile()) {
2398      qualifiers = 2;
2399    }
2400    // This is a variant of int **x; const int **y = (const int **)x;
2401    if (qualifiers == -1)
2402      Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2403        SrcType << DestType;
2404    else
2405      Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2406        TheOffendingSrcType << TheOffendingDestType << qualifiers;
2407  }
2408}
2409
2410ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2411                                     TypeSourceInfo *CastTypeInfo,
2412                                     SourceLocation RPLoc,
2413                                     Expr *CastExpr) {
2414  CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2415  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2416  Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2417
2418  if (getLangOpts().CPlusPlus) {
2419    Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2420                          isa<InitListExpr>(CastExpr));
2421  } else {
2422    Op.CheckCStyleCast();
2423  }
2424
2425  if (Op.SrcExpr.isInvalid())
2426    return ExprError();
2427
2428  return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2429                              Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2430                              &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2431}
2432
2433ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2434                                            SourceLocation LPLoc,
2435                                            Expr *CastExpr,
2436                                            SourceLocation RPLoc) {
2437  assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2438  CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2439  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2440  Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2441
2442  Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2443  if (Op.SrcExpr.isInvalid())
2444    return ExprError();
2445
2446  if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2447    ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2448
2449  return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2450                         Op.ValueKind, CastTypeInfo, Op.Kind,
2451                         Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
2452}
2453