-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSILDeclRef.cpp
1872 lines (1613 loc) · 63.6 KB
/
SILDeclRef.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
//===--- SILDeclRef.cpp - Implements SILDeclRef ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILDeclRef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Assertions.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILLocation.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
/// Get the method dispatch mechanism for a method.
MethodDispatch
swift::getMethodDispatch(AbstractFunctionDecl *method) {
// Some methods are forced to be statically dispatched.
if (method->hasForcedStaticDispatch())
return MethodDispatch::Static;
if (method->getAttrs().hasAttribute<DistributedActorAttr>())
return MethodDispatch::Static;
// Import-as-member declarations are always statically referenced.
if (method->isImportAsMember())
return MethodDispatch::Static;
auto dc = method->getDeclContext();
if (dc->getSelfClassDecl()) {
if (method->shouldUseObjCDispatch()) {
return MethodDispatch::Class;
}
// Final methods can be statically referenced.
if (method->isFinal())
return MethodDispatch::Static;
// Imported class methods are dynamically dispatched.
if (method->isObjC() && method->hasClangNode())
return MethodDispatch::Class;
// Members defined directly inside a class are dynamically dispatched.
if (isa<ClassDecl>(dc)) {
// Native convenience initializers are not dynamically dispatched unless
// required.
if (auto ctor = dyn_cast<ConstructorDecl>(method)) {
if (!ctor->isRequired() && !ctor->isDesignatedInit()
&& !requiresForeignEntryPoint(ctor))
return MethodDispatch::Static;
}
return MethodDispatch::Class;
}
}
// Otherwise, it can be referenced statically.
return MethodDispatch::Static;
}
bool swift::requiresForeignToNativeThunk(ValueDecl *vd) {
// Functions imported from C, Objective-C methods imported from Objective-C,
// as well as methods in @objc protocols (even protocols defined in Swift)
// require a foreign to native thunk.
auto dc = vd->getDeclContext();
if (auto proto = dyn_cast<ProtocolDecl>(dc))
if (proto->isObjC())
return true;
if (auto fd = dyn_cast<FuncDecl>(vd))
return fd->hasClangNode();
return false;
}
bool swift::requiresForeignEntryPoint(ValueDecl *vd) {
assert(!isa<AbstractStorageDecl>(vd));
if (vd->shouldUseObjCDispatch()) {
return true;
}
if (vd->isObjC() && isa<ProtocolDecl>(vd->getDeclContext()))
return true;
if (vd->isImportAsMember())
return true;
if (vd->hasClangNode())
return true;
if (auto *accessor = dyn_cast<AccessorDecl>(vd)) {
// Property accessors should be generated alongside the property.
if (accessor->isGetterOrSetter()) {
auto *asd = accessor->getStorage();
if (asd->isObjC() && asd->hasClangNode())
return true;
}
}
return false;
}
SILDeclRef::SILDeclRef(ValueDecl *vd, SILDeclRef::Kind kind, bool isForeign,
bool isDistributedThunk, bool isKnownToBeLocal,
bool isRuntimeAccessible,
SILDeclRef::BackDeploymentKind backDeploymentKind,
AutoDiffDerivativeFunctionIdentifier *derivativeId)
: loc(vd), kind(kind), isForeign(isForeign), distributedThunk(isDistributedThunk),
isKnownToBeLocal(isKnownToBeLocal),
isRuntimeAccessible(isRuntimeAccessible),
backDeploymentKind(backDeploymentKind), defaultArgIndex(0),
isAsyncLetClosure(0), pointer(derivativeId) {}
SILDeclRef::SILDeclRef(SILDeclRef::Loc baseLoc, bool asForeign,
bool asDistributed, bool asDistributedKnownToBeLocal)
: isRuntimeAccessible(false),
backDeploymentKind(SILDeclRef::BackDeploymentKind::None),
defaultArgIndex(0), isAsyncLetClosure(0),
pointer((AutoDiffDerivativeFunctionIdentifier *)nullptr) {
if (auto *vd = baseLoc.dyn_cast<ValueDecl*>()) {
if (auto *fd = dyn_cast<FuncDecl>(vd)) {
// Map FuncDecls directly to Func SILDeclRefs.
loc = fd;
kind = Kind::Func;
}
// Map ConstructorDecls to the Allocator SILDeclRef of the constructor.
else if (auto *cd = dyn_cast<ConstructorDecl>(vd)) {
loc = cd;
kind = Kind::Allocator;
}
// Map EnumElementDecls to the EnumElement SILDeclRef of the element.
else if (auto *ed = dyn_cast<EnumElementDecl>(vd)) {
loc = ed;
kind = Kind::EnumElement;
}
// VarDecl constants require an explicit kind.
else if (isa<VarDecl>(vd)) {
llvm_unreachable("must create SILDeclRef for VarDecl with explicit kind");
}
// Map DestructorDecls to the Deallocator of the destructor.
else if (auto dtor = dyn_cast<DestructorDecl>(vd)) {
loc = dtor;
kind = Kind::Deallocator;
}
else {
llvm_unreachable("invalid loc decl for SILDeclRef!");
}
} else if (auto *ACE = baseLoc.dyn_cast<AbstractClosureExpr *>()) {
loc = ACE;
kind = Kind::Func;
if (ACE->getASTContext().LangOpts.hasFeature(
Feature::RegionBasedIsolation)) {
assert(ACE->getASTContext().LangOpts.hasFeature(
Feature::SendingArgsAndResults) &&
"Sending args and results should always be enabled");
if (auto *autoClosure = dyn_cast<AutoClosureExpr>(ACE)) {
isAsyncLetClosure =
autoClosure->getThunkKind() == AutoClosureExpr::Kind::AsyncLet;
}
}
} else {
llvm_unreachable("impossible SILDeclRef loc");
}
isForeign = asForeign;
distributedThunk = asDistributed;
isKnownToBeLocal = asDistributedKnownToBeLocal;
}
SILDeclRef::SILDeclRef(SILDeclRef::Loc baseLoc,
GenericSignature prespecializedSig)
: SILDeclRef(baseLoc, false, false) {
pointer = prespecializedSig.getPointer();
}
std::optional<AnyFunctionRef> SILDeclRef::getAnyFunctionRef() const {
switch (getLocKind()) {
case LocKind::Decl:
if (auto *afd = getAbstractFunctionDecl())
return AnyFunctionRef(afd);
return std::nullopt;
case LocKind::Closure:
return AnyFunctionRef(getAbstractClosureExpr());
case LocKind::File:
return std::nullopt;
}
llvm_unreachable("Unhandled case in switch");
}
DeclContext *SILDeclRef::getInnermostDeclContext() const {
if (!loc)
return nullptr;
switch (getLocKind()) {
case LocKind::Decl:
return getDecl()->getInnermostDeclContext();
case LocKind::Closure:
return getAbstractClosureExpr();
case LocKind::File:
return getFileUnit();
}
llvm_unreachable("Unhandled case in switch");
}
ASTContext &SILDeclRef::getASTContext() const {
auto *DC = getInnermostDeclContext();
assert(DC && "Must have a decl context");
return DC->getASTContext();
}
std::optional<AvailabilityRange> SILDeclRef::getAvailabilityForLinkage() const {
// Back deployment thunks and fallbacks don't have availability since they
// are non-ABI.
// FIXME: Generalize this check to all kinds of non-ABI functions.
if (backDeploymentKind != SILDeclRef::BackDeploymentKind::None)
return std::nullopt;
return getDecl()->getAvailabilityForLinkage();
}
bool SILDeclRef::isThunk() const {
return isForeignToNativeThunk() || isNativeToForeignThunk() ||
isDistributedThunk() || isBackDeploymentThunk();
}
bool SILDeclRef::isClangImported() const {
if (!hasDecl())
return false;
ValueDecl *d = getDecl();
DeclContext *moduleContext = d->getDeclContext()->getModuleScopeContext();
if (isa<ClangModuleUnit>(moduleContext)) {
if (isClangGenerated())
return true;
if (isa<ConstructorDecl>(d) || isa<EnumElementDecl>(d))
return !isForeign;
if (auto *FD = dyn_cast<FuncDecl>(d))
if (isa<AccessorDecl>(FD) ||
isa<NominalTypeDecl>(d->getDeclContext()))
return !isForeign;
}
return false;
}
bool SILDeclRef::isClangGenerated() const {
if (!hasDecl())
return false;
return isClangGenerated(getDecl()->getClangNode());
}
// FIXME: this is a weird predicate.
bool SILDeclRef::isClangGenerated(ClangNode node) {
if (auto nd = dyn_cast_or_null<clang::NamedDecl>(node.getAsDecl())) {
// ie, 'static inline' functions for which we must ask Clang to emit a body
// for explicitly
if (!nd->isExternallyVisible())
return true;
}
return false;
}
bool SILDeclRef::isImplicit() const {
switch (getLocKind()) {
case LocKind::Decl:
return getDecl()->isImplicit();
case LocKind::Closure:
return getAbstractClosureExpr()->isImplicit();
case LocKind::File:
// Files are currently never considered implicit.
return false;
}
llvm_unreachable("Unhandled case in switch");
}
bool SILDeclRef::hasUserWrittenCode() const {
// Non-implicit decls generally have user-written code.
if (!isImplicit()) {
switch (kind) {
case Kind::PropertyWrapperBackingInitializer: {
// Only has user-written code if any of the property wrappers have
// arguments to apply. Otherwise, it's just a forwarding initializer for
// the wrappedValue.
auto *var = cast<VarDecl>(getDecl());
return llvm::any_of(var->getAttachedPropertyWrappers(), [&](auto *attr) {
return attr->hasArgs();
});
}
case Kind::PropertyWrapperInitFromProjectedValue:
// Never has user-written code, is just a forwarding initializer.
return false;
default:
if (auto decl = getDecl()) {
// Declarations synthesized by ClangImporter by definition don't have
// user written code, but despite that they aren't always marked
// implicit.
auto moduleContext = decl->getDeclContext()->getModuleScopeContext();
if (isa<ClangModuleUnit>(moduleContext))
return false;
}
// TODO: This checking is currently conservative, we ought to
// exhaustively handle all the cases here, and use emitOrDelayFunction
// in more cases to take advantage of it.
return true;
}
llvm_unreachable("Unhandled case in switch!");
}
// Implicit decls generally don't have user-written code, but some splice
// user code into their body.
switch (kind) {
case Kind::Func: {
if (getAbstractClosureExpr()) {
// Auto-closures have user-written code.
if (auto *ACE = getAutoClosureExpr()) {
// Currently all types of auto-closures can contain user code. Note this
// logic does not affect delayed emission, as we eagerly emit all
// closure definitions. This does however affect profiling.
switch (ACE->getThunkKind()) {
case AutoClosureExpr::Kind::None:
case AutoClosureExpr::Kind::SingleCurryThunk:
case AutoClosureExpr::Kind::DoubleCurryThunk:
case AutoClosureExpr::Kind::AsyncLet:
return true;
}
llvm_unreachable("Unhandled case in switch!");
}
// Otherwise, assume an implicit closure doesn't have user code.
return false;
}
// Lazy getters splice in the user-written initializer expr.
if (auto *accessor = dyn_cast<AccessorDecl>(getFuncDecl())) {
auto *storage = accessor->getStorage();
if (accessor->isGetter() && !storage->isImplicit() &&
storage->getAttrs().hasAttribute<LazyAttr>()) {
return true;
}
}
return false;
}
case Kind::StoredPropertyInitializer: {
// Property wrapper initializers for the implicit backing storage can splice
// in the user-written initializer on the original property.
auto *var = cast<VarDecl>(getDecl());
if (auto *originalProperty = var->getOriginalWrappedProperty()) {
if (originalProperty->isPropertyMemberwiseInitializedWithWrappedType())
return true;
}
return false;
}
case Kind::Allocator:
case Kind::Initializer:
case Kind::EnumElement:
case Kind::Destroyer:
case Kind::Deallocator:
case Kind::IsolatedDeallocator:
case Kind::GlobalAccessor:
case Kind::DefaultArgGenerator:
case Kind::IVarInitializer:
case Kind::IVarDestroyer:
case Kind::PropertyWrapperBackingInitializer:
case Kind::PropertyWrapperInitFromProjectedValue:
case Kind::EntryPoint:
case Kind::AsyncEntryPoint:
// Implicit decls for these don't splice in user-written code.
return false;
}
llvm_unreachable("Unhandled case in switch!");
}
bool SILDeclRef::shouldBeEmittedForDebugger() const {
if (!isFunc())
return false;
if (getASTContext().SILOpts.OptMode != OptimizationMode::NoOptimization)
return false;;
if (!getASTContext().SILOpts.ShouldFunctionsBePreservedToDebugger)
return false;
if (getASTContext().LangOpts.hasFeature(Feature::Embedded))
return false;
ValueDecl *decl = getDecl();
DeclAttributes &attrs = decl->getAttrs();
if (attrs.hasSemanticsAttr("no.preserve.debugger"))
return false;
if (getLinkage(ForDefinition) == SILLinkage::Shared)
return false;
if (auto decl = getDecl())
if (!decl->isImplicit())
return true;
// Synthesized getters are still callable in the debugger.
if (auto *accessor = dyn_cast_or_null<AccessorDecl>(getFuncDecl())) {
return accessor->isSynthesized() && accessor->isGetterOrSetter();
};
return false;
}
namespace {
enum class LinkageLimit {
/// No limit.
None,
/// The linkage should behave as if the decl is private.
Private,
/// The declaration is emitted on-demand; it should end up with internal
/// or shared linkage.
OnDemand,
/// The declaration should never be made public.
NeverPublic,
/// The declaration should always be emitted into the client,
AlwaysEmitIntoClient,
};
} // end anonymous namespace
/// Compute the linkage limit for a given SILDeclRef. This augments the
/// mapping of access level to linkage to provide a maximum or minimum linkage.
static LinkageLimit getLinkageLimit(SILDeclRef constant) {
using Limit = LinkageLimit;
using Kind = SILDeclRef::Kind;
auto *d = constant.getDecl();
ASSERT(ABIRoleInfo(d).providesAPI() && "getLinkageLimit() for ABI decl?");
// Back deployment thunks and fallbacks are emitted into the client.
if (constant.backDeploymentKind != SILDeclRef::BackDeploymentKind::None)
return Limit::AlwaysEmitIntoClient;
if (auto *fn = dyn_cast<AbstractFunctionDecl>(d)) {
// Native-to-foreign thunks for top-level decls are created on-demand,
// unless they are marked @_cdecl, in which case they expose a dedicated
// entry-point with the visibility of the function.
//
// Native-to-foreign thunks for methods are always just private, since
// they're anchored by Objective-C metadata.
auto &attrs = fn->getAttrs();
if (constant.isNativeToForeignThunk() && !attrs.hasAttribute<CDeclAttr>()) {
auto isTopLevel = fn->getDeclContext()->isModuleScopeContext();
return isTopLevel ? Limit::OnDemand : Limit::Private;
}
}
if (auto fn = constant.getFuncDecl()) {
// Forced-static-dispatch functions are created on-demand and have
// at best shared linkage.
if (fn->hasForcedStaticDispatch())
return Limit::OnDemand;
}
if (isa<DestructorDecl>(d)) {
// The destructor of a class implemented with @_objcImplementation is only
// ever called by its ObjC thunk, so it should not be public.
if (d->getDeclContext()->getSelfNominalTypeDecl()->hasClangNode())
return Limit::OnDemand;
}
switch (constant.kind) {
case Kind::Func:
case Kind::Allocator:
case Kind::Initializer:
case Kind::Deallocator:
case Kind::IsolatedDeallocator:
case Kind::Destroyer: {
// @_alwaysEmitIntoClient declarations are like the default arguments of
// public functions; they are roots for dead code elimination and have
// serialized bodies, but no public symbol in the generated binary.
if (d->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>())
return Limit::AlwaysEmitIntoClient;
if (auto accessor = dyn_cast<AccessorDecl>(d)) {
auto *storage = accessor->getStorage();
if (storage->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>())
return Limit::AlwaysEmitIntoClient;
}
break;
}
case Kind::EnumElement:
return Limit::OnDemand;
case Kind::GlobalAccessor:
// global unsafeMutableAddressor should be kept hidden if its decl
// is resilient.
return cast<VarDecl>(d)->isResilient() ? Limit::NeverPublic : Limit::None;
case Kind::DefaultArgGenerator:
// If the default argument is to be serialized, only use non-ABI public
// linkage. If the argument is not to be serialized, don't use a limit.
// This actually means that default arguments *can be ABI public* if
// `isSerialized()` returns false and the effective access level is public,
// which happens under `-enable-testing` with an internal decl.
return constant.isSerialized() ? Limit::AlwaysEmitIntoClient : Limit::None;
case Kind::PropertyWrapperBackingInitializer:
case Kind::PropertyWrapperInitFromProjectedValue: {
if (!d->getDeclContext()->isTypeContext()) {
// If the backing initializer is to be serialized, only use non-ABI public
// linkage. If the initializer is not to be serialized, don't use a limit.
// This actually means that it *can be ABI public* if `isSerialized()`
// returns false and the effective access level is public, which happens
// under `-enable-testing` with an internal decl.
return constant.isSerialized() ? Limit::AlwaysEmitIntoClient
: Limit::None;
}
// Otherwise, regular property wrapper backing initializers (for properties)
// are treated just like stored property initializers.
LLVM_FALLTHROUGH;
}
case Kind::StoredPropertyInitializer: {
// Stored property initializers get the linkage of their containing type.
// There are three cases:
//
// 1) Type is formally @_fixed_layout/@frozen. Root initializers can be
// declared @inlinable. The property initializer must only reference
// public symbols, and is serialized, so we give it PublicNonABI linkage.
//
// 2) Type is not formally @_fixed_layout/@frozen and the module is not
// resilient. Root initializers can be declared @inlinable. This is the
// annoying case. We give the initializer public linkage if the type is
// public.
//
// 3) Type is resilient. The property initializer is never public because
// root initializers cannot be @inlinable.
//
// FIXME: Get rid of case 2 somehow.
if (constant.isSerialized())
return Limit::AlwaysEmitIntoClient;
// FIXME: This should always be true.
if (d->getModuleContext()->isStrictlyResilient())
return Limit::NeverPublic;
break;
}
case Kind::IVarInitializer:
case Kind::IVarDestroyer:
// ivar initializers and destroyers are completely contained within the
// class from which they come, and never get seen externally.
return Limit::NeverPublic;
case Kind::EntryPoint:
case Kind::AsyncEntryPoint:
llvm_unreachable("Already handled");
}
return Limit::None;
}
SILLinkage SILDeclRef::getDefinitionLinkage() const {
using Limit = LinkageLimit;
auto privateLinkage = [&]() {
// Private decls may still be serialized if they are e.g in an inlinable
// function. In such a case, they receive shared linkage.
return isNotSerialized() ? SILLinkage::Private : SILLinkage::Shared;
};
// Prespecializations are public.
if (getSpecializedSignature())
return SILLinkage::Public;
// Closures can only be referenced from the same file.
if (getAbstractClosureExpr())
return privateLinkage();
// The main entry-point is public.
if (kind == Kind::EntryPoint)
return SILLinkage::Public;
if (kind == Kind::AsyncEntryPoint) {
// async main entrypoint is referenced only from @main and
// they are in the same SIL module. Hiding this entrypoint
// from other object file makes it possible to link multiple
// executable targets for SwiftPM testing with -entry-point-function-name
return SILLinkage::Private;
}
// Calling convention thunks have shared linkage.
if (isForeignToNativeThunk())
return SILLinkage::Shared;
// Declarations imported from Clang modules have shared linkage.
if (isClangImported())
return SILLinkage::Shared;
const auto limit = getLinkageLimit(*this);
if (limit == Limit::Private)
return privateLinkage();
auto *decl = getDecl();
if (isPropertyWrapperBackingInitializer()) {
auto *dc = decl->getDeclContext();
// External property wrapper backing initializers have linkage based
// on the access level of their function.
if (isa<ParamDecl>(decl)) {
if (isa<AbstractClosureExpr>(dc))
return privateLinkage();
decl = cast<ValueDecl>(dc->getAsDecl());
}
// Property wrappers in types have linkage based on the access level of
// their nominal.
if (dc->isTypeContext())
decl = cast<NominalTypeDecl>(dc);
}
// Stored property initializers have linkage based on the access level of
// their nominal.
if (isStoredPropertyInitializer())
decl = cast<NominalTypeDecl>(
decl->getDeclContext()->getImplementedObjCContext());
// Compute the effective access level, taking e.g testable into consideration.
auto effectiveAccess = decl->getEffectiveAccess();
// Private setter implementations for an internal storage declaration should
// be at least internal as well, so that a dynamically-writable
// keypath can be formed from other files in the same module.
if (auto *accessor = dyn_cast<AccessorDecl>(decl)) {
auto storageAccess = accessor->getStorage()->getEffectiveAccess();
if (accessor->isSetter() && storageAccess >= AccessLevel::Internal)
effectiveAccess = std::max(effectiveAccess, AccessLevel::Internal);
}
switch (effectiveAccess) {
case AccessLevel::Private:
case AccessLevel::FilePrivate:
return privateLinkage();
case AccessLevel::Internal:
assert(!isSerialized() &&
"Serialized decls should either be private (for decls in inlinable "
"code), or they should be public");
if (limit == Limit::OnDemand)
return SILLinkage::Shared;
return SILLinkage::Hidden;
case AccessLevel::Package:
switch (limit) {
case Limit::None:
return SILLinkage::Package;
case Limit::AlwaysEmitIntoClient:
// Drop the AEIC if the enclosing decl is not effectively public.
// This matches what we do in the `internal` case.
if (isSerialized())
return SILLinkage::PackageNonABI;
else return SILLinkage::Package;
case Limit::OnDemand:
return SILLinkage::Shared;
case Limit::NeverPublic:
return SILLinkage::Hidden;
case Limit::Private:
llvm_unreachable("Already handled");
}
case AccessLevel::Public:
case AccessLevel::Open:
switch (limit) {
case Limit::None:
return SILLinkage::Public;
case Limit::AlwaysEmitIntoClient:
return SILLinkage::PublicNonABI;
case Limit::OnDemand:
return SILLinkage::Shared;
case Limit::NeverPublic:
return SILLinkage::Hidden;
case Limit::Private:
llvm_unreachable("Already handled");
}
}
llvm_unreachable("unhandled access");
}
SILLinkage SILDeclRef::getLinkage(ForDefinition_t forDefinition) const {
// Add external to the linkage of the definition
// (e.g. Public -> PublicExternal) if this is a declaration.
auto linkage = getDefinitionLinkage();
return forDefinition ? linkage : addExternalToLinkage(linkage);
}
SILDeclRef SILDeclRef::getDefaultArgGenerator(Loc loc,
unsigned defaultArgIndex) {
SILDeclRef result;
result.loc = loc;
result.kind = Kind::DefaultArgGenerator;
result.defaultArgIndex = defaultArgIndex;
return result;
}
SILDeclRef SILDeclRef::getMainDeclEntryPoint(ValueDecl *decl) {
auto *file = cast<FileUnit>(decl->getDeclContext()->getModuleScopeContext());
assert(file->getMainDecl() == decl);
SILDeclRef result;
result.loc = decl;
result.kind = Kind::EntryPoint;
return result;
}
SILDeclRef SILDeclRef::getAsyncMainDeclEntryPoint(ValueDecl *decl) {
auto *file = cast<FileUnit>(decl->getDeclContext()->getModuleScopeContext());
assert(file->getMainDecl() == decl);
SILDeclRef result;
result.loc = decl;
result.kind = Kind::AsyncEntryPoint;
return result;
}
SILDeclRef SILDeclRef::getAsyncMainFileEntryPoint(FileUnit *file) {
assert(file->hasEntryPoint() && !file->getMainDecl());
SILDeclRef result;
result.loc = file;
result.kind = Kind::AsyncEntryPoint;
return result;
}
SILDeclRef SILDeclRef::getMainFileEntryPoint(FileUnit *file) {
assert(file->hasEntryPoint() && !file->getMainDecl());
SILDeclRef result;
result.loc = file;
result.kind = Kind::EntryPoint;
return result;
}
bool SILDeclRef::hasClosureExpr() const {
return loc.is<AbstractClosureExpr *>()
&& isa<ClosureExpr>(getAbstractClosureExpr());
}
bool SILDeclRef::hasAutoClosureExpr() const {
return loc.is<AbstractClosureExpr *>()
&& isa<AutoClosureExpr>(getAbstractClosureExpr());
}
bool SILDeclRef::hasFuncDecl() const {
return loc.is<ValueDecl *>() && isa<FuncDecl>(getDecl());
}
ClosureExpr *SILDeclRef::getClosureExpr() const {
return dyn_cast_or_null<ClosureExpr>(getAbstractClosureExpr());
}
AutoClosureExpr *SILDeclRef::getAutoClosureExpr() const {
return dyn_cast_or_null<AutoClosureExpr>(getAbstractClosureExpr());
}
FuncDecl *SILDeclRef::getFuncDecl() const {
return dyn_cast_or_null<FuncDecl>(getDecl());
}
ModuleDecl *SILDeclRef::getModuleContext() const {
if (hasDecl()) {
return getDecl()->getModuleContext();
} else if (hasFileUnit()) {
return getFileUnit()->getParentModule();
} else if (hasClosureExpr()) {
return getClosureExpr()->getParentModule();
} else if (hasAutoClosureExpr()) {
return getAutoClosureExpr()->getParentModule();
}
llvm_unreachable("Unknown declaration reference");
}
bool SILDeclRef::isSetter() const {
if (!hasDecl())
return false;
if (auto accessor = dyn_cast<AccessorDecl>(getDecl()))
return accessor->isSetter();
return false;
}
AbstractFunctionDecl *SILDeclRef::getAbstractFunctionDecl() const {
return dyn_cast_or_null<AbstractFunctionDecl>(getDecl());
}
bool SILDeclRef::isInitAccessor() const {
if (kind != Kind::Func || !hasDecl())
return false;
if (auto accessor = dyn_cast<AccessorDecl>(getDecl()))
return accessor->getAccessorKind() == AccessorKind::Init;
return false;
}
/// True if the function should be treated as transparent.
bool SILDeclRef::isTransparent() const {
if (isEnumElement())
return true;
if (isStoredPropertyInitializer())
return true;
if (hasAutoClosureExpr()) {
auto *ace = getAutoClosureExpr();
switch (ace->getThunkKind()) {
case AutoClosureExpr::Kind::None:
return true;
case AutoClosureExpr::Kind::AsyncLet:
case AutoClosureExpr::Kind::DoubleCurryThunk:
case AutoClosureExpr::Kind::SingleCurryThunk:
break;
}
}
// To support using metatypes as type hints in Embedded Swift. A default
// argument generator might be returning a metatype, which we normally don't
// support in Embedded Swift, but to still allow metatypes as type hints, we
// make the generator always inline to the callee by marking it transparent.
if (getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
if (isDefaultArgGenerator() && hasDecl()) {
auto *decl = getDecl();
auto *param = getParameterAt(decl, defaultArgIndex);
Type paramType = param->getTypeOfDefaultExpr();
if (paramType && paramType->is<MetatypeType>())
return true;
}
}
if (hasDecl()) {
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(getDecl()))
return AFD->isTransparent();
if (auto *ASD = dyn_cast<AbstractStorageDecl>(getDecl()))
return ASD->isTransparent();
}
return false;
}
bool SILDeclRef::isSerialized() const {
return getSerializedKind() == IsSerialized;
}
bool SILDeclRef::isNotSerialized() const {
return getSerializedKind() == IsNotSerialized;
}
/// True if the function should have its body serialized.
SerializedKind_t SILDeclRef::getSerializedKind() const {
if (auto closure = getAbstractClosureExpr()) {
// Ask the AST if we're inside an @inlinable context.
if (closure->getResilienceExpansion() == ResilienceExpansion::Minimal) {
return IsSerialized;
}
return IsNotSerialized;
}
if (kind == Kind::EntryPoint || kind == Kind::AsyncEntryPoint)
return IsNotSerialized;
if (isIVarInitializerOrDestroyer())
return IsNotSerialized;
auto *d = getDecl();
ASSERT(ABIRoleInfo(d).providesAPI()
&& "should not get serialization info from ABI-only decl");
// Default and property wrapper argument generators are serialized if the
// containing declaration is public.
if (isDefaultArgGenerator() || (isPropertyWrapperBackingInitializer() &&
isa<ParamDecl>(d))) {
if (isPropertyWrapperBackingInitializer()) {
if (auto *func = dyn_cast_or_null<ValueDecl>(d->getDeclContext()->getAsDecl())) {
d = func;
}
}
// Ask the AST if we're inside an @inlinable context.
if (d->getDeclContext()->getResilienceExpansion()
== ResilienceExpansion::Minimal) {
return IsSerialized;
}
// Otherwise, check if the owning declaration is public.
auto scope =
d->getFormalAccessScope(/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/true);
if (scope.isPublic())
return IsSerialized;
return IsNotSerialized;
}
// Stored property initializers are inlinable if the type is explicitly
// marked as @frozen.
if (isStoredPropertyInitializer() || (isPropertyWrapperBackingInitializer() &&
d->getDeclContext()->isTypeContext())) {
auto *nominal = dyn_cast<NominalTypeDecl>(d->getDeclContext());
// If this isn't in a nominal, it must be in an @objc @implementation
// extension. We don't serialize those since clients outside the module
// don't think of these as Swift classes.
if (!nominal) {
ASSERT(isa<ExtensionDecl>(d->getDeclContext()) &&
cast<ExtensionDecl>(d->getDeclContext())->isObjCImplementation());
return IsNotSerialized;
}
auto scope =
nominal->getFormalAccessScope(/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/true);
if (!scope.isPublic())
return IsNotSerialized;
if (nominal->isFormallyResilient())
return IsNotSerialized;
return IsSerialized;
}
// Note: if 'd' is a function, then 'dc' is the function itself, not
// its parent context.
auto *dc = d->getInnermostDeclContext();
// Local functions are serializable if their parent function is
// serializable.
if (d->getDeclContext()->isLocalContext()) {
if (dc->getResilienceExpansion() == ResilienceExpansion::Minimal)
return IsSerialized;
return IsNotSerialized;
}
// Anything else that is not public is not serializable.
if (d->getEffectiveAccess() < AccessLevel::Public)
return IsNotSerialized;
// Enum element constructors are serializable if the enum is
// @usableFromInline or public.
if (isEnumElement())
return IsSerialized;
// 'read' and 'modify' accessors synthesized on-demand are serialized if
// visible outside the module.
if (auto fn = dyn_cast<FuncDecl>(d))
if (!isClangImported() &&
fn->hasForcedStaticDispatch())
return IsSerialized;
if (isForeignToNativeThunk())
return IsSerialized;
// The allocating entry point for designated initializers are serialized
// if the class is @usableFromInline or public. Actors are excluded because
// whether the init is designated is not clearly reflected in the source code.
if (kind == SILDeclRef::Kind::Allocator) {
auto *ctor = cast<ConstructorDecl>(d);
if (auto classDecl = ctor->getDeclContext()->getSelfClassDecl()) {
if (!classDecl->isAnyActor() && ctor->isDesignatedInit())
if (!ctor->hasClangNode())
return IsSerialized;
}
}
if (isForeign) {
// @objc thunks for methods are not serializable since they're only
// referenced from the method table.
if (d->getDeclContext()->isTypeContext())
return IsNotSerialized;
// @objc thunks for top-level functions are serializable since they're
// referenced from @convention(c) conversions inside inlinable
// functions.
return IsSerialized;
}
// Declarations imported from Clang modules are serialized if
// referenced from an inlinable context.
if (isClangImported())
return IsSerialized;