Coverage Report

Created: 2022-05-14 11:35

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