forked from apple/swift-clang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SemaCast.cpp
2785 lines (2467 loc) · 107 KB
/
SemaCast.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for cast expressions, including
// 1) C-style casts like '(int) x'
// 2) C++ functional casts like 'int(x)'
// 3) C++ named casts like 'static_cast<int>(x)'
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "llvm/ADT/SmallVector.h"
#include <set>
using namespace clang;
enum TryCastResult {
TC_NotApplicable, ///< The cast method is not applicable.
TC_Success, ///< The cast method is appropriate and successful.
TC_Extension, ///< The cast method is appropriate and accepted as a
///< language extension.
TC_Failed ///< The cast method is appropriate, but failed. A
///< diagnostic has been emitted.
};
static bool isValidCast(TryCastResult TCR) {
return TCR == TC_Success || TCR == TC_Extension;
}
enum CastType {
CT_Const, ///< const_cast
CT_Static, ///< static_cast
CT_Reinterpret, ///< reinterpret_cast
CT_Dynamic, ///< dynamic_cast
CT_CStyle, ///< (Type)expr
CT_Functional ///< Type(expr)
};
namespace {
struct CastOperation {
CastOperation(Sema &S, QualType destType, ExprResult src)
: Self(S), SrcExpr(src), DestType(destType),
ResultType(destType.getNonLValueExprType(S.Context)),
ValueKind(Expr::getValueKindForType(destType)),
Kind(CK_Dependent), IsARCUnbridgedCast(false) {
if (const BuiltinType *placeholder =
src.get()->getType()->getAsPlaceholderType()) {
PlaceholderKind = placeholder->getKind();
} else {
PlaceholderKind = (BuiltinType::Kind) 0;
}
}
Sema &Self;
ExprResult SrcExpr;
QualType DestType;
QualType ResultType;
ExprValueKind ValueKind;
CastKind Kind;
BuiltinType::Kind PlaceholderKind;
CXXCastPath BasePath;
bool IsARCUnbridgedCast;
SourceRange OpRange;
SourceRange DestRange;
// Top-level semantics-checking routines.
void CheckConstCast();
void CheckReinterpretCast();
void CheckStaticCast();
void CheckDynamicCast();
void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
void CheckCStyleCast();
void updatePartOfExplicitCastFlags(CastExpr *CE) {
// Walk down from the CE to the OrigSrcExpr, and mark all immediate
// ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
// (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
ICE->setIsPartOfExplicitCast(true);
}
/// Complete an apparently-successful cast operation that yields
/// the given expression.
ExprResult complete(CastExpr *castExpr) {
// If this is an unbridged cast, wrap the result in an implicit
// cast that yields the unbridged-cast placeholder type.
if (IsARCUnbridgedCast) {
castExpr = ImplicitCastExpr::Create(Self.Context,
Self.Context.ARCUnbridgedCastTy,
CK_Dependent, castExpr, nullptr,
castExpr->getValueKind());
}
updatePartOfExplicitCastFlags(castExpr);
return castExpr;
}
// Internal convenience methods.
/// Try to handle the given placeholder expression kind. Return
/// true if the source expression has the appropriate placeholder
/// kind. A placeholder can only be claimed once.
bool claimPlaceholder(BuiltinType::Kind K) {
if (PlaceholderKind != K) return false;
PlaceholderKind = (BuiltinType::Kind) 0;
return true;
}
bool isPlaceholder() const {
return PlaceholderKind != 0;
}
bool isPlaceholder(BuiltinType::Kind K) const {
return PlaceholderKind == K;
}
// Language specific cast restrictions for address spaces.
void checkAddressSpaceCast(QualType SrcType, QualType DestType);
void checkCastAlign() {
Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
}
void checkObjCConversion(Sema::CheckedConversionKind CCK) {
assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
Expr *src = SrcExpr.get();
if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
Sema::ACR_unbridged)
IsARCUnbridgedCast = true;
SrcExpr = src;
}
/// Check for and handle non-overload placeholder expressions.
void checkNonOverloadPlaceholders() {
if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
return;
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid())
return;
PlaceholderKind = (BuiltinType::Kind) 0;
}
};
}
static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
QualType DestType);
// The Try functions attempt a specific way of casting. If they succeed, they
// return TC_Success. If their way of casting is not appropriate for the given
// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
// to emit if no other way succeeds. If their way of casting is appropriate but
// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
// they emit a specialized diagnostic.
// All diagnostics returned by these functions must expect the same three
// arguments:
// %0: Cast Type (a value from the CastType enumeration)
// %1: Source Type
// %2: Destination Type
static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
CastKind &Kind,
CXXCastPath &BasePath,
unsigned &msg);
static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
SourceRange OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
QualType DestType, bool CStyle,
SourceRange OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
CanQualType DestType, bool CStyle,
SourceRange OpRange,
QualType OrigSrcType,
QualType OrigDestType, unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
QualType SrcType,
QualType DestType,bool CStyle,
SourceRange OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
SourceRange OpRange,
unsigned &msg, CastKind &Kind,
bool ListInitialization);
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
SourceRange OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath,
bool ListInitialization);
static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
unsigned &msg);
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
SourceRange OpRange,
unsigned &msg,
CastKind &Kind);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult
Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
SourceLocation LAngleBracketLoc, Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc, Expr *E,
SourceLocation RParenLoc) {
assert(!D.isInvalidType());
TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
if (D.isInvalidType())
return ExprError();
if (getLangOpts().CPlusPlus) {
// Check that there are no default arguments (C++ only).
CheckExtraCXXDefaultArguments(D);
}
return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
SourceRange(LAngleBracketLoc, RAngleBracketLoc),
SourceRange(LParenLoc, RParenLoc));
}
ExprResult
Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
TypeSourceInfo *DestTInfo, Expr *E,
SourceRange AngleBrackets, SourceRange Parens) {
ExprResult Ex = E;
QualType DestType = DestTInfo->getType();
// If the type is dependent, we won't do the semantic analysis now.
bool TypeDependent =
DestType->isDependentType() || Ex.get()->isTypeDependent();
CastOperation Op(*this, DestType, E);
Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
Op.DestRange = AngleBrackets;
switch (Kind) {
default: llvm_unreachable("Unknown C++ cast!");
case tok::kw_const_cast:
if (!TypeDependent) {
Op.CheckConstCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
}
return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
case tok::kw_dynamic_cast: {
// OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
if (getLangOpts().OpenCLCPlusPlus) {
return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
<< "dynamic_cast");
}
if (!TypeDependent) {
Op.CheckDynamicCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
}
case tok::kw_reinterpret_cast: {
if (!TypeDependent) {
Op.CheckReinterpretCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
}
return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
nullptr, DestTInfo, OpLoc,
Parens.getEnd(),
AngleBrackets));
}
case tok::kw_static_cast: {
if (!TypeDependent) {
Op.CheckStaticCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
}
return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
}
}
}
/// Try to diagnose a failed overloaded cast. Returns true if
/// diagnostics were emitted.
static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
SourceRange range, Expr *src,
QualType destType,
bool listInitialization) {
switch (CT) {
// These cast kinds don't consider user-defined conversions.
case CT_Const:
case CT_Reinterpret:
case CT_Dynamic:
return false;
// These do.
case CT_Static:
case CT_CStyle:
case CT_Functional:
break;
}
QualType srcType = src->getType();
if (!destType->isRecordType() && !srcType->isRecordType())
return false;
InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
InitializationKind initKind
= (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
range, listInitialization)
: (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
listInitialization)
: InitializationKind::CreateCast(/*type range?*/ range);
InitializationSequence sequence(S, entity, initKind, src);
assert(sequence.Failed() && "initialization succeeded on second try?");
switch (sequence.getFailureKind()) {
default: return false;
case InitializationSequence::FK_ConstructorOverloadFailed:
case InitializationSequence::FK_UserConversionOverloadFailed:
break;
}
OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
unsigned msg = 0;
OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
switch (sequence.getFailedOverloadResult()) {
case OR_Success: llvm_unreachable("successful failed overload");
case OR_No_Viable_Function:
if (candidates.empty())
msg = diag::err_ovl_no_conversion_in_cast;
else
msg = diag::err_ovl_no_viable_conversion_in_cast;
howManyCandidates = OCD_AllCandidates;
break;
case OR_Ambiguous:
msg = diag::err_ovl_ambiguous_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
case OR_Deleted:
msg = diag::err_ovl_deleted_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
}
S.Diag(range.getBegin(), msg)
<< CT << srcType << destType
<< range << src->getSourceRange();
candidates.NoteCandidates(S, howManyCandidates, src);
return true;
}
/// Diagnose a failed cast.
static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
SourceRange opRange, Expr *src, QualType destType,
bool listInitialization) {
if (msg == diag::err_bad_cxx_cast_generic &&
tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
listInitialization))
return;
S.Diag(opRange.getBegin(), msg) << castType
<< src->getType() << destType << opRange << src->getSourceRange();
// Detect if both types are (ptr to) class, and note any incompleteness.
int DifferentPtrness = 0;
QualType From = destType;
if (auto Ptr = From->getAs<PointerType>()) {
From = Ptr->getPointeeType();
DifferentPtrness++;
}
QualType To = src->getType();
if (auto Ptr = To->getAs<PointerType>()) {
To = Ptr->getPointeeType();
DifferentPtrness--;
}
if (!DifferentPtrness) {
auto RecFrom = From->getAs<RecordType>();
auto RecTo = To->getAs<RecordType>();
if (RecFrom && RecTo) {
auto DeclFrom = RecFrom->getAsCXXRecordDecl();
if (!DeclFrom->isCompleteDefinition())
S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
<< DeclFrom->getDeclName();
auto DeclTo = RecTo->getAsCXXRecordDecl();
if (!DeclTo->isCompleteDefinition())
S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
<< DeclTo->getDeclName();
}
}
}
namespace {
/// The kind of unwrapping we did when determining whether a conversion casts
/// away constness.
enum CastAwayConstnessKind {
/// The conversion does not cast away constness.
CACK_None = 0,
/// We unwrapped similar types.
CACK_Similar = 1,
/// We unwrapped dissimilar types with similar representations (eg, a pointer
/// versus an Objective-C object pointer).
CACK_SimilarKind = 2,
/// We unwrapped representationally-unrelated types, such as a pointer versus
/// a pointer-to-member.
CACK_Incoherent = 3,
};
}
/// Unwrap one level of types for CastsAwayConstness.
///
/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
/// both types, provided that they're both pointer-like or array-like. Unlike
/// the Sema function, doesn't care if the unwrapped pieces are related.
///
/// This function may remove additional levels as necessary for correctness:
/// the resulting T1 is unwrapped sufficiently that it is never an array type,
/// so that its qualifiers can be directly compared to those of T2 (which will
/// have the combined set of qualifiers from all indermediate levels of T2),
/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
/// with those from T2.
static CastAwayConstnessKind
unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
enum { None, Ptr, MemPtr, BlockPtr, Array };
auto Classify = [](QualType T) {
if (T->isAnyPointerType()) return Ptr;
if (T->isMemberPointerType()) return MemPtr;
if (T->isBlockPointerType()) return BlockPtr;
// We somewhat-arbitrarily don't look through VLA types here. This is at
// least consistent with the behavior of UnwrapSimilarTypes.
if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
return None;
};
auto Unwrap = [&](QualType T) {
if (auto *AT = Context.getAsArrayType(T))
return AT->getElementType();
return T->getPointeeType();
};
CastAwayConstnessKind Kind;
if (T2->isReferenceType()) {
// Special case: if the destination type is a reference type, unwrap it as
// the first level. (The source will have been an lvalue expression in this
// case, so there is no corresponding "reference to" in T1 to remove.) This
// simulates removing a "pointer to" from both sides.
T2 = T2->getPointeeType();
Kind = CastAwayConstnessKind::CACK_Similar;
} else if (Context.UnwrapSimilarTypes(T1, T2)) {
Kind = CastAwayConstnessKind::CACK_Similar;
} else {
// Try unwrapping mismatching levels.
int T1Class = Classify(T1);
if (T1Class == None)
return CastAwayConstnessKind::CACK_None;
int T2Class = Classify(T2);
if (T2Class == None)
return CastAwayConstnessKind::CACK_None;
T1 = Unwrap(T1);
T2 = Unwrap(T2);
Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
: CastAwayConstnessKind::CACK_Incoherent;
}
// We've unwrapped at least one level. If the resulting T1 is a (possibly
// multidimensional) array type, any qualifier on any matching layer of
// T2 is considered to correspond to T1. Decompose down to the element
// type of T1 so that we can compare properly.
while (true) {
Context.UnwrapSimilarArrayTypes(T1, T2);
if (Classify(T1) != Array)
break;
auto T2Class = Classify(T2);
if (T2Class == None)
break;
if (T2Class != Array)
Kind = CastAwayConstnessKind::CACK_Incoherent;
else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
Kind = CastAwayConstnessKind::CACK_SimilarKind;
T1 = Unwrap(T1);
T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
}
return Kind;
}
/// Check if the pointer conversion from SrcType to DestType casts away
/// constness as defined in C++ [expr.const.cast]. This is used by the cast
/// checkers. Both arguments must denote pointer (possibly to member) types.
///
/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
static CastAwayConstnessKind
CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
bool CheckCVR, bool CheckObjCLifetime,
QualType *TheOffendingSrcType = nullptr,
QualType *TheOffendingDestType = nullptr,
Qualifiers *CastAwayQualifiers = nullptr) {
// If the only checking we care about is for Objective-C lifetime qualifiers,
// and we're not in ObjC mode, there's nothing to check.
if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
return CastAwayConstnessKind::CACK_None;
if (!DestType->isReferenceType()) {
assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
SrcType->isBlockPointerType()) &&
"Source type is not pointer or pointer to member.");
assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
DestType->isBlockPointerType()) &&
"Destination type is not pointer or pointer to member.");
}
QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
UnwrappedDestType = Self.Context.getCanonicalType(DestType);
// Find the qualifiers. We only care about cvr-qualifiers for the
// purpose of this check, because other qualifiers (address spaces,
// Objective-C GC, etc.) are part of the type's identity.
QualType PrevUnwrappedSrcType = UnwrappedSrcType;
QualType PrevUnwrappedDestType = UnwrappedDestType;
auto WorstKind = CastAwayConstnessKind::CACK_Similar;
bool AllConstSoFar = true;
while (auto Kind = unwrapCastAwayConstnessLevel(
Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
// Track the worst kind of unwrap we needed to do before we found a
// problem.
if (Kind > WorstKind)
WorstKind = Kind;
// Determine the relevant qualifiers at this level.
Qualifiers SrcQuals, DestQuals;
Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
// We do not meaningfully track object const-ness of Objective-C object
// types. Remove const from the source type if either the source or
// the destination is an Objective-C object type.
if (UnwrappedSrcType->isObjCObjectType() ||
UnwrappedDestType->isObjCObjectType())
SrcQuals.removeConst();
if (CheckCVR) {
Qualifiers SrcCvrQuals =
Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
Qualifiers DestCvrQuals =
Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
if (SrcCvrQuals != DestCvrQuals) {
if (CastAwayQualifiers)
*CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
// If we removed a cvr-qualifier, this is casting away 'constness'.
if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
if (TheOffendingSrcType)
*TheOffendingSrcType = PrevUnwrappedSrcType;
if (TheOffendingDestType)
*TheOffendingDestType = PrevUnwrappedDestType;
return WorstKind;
}
// If any prior level was not 'const', this is also casting away
// 'constness'. We noted the outermost type missing a 'const' already.
if (!AllConstSoFar)
return WorstKind;
}
}
if (CheckObjCLifetime &&
!DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
return WorstKind;
// If we found our first non-const-qualified type, this may be the place
// where things start to go wrong.
if (AllConstSoFar && !DestQuals.hasConst()) {
AllConstSoFar = false;
if (TheOffendingSrcType)
*TheOffendingSrcType = PrevUnwrappedSrcType;
if (TheOffendingDestType)
*TheOffendingDestType = PrevUnwrappedDestType;
}
PrevUnwrappedSrcType = UnwrappedSrcType;
PrevUnwrappedDestType = UnwrappedDestType;
}
return CastAwayConstnessKind::CACK_None;
}
static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
unsigned &DiagID) {
switch (CACK) {
case CastAwayConstnessKind::CACK_None:
llvm_unreachable("did not cast away constness");
case CastAwayConstnessKind::CACK_Similar:
// FIXME: Accept these as an extension too?
case CastAwayConstnessKind::CACK_SimilarKind:
DiagID = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
case CastAwayConstnessKind::CACK_Incoherent:
DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
return TC_Extension;
}
llvm_unreachable("unexpected cast away constness kind");
}
/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
/// checked downcasts in class hierarchies.
void CastOperation::CheckDynamicCast() {
if (ValueKind == VK_RValue)
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else if (isPlaceholder())
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
QualType OrigSrcType = SrcExpr.get()->getType();
QualType DestType = Self.Context.getCanonicalType(this->DestType);
// C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
// or "pointer to cv void".
QualType DestPointee;
const PointerType *DestPointer = DestType->getAs<PointerType>();
const ReferenceType *DestReference = nullptr;
if (DestPointer) {
DestPointee = DestPointer->getPointeeType();
} else if ((DestReference = DestType->getAs<ReferenceType>())) {
DestPointee = DestReference->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
<< this->DestType << DestRange;
SrcExpr = ExprError();
return;
}
const RecordType *DestRecord = DestPointee->getAs<RecordType>();
if (DestPointee->isVoidType()) {
assert(DestPointer && "Reference to void is not possible");
} else if (DestRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
diag::err_bad_dynamic_cast_incomplete,
DestRange)) {
SrcExpr = ExprError();
return;
}
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< DestPointee.getUnqualifiedType() << DestRange;
SrcExpr = ExprError();
return;
}
// C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
// complete class type, [...]. If T is an lvalue reference type, v shall be
// an lvalue of a complete class type, [...]. If T is an rvalue reference
// type, v shall be an expression having a complete class type, [...]
QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
QualType SrcPointee;
if (DestPointer) {
if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
SrcPointee = SrcPointer->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
<< OrigSrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
} else if (DestReference->isLValueReferenceType()) {
if (!SrcExpr.get()->isLValue()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
}
SrcPointee = SrcType;
} else {
// If we're dynamic_casting from a prvalue to an rvalue reference, we need
// to materialize the prvalue before we bind the reference to it.
if (SrcExpr.get()->isRValue())
SrcExpr = Self.CreateMaterializeTemporaryExpr(
SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
SrcPointee = SrcType;
}
const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
if (SrcRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
diag::err_bad_dynamic_cast_incomplete,
SrcExpr.get())) {
SrcExpr = ExprError();
return;
}
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
assert((DestPointer || DestReference) &&
"Bad destination non-ptr/ref slipped through.");
assert((DestRecord || DestPointee->isVoidType()) &&
"Bad destination pointee slipped through.");
assert(SrcRecord && "Bad source pointee slipped through.");
// C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
SrcExpr = ExprError();
return;
}
// C++ 5.2.7p3: If the type of v is the same as the required result type,
// [except for cv].
if (DestRecord == SrcRecord) {
Kind = CK_NoOp;
return;
}
// C++ 5.2.7p5
// Upcasts are resolved statically.
if (DestRecord &&
Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
OpRange.getBegin(), OpRange,
&BasePath)) {
SrcExpr = ExprError();
return;
}
Kind = CK_DerivedToBase;
return;
}
// C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
assert(SrcDecl && "Definition missing");
if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
}
// dynamic_cast is not available with -fno-rtti.
// As an exception, dynamic_cast to void* is available because it doesn't
// use RTTI.
if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
SrcExpr = ExprError();
return;
}
// Done. Everything else is run-time checks.
Kind = CK_Dynamic;
}
/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
/// like this:
/// const char *str = "literal";
/// legacy_function(const_cast\<char*\>(str));
void CastOperation::CheckConstCast() {
if (ValueKind == VK_RValue)
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else if (isPlaceholder())
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
unsigned msg = diag::err_bad_cxx_cast_generic;
auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
if (TCR != TC_Success && msg != 0) {
Self.Diag(OpRange.getBegin(), msg) << CT_Const
<< SrcExpr.get()->getType() << DestType << OpRange;
}
if (!isValidCast(TCR))
SrcExpr = ExprError();
}
/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
/// or downcast between respective pointers or references.
static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
QualType DestType,
SourceRange OpRange) {
QualType SrcType = SrcExpr->getType();
// When casting from pointer or reference, get pointee type; use original
// type otherwise.
const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
const CXXRecordDecl *SrcRD =
SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
// Examining subobjects for records is only possible if the complete and
// valid definition is available. Also, template instantiation is not
// allowed here.
if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
return;
const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
return;
enum {
ReinterpretUpcast,
ReinterpretDowncast
} ReinterpretKind;
CXXBasePaths BasePaths;
if (SrcRD->isDerivedFrom(DestRD, BasePaths))
ReinterpretKind = ReinterpretUpcast;
else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
ReinterpretKind = ReinterpretDowncast;
else
return;
bool VirtualBase = true;
bool NonZeroOffset = false;
for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
E = BasePaths.end();
I != E; ++I) {
const CXXBasePath &Path = *I;
CharUnits Offset = CharUnits::Zero();
bool IsVirtual = false;
for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
IElem != EElem; ++IElem) {
IsVirtual = IElem->Base->isVirtual();
if (IsVirtual)
break;
const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
assert(BaseRD && "Base type should be a valid unqualified class type");
// Don't check if any base has invalid declaration or has no definition
// since it has no layout info.
const CXXRecordDecl *Class = IElem->Class,
*ClassDefinition = Class->getDefinition();
if (Class->isInvalidDecl() || !ClassDefinition ||
!ClassDefinition->isCompleteDefinition())
return;
const ASTRecordLayout &DerivedLayout =
Self.Context.getASTRecordLayout(Class);
Offset += DerivedLayout.getBaseClassOffset(BaseRD);
}
if (!IsVirtual) {
// Don't warn if any path is a non-virtually derived base at offset zero.
if (Offset.isZero())
return;
// Offset makes sense only for non-virtual bases.
else
NonZeroOffset = true;
}
VirtualBase = VirtualBase && IsVirtual;
}
(void) NonZeroOffset; // Silence set but not used warning.
assert((VirtualBase || NonZeroOffset) &&
"Should have returned if has non-virtual base with zero offset");
QualType BaseType =
ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
QualType DerivedType =
ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
SourceLocation BeginLoc = OpRange.getBegin();
Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
<< DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
<< OpRange;
Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
<< int(ReinterpretKind)
<< FixItHint::CreateReplacement(BeginLoc, "static_cast");
}
/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
/// valid.
/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
/// like this:
/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
void CastOperation::CheckReinterpretCast() {
if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr =
TryReinterpretCast(Self, SrcExpr, DestType,
/*CStyle*/false, OpRange, msg, Kind);
if (tcr != TC_Success && msg != 0) {
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
//FIXME: &f<int>; is overloaded and resolvable
Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
<< OverloadExpr::find(SrcExpr.get()).Expression->getName()
<< DestType << OpRange;
Self.NoteAllOverloadCandidates(SrcExpr.get());
} else {
diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
DestType, /*listInitialization=*/false);
}
}
if (isValidCast(tcr)) {
if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
checkObjCConversion(Sema::CCK_OtherCast);
DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
} else {
SrcExpr = ExprError();
}
}
/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
/// implicit conversions explicit and getting rid of data loss warnings.
void CastOperation::CheckStaticCast() {
if (isPlaceholder()) {
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid())
return;
}
// This test is outside everything else because it's the only case where
// a non-lvalue-reference target type does not lead to decay.
// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
if (DestType->isVoidType()) {
Kind = CK_ToVoid;