Coverage Report

Created: 2021-08-24 07:12

/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.26M
static bool isValidCast(TryCastResult TCR) {
43
1.26M
  return TCR == TC_Success || 
TCR == TC_Extension566k
;
44
1.26M
}
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.73M
        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.73M
      if (!S.Context.getLangOpts().ObjC && 
!DestType->isRecordType()4.35M
&&
69
4.73M
          
!DestType->isArrayType()4.33M
) {
70
4.33M
        DestType = DestType.getUnqualifiedType();
71
4.33M
      }
72
73
4.73M
      if (const BuiltinType *placeholder =
74
4.73M
            src.get()->getType()->getAsPlaceholderType()) {
75
1.06k
        PlaceholderKind = placeholder->getKind();
76
4.73M
      } else {
77
4.73M
        PlaceholderKind = (BuiltinType::Kind) 0;
78
4.73M
      }
79
4.73M
    }
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.73M
    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.56M
      for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); 
CE = ICE2.83M
)
109
2.83M
        ICE->setIsPartOfExplicitCast(true);
110
4.73M
    }
111
112
    /// Complete an apparently-successful cast operation that yields
113
    /// the given expression.
114
4.73M
    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.73M
      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.73M
      updatePartOfExplicitCastFlags(castExpr);
124
4.73M
      return castExpr;
125
4.73M
    }
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
3.89M
    bool claimPlaceholder(BuiltinType::Kind K) {
133
3.89M
      if (PlaceholderKind != K) 
return false3.89M
;
134
135
674
      PlaceholderKind = (BuiltinType::Kind) 0;
136
674
      return true;
137
3.89M
    }
138
139
783k
    bool isPlaceholder() const {
140
783k
      return PlaceholderKind != 0;
141
783k
    }
142
607k
    bool isPlaceholder(BuiltinType::Kind K) const {
143
607k
      return PlaceholderKind == K;
144
607k
    }
145
146
    // Language specific cast restrictions for address spaces.
147
    void checkAddressSpaceCast(QualType SrcType, QualType DestType);
148
149
161k
    void checkCastAlign() {
150
161k
      Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
151
161k
    }
152
153
14.9k
    void checkObjCConversion(Sema::CheckedConversionKind CCK) {
154
14.9k
      assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
155
156
0
      Expr *src = SrcExpr.get();
157
14.9k
      if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
158
14.9k
          Sema::ACR_unbridged)
159
122
        IsARCUnbridgedCast = true;
160
14.9k
      SrcExpr = src;
161
14.9k
    }
162
163
    /// Check for and handle non-overload placeholder expressions.
164
596
    void checkNonOverloadPlaceholders() {
165
596
      if (!isPlaceholder() || 
isPlaceholder(BuiltinType::Overload)314
)
166
525
        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
99.8k
                    SourceLocation OpLoc) {
177
99.8k
    if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
178
7.09k
      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
7.09k
    }
186
99.8k
  }
187
188
  struct CheckNoDerefRAII {
189
100k
    CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
190
100k
    ~CheckNoDerefRAII() {
191
100k
      if (!Op.SrcExpr.isInvalid())
192
99.8k
        CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
193
99.8k
                     Op.OpRange.getBegin());
194
100k
    }
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
149k
                        SourceLocation RParenLoc) {
278
279
149k
  assert(!D.isInvalidType());
280
281
0
  TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
282
149k
  if (D.isInvalidType())
283
35
    return ExprError();
284
285
149k
  if (getLangOpts().CPlusPlus) {
286
    // Check that there are no default arguments (C++ only).
287
149k
    CheckExtraCXXDefaultArguments(D);
288
149k
  }
289
290
149k
  return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
291
149k
                           SourceRange(LAngleBracketLoc, RAngleBracketLoc),
292
149k
                           SourceRange(LParenLoc, RParenLoc));
293
149k
}
294
295
ExprResult
296
Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
297
                        TypeSourceInfo *DestTInfo, Expr *E,
298
217k
                        SourceRange AngleBrackets, SourceRange Parens) {
299
217k
  ExprResult Ex = E;
300
217k
  QualType DestType = DestTInfo->getType();
301
302
  // If the type is dependent, we won't do the semantic analysis now.
303
217k
  bool TypeDependent =
304
217k
      DestType->isDependentType() || 
Ex.get()->isTypeDependent()122k
;
305
306
217k
  CastOperation Op(*this, DestType, E);
307
217k
  Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
308
217k
  Op.DestRange = AngleBrackets;
309
310
217k
  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.01k
  case tok::kw_const_cast:
324
6.01k
    if (!TypeDependent) {
325
2.22k
      Op.CheckConstCast();
326
2.22k
      if (Op.SrcExpr.isInvalid())
327
116
        return ExprError();
328
2.10k
      DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
329
2.10k
    }
330
5.90k
    return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
331
5.90k
                                  Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
332
5.90k
                                                OpLoc, Parens.getEnd(),
333
5.90k
                                                AngleBrackets));
334
335
1.27k
  case tok::kw_dynamic_cast: {
336
    // dynamic_cast is not supported in C++ for OpenCL.
337
1.27k
    if (getLangOpts().OpenCLCPlusPlus) {
338
1
      return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
339
1
                       << "dynamic_cast");
340
1
    }
341
342
1.27k
    if (!TypeDependent) {
343
387
      Op.CheckDynamicCast();
344
387
      if (Op.SrcExpr.isInvalid())
345
53
        return ExprError();
346
387
    }
347
1.21k
    return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
348
1.21k
                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
349
1.21k
                                                  &Op.BasePath, DestTInfo,
350
1.21k
                                                  OpLoc, Parens.getEnd(),
351
1.21k
                                                  AngleBrackets));
352
1.27k
  }
353
8.38k
  case tok::kw_reinterpret_cast: {
354
8.38k
    if (!TypeDependent) {
355
2.97k
      Op.CheckReinterpretCast();
356
2.97k
      if (Op.SrcExpr.isInvalid())
357
125
        return ExprError();
358
2.84k
      DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
359
2.84k
    }
360
8.26k
    return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
361
8.26k
                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
362
8.26k
                                                      nullptr, DestTInfo, OpLoc,
363
8.26k
                                                      Parens.getEnd(),
364
8.26k
                                                      AngleBrackets));
365
8.38k
  }
366
201k
  case tok::kw_static_cast: {
367
201k
    if (!TypeDependent) {
368
97.6k
      Op.CheckStaticCast();
369
97.6k
      if (Op.SrcExpr.isInvalid())
370
202
        return ExprError();
371
97.4k
      DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
372
97.4k
    }
373
374
201k
    return Op.complete(CXXStaticCastExpr::Create(
375
201k
        Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
376
201k
        &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,
377
201k
        Parens.getEnd(), AngleBrackets));
378
201k
  }
379
217k
  }
380
217k
}
381
382
ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
383
                                         ExprResult Operand,
384
609
                                         SourceLocation RParenLoc) {
385
609
  assert(!D.isInvalidType());
386
387
0
  TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
388
609
  if (D.isInvalidType())
389
0
    return ExprError();
390
391
609
  return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
392
609
}
393
394
ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
395
                                         TypeSourceInfo *TSI, Expr *Operand,
396
694
                                         SourceLocation RParenLoc) {
397
694
  CastOperation Op(*this, TSI->getType(), Operand);
398
694
  Op.OpRange = SourceRange(KWLoc, RParenLoc);
399
694
  TypeLoc TL = TSI->getTypeLoc();
400
694
  Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
401
402
694
  if (!Operand->isTypeDependent() && 
!TSI->getType()->isDependentType()688
) {
403
688
    Op.CheckBuiltinBitCast();
404
688
    if (Op.SrcExpr.isInvalid())
405
6
      return ExprError();
406
688
  }
407
408
688
  BuiltinBitCastExpr *BCE =
409
688
      new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
410
688
                                       Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
411
688
  return Op.complete(BCE);
412
694
}
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
195
                                      bool listInitialization) {
420
195
  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
166
  case CT_Functional:
432
166
    break;
433
195
  }
434
435
166
  QualType srcType = src->getType();
436
166
  if (!destType->isRecordType() && 
!srcType->isRecordType()124
)
437
113
    return false;
438
439
53
  InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
440
53
  InitializationKind initKind
441
53
    = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
442
10
                                                      range, listInitialization)
443
53
    : 
(CT == CT_Functional)43
? InitializationKind::CreateFunctionalCast(range,
444
32
                                                             listInitialization)
445
43
    : 
InitializationKind::CreateCast(/*type range?*/ range)11
;
446
53
  InitializationSequence sequence(S, entity, initKind, src);
447
448
53
  assert(sequence.Failed() && "initialization succeeded on second try?");
449
0
  switch (sequence.getFailureKind()) {
450
0
  default: return false;
451
452
42
  case InitializationSequence::FK_ConstructorOverloadFailed:
453
53
  case InitializationSequence::FK_UserConversionOverloadFailed:
454
53
    break;
455
53
  }
456
457
53
  OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
458
459
53
  unsigned msg = 0;
460
53
  OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
461
462
53
  switch (sequence.getFailedOverloadResult()) {
463
0
  case OR_Success: llvm_unreachable("successful failed overload");
464
40
  case OR_No_Viable_Function:
465
40
    if (candidates.empty())
466
10
      msg = diag::err_ovl_no_conversion_in_cast;
467
30
    else
468
30
      msg = diag::err_ovl_no_viable_conversion_in_cast;
469
40
    howManyCandidates = OCD_AllCandidates;
470
40
    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
53
  }
482
483
53
  candidates.NoteCandidates(
484
53
      PartialDiagnosticAt(range.getBegin(),
485
53
                          S.PDiag(msg) << CT << srcType << destType << range
486
53
                                       << src->getSourceRange()),
487
53
      S, howManyCandidates, src);
488
489
53
  return true;
490
53
}
491
492
/// Diagnose a failed cast.
493
static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
494
                            SourceRange opRange, Expr *src, QualType destType,
495
416
                            bool listInitialization) {
496
416
  if (msg == diag::err_bad_cxx_cast_generic &&
497
416
      tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
498
195
                                listInitialization))
499
53
    return;
500
501
363
  S.Diag(opRange.getBegin(), msg) << castType
502
363
    << src->getType() << destType << opRange << src->getSourceRange();
503
504
  // Detect if both types are (ptr to) class, and note any incompleteness.
505
363
  int DifferentPtrness = 0;
506
363
  QualType From = destType;
507
363
  if (auto Ptr = From->getAs<PointerType>()) {
508
208
    From = Ptr->getPointeeType();
509
208
    DifferentPtrness++;
510
208
  }
511
363
  QualType To = src->getType();
512
363
  if (auto Ptr = To->getAs<PointerType>()) {
513
223
    To = Ptr->getPointeeType();
514
223
    DifferentPtrness--;
515
223
  }
516
363
  if (!DifferentPtrness) {
517
332
    auto RecFrom = From->getAs<RecordType>();
518
332
    auto RecTo = To->getAs<RecordType>();
519
332
    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
332
  }
528
363
}
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
514k
unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
561
514k
  enum { None, Ptr, MemPtr, BlockPtr, Array };
562
542k
  auto Classify = [](QualType T) {
563
542k
    if (T->isAnyPointerType()) 
return Ptr27.6k
;
564
515k
    if (T->isMemberPointerType()) 
return MemPtr83
;
565
515k
    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
515k
    if (T->isConstantArrayType() || 
T->isIncompleteArrayType()513k
)
return Array1.85k
;
569
513k
    return None;
570
515k
  };
571
572
514k
  auto Unwrap = [&](QualType T) {
573
25.1k
    if (auto *AT = Context.getAsArrayType(T))
574
213
      return AT->getElementType();
575
24.9k
    return T->getPointeeType();
576
25.1k
  };
577
578
514k
  CastAwayConstnessKind Kind;
579
580
514k
  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
514k
  } else if (Context.UnwrapSimilarTypes(T1, T2)) {
588
251k
    Kind = CastAwayConstnessKind::CACK_Similar;
589
262k
  } else {
590
    // Try unwrapping mismatching levels.
591
262k
    int T1Class = Classify(T1);
592
262k
    if (T1Class == None)
593
248k
      return CastAwayConstnessKind::CACK_None;
594
595
14.4k
    int T2Class = Classify(T2);
596
14.4k
    if (T2Class == None)
597
1.99k
      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
264k
  
while (264k
true) {
610
264k
    Context.UnwrapSimilarArrayTypes(T1, T2);
611
612
264k
    if (Classify(T1) != Array)
613
263k
      break;
614
615
969
    auto T2Class = Classify(T2);
616
969
    if (T2Class == None)
617
820
      break;
618
619
149
    if (T2Class != Array)
620
85
      Kind = CastAwayConstnessKind::CACK_Incoherent;
621
64
    else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
622
58
      Kind = CastAwayConstnessKind::CACK_SimilarKind;
623
624
149
    T1 = Unwrap(T1);
625
149
    T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
626
149
  }
627
628
264k
  return Kind;
629
514k
}
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
272k
                   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
272k
  if (!CheckCVR && 
CheckObjCLifetime33.6k
&&
!Self.Context.getLangOpts().ObjC33.6k
)
646
7.99k
    return CastAwayConstnessKind::CACK_None;
647
648
264k
  if (!DestType->isReferenceType()) {
649
263k
    assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
650
263k
            SrcType->isBlockPointerType()) &&
651
263k
           "Source type is not pointer or pointer to member.");
