Coverage Report

Created: 2020-02-25 14:32

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