Coverage Report

Created: 2020-10-24 06:27

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