652
0
    assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
653
263k
            DestType->isBlockPointerType()) &&
654
263k
           "Destination type is not pointer or pointer to member.");
655
263k
  }
656
657
0
  QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
658
264k
           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
264k
  QualType PrevUnwrappedSrcType = UnwrappedSrcType;
664
264k
  QualType PrevUnwrappedDestType = UnwrappedDestType;
665
264k
  auto WorstKind = CastAwayConstnessKind::CACK_Similar;
666
264k
  bool AllConstSoFar = true;
667
514k
  while (auto Kind = unwrapCastAwayConstnessLevel(
668
264k
             Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
669
    // Track the worst kind of unwrap we needed to do before we found a
670
    // problem.
671
264k
    if (Kind > WorstKind)
672
12.5k
      WorstKind = Kind;
673
674
    // Determine the relevant qualifiers at this level.
675
264k
    Qualifiers SrcQuals, DestQuals;
676
264k
    Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
677
264k
    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
264k
    if (UnwrappedSrcType->isObjCObjectType() ||
683
264k
        
UnwrappedDestType->isObjCObjectType()263k
)
684
12.7k
      SrcQuals.removeConst();
685
686
264k
    if (CheckCVR) {
687
238k
      Qualifiers SrcCvrQuals =
688
238k
          Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
689
238k
      Qualifiers DestCvrQuals =
690
238k
          Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
691
692
238k
      if (SrcCvrQuals != DestCvrQuals) {
693
19.6k
        if (CastAwayQualifiers)
694
19.3k
          *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
695
696
        // If we removed a cvr-qualifier, this is casting away 'constness'.
697
19.6k
        if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
698
13.9k
          if (TheOffendingSrcType)
699
13.8k
            *TheOffendingSrcType = PrevUnwrappedSrcType;
700
13.9k
          if (TheOffendingDestType)
701
13.8k
            *TheOffendingDestType = PrevUnwrappedDestType;
702
13.9k
          return WorstKind;
703
13.9k
        }
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.69k
        if (!AllConstSoFar)
708
28
          return WorstKind;
709
5.69k
      }
710
238k
    }
711
712
250k
    if (CheckObjCLifetime &&
713
250k
        
!DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)25.6k
)
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
250k
    if (AllConstSoFar && 
!DestQuals.hasConst()250k
) {
719
168k
      AllConstSoFar = false;
720
168k
      if (TheOffendingSrcType)
721
153k
        *TheOffendingSrcType = PrevUnwrappedSrcType;
722
168k
      if (TheOffendingDestType)
723
153k
        *TheOffendingDestType = PrevUnwrappedDestType;
724
168k
    }
725
726
250k
    PrevUnwrappedSrcType = UnwrappedSrcType;
727
250k
    PrevUnwrappedDestType = UnwrappedDestType;
728
250k
  }
729
730
250k
  return CastAwayConstnessKind::CACK_None;
731
264k
}
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
57
  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.22k
void CastOperation::CheckConstCast() {
924
2.22k
  CheckNoDerefRAII NoderefCheck(*this);
925
926
2.22k
  if (ValueKind == VK_PRValue)
927
1.97k
    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
928
248
  else if (isPlaceholder())
929
1
    SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
930
2.22k
  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
931
0
    return;
932
933
2.22k
  unsigned msg = diag::err_bad_cxx_cast_generic;
934
2.22k
  auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
935
2.22k
  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.22k
  if (!isValidCast(TCR))
940
116
    SrcExpr = ExprError();
941
2.22k
}
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 ? 
SrcPointeeRD529
:
SrcType->getAsCXXRecordDecl()2.31k
;
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()699
||
SrcRD->isInvalidDecl()670
)
971
2.19k
    return;
972
973
650
  const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
974
975
650
  if (!DestRD || 
!DestRD->isCompleteDefinition()589
||
DestRD->isInvalidDecl()575
)
976
75
    return;
977
978
575
  enum {
979
575
    ReinterpretUpcast,
980
575
    ReinterpretDowncast
981
575
  } ReinterpretKind;
982
983
575
  CXXBasePaths BasePaths;
984
985
575
  if (SrcRD->isDerivedFrom(DestRD, BasePaths))
986
243
    ReinterpretKind = ReinterpretUpcast;
987
332
  else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
988
166
    ReinterpretKind = ReinterpretDowncast;
989
166
  else
990
166
    return;
991
992
409
  bool VirtualBase = true;
993
409
  bool NonZeroOffset = false;
994
409
  for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
995
409
                                          E = BasePaths.end();
996
529
       I != E; 
++I120
) {
997
425
    const CXXBasePath &Path = *I;
998
425
    CharUnits Offset = CharUnits::Zero();
999
425
    bool IsVirtual = false;
1000
425
    for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
1001
778
         IElem != EElem; 
++IElem353
) {
1002
449
      IsVirtual = IElem->Base->isVirtual();
1003
449
      if (IsVirtual)
1004
96
        break;
1005
353
      const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
1006
353
      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
353
                          *ClassDefinition = Class->getDefinition();
1011
353
      if (Class->isInvalidDecl() || !ClassDefinition ||
1012
353
          !ClassDefinition->isCompleteDefinition())
1013
0
        return;
1014
1015
353
      const ASTRecordLayout &DerivedLayout =
1016
353
          Self.Context.getASTRecordLayout(Class);
1017
353
      Offset += DerivedLayout.getBaseClassOffset(BaseRD);
1018
353
    }
1019
425
    if (!IsVirtual) {
1020
      // Don't warn if any path is a non-virtually derived base at offset zero.
1021
329
      if (Offset.isZero())
1022
305
        return;
1023
      // Offset makes sense only for non-virtual bases.
1024
24
      else
1025
24
        NonZeroOffset = true;
1026
329
    }
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.31M
                                  QualType DestType) {
1064
1.31M
  if (Self.Diags.isIgnored(diag::warn_cast_function_type,
1065
1.31M
                           SrcExpr.get()->getExprLoc()))
1066
1.31M
    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.97k
void CastOperation::CheckReinterpretCast() {
1138
2.97k
  if (ValueKind == VK_PRValue && 
!isPlaceholder(BuiltinType::Overload)2.68k
)
1139
2.62k
    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1140
349
  else
1141
349
    checkNonOverloadPlaceholders();
1142
2.97k
  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1143
0
    return;
1144
1145
2.97k
  unsigned msg = diag::err_bad_cxx_cast_generic;
1146
2.97k
  TryCastResult tcr =
1147
2.97k
    TryReinterpretCast(Self, SrcExpr, DestType,
1148
2.97k
                       /*CStyle*/false, OpRange, msg, Kind);
1149
2.97k
  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.97k
  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.97k
}
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
97.6k
void CastOperation::CheckStaticCast() {
1183
97.6k
  CheckNoDerefRAII NoderefCheck(*this);
1184
1185
97.6k
  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
97.6k
  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
97.6k
  if (ValueKind == VK_PRValue && 
!DestType->isRecordType()54.9k
&&
1211
97.6k
      
!isPlaceholder(BuiltinType::Overload)54.7k
) {
1212
54.7k
    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1213
54.7k
    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1214
0
      return;
1215
54.7k
  }
1216
1217
97.6k
  unsigned msg = diag::err_bad_cxx_cast_generic;
1218
97.6k
  TryCastResult tcr
1219
97.6k
    = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
1220
97.6k
                    Kind, BasePath, /*ListInitialization=*/false);
1221
97.6k
  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
97.6k
  if (isValidCast(tcr)) {
1237
97.4k
    if (Kind == CK_BitCast)
1238
3.39k
      checkCastAlign();
1239
97.4k
    if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1240
267
      checkObjCConversion(Sema::CCK_OtherCast);
1241
97.4k
  } else {
1242
198
    SrcExpr = ExprError();
1243
198
  }
1244
97.6k
}
1245
1246
59.7k
static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1247
59.7k
  auto *SrcPtrType = SrcType->getAs<PointerType>();
1248
59.7k
  if (!SrcPtrType)
1249
80
    return false;
1250
59.7k
  auto *DestPtrType = DestType->getAs<PointerType>();
1251
59.7k
  if (!DestPtrType)
1252
4.94k
    return false;
1253
54.7k
  return SrcPtrType->getPointeeType().getAddressSpace() !=
1254
54.7k
         DestPtrType->getPointeeType().getAddressSpace();
1255
59.7k
}
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
663k
                                   bool ListInitialization) {
1266
  // Determine whether we have the semantics of a C-style cast.
1267
663k
  bool CStyle
1268
663k
    = (CCK == Sema::CCK_CStyleCast || 
CCK == Sema::CCK_FunctionalCast156k
);
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
663k
  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
663k
  tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1291
663k
                                   OpRange, msg, Kind, BasePath);
1292
663k
  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
663k
  tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1299
663k
                              BasePath, msg);
1300
663k
  if (tcr != TC_NotApplicable)
1301
31.9k
    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
631k
  tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1306
631k
                              Kind, ListInitialization);
1307
631k
  if (SrcExpr.isInvalid())
1308
0
    return TC_Failed;
1309
631k
  if (tcr != TC_NotApplicable)
1310
559k
    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.
1317
  // In the CStyle case, the earlier attempt to const_cast should have taken
1318
  // care of reverse qualification conversions.
1319
1320
72.2k
  QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1321
1322
  // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1323
  // converted to an integral type. [...] A value of a scoped enumeration type
1324
  // can also be explicitly converted to a floating-point type [...].
1325
72.2k
  if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1326
1.72k
    if (Enum->getDecl()->isScoped()) {
1327
1.71k
      if (DestType->isBooleanType()) {
1328
2
        Kind = CK_IntegralToBoolean;
1329
2
        return TC_Success;
1330
1.71k
      } else if (DestType->isIntegralType(Self.Context)) {
1331
1.70k
        Kind = CK_IntegralCast;
1332
1.70k
        return TC_Success;
1333
1.70k
      } else 
if (4
DestType->isRealFloatingType()4
) {
1334
4
        Kind = CK_IntegralToFloating;
1335
4
        return TC_Success;
1336
4
      }
1337
1.71k
    }
1338
1.72k
  }
1339
1340
  // Reverse integral promotion/conversion. All such conversions are themselves
1341
  // again integral promotions or conversions and are thus already handled by
1342
  // p2 (TryDirectInitialization above).
1343
  // (Note: any data loss warnings should be suppressed.)
1344
  // The exception is the reverse of enum->integer, i.e. integer->enum (and
1345
  // enum->enum). See also C++ 5.2.9p7.
1346
  // The same goes for reverse floating point promotion/conversion and
1347
  // floating-integral conversions. Again, only floating->enum is relevant.
1348
70.5k
  if (DestType->isEnumeralType()) {
1349
1.55k
    if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1350
1.55k
                                 diag::err_bad_cast_incomplete)) {
1351
4
      SrcExpr = ExprError();
1352
4
      return TC_Failed;
1353
4
    }
1354
1.54k
    if (SrcType->isIntegralOrEnumerationType()) {
1355
      // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1356
      // type, the value is first converted to that type by integral conversion
1357
1.54k
      const EnumType *Enum = DestType->getAs<EnumType>();
1358
1.54k
      Kind = Enum->getDecl()->isFixed() &&
1359
1.54k
                     
Enum->getDecl()->getIntegerType()->isBooleanType()1.27k
1360
1.54k
                 ? 
CK_IntegralToBoolean14
1361
1.54k
                 : 
CK_IntegralCast1.52k
;
1362
1.54k
      return TC_Success;
1363
1.54k
    } else 
if (8
SrcType->isRealFloatingType()8
) {
1364
4
      Kind = CK_FloatingToIntegral;
1365
4
      return TC_Success;
1366
4
    }
1367
1.54k
  }
1368
1369
  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1370
  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1371
69.0k
  tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1372
69.0k
                                 Kind, BasePath);
1373
69.0k
  if (tcr != TC_NotApplicable)
1374
913
    return tcr;
1375
1376
  // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1377
  // conversion. C++ 5.2.9p9 has additional information.
1378
  // DR54's access restrictions apply here also.
1379
68.1k
  tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1380
68.1k
                                     OpRange, msg, Kind, BasePath);
1381
68.1k
  if (tcr != TC_NotApplicable)
1382
119
    return tcr;
1383
1384
  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1385
  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1386
  // just the usual constness stuff.
1387
67.9k
  if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1388
60.1k
    QualType SrcPointee = SrcPointer->getPointeeType();
1389
60.1k
    if (SrcPointee->isVoidType()) {
1390
26.3k
      if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1391
25.1k
        QualType DestPointee = DestPointer->getPointeeType();
1392
25.1k
        if (DestPointee->isIncompleteOrObjectType()) {
1393
          // This is definitely the intended conversion, but it might fail due
1394
          // to a qualifier violation. Note that we permit Objective-C lifetime
1395
          // and GC qualifier mismatches here.
1396
24.8k
          if (!CStyle) {
1397
3.40k
            Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1398
3.40k
            Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1399
3.40k
            DestPointeeQuals.removeObjCGCAttr();
1400
3.40k
            DestPointeeQuals.removeObjCLifetime();
1401
3.40k
            SrcPointeeQuals.removeObjCGCAttr();
1402
3.40k
            SrcPointeeQuals.removeObjCLifetime();
1403
3.40k
            if (DestPointeeQuals != SrcPointeeQuals &&
1404
3.40k
                
!DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)46
) {
1405
27
              msg = diag::err_bad_cxx_cast_qualifiers_away;
1406
27
              return TC_Failed;
1407
27
            }
1408
3.40k
          }
1409
24.8k
          Kind = IsAddressSpaceConversion(SrcType, DestType)
1410
24.8k
                     ? 
CK_AddressSpaceConversion14
1411
24.8k
                     : 
CK_BitCast24.8k
;
1412
24.8k
          return TC_Success;
1413
24.8k
        }
