-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathCasting.cpp
2680 lines (2403 loc) · 95.3 KB
/
Casting.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
//===--- Casting.cpp - Swift Language Dynamic Casting Support -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the dynamic cast runtime functions.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/LLVM.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Enum.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "swift/Runtime/Debug.h"
#include "ErrorObject.h"
#include "ExistentialMetadataImpl.h"
#include "Private.h"
#include "../SwiftShims/RuntimeShims.h"
#include "stddef.h"
#include <cstring>
#include <type_traits>
// FIXME: SR-946 - we ideally want to switch off of using pthread_rwlock
// directly and instead expand Mutex.h to support rwlocks.
#include <mutex>
// FIXME: Clang defines max_align_t in stddef.h since 3.6.
// Remove this hack when we don't care about older Clangs on all platforms.
#ifdef __APPLE__
typedef std::max_align_t swift_max_align_t;
#else
typedef long double swift_max_align_t;
#endif
using namespace swift;
using namespace metadataimpl;
#if SWIFT_OBJC_INTEROP
#include <objc/NSObject.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <objc/objc.h>
// Aliases for Objective-C runtime entry points.
static const char *class_getName(const ClassMetadata* type) {
return class_getName(
reinterpret_cast<Class>(const_cast<ClassMetadata*>(type)));
}
// Aliases for Swift runtime entry points for Objective-C types.
extern "C" const void *swift_dynamicCastObjCProtocolConditional(
const void *object,
size_t numProtocols,
const ProtocolDescriptor * const *protocols);
#endif
namespace {
enum class TypeSyntaxLevel {
/// Any type syntax is valid.
Type,
/// Function types must be parenthesized.
TypeSimple,
};
}
static void _buildNameForMetadata(const Metadata *type,
TypeSyntaxLevel level,
bool qualified,
std::string &result);
static void _buildNominalTypeName(const NominalTypeDescriptor *ntd,
const Metadata *type,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.DisplayDebuggerGeneratedModule = false;
options.QualifyEntities = qualified;
// Demangle the basic type name.
result += Demangle::demangleTypeAsString(ntd->Name,
strlen(ntd->Name),
options);
// If generic, demangle the type parameters.
if (ntd->GenericParams.NumPrimaryParams > 0) {
result += "<";
auto typeBytes = reinterpret_cast<const char *>(type);
auto genericParam = reinterpret_cast<const Metadata * const *>(
typeBytes + sizeof(void*) * ntd->GenericParams.Offset);
for (unsigned i = 0, e = ntd->GenericParams.NumPrimaryParams;
i < e; ++i, ++genericParam) {
if (i > 0)
result += ", ";
_buildNameForMetadata(*genericParam, TypeSyntaxLevel::Type, qualified,
result);
}
result += ">";
}
}
static const char *_getProtocolName(const ProtocolDescriptor *protocol) {
const char *name = protocol->Name;
// An Objective-C protocol's name is unmangled.
#if SWIFT_OBJC_INTEROP
if (!protocol->Flags.isSwift())
return name;
#endif
// Protocol names are emitted with the _Tt prefix so that ObjC can
// recognize them as mangled Swift names.
assert(name[0] == '_' && name[1] == 'T' && name[2] == 't');
return name + 3;
}
static void _buildExistentialTypeName(const ProtocolDescriptorList *protocols,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.QualifyEntities = qualified;
options.DisplayDebuggerGeneratedModule = false;
// If there's only one protocol, the existential type name is the protocol
// name.
auto descriptors = protocols->getProtocols();
if (protocols->NumProtocols == 1) {
auto name = _getProtocolName(descriptors[0]);
result += Demangle::demangleTypeAsString(name,
strlen(name),
options);
return;
}
result += "protocol<";
for (unsigned i = 0, e = protocols->NumProtocols; i < e; ++i) {
if (i > 0)
result += ", ";
auto name = _getProtocolName(descriptors[i]);
result += Demangle::demangleTypeAsString(name,
strlen(name),
options);
}
result += ">";
}
static void _buildFunctionTypeName(const FunctionTypeMetadata *func,
bool qualified,
std::string &result) {
if (func->getNumArguments() == 1) {
auto firstArgument = func->getArguments()[0].getPointer();
bool isInout = func->getArguments()[0].getFlag();
// This could be a single input tuple, with one or more arguments inside,
// but guaranteed to not have inout types.
if (auto tupleMetadata = dyn_cast<TupleTypeMetadata>(firstArgument)) {
_buildNameForMetadata(tupleMetadata,
TypeSyntaxLevel::TypeSimple,
qualified,
result);
} else {
if (isInout)
result += "inout ";
_buildNameForMetadata(firstArgument,
TypeSyntaxLevel::TypeSimple,
qualified,
result);
}
} else {
result += "(";
for (size_t i = 0; i < func->getNumArguments(); ++i) {
auto arg = func->getArguments()[i].getPointer();
bool isInout = func->getArguments()[i].getFlag();
if (isInout)
result += "inout ";
_buildNameForMetadata(arg, TypeSyntaxLevel::TypeSimple,
qualified, result);
if (i < func->getNumArguments() - 1) {
result += ", ";
}
}
result += ")";
}
if (func->throws()) {
result += " throws";
}
result += " -> ";
_buildNameForMetadata(func->ResultType,
TypeSyntaxLevel::Type,
qualified,
result);
}
// Build a user-comprehensible name for a type.
static void _buildNameForMetadata(const Metadata *type,
TypeSyntaxLevel level,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.DisplayDebuggerGeneratedModule = false;
switch (type->getKind()) {
case MetadataKind::Class: {
auto classType = static_cast<const ClassMetadata *>(type);
#if SWIFT_OBJC_INTEROP
// Look through artificial subclasses.
while (classType->isTypeMetadata() && classType->isArtificialSubclass())
classType = classType->SuperClass;
// Ask the Objective-C runtime to name ObjC classes.
if (!classType->isTypeMetadata()) {
result += class_getName(classType);
return;
}
#endif
return _buildNominalTypeName(classType->getDescription(),
classType, qualified,
result);
}
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Struct: {
auto structType = static_cast<const StructMetadata *>(type);
return _buildNominalTypeName(structType->Description,
type, qualified, result);
}
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
auto objcWrapper = static_cast<const ObjCClassWrapperMetadata *>(type);
result += class_getName(objcWrapper->Class);
#else
assert(false && "no ObjC interop");
#endif
return;
}
case MetadataKind::ForeignClass: {
auto foreign = static_cast<const ForeignClassMetadata *>(type);
const char *name = foreign->getName();
size_t len = strlen(name);
result += Demangle::demangleTypeAsString(name, len, options);
return;
}
case MetadataKind::Existential: {
auto exis = static_cast<const ExistentialTypeMetadata *>(type);
_buildExistentialTypeName(&exis->Protocols, qualified, result);
return;
}
case MetadataKind::ExistentialMetatype: {
auto metatype = static_cast<const ExistentialMetatypeMetadata *>(type);
_buildNameForMetadata(metatype->InstanceType, TypeSyntaxLevel::TypeSimple,
qualified,
result);
result += ".Type";
return;
}
case MetadataKind::Function: {
if (level >= TypeSyntaxLevel::TypeSimple)
result += "(";
auto func = static_cast<const FunctionTypeMetadata *>(type);
switch (func->getConvention()) {
case FunctionMetadataConvention::Swift:
break;
case FunctionMetadataConvention::Thin:
result += "@convention(thin) ";
break;
case FunctionMetadataConvention::Block:
result += "@convention(block) ";
break;
case FunctionMetadataConvention::CFunctionPointer:
result += "@convention(c) ";
break;
}
_buildFunctionTypeName(func, qualified, result);
if (level >= TypeSyntaxLevel::TypeSimple)
result += ")";
return;
}
case MetadataKind::Metatype: {
auto metatype = static_cast<const MetatypeMetadata *>(type);
_buildNameForMetadata(metatype->InstanceType, TypeSyntaxLevel::TypeSimple,
qualified, result);
if (metatype->InstanceType->isAnyExistentialType())
result += ".Protocol";
else
result += ".Type";
return;
}
case MetadataKind::Tuple: {
auto tuple = static_cast<const TupleTypeMetadata *>(type);
result += "(";
auto elts = tuple->getElements();
for (unsigned i = 0, e = tuple->NumElements; i < e; ++i) {
if (i > 0)
result += ", ";
_buildNameForMetadata(elts[i].Type, TypeSyntaxLevel::Type, qualified,
result);
}
result += ")";
return;
}
case MetadataKind::Opaque: {
// TODO
result += "<<<opaque type>>>";
return;
}
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
break;
}
result += "<<<invalid type>>>";
}
/// Return a user-comprehensible name for the given type.
std::string swift::nameForMetadata(const Metadata *type,
bool qualified) {
std::string result;
_buildNameForMetadata(type, TypeSyntaxLevel::Type, qualified, result);
return result;
}
SWIFT_RUNTIME_EXPORT
extern "C"
TwoWordPair<const char *, uintptr_t>::Return
swift_getTypeName(const Metadata *type, bool qualified) {
using Pair = TwoWordPair<const char *, uintptr_t>;
using Key = llvm::PointerIntPair<const Metadata *, 1, bool>;
static pthread_rwlock_t TypeNameCacheLock = PTHREAD_RWLOCK_INITIALIZER;
static Lazy<llvm::DenseMap<Key, std::pair<const char *, size_t>>>
TypeNameCache;
Key key(type, qualified);
auto &cache = TypeNameCache.get();
pthread_rwlock_rdlock(&TypeNameCacheLock);
auto found = cache.find(key);
if (found != cache.end()) {
auto result = found->second;
pthread_rwlock_unlock(&TypeNameCacheLock);
return Pair{result.first, result.second};
}
pthread_rwlock_unlock(&TypeNameCacheLock);
pthread_rwlock_wrlock(&TypeNameCacheLock);
// Someone may have beaten us to the write lock.
found = cache.find(key);
if (found != cache.end()) {
auto result = found->second;
pthread_rwlock_unlock(&TypeNameCacheLock);
return Pair{result.first, result.second};
}
// Build the metadata name.
auto name = nameForMetadata(type, qualified);
// Copy it to memory we can reference forever.
auto size = name.size();
auto result = (char*)malloc(size + 1);
memcpy(result, name.data(), size);
result[size] = 0;
cache.insert({key, {result, size}});
pthread_rwlock_unlock(&TypeNameCacheLock);
return Pair{result, size};
}
/// Report a dynamic cast failure.
// This is noinline with asm("") to preserve this frame in stack traces.
// We want "dynamicCastFailure" to appear in crash logs even we crash
// during the diagnostic because some Metadata is invalid.
LLVM_ATTRIBUTE_NORETURN
LLVM_ATTRIBUTE_NOINLINE
void
swift::swift_dynamicCastFailure(const void *sourceType, const char *sourceName,
const void *targetType, const char *targetName,
const char *message) {
asm("");
swift::fatalError(/* flags = */ 0,
"Could not cast value of type '%s' (%p) to '%s' (%p)%s%s\n",
sourceName, sourceType,
targetName, targetType,
message ? ": " : ".",
message ? message : "");
}
LLVM_ATTRIBUTE_NORETURN
void
swift::swift_dynamicCastFailure(const Metadata *sourceType,
const Metadata *targetType,
const char *message) {
std::string sourceName = nameForMetadata(sourceType);
std::string targetName = nameForMetadata(targetType);
swift_dynamicCastFailure(sourceType, sourceName.c_str(),
targetType, targetName.c_str(), message);
}
/// Report a corrupted type object.
LLVM_ATTRIBUTE_NORETURN
LLVM_ATTRIBUTE_ALWAYS_INLINE // Minimize trashed registers
static void _failCorruptType(const Metadata *type) {
swift::crash("Corrupt Swift type object");
}
#if SWIFT_OBJC_INTEROP
// Objective-c bridging helpers.
namespace {
struct _ObjectiveCBridgeableWitnessTable;
}
static const _ObjectiveCBridgeableWitnessTable *
findBridgeWitness(const Metadata *T);
static bool _dynamicCastValueToClassViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags);
static bool _dynamicCastValueToClassExistentialViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialTypeMetadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags);
static bool _dynamicCastClassToValueViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *targetBridgeWitness,
DynamicCastFlags flags);
#endif
/// A convenient method for failing out of a dynamic cast.
static bool _fail(OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *targetType, DynamicCastFlags flags,
const Metadata *srcDynamicType = nullptr) {
if (flags & DynamicCastFlags::Unconditional) {
const Metadata *srcTypeToReport =
srcDynamicType ? srcDynamicType
: srcType;
swift_dynamicCastFailure(srcTypeToReport, targetType);
}
if (flags & DynamicCastFlags::DestroyOnFailure)
srcType->vw_destroy(srcValue);
return false;
}
/// A convenient method for succeeding at a dynamic cast.
static bool _succeed(OpaqueValue *dest, OpaqueValue *src,
const Metadata *srcType, DynamicCastFlags flags) {
if (flags & DynamicCastFlags::TakeOnSuccess) {
srcType->vw_initializeWithTake(dest, src);
} else {
srcType->vw_initializeWithCopy(dest, src);
}
return true;
}
/// Dynamically cast a class metatype to a Swift class metatype.
static const ClassMetadata *
_dynamicCastClassMetatype(const ClassMetadata *sourceType,
const ClassMetadata *targetType) {
do {
if (sourceType == targetType) {
return sourceType;
}
sourceType = _swift_getSuperclass(sourceType);
} while (sourceType);
return nullptr;
}
/// Dynamically cast a class instance to a Swift class type.
SWIFT_RT_ENTRY_VISIBILITY
const void *
swift::swift_dynamicCastClass(const void *object,
const ClassMetadata *targetType)
SWIFT_CC(RegisterPreservingCC_IMPL) {
#if SWIFT_OBJC_INTEROP
assert(!targetType->isPureObjC());
// Swift native classes never have a tagged-pointer representation.
if (isObjCTaggedPointerOrNull(object)) {
return nullptr;
}
#endif
auto isa = _swift_getClassOfAllocated(object);
if (_dynamicCastClassMetatype(isa, targetType))
return object;
return nullptr;
}
/// Dynamically cast a class object to a Swift class type.
const void *
swift::swift_dynamicCastClassUnconditional(const void *object,
const ClassMetadata *targetType) {
auto value = swift_dynamicCastClass(object, targetType);
if (value) return value;
swift_dynamicCastFailure(_swift_getClass(object), targetType);
}
#if SWIFT_OBJC_INTEROP
static bool _unknownClassConformsToObjCProtocol(const OpaqueValue *value,
const ProtocolDescriptor *protocol) {
const void *object
= *reinterpret_cast<const void * const *>(value);
return swift_dynamicCastObjCProtocolConditional(object, 1, &protocol);
}
#endif
/// Check whether a type conforms to a protocol.
///
/// \param value - can be null, in which case the question should
/// be answered abstractly if possible
/// \param conformance - if non-null, and the protocol requires a
/// witness table, and the type implements the protocol, the witness
/// table will be placed here
static bool _conformsToProtocol(const OpaqueValue *value,
const Metadata *type,
const ProtocolDescriptor *protocol,
const WitnessTable **conformance) {
// Handle AnyObject directly.
if (protocol->Flags.getSpecialProtocol() == SpecialProtocol::AnyObject) {
switch (type->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
// Classes conform to AnyObject.
return true;
case MetadataKind::Existential: {
auto sourceExistential = cast<ExistentialTypeMetadata>(type);
// The existential conforms to AnyObject if it's class-constrained.
// FIXME: It also must not carry witness tables.
return sourceExistential->isClassBounded();
}
case MetadataKind::ExistentialMetatype:
case MetadataKind::Metatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return false;
}
_failCorruptType(type);
}
// Look up the witness table for protocols that need them.
if (protocol->Flags.needsWitnessTable()) {
auto witness = swift_conformsToProtocol(type, protocol);
if (!witness)
return false;
if (conformance)
*conformance = witness;
return true;
}
// For Objective-C protocols, check whether we have a class that
// conforms to the given protocol.
switch (type->getKind()) {
case MetadataKind::Class:
#if SWIFT_OBJC_INTEROP
if (value) {
return _unknownClassConformsToObjCProtocol(value, protocol);
} else {
return classConformsToObjCProtocol(type, protocol);
}
#endif
return false;
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
if (value) {
return _unknownClassConformsToObjCProtocol(value, protocol);
} else {
auto wrapper = cast<ObjCClassWrapperMetadata>(type);
return classConformsToObjCProtocol(wrapper->Class, protocol);
}
#endif
return false;
}
case MetadataKind::ForeignClass:
#if SWIFT_OBJC_INTEROP
if (value)
return _unknownClassConformsToObjCProtocol(value, protocol);
return false;
#else
_failCorruptType(type);
#endif
case MetadataKind::Existential: // FIXME
case MetadataKind::ExistentialMetatype: // FIXME
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return false;
}
return false;
}
/// Check whether a type conforms to the given protocols, filling in a
/// list of conformances.
static bool _conformsToProtocols(const OpaqueValue *value,
const Metadata *type,
const ProtocolDescriptorList &protocols,
const WitnessTable **conformances) {
for (unsigned i = 0, n = protocols.NumProtocols; i != n; ++i) {
const ProtocolDescriptor *protocol = protocols[i];
if (!_conformsToProtocol(value, type, protocol, conformances))
return false;
if (protocol->Flags.needsWitnessTable()) {
assert(*conformances != nullptr);
++conformances;
}
}
return true;
}
static bool shouldDeallocateSource(bool castSucceeded, DynamicCastFlags flags) {
return (castSucceeded && (flags & DynamicCastFlags::TakeOnSuccess)) ||
(!castSucceeded && (flags & DynamicCastFlags::DestroyOnFailure));
}
/// Given that a cast operation is complete, maybe deallocate an
/// opaque existential value.
static void _maybeDeallocateOpaqueExistential(OpaqueValue *srcExistential,
bool castSucceeded,
DynamicCastFlags flags) {
if (shouldDeallocateSource(castSucceeded, flags)) {
auto container =
reinterpret_cast<OpaqueExistentialContainer *>(srcExistential);
container->Type->vw_deallocateBuffer(&container->Buffer);
}
}
/// Given a possibly-existential value, find its dynamic type and the
/// address of its storage.
static void findDynamicValueAndType(OpaqueValue *value, const Metadata *type,
OpaqueValue *&outValue,
const Metadata *&outType,
bool &inoutCanTake) {
switch (type->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
// TODO: avoid unnecessary repeat lookup of
// ObjCClassWrapper/ForeignClass when the type matches.
outValue = value;
outType = swift_getObjectType(*reinterpret_cast<HeapObject**>(value));
return;
}
case MetadataKind::Existential: {
auto existentialType = cast<ExistentialTypeMetadata>(type);
switch (existentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
// Class existentials can't recursively contain existential containers,
// so we can fast-path by not bothering to recur.
auto existential =
reinterpret_cast<ClassExistentialContainer*>(value);
outValue = (OpaqueValue*) &existential->Value;
outType = swift_getObjectType((HeapObject*) existential->Value);
return;
}
case ExistentialTypeRepresentation::Opaque:
case ExistentialTypeRepresentation::ErrorProtocol: {
OpaqueValue *innerValue
= existentialType->projectValue(value);
const Metadata *innerType = existentialType->getDynamicType(value);
inoutCanTake &= existentialType->mayTakeValue(value);
return findDynamicValueAndType(innerValue, innerType,
outValue, outType, inoutCanTake);
}
}
}
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype: {
auto storedType = *(const Metadata **) value;
outValue = value;
outType = swift_getMetatypeMetadata(storedType);
return;
}
// Non-polymorphic types.
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
outValue = value;
outType = type;
return;
}
_failCorruptType(type);
}
extern "C" const Metadata *
swift::swift_getDynamicType(OpaqueValue *value, const Metadata *self) {
OpaqueValue *outValue;
const Metadata *outType;
bool canTake = false;
findDynamicValueAndType(value, self, outValue, outType, canTake);
return outType;
}
/// Given a possibly-existential value, deallocate any buffer in its storage.
static void deallocateDynamicValue(OpaqueValue *value, const Metadata *type) {
switch (type->getKind()) {
case MetadataKind::Existential: {
auto existentialType = cast<ExistentialTypeMetadata>(type);
switch (existentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class:
// Nothing to clean up.
break;
case ExistentialTypeRepresentation::ErrorProtocol:
// TODO: We could clean up from a reclaimed uniquely-referenced error box.
break;
case ExistentialTypeRepresentation::Opaque:
auto existential =
reinterpret_cast<OpaqueExistentialContainer*>(value);
// Handle the possibility of nested existentials.
OpaqueValue *existentialValue =
existential->Type->vw_projectBuffer(&existential->Buffer);
deallocateDynamicValue(existentialValue, existential->Type);
// Deallocate the buffer.
existential->Type->vw_deallocateBuffer(&existential->Buffer);
break;
}
return;
}
// None of the rest of these require deallocation.
case MetadataKind::Class:
case MetadataKind::ForeignClass:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return;
}
_failCorruptType(type);
}
#if SWIFT_OBJC_INTEROP
SWIFT_RUNTIME_EXPORT
extern "C" id
swift_dynamicCastMetatypeToObjectConditional(const Metadata *metatype) {
switch (metatype->getKind()) {
case MetadataKind::Class:
// Swift classes are objects in and of themselves.
return (id)metatype;
case MetadataKind::ObjCClassWrapper: {
// Unwrap ObjC class objects.
auto wrapper = static_cast<const ObjCClassWrapperMetadata*>(metatype);
return (id)wrapper->getClassObject();
}
// Other kinds of metadata don't cast to AnyObject.
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
case MetadataKind::Existential:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::ForeignClass:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
return nullptr;
}
}
SWIFT_RUNTIME_EXPORT
extern "C" id
swift_dynamicCastMetatypeToObjectUnconditional(const Metadata *metatype) {
switch (metatype->getKind()) {
case MetadataKind::Class:
// Swift classes are objects in and of themselves.
return (id)metatype;
case MetadataKind::ObjCClassWrapper: {
// Unwrap ObjC class objects.
auto wrapper = static_cast<const ObjCClassWrapperMetadata*>(metatype);
return (id)wrapper->getClassObject();
}
// Other kinds of metadata don't cast to AnyObject.
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
case MetadataKind::Existential:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::ForeignClass:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject: {
std::string sourceName = nameForMetadata(metatype);
swift_dynamicCastFailure(metatype, sourceName.c_str(),
nullptr, "AnyObject",
"only class metatypes can be converted to AnyObject");
}
}
}
#endif
/// Perform a dynamic cast to an existential type.
static bool _dynamicCastToExistential(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialTypeMetadata *targetType,
DynamicCastFlags flags) {
#if SWIFT_OBJC_INTEROP
// This variable's lifetime needs to be for the whole function, but is
// only valid with Objective-C interop enabled.
id tmp;
#endif
// Find the actual type of the source.
OpaqueValue *srcDynamicValue;
const Metadata *srcDynamicType;
bool canTake = true;
findDynamicValueAndType(src, srcType, srcDynamicValue, srcDynamicType,
canTake);
auto maybeDeallocateSourceAfterSuccess = [&] {
if (shouldDeallocateSource(/*succeeded*/ true, flags)) {
// If we're able to take the dynamic value, then clean up any leftover
// buffers it may have been contained in.
if (canTake && src != srcDynamicValue)
deallocateDynamicValue(src, srcType);
// Otherwise, deallocate the original value wholesale if we couldn't take
// it.
else if (!canTake)
srcType->vw_destroy(src);
}
};
// The representation of an existential is different for some protocols.
switch (targetType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto destExistential =
reinterpret_cast<ClassExistentialContainer*>(dest);
// If the source type is a value type, it cannot possibly conform
// to a class-bounded protocol.
switch (srcDynamicType->getKind()) {
case MetadataKind::ExistentialMetatype:
case MetadataKind::Metatype: {
#if SWIFT_OBJC_INTEROP
// Class metadata can be used as an object when ObjC interop is available.
auto metatypePtr = reinterpret_cast<const Metadata **>(src);
auto metatype = *metatypePtr;
tmp = swift_dynamicCastMetatypeToObjectConditional(metatype);
// If the cast succeeded, use the result value as the class instance
// below.
if (tmp) {
srcDynamicValue = reinterpret_cast<OpaqueValue*>(&tmp);
srcDynamicType = reinterpret_cast<const Metadata*>(tmp);
break;
}
#endif
// Otherwise, metatypes aren't class objects.
return _fail(src, srcType, targetType, flags);
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
case MetadataKind::Existential:
// Handle these cases below.
break;
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
#if SWIFT_OBJC_INTEROP
// If the source type is bridged to Objective-C, try to bridge.
if (auto srcBridgeWitness = findBridgeWitness(srcDynamicType)) {
DynamicCastFlags subFlags
= flags - (DynamicCastFlags::TakeOnSuccess |
DynamicCastFlags::DestroyOnFailure);
bool success = _dynamicCastValueToClassExistentialViaObjCBridgeable(
dest,
srcDynamicValue,
srcDynamicType,
targetType,
srcBridgeWitness,
subFlags);
// Destroy the source value, since we avoided taking or destroying
// it above.
if (shouldDeallocateSource(success, flags)) {
srcType->vw_destroy(src);
}
return success;
}
#endif
break;
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
// Will never succeed.
return _fail(src, srcType, targetType, flags);
}
// Check for protocol conformances and fill in the witness tables.
if (!_conformsToProtocols(srcDynamicValue, srcDynamicType,
targetType->Protocols,
destExistential->getWitnessTables())) {
return _fail(src, srcType, targetType, flags, srcDynamicType);
}
auto object = *(reinterpret_cast<HeapObject**>(srcDynamicValue));
destExistential->Value = object;
if (!canTake || !(flags & DynamicCastFlags::TakeOnSuccess)) {
swift_retain(object);
}
maybeDeallocateSourceAfterSuccess();
return true;