1414
1415
        // Microsoft permits static_cast from 'pointer-to-void' to
1416
        // 'pointer-to-function'.
1417
328
        if (!CStyle && 
Self.getLangOpts().MSVCCompat5
&&
1418
328
            
DestPointee->isFunctionType()4
) {
1419
4
          Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1420
4
          Kind = CK_BitCast;
1421
4
          return TC_Success;
1422
4
        }
1423
328
      }
1424
1.18k
      else if (DestType->isObjCObjectPointerType()) {
1425
        // allow both c-style cast and static_cast of objective-c pointers as
1426
        // they are pervasive.
1427
647
        Kind = CK_CPointerToObjCPointerCast;
1428
647
        return TC_Success;
1429
647
      }
1430
535
      else if (CStyle && DestType->isBlockPointerType()) {
1431
        // allow c-style cast of void * to block pointers.
1432
11
        Kind = CK_AnyPointerToBlockPointerCast;
1433
11
        return TC_Success;
1434
11
      }
1435
26.3k
    }
1436
60.1k
  }
1437
  // Allow arbitrary objective-c pointer conversion with static casts.
1438
42.4k
  if (SrcType->isObjCObjectPointerType() &&
1439
42.4k
      
DestType->isObjCObjectPointerType()88
) {
1440
3
    Kind = CK_BitCast;
1441
3
    return TC_Success;
1442
3
  }
1443
  // Allow ns-pointer to cf-pointer conversion in either direction
1444
  // with static casts.
1445
42.4k
  if (!CStyle &&
1446
42.4k
      
Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)143
)
1447
22
    return TC_Success;
1448
1449
  // See if it looks like the user is trying to convert between
1450
  // related record types, and select a better diagnostic if so.
1451
42.4k
  if (auto SrcPointer = SrcType->getAs<PointerType>())
1452
34.6k
    if (auto DestPointer = DestType->getAs<PointerType>())
1453
28.3k
      if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1454
28.3k
          
DestPointer->getPointeeType()->getAs<RecordType>()9.27k
)
1455
555
       msg = diag::err_bad_cxx_cast_unrelated_class;
1456
1457
42.4k
  if (SrcType->isMatrixType() && 
DestType->isMatrixType()52
) {
1458
44
    if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) {
1459
4
      SrcExpr = ExprError();
1460
4
      return TC_Failed;
1461
4
    }
1462
40
    return TC_Success;
1463
44
  }
1464
1465
  // We tried everything. Everything! Nothing works! :-(
1466
42.3k
  return TC_NotApplicable;
1467
42.4k
}
1468
1469
/// Tests whether a conversion according to N2844 is valid.
1470
TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1471
                                    QualType DestType, bool CStyle,
1472
                                    CastKind &Kind, CXXCastPath &BasePath,
1473
663k
                                    unsigned &msg) {
1474
  // C++11 [expr.static.cast]p3:
1475
  //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1476
  //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1477
663k
  const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1478
663k
  if (!R)
1479
631k
    return TC_NotApplicable;
1480
1481
32.0k
  if (!SrcExpr->isGLValue())
1482
50
    return TC_NotApplicable;
1483
1484
  // Because we try the reference downcast before this function, from now on
1485
  // this is the only cast possibility, so we issue an error if we fail now.
1486
  // FIXME: Should allow casting away constness if CStyle.
1487
31.9k
  QualType FromType = SrcExpr->getType();
1488
31.9k
  QualType ToType = R->getPointeeType();
1489
31.9k
  if (CStyle) {
1490
6
    FromType = FromType.getUnqualifiedType();
1491
6
    ToType = ToType.getUnqualifiedType();
1492
6
  }
1493
1494
31.9k
  Sema::ReferenceConversions RefConv;
1495
31.9k
  Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1496
31.9k
      SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
1497
31.9k
  if (RefResult != Sema::Ref_Compatible) {
1498
15
    if (CStyle || 
RefResult == Sema::Ref_Incompatible13
)
1499
11
      return TC_NotApplicable;
1500
    // Diagnose types which are reference-related but not compatible here since
1501
    // we can provide better diagnostics. In these cases forwarding to
1502
    // [expr.static.cast]p4 should never result in a well-formed cast.
1503
4
    msg = SrcExpr->isLValue() ? 
diag::err_bad_lvalue_to_rvalue_cast2
1504
4
                              : 
diag::err_bad_rvalue_to_rvalue_cast2
;
1505
4
    return TC_Failed;
1506
15
  }
1507
1508
31.9k
  if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1509
16
    Kind = CK_DerivedToBase;
1510
16
    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1511
16
                       /*DetectVirtual=*/true);
1512
16
    if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
1513
16
                            R->getPointeeType(), Paths))
1514
0
      return TC_NotApplicable;
1515
1516
16
    Self.BuildBasePathArray(Paths, BasePath);
1517
16
  } else
1518
31.9k
    Kind = CK_NoOp;
1519
1520
31.9k
  return TC_Success;
1521
31.9k
}
1522
1523
/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1524
TryCastResult
1525
TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1526
                           bool CStyle, SourceRange OpRange,
1527
                           unsigned &msg, CastKind &Kind,
1528
663k
                           CXXCastPath &BasePath) {
1529
  // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1530
  //   cast to type "reference to cv2 D", where D is a class derived from B,
1531
  //   if a valid standard conversion from "pointer to D" to "pointer to B"
1532
  //   exists, cv2 >= cv1, and B is not a virtual base class of D.
1533
  // In addition, DR54 clarifies that the base must be accessible in the
1534
  // current context. Although the wording of DR54 only applies to the pointer
1535
  // variant of this rule, the intent is clearly for it to apply to the this
1536
  // conversion as well.
1537
1538
663k
  const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1539
663k
  if (!DestReference) {
1540
620k
    return TC_NotApplicable;
1541
620k
  }
1542
43.0k
  bool RValueRef = DestReference->isRValueReferenceType();
1543
43.0k
  if (!RValueRef && 
!SrcExpr->isLValue()11.0k
) {
1544
    // We know the left side is an lvalue reference, so we can suggest a reason.
1545
77
    msg = diag::err_bad_cxx_cast_rvalue;
1546
77
    return TC_NotApplicable;
1547
77
  }
1548
1549
43.0k
  QualType DestPointee = DestReference->getPointeeType();
1550
1551
  // FIXME: If the source is a prvalue, we should issue a warning (because the
1552
  // cast always has undefined behavior), and for AST consistency, we should
1553
  // materialize a temporary.
1554
43.0k
  return TryStaticDowncast(Self,
1555
43.0k
                           Self.Context.getCanonicalType(SrcExpr->getType()),
1556
43.0k
                           Self.Context.getCanonicalType(DestPointee), CStyle,
1557
43.0k
                           OpRange, SrcExpr->getType(), DestType, msg, Kind,
1558
43.0k
                           BasePath);
1559
43.0k
}
1560
1561
/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1562
TryCastResult
1563
TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1564
                         bool CStyle, SourceRange OpRange,
1565
                         unsigned &msg, CastKind &Kind,
1566
69.0k
                         CXXCastPath &BasePath) {
1567
  // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1568
  //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
1569
  //   is a class derived from B, if a valid standard conversion from "pointer
1570
  //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1571
  //   class of D.
1572
  // In addition, DR54 clarifies that the base must be accessible in the
1573
  // current context.
1574
1575
69.0k
  const PointerType *DestPointer = DestType->getAs<PointerType>();
1576
69.0k
  if (!DestPointer) {
1577
13.3k
    return TC_NotApplicable;
1578
13.3k
  }
1579
1580
55.6k
  const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1581
55.6k
  if (!SrcPointer) {
1582
1.54k
    msg = diag::err_bad_static_cast_pointer_nonpointer;
1583
1.54k
    return TC_NotApplicable;
1584
1.54k
  }
1585
1586
54.1k
  return TryStaticDowncast(Self,
1587
54.1k
                   Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1588
54.1k
                  Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1589
54.1k
                           CStyle, OpRange, SrcType, DestType, msg, Kind,
1590
54.1k
                           BasePath);
1591
55.6k
}
1592
1593
/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1594
/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1595
/// DestType is possible and allowed.
1596
TryCastResult
1597
TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1598
                  bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1599
                  QualType OrigDestType, unsigned &msg,
1600
97.1k
                  CastKind &Kind, CXXCastPath &BasePath) {
1601
  // We can only work with complete types. But don't complain if it doesn't work
1602
97.1k
  if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1603
97.1k
      
!Self.isCompleteType(OpRange.getBegin(), DestType)71.7k
)
1604
26.9k
    return TC_NotApplicable;
1605
1606
  // Downcast can only happen in class hierarchies, so we need classes.
1607
70.2k
  if (!DestType->getAs<RecordType>() || 
!SrcType->getAs<RecordType>()47.9k
) {
1608
32.2k
    return TC_NotApplicable;
1609
32.2k
  }
1610
1611
38.0k
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1612
38.0k
                     /*DetectVirtual=*/true);
1613
38.0k
  if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1614
36.9k
    return TC_NotApplicable;
1615
36.9k
  }
1616
1617
  // Target type does derive from source type. Now we're serious. If an error
1618
  // appears now, it's not ignored.
1619
  // This may not be entirely in line with the standard. Take for example:
1620
  // struct A {};
1621
  // struct B : virtual A {
1622
  //   B(A&);
1623
  // };
1624
  //
1625
  // void f()
1626
  // {
1627
  //   (void)static_cast<const B&>(*((A*)0));
1628
  // }
1629
  // As far as the standard is concerned, p5 does not apply (A is virtual), so
1630
  // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1631
  // However, both GCC and Comeau reject this example, and accepting it would
1632
  // mean more complex code if we're to preserve the nice error message.
1633
  // FIXME: Being 100% compliant here would be nice to have.
1634
1635
  // Must preserve cv, as always, unless we're in C-style mode.
1636
1.07k
  if (!CStyle && 
!DestType.isAtLeastAsQualifiedAs(SrcType)923
) {
1637
8
    msg = diag::err_bad_cxx_cast_qualifiers_away;
1638
8
    return TC_Failed;
1639
8
  }
1640
1641
1.06k
  if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1642
    // This code is analoguous to that in CheckDerivedToBaseConversion, except
1643
    // that it builds the paths in reverse order.
1644
    // To sum up: record all paths to the base and build a nice string from
1645
    // them. Use it to spice up the error message.
1646
6
    if (!Paths.isRecordingPaths()) {
1647
0
      Paths.clear();
1648
0
      Paths.setRecordingPaths(true);
1649
0
      Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1650
0
    }
1651
6
    std::string PathDisplayStr;
1652
6
    std::set<unsigned> DisplayedPaths;
1653
12
    for (clang::CXXBasePath &Path : Paths) {
1654
12
      if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1655
        // We haven't displayed a path to this particular base
1656
        // class subobject yet.
1657
12
        PathDisplayStr += "\n    ";
1658
12
        for (CXXBasePathElement &PE : llvm::reverse(Path))
1659
36
          PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1660
12
        PathDisplayStr += QualType(DestType).getAsString();
1661
12
      }
1662
12
    }
1663
1664
6
    Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1665
6
      << QualType(SrcType).getUnqualifiedType()
1666
6
      << QualType(DestType).getUnqualifiedType()
1667
6
      << PathDisplayStr << OpRange;
1668
6
    msg = 0;
1669
6
    return TC_Failed;
1670
6
  }
1671
1672
1.06k
  if (Paths.getDetectedVirtual() != nullptr) {
1673
36
    QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1674
36
    Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1675
36
      << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1676
36
    msg = 0;
1677
36
    return TC_Failed;
1678
36
  }
1679
1680
1.02k
  if (!CStyle) {
1681
893
    switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1682
893
                                      SrcType, DestType,
1683
893
                                      Paths.front(),
1684
893
                                diag::err_downcast_from_inaccessible_base)) {
1685
879
    case Sema::AR_accessible:
1686
891
    case Sema::AR_delayed:     // be optimistic
1687
891
    case Sema::AR_dependent:   // be optimistic
1688
891
      break;
1689
1690
2
    case Sema::AR_inaccessible:
1691
2
      msg = 0;
1692
2
      return TC_Failed;
1693
893
    }
1694
893
  }
1695
1696
1.02k
  Self.BuildBasePathArray(Paths, BasePath);
1697
1.02k
  Kind = CK_BaseToDerived;
1698
1.02k
  return TC_Success;
1699
1.02k
}
1700
1701
/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1702
/// C++ 5.2.9p9 is valid:
1703
///
1704
///   An rvalue of type "pointer to member of D of type cv1 T" can be
1705
///   converted to an rvalue of type "pointer to member of B of type cv2 T",
1706
///   where B is a base class of D [...].
1707
///
1708
TryCastResult
1709
TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1710
                             QualType DestType, bool CStyle,
1711
                             SourceRange OpRange,
1712
                             unsigned &msg, CastKind &Kind,
1713
68.1k
                             CXXCastPath &BasePath) {
1714
68.1k
  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1715
68.1k
  if (!DestMemPtr)
1716
67.9k
    return TC_NotApplicable;
1717
1718
169
  bool WasOverloadedFunction = false;
1719
169
  DeclAccessPair FoundOverload;
1720
169
  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1721
11
    if (FunctionDecl *Fn
1722
11
          = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1723
11
                                                    FoundOverload)) {
1724
11
      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1725
11
      SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1726
11
                      Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1727
11
      WasOverloadedFunction = true;
1728
11
    }
1729
11
  }
1730
1731
169
  const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1732
169
  if (!SrcMemPtr) {
1733
1
    msg = diag::err_bad_static_cast_member_pointer_nonmp;
1734
1
    return TC_NotApplicable;
1735
1
  }
1736
1737
  // Lock down the inheritance model right now in MS ABI, whether or not the
1738
  // pointee types are the same.
1739
168
  if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1740
19
    (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1741
19
    (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1742
19
  }
1743
1744
  // T == T, modulo cv
1745
168
  if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1746
168
                                           DestMemPtr->getPointeeType()))
1747
33
    return TC_NotApplicable;
1748
1749
  // B base of D
1750
135
  QualType SrcClass(SrcMemPtr->getClass(), 0);
1751
135
  QualType DestClass(DestMemPtr->getClass(), 0);
1752
135
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1753
135
                  /*DetectVirtual=*/true);
1754
135
  if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1755
16
    return TC_NotApplicable;
1756
1757
  // B is a base of D. But is it an allowed base? If not, it's a hard error.
1758
119
  if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1759
3
    Paths.clear();
1760
3
    Paths.setRecordingPaths(true);
1761
3
    bool StillOkay =
1762
3
        Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1763
3
    assert(StillOkay);
1764
0
    (void)StillOkay;
1765
3
    std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1766
3
    Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1767
3
      << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1768
3
    msg = 0;
1769
3
    return TC_Failed;
1770
3
  }
1771
1772
116
  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1773
15
    Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1774
15
      << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1775
15
    msg = 0;
1776
15
    return TC_Failed;
1777
15
  }
1778
1779
101
  if (!CStyle) {
1780
26
    switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1781
26
                                      DestClass, SrcClass,
1782
26
                                      Paths.front(),
1783
26
                                      diag::err_upcast_to_inaccessible_base)) {
1784
21
    case Sema::AR_accessible:
1785
25
    case Sema::AR_delayed:
1786
25
    case Sema::AR_dependent:
1787
      // Optimistically assume that the delayed and dependent cases
1788
      // will work out.
1789
25
      break;
1790
1791
1
    case Sema::AR_inaccessible:
1792
1
      msg = 0;
1793
1
      return TC_Failed;
1794
26
    }
1795
26
  }
1796
1797
100
  if (WasOverloadedFunction) {
1798
    // Resolve the address of the overloaded function again, this time
1799
    // allowing complaints if something goes wrong.
1800
10
    FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1801
10
                                                               DestType,
1802
10
                                                               true,
1803
10
                                                               FoundOverload);
1804
10
    if (!Fn) {
1805
0
      msg = 0;
1806
0
      return TC_Failed;
1807
0
    }
1808
1809
10
    SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1810
10
    if (!SrcExpr.isUsable()) {
1811
0
      msg = 0;
1812
0
      return TC_Failed;
1813
0
    }
1814
10
  }
1815
1816
100
  Self.BuildBasePathArray(Paths, BasePath);
1817
100
  Kind = CK_DerivedToBaseMemberPointer;
1818
100
  return TC_Success;
1819
100
}
1820
1821
/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1822
/// is valid:
1823
///
1824
///   An expression e can be explicitly converted to a type T using a
1825
///   @c static_cast if the declaration "T t(e);" is well-formed [...].
1826
TryCastResult
1827
TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1828
                      Sema::CheckedConversionKind CCK,
1829
                      SourceRange OpRange, unsigned &msg,
1830
631k
                      CastKind &Kind, bool ListInitialization) {
1831
631k
  if (DestType->isRecordType()) {
1832
25.6k
    if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1833
25.6k
                                 diag::err_bad_cast_incomplete) ||
1834
25.6k
        Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1835
25.6k
                                    diag::err_allocation_of_abstract_type)) {
1836
22
      msg = 0;
1837
22
      return TC_Failed;
1838
22
    }
1839
25.6k
  }
1840
1841
631k
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1842
631k
  InitializationKind InitKind
1843
631k
    = (CCK == Sema::CCK_CStyleCast)
1844
631k
        ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1845
506k
                                               ListInitialization)
1846
631k
    : 
(CCK == Sema::CCK_FunctionalCast)124k
1847
124k
        ? 
InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)59.3k
1848
124k
    : 
InitializationKind::CreateCast(OpRange)65.5k
;
1849
631k
  Expr *SrcExprRaw = SrcExpr.get();
1850
  // FIXME: Per DR242, we should check for an implicit conversion sequence
1851
  // or for a constructor that could be invoked by direct-initialization
1852
  // here, not for an initialization sequence.
1853
631k
  InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1854
1855
  // At this point of CheckStaticCast, if the destination is a reference,
1856
  // or the expression is an overload expression this has to work.
1857
  // There is no other way that works.
1858
  // On the other hand, if we're checking a C-style cast, we've still got
1859
  // the reinterpret_cast way.
1860
631k
  bool CStyle
1861
631k
    = (CCK == Sema::CCK_CStyleCast || 
CCK == Sema::CCK_FunctionalCast124k
);
1862
631k
  if (InitSeq.Failed() && 
(72.2k
CStyle72.2k
||
!DestType->isReferenceType()7.00k
))
1863
72.2k
    return TC_NotApplicable;
1864
1865
559k
  ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1866
559k
  if (Result.isInvalid()) {
1867
28
    msg = 0;
1868
28
    return TC_Failed;
1869
28
  }
1870
1871
559k
  if (InitSeq.isConstructorInitialization())
1872
25.5k
    Kind = CK_ConstructorConversion;
1873
533k
  else
1874
533k
    Kind = CK_NoOp;
1875
1876
559k
  SrcExpr = Result;
1877
559k
  return TC_Success;
1878
559k
}
1879
1880
/// TryConstCast - See if a const_cast from source to destination is allowed,
1881
/// and perform it if it is.
1882
static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1883
                                  QualType DestType, bool CStyle,
1884
576k
                                  unsigned &msg) {
1885
576k
  DestType = Self.Context.getCanonicalType(DestType);
1886
576k
  QualType SrcType = SrcExpr.get()->getType();
1887
576k
  bool NeedToMaterializeTemporary = false;
1888
1889
576k
  if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1890
    // C++11 5.2.11p4:
1891
    //   if a pointer to T1 can be explicitly converted to the type "pointer to
1892
    //   T2" using a const_cast, then the following conversions can also be
1893
    //   made:
1894
    //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
1895
    //       type T2 using the cast const_cast<T2&>;
1896
    //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
1897
    //       type T2 using the cast const_cast<T2&&>; and
1898
    //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
1899
    //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1900
1901
856
    if (isa<LValueReferenceType>(DestTypeTmp) && 
!SrcExpr.get()->isLValue()766
) {
1902
      // Cannot const_cast non-lvalue to lvalue reference type. But if this
1903
      // is C-style, static_cast might find a way, so we simply suggest a
1904
      // message and tell the parent to keep searching.
1905
62
      msg = diag::err_bad_cxx_cast_rvalue;
1906
62
      return TC_NotApplicable;
1907
62
    }
1908
1909
794
    if (isa<RValueReferenceType>(DestTypeTmp) && 
SrcExpr.get()->isPRValue()90
) {
1910
48
      if (!SrcType->isRecordType()) {
1911
        // Cannot const_cast non-class prvalue to rvalue reference type. But if
1912
        // this is C-style, static_cast can do this.
1913
11
        msg = diag::err_bad_cxx_cast_rvalue;
1914
11
        return TC_NotApplicable;
1915
11
      }
1916
1917
      // Materialize the class prvalue so that the const_cast can bind a
1918
      // reference to it.
1919
37
      NeedToMaterializeTemporary = true;
1920
37
    }
1921
1922
    // It's not completely clear under the standard whether we can
1923
    // const_cast bit-field gl-values.  Doing so would not be
1924
    // intrinsically complicated, but for now, we say no for
1925
    // consistency with other compilers and await the word of the
1926
    // committee.
1927
783
    if (SrcExpr.get()->refersToBitField()) {
1928
6
      msg = diag::err_bad_cxx_cast_bitfield;
1929
6
      return TC_NotApplicable;
1930
6
    }
1931
1932
777
    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1933
777
    SrcType = Self.Context.getPointerType(SrcType);
1934
777
  }
1935
1936
  // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1937
  //   the rules for const_cast are the same as those used for pointers.
1938
1939
576k
  if (!DestType->isPointerType() &&
1940
576k
      
!DestType->isMemberPointerType()505k
&&
1941
576k
      
!DestType->isObjCObjectPointerType()505k
) {
1942
    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1943
    // was a reference type, we converted it to a pointer above.
1944
    // The status of rvalue references isn't entirely clear, but it looks like
1945
    // conversion to them is simply invalid.
1946
    // C++ 5.2.11p3: For two pointer types [...]
1947
499k
    if (!CStyle)
1948
3
      msg = diag::err_bad_const_cast_dest;
1949
499k
    return TC_NotApplicable;
1950
499k
  }
1951
76.7k
  if (DestType->isFunctionPointerType() ||
1952
76.7k
      
DestType->isMemberFunctionPointerType()75.6k
) {
1953
    // Cannot cast direct function pointers.
1954
    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1955
    // T is the ultimate pointee of source and target type.
1956
1.15k
    if (!CStyle)
1957
6
      msg = diag::err_bad_const_cast_dest;
1958
1.15k
    return TC_NotApplicable;
1959
1.15k
  }
1960
1961
  // C++ [expr.const.cast]p3:
1962
  //   "For two similar types T1 and T2, [...]"
1963
  //
1964
  // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1965
  // type qualifiers. (Likewise, we ignore other changes when determining
1966
  // whether a cast casts away constness.)
1967
75.5k
  if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
1968
64.9k
    return TC_NotApplicable;
1969
1970
10.6k
  if (NeedToMaterializeTemporary)
1971
    // This is a const_cast from a class prvalue to an rvalue reference type.
1972
    // Materialize a temporary to store the result of the conversion.
1973
30
    SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1974
30
                                                  SrcExpr.get(),
1975
30
                                                  /*IsLValueReference*/ false);
1976
1977
10.6k
  return TC_Success;
1978
75.5k
}
1979
1980
// Checks for undefined behavior in reinterpret_cast.
1981
// The cases that is checked for is:
1982
// *reinterpret_cast<T*>(&a)
1983
// reinterpret_cast<T&>(a)
1984
// where accessing 'a' as type 'T' will result in undefined behavior.
1985
void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1986
                                          bool IsDereference,
1987
485
                                          SourceRange Range) {
1988
485
  unsigned DiagID = IsDereference ?
1989
205
                        diag::warn_pointer_indirection_from_incompatible_type :
1990
485
                        
diag::warn_undefined_reinterpret_cast280
;
1991
1992
485
  if (Diags.isIgnored(DiagID, Range.getBegin()))
1993
376
    return;
1994
1995
109
  QualType SrcTy, DestTy;
1996
109
  if (IsDereference) {
1997
58
    if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1998
0
      return;
1999
0
    }
2000
58
    SrcTy = SrcType->getPointeeType();
2001
58
    DestTy = DestType->getPointeeType();
2002
58
  } else {
2003
51
    if (!DestType->getAs<ReferenceType>()) {
2004
0
      return;
2005
0
    }
2006
51
    SrcTy = SrcType;
2007
51
    DestTy = DestType->getPointeeType();
2008
51
  }
2009
2010
  // Cast is compatible if the types are the same.
2011
109
  if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
2012
44
    return;
2013
44
  }
2014
  // or one of the types is a char or void type
2015
65
  if (DestTy->isAnyCharacterType() || 
DestTy->isVoidType()50
||
2016
65
      
SrcTy->isAnyCharacterType()45
||
SrcTy->isVoidType()37
) {
2017
33
    return;
2018
33
  }
2019
  // or one of the types is a tag type.
2020
32
  if (SrcTy->getAs<TagType>() || 
DestTy->getAs<TagType>()24
) {
2021
8
    return;
2022
8
  }
2023
2024
  // FIXME: Scoped enums?
2025
24
  if ((SrcTy->isUnsignedIntegerType() && 
DestTy->isSignedIntegerType()8
) ||
2026
24
      
(16
SrcTy->isSignedIntegerType()16
&&
DestTy->isUnsignedIntegerType()12
)) {
2027
16
    if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
2028
16
      return;
2029
16
    }
2030
16
  }
2031
2032
8
  Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
2033
8
}
2034
2035
static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
2036
769k
                                  QualType DestType) {
2037
769k
  QualType SrcType = SrcExpr.get()->getType();
2038
769k
  if (Self.Context.hasSameType(SrcType, DestType))
2039
541k
    return;
2040
228k
  if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
2041
134k
    if (SrcPtrTy->isObjCSelType()) {
2042
8
      QualType DT = DestType;
2043
8
      if (isa<PointerType>(DestType))
2044
8
        DT = DestType->getPointeeType();
2045
8
      if (!DT.getUnqualifiedType()->isVoidType())
2046
4
        Self.Diag(SrcExpr.get()->getExprLoc(),
2047
4
                  diag::warn_cast_pointer_from_sel)
2048
4
        << SrcType << DestType << SrcExpr.get()->getSourceRange();
2049
8
    }
2050
228k
}
2051
2052
/// Diagnose casts that change the calling convention of a pointer to a function
2053
/// defined in the current TU.
2054
static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
2055
770k
                                    QualType DstType, SourceRange OpRange) {
2056
  // Check if this cast would change the calling convention of a function
2057
  // pointer type.
2058
770k
  QualType SrcType = SrcExpr.get()->getType();
2059
770k
  if (Self.Context.hasSameType(SrcType, DstType) ||
2060
770k
      
!SrcType->isFunctionPointerType()229k
||
!DstType->isFunctionPointerType()2.30k
)
2061
770k
    return;
2062
144
  const auto *SrcFTy =
2063
144
      SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2064
144
  const auto *DstFTy =
2065
144
      DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2066
144
  CallingConv SrcCC = SrcFTy->getCallConv();
2067
144
  CallingConv DstCC = DstFTy->getCallConv();
2068
144
  if (SrcCC == DstCC)
2069
112
    return;
2070
2071
  // We have a calling convention cast. Check if the source is a pointer to a
2072
  // known, specific function that has already been defined.
2073
32
  Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
2074
32
  if (auto *UO = dyn_cast<UnaryOperator>(Src))
2075
8
    if (UO->getOpcode() == UO_AddrOf)
2076
8
      Src = UO->getSubExpr()->IgnoreParenImpCasts();
2077
32
  auto *DRE = dyn_cast<DeclRefExpr>(Src);
2078
32
  if (!DRE)
2079
0
    return;
2080
32
  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2081
32
  if (!FD)
2082
4
    return;
2083
2084
  // Only warn if we are casting from the default convention to a non-default
2085
  // convention. This can happen when the programmer forgot to apply the calling
2086
  // convention to the function declaration and then inserted this cast to
2087
  // satisfy the type system.
2088
28
  CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
2089
28
      FD->isVariadic(), FD->isCXXInstanceMember());
2090
28
  if (DstCC == DefaultCC || 
SrcCC != DefaultCC24
)
2091
4
    return;
2092
2093
  // Diagnose this cast, as it is probably bad.
2094
24
  StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
2095
24
  StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
2096
24
  Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
2097
24
      << SrcCCName << DstCCName << OpRange;
2098
2099
  // The checks above are cheaper than checking if the diagnostic is enabled.
2100
  // However, it's worth checking if the warning is enabled before we construct
2101
  // a fixit.
2102
24
  if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
2103
0
    return;
2104
2105
  // Try to suggest a fixit to change the calling convention of the function
2106
  // whose address was taken. Try to use the latest macro for the convention.
2107
  // For example, users probably want to write "WINAPI" instead of "__stdcall"
2108
  // to match the Windows header declarations.
2109
24
  SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2110
24
  Preprocessor &PP = Self.getPreprocessor();
2111
24
  SmallVector<TokenValue, 6> AttrTokens;
2112
24
  SmallString<64> CCAttrText;
2113
24
  llvm::raw_svector_ostream OS(CCAttrText);
2114
24
  if (Self.getLangOpts().MicrosoftExt) {
2115
    // __stdcall or __vectorcall
2116
18
    OS << "__" << DstCCName;
2117
18
    IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
2118
18
    AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2119
18
                             ? TokenValue(II->getTokenID())
2120
18
                             : 
TokenValue(II)0
);
2121
18
  } else {
2122
    // __attribute__((stdcall)) or __attribute__((vectorcall))
2123
6
    OS << "__attribute__((" << DstCCName << "))";
2124
6
    AttrTokens.push_back(tok::kw___attribute);
2125
6
    AttrTokens.push_back(tok::l_paren);
2126
6
    AttrTokens.push_back(tok::l_paren);
2127
6
    IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
2128
6
    AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2129
6
                             ? 
TokenValue(II->getTokenID())0
2130
6
                             : TokenValue(II));
2131
6
    AttrTokens.push_back(tok::r_paren);
2132
6
    AttrTokens.push_back(tok::r_paren);
2133
6
  }
2134
24
  StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
2135
24
  if (!AttrSpelling.empty())
2136
20
    CCAttrText = AttrSpelling;
2137
24
  OS << ' ';
2138
24
  Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
2139
24
      << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
2140
24
}
2141
2142
static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2143
                                  const Expr *SrcExpr, QualType DestType,
2144
156k
                                  Sema &Self) {
2145
156k
  QualType SrcType = SrcExpr->getType();
2146
2147
  // Not warning on reinterpret_cast, boolean, constant expressions, etc
2148
  // are not explicit design choices, but consistent with GCC's behavior.
2149
  // Feel free to modify them if you've reason/evidence for an alternative.
2150
156k
  if (CStyle && 
SrcType->isIntegralType(Self.Context)156k
2151
156k
      && 
!SrcType->isBooleanType()8.82k
2152
156k
      && 
!SrcType->isEnumeralType()8.82k
2153
156k
      && 
!SrcExpr->isIntegerConstantExpr(Self.Context)8.82k
2154
156k
      && Self.Context.getTypeSize(DestType) >
2155
3.31k
         Self.Context.getTypeSize(SrcType)) {
2156
    // Separate between casts to void* and non-void* pointers.
2157
    // Some APIs use (abuse) void* for something like a user context,
2158
    // and often that value is an integer even if it isn't a pointer itself.
2159
    // Having a separate warning flag allows users to control the warning
2160
    // for their workflow.
2161
55
    unsigned Diag = DestType->isVoidPointerType() ?
2162
8
                      diag::warn_int_to_void_pointer_cast
2163
55
                    : 
diag::warn_int_to_pointer_cast47
;
2164
55
    Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2165
55
  }
2166
156k
}
2167
2168
static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
2169
110
                                             ExprResult &Result) {
2170
  // We can only fix an overloaded reinterpret_cast if
2171
  // - it is a template with explicit arguments that resolves to an lvalue
2172
  //   unambiguously, or
2173
  // - it is the only function in an overload set that may have its address
2174
  //   taken.
2175
2176
110
  Expr *E = Result.get();
2177
  // TODO: what if this fails because of DiagnoseUseOfDecl or something
2178
  // like it?
2179
110
  if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2180
110
          Result,
2181
110
          Expr::getValueKindForType(DestType) ==
2182
110
              VK_PRValue // Convert Fun to Ptr
2183
110
          ) &&
2184
110
      
Result.isUsable()40
)
2185
40
    return true;
2186
2187
  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2188
  // preserves Result.
2189
70
  Result = E;
2190
70
  if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2191
70
          Result, /*DoFunctionPointerConversion=*/true))
2192
33
    return false;
2193
37
  return Result.isUsable();
2194
70
}
2195
2196
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
2197
                                        QualType DestType, bool CStyle,
2198
                                        SourceRange OpRange,
2199
                                        unsigned &msg,
2200
45.2k
                                        CastKind &Kind) {
2201
45.2k
  bool IsLValueCast = false;
2202
2203
45.2k
  DestType = Self.Context.getCanonicalType(DestType);
2204
45.2k
  QualType SrcType = SrcExpr.get()->getType();
2205
2206
  // Is the source an overloaded name? (i.e. &foo)
2207
  // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2208
45.2k
  if (SrcType == Self.Context.OverloadTy) {
2209
110
    ExprResult FixedExpr = SrcExpr;
2210
110
    if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
2211
33
      return TC_NotApplicable;
2212
2213
77
    assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2214
0
    SrcExpr = FixedExpr;
2215
77
    SrcType = SrcExpr.get()->getType();
2216
77
  }
2217
2218
45.2k
  if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2219
527
    if (!SrcExpr.get()->isGLValue()) {
2220
      // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2221
      // similar comment in const_cast.
2222
5
      msg = diag::err_bad_cxx_cast_rvalue;
2223
5
      return TC_NotApplicable;
2224
5
    }
2225
2226
522
    if (!CStyle) {
2227
280
      Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2228
280
                                          /*IsDereference=*/false, OpRange);
2229
280
    }
2230
2231
    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2232
    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
2233
    //   built-in & and * operators.
2234
2235
522
    const char *inappropriate = nullptr;
2236
522
    switch (SrcExpr.get()->getObjectKind()) {
2237
518
    case OK_Ordinary:
2238
518
      break;
2239
2
    case OK_BitField:
2240
2
      msg = diag::err_bad_cxx_cast_bitfield;
2241
2
      return TC_NotApplicable;
2242
      // FIXME: Use a specific diagnostic for the rest of these cases.
2243
1
    case OK_VectorComponent: inappropriate = "vector element";      break;
2244
1
    case OK_MatrixComponent:
2245
1
      inappropriate = "matrix element";
2246
1
      break;
2247
0
    case OK_ObjCProperty:    inappropriate = "property expression"; break;
2248
0
    case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
2249
0
                             break;
2250
522
    }
2251
520
    if (inappropriate) {
2252
2
      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2253
2
          << inappropriate << DestType
2254
2
          << OpRange << SrcExpr.get()->getSourceRange();
2255
2
      msg = 0; SrcExpr = ExprError();
2256
2
      return TC_NotApplicable;
2257
2
    }
2258
2259
    // This code does this transformation for the checked types.
2260
518
    DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2261
518
    SrcType = Self.Context.getPointerType(SrcType);
2262
2263
518
    IsLValueCast = true;
2264
518
  }
2265
2266
  // Canonicalize source for comparison.
2267
45.2k
  SrcType = Self.Context.getCanonicalType(SrcType);
2268
2269
45.2k
  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2270
45.2k
                          *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2271
45.2k
  if (DestMemPtr && 
SrcMemPtr72
) {
2272
    // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2273
    //   can be explicitly converted to an rvalue of type "pointer to member
2274
    //   of Y of type T2" if T1 and T2 are both function types or both object
2275
    //   types.
2276
69
    if (DestMemPtr->isMemberFunctionPointer() !=
2277
69
        SrcMemPtr->isMemberFunctionPointer())
2278
6
      return TC_NotApplicable;
2279
2280
63
    if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2281
      // We need to determine the inheritance model that the class will use if
2282
      // haven't yet.
2283
19
      (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2284
19
      (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2285
19
    }
2286
2287
    // Don't allow casting between member pointers of different sizes.
2288
63
    if (Self.Context.getTypeSize(DestMemPtr) !=
2289
63
        Self.Context.getTypeSize(SrcMemPtr)) {
2290
2
      msg = diag::err_bad_cxx_cast_member_pointer_size;
2291
2
      return TC_Failed;
2292
2
    }
2293
2294
    // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2295
    //   constness.
2296
    // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2297
    // we accept it.
2298
61
    if (auto CACK =
2299
61
            CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2300
61
                               /*CheckObjCLifetime=*/CStyle))
2301
1
      return getCastAwayConstnessCastKind(CACK, msg);
2302
2303
    // A valid member pointer cast.
2304
60
    assert(!IsLValueCast);
2305
0
    Kind = CK_ReinterpretMemberPointer;
2306
60
    return TC_Success;
2307
61
  }
2308
2309
  // See below for the enumeral issue.
2310
45.1k
  if (SrcType->isNullPtrType() && 
DestType->isIntegralType(Self.Context)6
) {
2311
    // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2312
    //   type large enough to hold it. A value of std::nullptr_t can be
2313
    //   converted to an integral type; the conversion has the same meaning
2314
    //   and validity as a conversion of (void*)0 to the integral type.
2315
6
    if (Self.Context.getTypeSize(SrcType) >
2316
6
        Self.Context.getTypeSize(DestType)) {
2317
1
      msg = diag::err_bad_reinterpret_cast_small_int;
2318
1
      return TC_Failed;
2319
1
    }
2320
5
    Kind = CK_PointerToIntegral;
2321
5
    return TC_Success;
2322
6
  }
2323
2324
  // Allow reinterpret_casts between vectors of the same size and
2325
  // between vectors and integers of the same size.
2326
45.1k
  bool destIsVector = DestType->isVectorType();
2327
45.1k
  bool srcIsVector = SrcType->isVectorType();
2328
45.1k
  if (srcIsVector || 
destIsVector39.6k
) {
2329
    // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2330
5.82k
    if (Self.isValidSveBitcast(SrcType, DestType)) {
2331
120
      Kind = CK_BitCast;
2332
120
      return TC_Success;
2333
120
    }
2334
2335
    // The non-vector type, if any, must have integral type.  This is
2336
    // the same rule that C vector casts use; note, however, that enum
2337
    // types are not integral in C++.
2338
5.70k
    if ((!destIsVector && 
!DestType->isIntegralType(Self.Context)446
) ||
2339
5.70k
        
(5.70k
!srcIsVector5.70k
&&
!SrcType->isIntegralType(Self.Context)313
))
2340
10
      return TC_NotApplicable;
2341
2342
    // The size we want to consider is eltCount * eltSize.
2343
    // That's exactly what the lax-conversion rules will check.
2344
5.69k
    if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2345
5.67k
      Kind = CK_BitCast;
2346
5.67k
      return TC_Success;
2347
5.67k
    }
2348
2349
25
    if (Self.LangOpts.OpenCL && 
!CStyle5
) {
2350
5
      if (DestType->isExtVectorType() || 
SrcType->isExtVectorType()3
) {
2351
        // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2352
5
        if (Self.areVectorTypesSameSize(SrcType, DestType)) {
2353
4
          Kind = CK_BitCast;
2354
4
          return TC_Success;
2355
4
        }
2356
5
      }
2357
5
    }
2358
2359
    // Otherwise, pick a reasonable diagnostic.
2360
21
    if (!destIsVector)
2361
3
      msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2362
18
    else if (!srcIsVector)
2363
1
      msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2364
17
    else
2365
17
      msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2366
2367
21
    return TC_Failed;
2368
25
  }
2369
2370
39.3k
  if (SrcType == DestType) {
2371
    // C++ 5.2.10p2 has a note that mentions that, subject to all other
2372
    // restrictions, a cast to the same type is allowed so long as it does not
2373
    // cast away constness. In C++98, the intent was not entirely clear here,
2374
    // since all other paragraphs explicitly forbid casts to the same type.
2375
    // C++11 clarifies this case with p2.
2376
    //
2377
    // The only allowed types are: integral, enumeration, pointer, or
2378
    // pointer-to-member types.  We also won't restrict Obj-C pointers either.
2379
88
    Kind = CK_NoOp;
2380
88
    TryCastResult Result = TC_NotApplicable;
2381
88
    if (SrcType->isIntegralOrEnumerationType() ||
2382
88
        
SrcType->isAnyPointerType()74
||
2383
88
        
SrcType->isMemberPointerType()7
||
2384
88
        
SrcType->isBlockPointerType()7
) {
2385
81
      Result = TC_Success;
2386
81
    }
2387
88
    return Result;
2388
88
  }
2389
2390
39.2k
  bool destIsPtr = DestType->isAnyPointerType() ||
2391
39.2k
                   
DestType->isBlockPointerType()2.32k
;
2392
39.2k
  bool srcIsPtr = SrcType->isAnyPointerType() ||
2393
39.2k
                  
SrcType->isBlockPointerType()2.03k
;
2394
39.2k
  if (!destIsPtr && 
!srcIsPtr2.31k
) {
2395
    // Except for std::nullptr_t->integer and lvalue->reference, which are
2396
    // handled above, at least one of the two arguments must be a pointer.
2397
70
    return TC_NotApplicable;
2398
70
  }
2399
2400
39.1k
  if (DestType->isIntegralType(Self.Context)) {
2401
2.24k
    assert(srcIsPtr && "One type must be a pointer");
2402
    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2403
    //   type large enough to hold it; except in Microsoft mode, where the
2404
    //   integral type size doesn't matter (except we don't allow bool).
2405
2.24k
    if ((Self.Context.getTypeSize(SrcType) >
2406
2.24k
         Self.Context.getTypeSize(DestType))) {
2407
37
      bool MicrosoftException =
2408
37
          Self.getLangOpts().MicrosoftExt && 
!DestType->isBooleanType()30
;
2409
37
      if (MicrosoftException) {
2410
24
        unsigned Diag = SrcType->isVoidPointerType()
2411
24
                            ? 
diag::warn_void_pointer_to_int_cast12
2412
24
                            : 
diag::warn_pointer_to_int_cast12
;
2413
24
        Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2414
24
      } else {
2415
13
        msg = diag::err_bad_reinterpret_cast_small_int;
2416
13
        return TC_Failed;
2417
13
      }
2418
37
    }
2419
2.22k
    Kind = CK_PointerToIntegral;
2420
2.22k
    return TC_Success;
2421
2.24k
  }
2422
2423
36.9k
  if (SrcType->isIntegralOrEnumerationType()) {
2424
1.95k
    assert(destIsPtr && "One type must be a pointer");
2425
0
    checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2426
    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2427
    //   converted to a pointer.
2428
    // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2429
    //   necessarily converted to a null pointer value.]
2430
1.95k
    Kind = CK_IntegralToPointer;
2431
1.95k
    return TC_Success;
2432
1.95k
  }
2433
2434
34.9k
  if (!destIsPtr || 
!srcIsPtr34.9k
) {
2435
    // With the valid non-pointer conversions out of the way, we can be even
2436
    // more stringent.
2437
9
    return TC_NotApplicable;
2438
9
  }
2439
2440
  // Cannot convert between block pointers and Objective-C object pointers.
2441
34.9k
  if ((SrcType->isBlockPointerType() && 
DestType->isObjCObjectPointerType()3
) ||
2442
34.9k
      
(34.9k
DestType->isBlockPointerType()34.9k
&&
SrcType->isObjCObjectPointerType()3
))
2443
2
    return TC_NotApplicable;
2444
2445
  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2446
  // The C-style cast operator can.
2447
34.9k
  TryCastResult SuccessResult = TC_Success;
2448
34.9k
  if (auto CACK =
2449
34.9k
          CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2450
34.9k
                             /*CheckObjCLifetime=*/CStyle))
2451
87
    SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2452
2453
34.9k
  if (IsAddressSpaceConversion(SrcType, DestType)) {
2454
125
    Kind = CK_AddressSpaceConversion;
2455
125
    assert(SrcType->isPointerType() && DestType->isPointerType());
2456
125
    if (!CStyle &&
2457
125
        !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2458
16
            SrcType->getPointeeType().getQualifiers())) {
2459
14
      SuccessResult = TC_Failed;
2460
14
    }
2461
34.8k
  } else if (IsLValueCast) {
2462
490
    Kind = CK_LValueBitCast;
2463
34.3k
  } else if (DestType->isObjCObjectPointerType()) {
2464
4.94k
    Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2465
29.3k
  } else if (DestType->isBlockPointerType()) {
2466
2
    if (!SrcType->isBlockPointerType()) {
2467
2
      Kind = CK_AnyPointerToBlockPointerCast;
2468
2
    } else {
2469
0
      Kind = CK_BitCast;
2470
0
    }
2471
29.3k
  } else {
2472
29.3k
    Kind = CK_BitCast;
2473
29.3k
  }
2474
2475
  // Any pointer can be cast to an Objective-C pointer type with a C-style
2476
  // cast.
2477
34.9k
  if (CStyle && 
DestType->isObjCObjectPointerType()33.5k
) {
2478
4.93k
    return SuccessResult;
2479
4.93k
  }
2480
30.0k
  if (CStyle)
2481
28.6k
    DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2482
2483
30.0k
  DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2484
2485
  // Not casting away constness, so the only remaining check is for compatible
2486
  // pointer categories.
2487
2488
30.0k
  if (SrcType->isFunctionPointerType()) {
2489
1.36k
    if (DestType->isFunctionPointerType()) {
2490
      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2491
      // a pointer to a function of a different type.
2492
95
      return SuccessResult;
2493
95
    }
2494
2495
    // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2496
    //   an object type or vice versa is conditionally-supported.
2497
    // Compilers support it in C++03 too, though, because it's necessary for
2498
    // casting the return value of dlsym() and GetProcAddress().
2499
    // FIXME: Conditionally-supported behavior should be configurable in the
2500
    // TargetInfo or similar.
2501
1.26k
    Self.Diag(OpRange.getBegin(),
2502
1.26k
              Self.getLangOpts().CPlusPlus11 ?
2503
935
                diag::warn_cxx98_compat_cast_fn_obj : 
diag::ext_cast_fn_obj330
)
2504
1.26k
      << OpRange;
2505
1.26k
    return SuccessResult;
2506
1.36k
  }
2507
2508
28.6k
  if (DestType->isFunctionPointerType()) {
2509
    // See above.
2510
459
    Self.Diag(OpRange.getBegin(),
2511
459
              Self.getLangOpts().CPlusPlus11 ?
2512
324
                diag::warn_cxx98_compat_cast_fn_obj : 
diag::ext_cast_fn_obj135
)
2513
459
      << OpRange;
2514
459
    return SuccessResult;
2515
459
  }
2516
2517
  // Diagnose address space conversion in nested pointers.
2518
28.1k
  QualType DestPtee = DestType->getPointeeType().isNull()
2519
28.1k
                          ? 
DestType->getPointeeType()0
2520
28.1k
                          : DestType->getPointeeType()->getPointeeType();
2521
28.1k
  QualType SrcPtee = SrcType->getPointeeType().isNull()
2522
28.1k
                         ? 
SrcType->getPointeeType()0
2523
28.1k
                         : SrcType->getPointeeType()->getPointeeType();
2524
28.2k
  while (!DestPtee.isNull() && 
!SrcPtee.isNull()236
) {
2525
108
    if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2526
7
      Self.Diag(OpRange.getBegin(),
2527
7
                diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2528
7
          << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2529
7
      break;
2530
7
    }
2531
101
    DestPtee = DestPtee->getPointeeType();
2532
101
    SrcPtee = SrcPtee->getPointeeType();
2533
101
  }
2534
2535
  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2536
  //   a pointer to an object of different type.
2537
  // Void pointers are not specified, but supported by every compiler out there.
2538
  // So we finish by allowing everything that remains - it's got to be two
2539
  // object pointers.
2540
28.1k
  return SuccessResult;
2541
28.6k
}
2542
2543
static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2544
                                         QualType DestType, bool CStyle,
2545
565k
                                         unsigned &msg, CastKind &Kind) {
2546
565k
  if (!Self.getLangOpts().OpenCL)
2547
    // FIXME: As compiler doesn't have any information about overlapping addr
2548
    // spaces at the moment we have to be permissive here.
2549
565k
    return TC_NotApplicable;
2550
  // Even though the logic below is general enough and can be applied to
2551
  // non-OpenCL mode too, we fast-path above because no other languages
2552
  // define overlapping address spaces currently.
2553
98
  auto SrcType = SrcExpr.get()->getType();
2554
  // FIXME: Should this be generalized to references? The reference parameter
2555
  // however becomes a reference pointee type here and therefore rejected.
2556
  // Perhaps this is the right behavior though according to C++.
2557
98
  auto SrcPtrType = SrcType->getAs<PointerType>();
2558
98
  if (!SrcPtrType)
2559
21
    return TC_NotApplicable;
2560
77
  auto DestPtrType = DestType->getAs<PointerType>();
2561
77
  if (!DestPtrType)
2562
2
    return TC_NotApplicable;
2563
75
  auto SrcPointeeType = SrcPtrType->getPointeeType();
2564
75
  auto DestPointeeType = DestPtrType->getPointeeType();
2565
75
  if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
2566
36
    msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2567
36
    return TC_Failed;
2568
36
  }
2569
39
  auto SrcPointeeTypeWithoutAS =
2570
39
      Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2571
39
  auto DestPointeeTypeWithoutAS =
2572
39
      Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2573
39
  if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2574
39
                               DestPointeeTypeWithoutAS)) {
2575
13
    Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2576
13
               ? 
CK_NoOp1
2577
13
               : 
CK_AddressSpaceConversion12
;
2578
13
    return TC_Success;
2579
26
  } else {
2580
26
    return TC_NotApplicable;
2581
26
  }
2582
39
}
2583
2584
3.82M
void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2585
  // In OpenCL only conversions between pointers to objects in overlapping
2586
  // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2587
  // with any named one, except for constant.
2588
2589
  // Converting the top level pointee addrspace is permitted for compatible
2590
  // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2591
  // if any of the nested pointee addrspaces differ, we emit a warning
2592
  // regardless of addrspace compatibility. This makes
2593
  //   local int ** p;
2594
  //   return (generic int **) p;
2595
  // warn even though local -> generic is permitted.
2596
3.82M
  if (Self.getLangOpts().OpenCL) {
2597
1.30k
    const Type *DestPtr, *SrcPtr;
2598
1.30k
    bool Nested = false;
2599
1.30k
    unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2600
1.30k
    DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2601
1.30k
    SrcPtr  = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2602
2603
1.68k
    while (isa<PointerType>(DestPtr) && 
isa<PointerType>(SrcPtr)1.08k
) {
2604
473
      const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2605
473
      const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2606
473
      QualType DestPPointee = DestPPtr->getPointeeType();
2607
473
      QualType SrcPPointee = SrcPPtr->getPointeeType();
2608
473
      if (Nested
2609
473
              ? 
DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()21
2610
473
              : 
!DestPPointee.isAddressSpaceOverlapping(SrcPPointee)452
) {
2611
96
        Self.Diag(OpRange.getBegin(), DiagID)
2612
96
            << SrcType << DestType << Sema::AA_Casting
2613
96
            << SrcExpr.get()->getSourceRange();
2614
96
        if (!Nested)
2615
85
          SrcExpr = ExprError();
2616
96
        return;
2617
96
      }
2618
2619
377
      DestPtr = DestPPtr->getPointeeType().getTypePtr();
2620
377
      SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2621
377
      Nested = true;
2622
377
      DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2623
377
    }
2624
1.30k
  }
2625
3.82M
}
2626
2627
3.35M
bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) {
2628
3.35M
  bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==
2629
3.35M
                     LangOptions::AltivecSrcCompatKind::XL;
2630
3.35M
  VectorType::VectorKind VKind = VecTy->getVectorKind();
2631
2632
3.35M
  if ((VKind == VectorType::AltiVecVector) ||
2633
3.35M
      
(3.14M
SrcCompatXL3.14M
&&
(108
(VKind == VectorType::AltiVecBool)108
||
2634
213k
                       
(VKind == VectorType::AltiVecPixel)12
))) {
2635
213k
    return true;
2636
213k
  }
2637
3.14M
  return false;
2638
3.35M
}
2639
2640
bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2641
3.35M
                                      QualType SrcTy) {
2642
3.35M
  bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==
2643
3.35M
                      LangOptions::AltivecSrcCompatKind::GCC;
2644
3.35M
  if (this->getLangOpts().AltiVec && 
SrcCompatGCC201k
) {
2645
72
    this->Diag(R.getBegin(),
2646
72
               diag::err_invalid_conversion_between_vector_and_integer)
2647
72
        << VecTy << SrcTy << R;
2648
72
    return true;
2649
72
  }
2650
3.35M
  return false;
2651
3.35M
}
2652
2653
void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2654
684k
                                       bool ListInitialization) {
2655
684k
  assert(Self.getLangOpts().CPlusPlus);
2656
2657
  // Handle placeholders.
2658
684k
  if (isPlaceholder()) {
2659
    // C-style casts can resolve __unknown_any types.
2660
836
    if (claimPlaceholder(BuiltinType::UnknownAny)) {
2661
614
      SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2662
614
                                         SrcExpr.get(), Kind,
2663
614
                                         ValueKind, BasePath);
2664
614
      return;
2665
614
    }
2666
2667
222
    checkNonOverloadPlaceholders();
2668
222
    if (SrcExpr.isInvalid())
2669
0
      return;
2670
222
  }
2671
2672
  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2673
  // This test is outside everything else because it's the only case where
2674
  // a non-lvalue-reference target type does not lead to decay.
2675
684k
  if (DestType->isVoidType()) {
2676
69.2k
    Kind = CK_ToVoid;
2677
2678
69.2k
    if (claimPlaceholder(BuiltinType::Overload)) {
2679
51
      Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2680
51
                  SrcExpr, /* Decay Function to ptr */ false,
2681
51
                  /* Complain */ true, DestRange, DestType,
2682
51
                  diag::err_bad_cstyle_cast_overload);
2683
51
      if (SrcExpr.isInvalid())
2684
13
        return;
2685
51
    }
2686
2687
69.2k
    SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2688
69.2k
    return;
2689
69.2k
  }
2690
2691
  // If the type is dependent, we won't do any other semantic analysis now.
2692
614k
  if (DestType->isDependentType() || 
SrcExpr.get()->isTypeDependent()604k
||
2693
614k
      
SrcExpr.get()->isValueDependent()577k
) {
2694
39.1k
    assert(Kind == CK_Dependent);
2695
0
    return;
2696
39.1k
  }
2697
2698
575k
  if (ValueKind == VK_PRValue && 
!DestType->isRecordType()575k
&&
2699
575k
      
!isPlaceholder(BuiltinType::Overload)549k
) {
2700
549k
    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2701
549k
    if (SrcExpr.isInvalid())
2702
2
      return;
2703
549k
  }
2704
2705
  // AltiVec vector initialization with a single literal.
2706
575k
  if (const VectorType *vecTy = DestType->getAs<VectorType>()) {
2707
330k
    if (Self.CheckAltivecInitFromScalar(OpRange, DestType,
2708
330k
                                        SrcExpr.get()->getType())) {
2709
0
      SrcExpr = ExprError();
2710
0
      return;
2711
0
    }
2712
330k
    if (Self.ShouldSplatAltivecScalarInCast(vecTy) &&
2713
330k
        
(22.0k
SrcExpr.get()->getType()->isIntegerType()22.0k
||
2714
22.0k
         
SrcExpr.get()->getType()->isFloatingType()20.9k
)) {
2715
1.29k
      Kind = CK_VectorSplat;
2716
1.29k
      SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2717
1.29k
      return;
2718
1.29k
    }
2719
330k
  }
2720
2721
  // C++ [expr.cast]p5: The conversions performed by
2722
  //   - a const_cast,
2723
  //   - a static_cast,
2724
  //   - a static_cast followed by a const_cast,
2725
  //   - a reinterpret_cast, or
2726
  //   - a reinterpret_cast followed by a const_cast,
2727
  //   can be performed using the cast notation of explicit type conversion.
2728
  //   [...] If a conversion can be interpreted in more than one of the ways
2729
  //   listed above, the interpretation that appears first in the list is used,
2730
  //   even if a cast resulting from that interpretation is ill-formed.
2731
  // In plain language, this means trying a const_cast ...
2732
  // Note that for address space we check compatibility after const_cast.
2733
574k
  unsigned msg = diag::err_bad_cxx_cast_generic;
2734
574k
  TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2735
574k
                                   /*CStyle*/ true, msg);
2736
574k
  if (SrcExpr.isInvalid())
2737
0
    return;
2738
574k
  if (isValidCast(tcr))
2739
8.54k
    Kind = CK_NoOp;
2740
2741
574k
  Sema::CheckedConversionKind CCK =
2742
574k
      FunctionalStyle ? 
Sema::CCK_FunctionalCast59.4k
:
Sema::CCK_CStyleCast515k
;
2743
574k
  if (tcr == TC_NotApplicable) {
2744
565k
    tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2745
565k
                              Kind);
2746
565k
    if (SrcExpr.isInvalid())
2747
0
      return;
2748
2749
565k
    if (tcr == TC_NotApplicable) {
2750
      // ... or if that is not possible, a static_cast, ignoring const and
2751
      // addr space, ...
2752
565k
      tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2753
565k
                          BasePath, ListInitialization);
2754
565k
      if (SrcExpr.isInvalid())
2755
6
        return;
2756
2757
565k
      if (tcr == TC_NotApplicable) {
2758
        // ... and finally a reinterpret_cast, ignoring const and addr space.
2759
42.2k
        tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2760
42.2k
                                 OpRange, msg, Kind);
2761
42.2k
        if (SrcExpr.isInvalid())
2762
0
          return;
2763
42.2k
      }
2764
565k
    }
2765
565k
  }
2766
2767
574k
  if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2768
574k
      
isValidCast(tcr)13.8k
)
2769
13.8k
    checkObjCConversion(CCK);
2770
2771
574k
  if (tcr != TC_Success && 
msg != 0227
) {
2772
174
    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2773
9
      DeclAccessPair Found;
2774
9
      FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2775
9
                                DestType,
2776
9
                                /*Complain*/ true,
2777
9
                                Found);
2778
9
      if (Fn) {
2779
        // If DestType is a function type (not to be confused with the function
2780
        // pointer type), it will be possible to resolve the function address,
2781
        // but the type cast should be considered as failure.
2782
1
        OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2783
1
        Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2784
1
          << OE->getName() << DestType << OpRange
2785
1
          << OE->getQualifierLoc().getSourceRange();
2786
1
        Self.NoteAllOverloadCandidates(SrcExpr.get());
2787
1
      }
2788
165
    } else {
2789
165
      diagnoseBadCast(Self, msg, (FunctionalStyle ? 
CT_Functional49
:
CT_CStyle116
),
2790
165
                      OpRange, SrcExpr.get(), DestType, ListInitialization);
2791
165
    }
2792
174
  }
2793
2794
574k
  if (isValidCast(tcr)) {
2795
574k
    if (Kind == CK_BitCast)
2796
55.4k
      checkCastAlign();
2797
2798
574k
    if (!checkCastFunctionType(Self, SrcExpr, DestType))
2799
6
      Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
2800
6
          << SrcExpr.get()->getType() << DestType << OpRange;
2801
2802
574k
  } else {
2803
227
    SrcExpr = ExprError();
2804
227
  }
2805
574k
}
2806
2807
/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2808
///  non-matching type. Such as enum function call to int, int call to
2809
/// pointer; etc. Cast to 'void' is an exception.
2810
static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2811
740k
                                  QualType DestType) {
2812
740k
  if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2813
740k
                           SrcExpr.get()->getExprLoc()))
2814
740k
    return;
2815
2816
27
  if (!isa<CallExpr>(SrcExpr.get()))
2817
4
    return;
2818
2819
23
  QualType SrcType = SrcExpr.get()->getType();
2820
23
  if (DestType.getUnqualifiedType()->isVoidType())
2821
0
    return;
2822
23
  if ((SrcType->isAnyPointerType() || 
SrcType->isBlockPointerType()19
)
2823
23
      && 
(4
DestType->isAnyPointerType()4
||
DestType->isBlockPointerType()2
))
2824
2
    return;
2825
21
  if (SrcType->isIntegerType() && 
DestType->isIntegerType()11
&&
2826
21
      
(SrcType->isBooleanType() == DestType->isBooleanType())8
&&
2827
21
      
(SrcType->isEnumeralType() == DestType->isEnumeralType())6
)
2828
5
    return;
2829
16
  if (SrcType->isRealFloatingType() && 
DestType->isRealFloatingType()4
)
2830
2
    return;
2831
14
  if (SrcType->isEnumeralType() && 
DestType->isEnumeralType()1
)
2832
0
    return;
2833
14
  if (SrcType->isComplexType() && 
DestType->isComplexType()2
)
2834
1
    return;
2835
13
  if (SrcType->isComplexIntegerType() && 
DestType->isComplexIntegerType()0
)
2836
0
    return;
2837
13
  if (SrcType->isFixedPointType() && 
DestType->isFixedPointType()2
)
2838
1
    return;
2839
2840
12
  Self.Diag(SrcExpr.get()->getExprLoc(),
2841
12
            diag::warn_bad_function_cast)
2842
12
            << SrcType << DestType << SrcExpr.get()->getSourceRange();
2843
12
}
2844
2845
/// Check the semantics of a C-style cast operation, in C.
2846
3.82M
void CastOperation::CheckCStyleCast() {
2847
3.82M
  assert(!Self.getLangOpts().CPlusPlus);
2848
2849
  // C-style casts can resolve __unknown_any types.
2850
3.82M
  if (claimPlaceholder(BuiltinType::UnknownAny)) {
2851
5
    SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2852
5
                                       SrcExpr.get(), Kind,
2853
5
                                       ValueKind, BasePath);
2854
5
    return;
2855
5
  }
2856
2857
  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2858
  // type needs to be scalar.
2859
3.82M
  if (DestType->isVoidType()) {
2860
    // We don't necessarily do lvalue-to-rvalue conversions on this.
2861
4.77k
    SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2862
4.77k
    if (SrcExpr.isInvalid())
2863
0
      return;
2864
2865
    // Cast to void allows any expr type.
2866
4.77k
    Kind = CK_ToVoid;
2867
4.77k
    return;
2868
4.77k
  }
2869
2870
  // If the type is dependent, we won't do any other semantic analysis now.
2871
3.82M
  if (Self.getASTContext().isDependenceAllowed() &&
2872
3.82M
      (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2873
3.82M
       
SrcExpr.get()->isValueDependent()3.82M
)) {
2874
359
    assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||
2875
359
            SrcExpr.get()->containsErrors()) &&
2876
359
           "should only occur in error-recovery path.");
2877
0
    assert(Kind == CK_Dependent);
2878
0
    return;
2879
359
  }
2880
2881
  // Overloads are allowed with C extensions, so we need to support them.
2882
3.82M
  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2883
20
    DeclAccessPair DAP;
2884
20
    if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2885
20
            SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2886
16
      SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2887
4
    else
2888
4
      return;
2889
16
    assert(SrcExpr.isUsable());
2890
16
  }
2891
3.82M
  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2892
3.82M
  if (SrcExpr.isInvalid())
2893
2
    return;
2894
3.82M
  QualType SrcType = SrcExpr.get()->getType();
2895
2896
3.82M
  assert(!SrcType->isPlaceholderType());
2897
2898
0
  checkAddressSpaceCast(SrcType, DestType);
2899
3.82M
  if (SrcExpr.isInvalid())
2900
85
    return;
2901
2902
3.82M
  if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2903
3.82M
                               diag::err_typecheck_cast_to_incomplete)) {
2904
4
    SrcExpr = ExprError();
2905
4
    return;
2906
4
  }
2907
2908
  // Allow casting a sizeless built-in type to itself.
2909
3.82M
  if (DestType->isSizelessBuiltinType() &&
2910
3.82M
      
Self.Context.hasSameUnqualifiedType(DestType, SrcType)75.0k
) {
2911
75.0k
    Kind = CK_NoOp;
2912
75.0k
    return;
2913
75.0k
  }
2914
2915
  // Allow bitcasting between compatible SVE vector types.
2916
3.74M
  if ((SrcType->isVectorType() || 
DestType->isVectorType()753k
) &&
2917
3.74M
      
Self.isValidSveBitcast(SrcType, DestType)3.00M
) {
2918
160
    Kind = CK_BitCast;
2919
160
    return;
2920
160
  }
2921
2922
3.74M
  if (!DestType->isScalarType() && 
!DestType->isVectorType()3.00M
&&
2923
3.74M
      
!DestType->isMatrixType()73
) {
2924
44
    const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2925
2926
44
    if (DestRecordTy && 
Self.Context.hasSameUnqualifiedType(DestType, SrcType)31
){
2927
      // GCC struct/union extension: allow cast to self.
2928
6
      Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2929
6
        << DestType << SrcExpr.get()->getSourceRange();
2930
6
      Kind = CK_NoOp;
2931
6
      return;
2932
6
    }
2933
2934
    // GCC's cast to union extension.
2935
38
    if (DestRecordTy && 
DestRecordTy->getDecl()->isUnion()25
) {
2936
24
      RecordDecl *RD = DestRecordTy->getDecl();
2937
24
      if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2938
21
        Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2939
21
          << SrcExpr.get()->getSourceRange();
2940
21
        Kind = CK_ToUnion;
2941
21
        return;
2942
21
      } else {
2943
3
        Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2944
3
          << SrcType << SrcExpr.get()->getSourceRange();
2945
3
        SrcExpr = ExprError();
2946
3
        return;
2947
3
      }
2948
24
    }
2949
2950
    // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2951
14
    if (Self.getLangOpts().OpenCL && 
DestType->isEventT()2
) {
2952
2
      Expr::EvalResult Result;
2953
2
      if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2954
2
        llvm::APSInt CastInt = Result.Val.getInt();
2955
2
        if (0 == CastInt) {
2956
1
          Kind = CK_ZeroToOCLOpaqueType;
2957
1
          return;
2958
1
        }
2959
1
        Self.Diag(OpRange.getBegin(),
2960
1
                  diag::err_opencl_cast_non_zero_to_event_t)
2961
1
                  << toString(CastInt, 10) << SrcExpr.get()->getSourceRange();
2962
1
        SrcExpr = ExprError();
2963
1
        return;
2964
2
      }
2965
2
    }
2966
2967
    // Reject any other conversions to non-scalar types.
2968
12
    Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2969
12
      << DestType << SrcExpr.get()->getSourceRange();
2970
12
    SrcExpr = ExprError();
2971
12
    return;
2972
14
  }
2973
2974
  // The type we're casting to is known to be a scalar, a vector, or a matrix.
2975
2976
  // Require the operand to be a scalar, a vector, or a matrix.
2977
3.74M
  if (!SrcType->isScalarType() && 
!SrcType->isVectorType()2.99M
&&
2978
3.74M
      
!SrcType->isMatrixType()48
) {
2979
19
    Self.Diag(SrcExpr.get()->getExprLoc(),
2980
19
              diag::err_typecheck_expect_scalar_operand)
2981
19
      << SrcType << SrcExpr.get()->getSourceRange();
2982
19
    SrcExpr = ExprError();
2983
19
    return;
2984
19
  }
2985
2986
3.74M
  if (DestType->isExtVectorType()) {
2987
82
    SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2988
82
    return;
2989
82
  }
2990
2991
3.74M
  if (DestType->getAs<MatrixType>() || 
SrcType->getAs<MatrixType>()3.74M
) {
2992
33
    if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))
2993
11
      SrcExpr = ExprError();
2994
33
    return;
2995
33
  }
2996
2997
3.74M
  if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2998
3.00M
    if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) {
2999
36
      SrcExpr = ExprError();
3000
36
      return;
3001
36
    }
3002
3.00M
    if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) &&
3003
3.00M
        
(171k
SrcType->isIntegerType()171k
||
SrcType->isFloatingType()163k
)) {
3004
9.37k
      Kind = CK_VectorSplat;
3005
9.37k
      SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
3006
2.99M
    } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
3007
42
      SrcExpr = ExprError();
3008
42
    }
3009
3.00M
    return;
3010
3.00M
  }
3011
3012
744k
  if (SrcType->isVectorType()) {
3013
3.43k
    if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
3014
3
      SrcExpr = ExprError();
3015
3.43k
    return;
3016
3.43k
  }
3017
3018
  // The source and target types are both scalars, i.e.
3019
  //   - arithmetic types (fundamental, enum, and complex)
3020
  //   - all kinds of pointers
3021
  // Note that member pointers were filtered out with C++, above.
3022
3023
740k
  if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
3024
2
    Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
3025
2
    SrcExpr = ExprError();
3026
2
    return;
3027
2
  }
3028
3029
  // Can't cast to or from bfloat
3030
740k
  if (DestType->isBFloat16Type() && 
!SrcType->isBFloat16Type()165
) {
3031
4
    Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
3032
4
        << SrcExpr.get()->getSourceRange();
3033
4
    SrcExpr = ExprError();
3034
4
    return;
3035
4
  }
3036
740k
  if (SrcType->isBFloat16Type() && 
!DestType->isBFloat16Type()163
) {
3037
2
    Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
3038
2
        << SrcExpr.get()->getSourceRange();
3039
2
    SrcExpr = ExprError();
3040
2
    return;
3041
2
  }
3042
3043
  // If either type is a pointer, the other type has to be either an
3044
  // integer or a pointer.
3045
740k
  if (!DestType->isArithmeticType()) {
3046
154k
    if (!SrcType->isIntegralType(Self.Context) && 
SrcType->isArithmeticType()147k
) {
3047
1
      Self.Diag(SrcExpr.get()->getExprLoc(),
3048
1
                diag::err_cast_pointer_from_non_pointer_int)
3049
1
        << SrcType << SrcExpr.get()->getSourceRange();
3050
1
      SrcExpr = ExprError();
3051
1
      return;
3052
1
    }
3053
154k
    checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
3054
154k
                          Self);
3055
586k
  } else if (!SrcType->isArithmeticType()) {
3056
3.14k
    if (!DestType->isIntegralType(Self.Context) &&
3057
3.14k
        
DestType->isArithmeticType()1
) {
3058
1
      Self.Diag(SrcExpr.get()->getBeginLoc(),
3059
1
                diag::err_cast_pointer_to_non_pointer_int)
3060
1
          << DestType << SrcExpr.get()->getSourceRange();
3061
1
      SrcExpr = ExprError();
3062
1
      return;
3063
1
    }
3064
3065
3.14k
    if ((Self.Context.getTypeSize(SrcType) >
3066
3.14k
         Self.Context.getTypeSize(DestType)) &&
3067
3.14k
        
!DestType->isBooleanType()92
) {
3068
      // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3069
      // Except as previously specified, the result is implementation-defined.
3070
      // If the result cannot be represented in the integer type, the behavior
3071
      // is undefined. The result need not be in the range of values of any
3072
      // integer type.
3073
80
      unsigned Diag;
3074
80
      if (SrcType->isVoidPointerType())
3075
28
        Diag = DestType->isEnumeralType() ? 
diag::warn_void_pointer_to_enum_cast2
3076
28
                                          : 
diag::warn_void_pointer_to_int_cast26
;
3077
52
      else if (DestType->isEnumeralType())
3078
2
        Diag = diag::warn_pointer_to_enum_cast;
3079
50
      else
3080
50
        Diag = diag::warn_pointer_to_int_cast;
3081
80
      Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
3082
80
    }
3083
3.14k
  }
3084
3085
740k
  if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
3086
1.15k
                                       "cl_khr_fp16", Self.getLangOpts())) {
3087
1.08k
    if (DestType->isHalfType()) {
3088
2
      Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
3089
2
          << DestType << SrcExpr.get()->getSourceRange();
3090
2
      SrcExpr = ExprError();
3091
2
      return;
3092
2
    }
3093
1.08k
  }
3094
3095
  // ARC imposes extra restrictions on casts.
3096
740k
  if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3097
850
    checkObjCConversion(Sema::CCK_CStyleCast);
3098
850
    if (SrcExpr.isInvalid())
3099
0
      return;
3100
3101
850
    const PointerType *CastPtr = DestType->getAs<PointerType>();
3102
850
    if (Self.getLangOpts().ObjCAutoRefCount && 
CastPtr839
) {
3103
336
      if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
3104
142
        Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
3105
142
        Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
3106
142
        if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
3107
142
            
ExprPtr->getPointeeType()->isObjCLifetimeType()42
&&
3108
142
            
!CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)33
) {
3109
14
          Self.Diag(SrcExpr.get()->getBeginLoc(),
3110
14
                    diag::err_typecheck_incompatible_ownership)
3111
14
              << SrcType << DestType << Sema::AA_Casting
3112
14
              << SrcExpr.get()->getSourceRange();
3113
14
          return;
3114
14
        }
3115
142
      }
3116
336
    }
3117
514
    else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
3118
4
      Self.Diag(SrcExpr.get()->getBeginLoc(),
3119
4
                diag::err_arc_convesion_of_weak_unavailable)
3120
4
          << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3121
4
      SrcExpr = ExprError();
3122
4
      return;
3123
4
    }
3124
850
  }
3125
3126
740k
  if (!checkCastFunctionType(Self, SrcExpr, DestType))
3127
3
    Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
3128
3
        << SrcType << DestType << OpRange;
3129
3130
740k
  DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
3131
740k
  DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
3132
740k
  DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
3133
740k
  Kind = Self.PrepareScalarCast(SrcExpr, DestType);
3134
740k
  if (SrcExpr.isInvalid())
3135
0
    return;
3136
3137
740k
  if (Kind == CK_BitCast)
3138
102k
    checkCastAlign();
3139
740k
}
3140
3141
688
void CastOperation::CheckBuiltinBitCast() {
3142
688
  QualType SrcType = SrcExpr.get()->getType();
3143
3144
688
  if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3145
688
                               diag::err_typecheck_cast_to_incomplete) ||
3146
688
      Self.RequireCompleteType(OpRange.getBegin(), SrcType,
3147
688
                               diag::err_incomplete_type)) {
3148
0
    SrcExpr = ExprError();
3149
0
    return;
3150
0
  }
3151
3152
688
  if (SrcExpr.get()->isPRValue())
3153
77
    SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
3154
77
                                                  /*IsLValueReference=*/false);
3155
3156
688
  CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
3157
688
  CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
3158
688
  if (DestSize != SourceSize) {
3159
2
    Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
3160
2
        << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
3161
2
    SrcExpr = ExprError();
3162
2
    return;
3163
2
  }
3164
3165
686
  if (!DestType.isTriviallyCopyableType(Self.Context)) {
3166
2
    Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3167
2
        << 1;
3168
2
    SrcExpr = ExprError();
3169
2
    return;
3170
2
  }
3171
3172
684
  if (!SrcType.isTriviallyCopyableType(Self.Context)) {
3173
2
    Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3174
2
        << 0;
3175
2
    SrcExpr = ExprError();
3176
2
    return;
3177
2
  }
3178
3179
682
  Kind = CK_LValueToRValueBitCast;
3180
682
}
3181
3182
/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3183
/// const, volatile or both.
3184
static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
3185
4.45M
                             QualType DestType) {
3186
4.45M
  if (SrcExpr.isInvalid())
3187
0
    return;
3188
3189
4.45M
  QualType SrcType = SrcExpr.get()->getType();
3190
4.45M
  if (!((SrcType->isAnyPointerType() && 
DestType->isAnyPointerType()245k
) ||
3191
4.45M
        
DestType->isLValueReferenceType()4.21M
))
3192
4.21M
    return;
3193
3194
237k
  QualType TheOffendingSrcType, TheOffendingDestType;
3195
237k
  Qualifiers CastAwayQualifiers;
3196
237k
  if (CastsAwayConstness(Self, SrcType, DestType, true, false,
3197
237k
                         &TheOffendingSrcType, &TheOffendingDestType,
3198
237k
                         &CastAwayQualifiers) !=
3199
237k
      CastAwayConstnessKind::CACK_Similar)
3200
223k
    return;
3201
3202
  // FIXME: 'restrict' is not properly handled here.
3203
13.9k
  int qualifiers = -1;
3204
13.9k
  if (CastAwayQualifiers.hasConst() && 
CastAwayQualifiers.hasVolatile()13.7k
) {
3205
14
    qualifiers = 0;
3206
13.8k
  } else if (CastAwayQualifiers.hasConst()) {
3207
13.7k
    qualifiers = 1;
3208
13.7k
  } else 
if (138
CastAwayQualifiers.hasVolatile()138
) {
3209
116
    qualifiers = 2;
3210
116
  }
3211
  // This is a variant of int **x; const int **y = (const int **)x;
3212
13.9k
  if (qualifiers == -1)
3213
22
    Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
3214
22
        << SrcType << DestType;
3215
13.8k
  else
3216
13.8k
    Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
3217
13.8k
        << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3218
13.9k
}
3219
3220
ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
3221
                                     TypeSourceInfo *CastTypeInfo,
3222
                                     SourceLocation RPLoc,
3223
4.45M
                                     Expr *CastExpr) {
3224
4.45M
  CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3225
4.45M
  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3226
4.45M
  Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
3227
3228
4.45M
  if (getLangOpts().CPlusPlus) {
3229
624k
    Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3230
624k
                          isa<InitListExpr>(CastExpr));
3231
3.82M
  } else {
3232
3.82M
    Op.CheckCStyleCast();
3233
3.82M
  }
3234
3235
4.45M
  if (Op.SrcExpr.isInvalid())
3236
416
    return ExprError();
3237
3238
  // -Wcast-qual
3239
4.45M
  DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3240
3241
4.45M
  return Op.complete(CStyleCastExpr::Create(
3242
4.45M
      Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3243
4.45M
      &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
3244
4.45M
}
3245
3246
ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
3247
                                            QualType Type,
3248
                                            SourceLocation LPLoc,
3249
                                            Expr *CastExpr,
3250
59.9k
                                            SourceLocation RPLoc) {
3251
59.9k
  assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
3252
0
  CastOperation Op(*this, Type, CastExpr);
3253
59.9k
  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3254
59.9k
  Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
3255
3256
59.9k
  Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3257
59.9k
  if (Op.SrcExpr.isInvalid())
3258
75
    return ExprError();
3259
3260
59.8k
  auto *SubExpr = Op.SrcExpr.get();
3261
59.8k
  if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
3262
5.48k
    SubExpr = BindExpr->getSubExpr();
3263
59.8k
  if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
3264
25.2k
    ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
3265
3266
59.8k
  return Op.complete(CXXFunctionalCastExpr::Create(
3267
59.8k
      Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
3268
59.8k
      Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
3269
59.9k
}