-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenMeta.cpp
7789 lines (6492 loc) · 280 KB
/
GenMeta.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
//===--- GenMeta.cpp - IR generation for metadata constructs --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for type metadata constructs.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "type-metadata-layout"
#include "swift/ABI/MetadataValues.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Attr.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsIRGen.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Mangler.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/Linking.h"
#include "swift/Parse/Lexer.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/Strings.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "Address.h"
#include "Callee.h"
#include "ClassLayout.h"
#include "ClassMetadataVisitor.h"
#include "ClassTypeInfo.h"
#include "ConstantBuilder.h"
#include "EnumMetadataVisitor.h"
#include "ExtendedExistential.h"
#include "Field.h"
#include "FixedTypeInfo.h"
#include "ForeignClassMetadataVisitor.h"
#include "GenArchetype.h"
#include "GenClass.h"
#include "GenDecl.h"
#include "GenPointerAuth.h"
#include "GenPoly.h"
#include "GenStruct.h"
#include "GenValueWitness.h"
#include "GenericArguments.h"
#include "HeapTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "MetadataLayout.h"
#include "MetadataRequest.h"
#include "ProtocolInfo.h"
#include "ScalarTypeInfo.h"
#include "StructLayout.h"
#include "StructMetadataVisitor.h"
#include "GenMeta.h"
using namespace swift;
using namespace irgen;
static Address emitAddressOfMetadataSlotAtIndex(IRGenFunction &IGF,
llvm::Value *metadata,
int index,
llvm::Type *objectTy) {
// Require the metadata to be some type that we recognize as a
// metadata pointer.
assert(metadata->getType() == IGF.IGM.TypeMetadataPtrTy);
return IGF.emitAddressAtOffset(metadata,
Offset(index * IGF.IGM.getPointerSize()),
objectTy, IGF.IGM.getPointerAlignment());
}
/// Emit a load from the given metadata at a constant index.
static llvm::LoadInst *emitLoadFromMetadataAtIndex(IRGenFunction &IGF,
llvm::Value *metadata,
llvm::Value **slotPtr,
int index,
llvm::Type *objectTy,
const llvm::Twine &suffix = "") {
Address slot =
emitAddressOfMetadataSlotAtIndex(IGF, metadata, index, objectTy);
if (slotPtr) *slotPtr = slot.getAddress();
// Load.
return IGF.Builder.CreateLoad(slot, metadata->getName() + suffix);
}
static Address createPointerSizedGEP(IRGenFunction &IGF,
Address base,
Size offset) {
return IGF.Builder.CreateConstArrayGEP(base,
IGF.IGM.getOffsetInWords(offset),
offset);
}
void IRGenModule::setTrueConstGlobal(llvm::GlobalVariable *var) {
disableAddressSanitizer(*this, var);
switch (TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("unknown object format");
case llvm::Triple::MachO:
var->setSection("__TEXT,__const");
break;
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
var->setSection(".rodata");
break;
case llvm::Triple::XCOFF:
case llvm::Triple::COFF:
var->setSection(".rdata");
break;
}
}
/*****************************************************************************/
/** Metadata completion ******************************************************/
/*****************************************************************************/
/// Does the metadata for the given type, which we are currently emitting,
/// require singleton metadata initialization structures and functions?
static bool needsSingletonMetadataInitialization(IRGenModule &IGM,
NominalTypeDecl *typeDecl) {
// Generic types never have singleton metadata initialization.
if (typeDecl->isGenericContext())
return false;
// Non-generic classes use singleton initialization if they have anything
// non-trivial about their metadata.
if (auto *classDecl = dyn_cast<ClassDecl>(typeDecl)) {
switch (IGM.getClassMetadataStrategy(classDecl)) {
case ClassMetadataStrategy::Resilient:
case ClassMetadataStrategy::Singleton:
case ClassMetadataStrategy::Update:
case ClassMetadataStrategy::FixedOrUpdate:
return true;
case ClassMetadataStrategy::Fixed:
return false;
}
}
assert(isa<StructDecl>(typeDecl) || isa<EnumDecl>(typeDecl));
// If the type is known to be fixed-layout, we can emit its metadata such
// that it doesn't need dynamic initialization.
auto &ti = IGM.getTypeInfoForUnlowered(typeDecl->getDeclaredTypeInContext());
if (ti.isFixedSize(ResilienceExpansion::Maximal))
return false;
return true;
}
using MetadataCompletionBodyEmitter =
void (IRGenFunction &IGF,
llvm::Value *metadata,
MetadataDependencyCollector *collector);
static void emitMetadataCompletionFunction(IRGenModule &IGM,
NominalTypeDecl *typeDecl,
llvm::function_ref<MetadataCompletionBodyEmitter> body) {
llvm::Function *f =
IGM.getAddrOfTypeMetadataCompletionFunction(typeDecl, ForDefinition);
f->setAttributes(IGM.constructInitialAttributes());
f->setDoesNotThrow();
IGM.setHasNoFramePointer(f);
IGM.setColocateMetadataSection(f);
IRGenFunction IGF(IGM, f);
// Skip instrumentation when building for TSan to avoid false positives.
// The synchronization for this happens in the Runtime and we do not see it.
if (IGM.IRGen.Opts.Sanitizers & SanitizerKind::Thread)
f->removeFnAttr(llvm::Attribute::SanitizeThread);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, f);
Explosion params = IGF.collectParameters();
llvm::Value *metadata = params.claimNext();
llvm::Value *context = params.claimNext();
llvm::Value *templatePointer = params.claimNext();
// TODO: use these?
(void) context;
(void) templatePointer;
MetadataDependencyCollector collector;
body(IGF, metadata, &collector);
// At the current insertion point, the metadata is now complete.
// Merge with any metadata dependencies we may have collected.
auto dependency = collector.finish(IGF);
auto returnValue = dependency.combine(IGF);
IGF.Builder.CreateRet(returnValue);
}
static bool needsForeignMetadataCompletionFunction(IRGenModule &IGM,
StructDecl *decl) {
// Currently, foreign structs never need a completion function.
return false;
}
static bool needsForeignMetadataCompletionFunction(IRGenModule &IGM,
EnumDecl *decl) {
// Currently, foreign enums never need a completion function.
return false;
}
static bool needsForeignMetadataCompletionFunction(IRGenModule &IGM,
ClassDecl *decl) {
return IGM.getOptions().LazyInitializeClassMetadata || decl->hasSuperclass();
}
/*****************************************************************************/
/** Nominal Type Descriptor Emission *****************************************/
/*****************************************************************************/
template <class Flags>
static Flags getMethodDescriptorFlags(ValueDecl *fn) {
if (isa<ConstructorDecl>(fn)) {
auto flags = Flags(Flags::Kind::Init); // 'init' is considered static
if (auto *afd = dyn_cast<AbstractFunctionDecl>(fn))
flags = flags.withIsAsync(afd->hasAsync());
return flags;
}
auto kind = [&] {
auto accessor = dyn_cast<AccessorDecl>(fn);
if (!accessor) return Flags::Kind::Method;
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
return Flags::Kind::Getter;
case AccessorKind::Set:
return Flags::Kind::Setter;
case AccessorKind::Read:
return Flags::Kind::ReadCoroutine;
case AccessorKind::Read2:
return Flags::Kind::Read2Coroutine;
case AccessorKind::Modify:
return Flags::Kind::ModifyCoroutine;
case AccessorKind::Modify2:
return Flags::Kind::Modify2Coroutine;
#define OPAQUE_ACCESSOR(ID, KEYWORD)
#define ACCESSOR(ID) \
case AccessorKind::ID:
case AccessorKind::DistributedGet:
#include "swift/AST/AccessorKinds.def"
llvm_unreachable("these accessors never appear in protocols or v-tables");
}
llvm_unreachable("bad kind");
}();
bool hasAsync = false;
if (auto *afd = dyn_cast<AbstractFunctionDecl>(fn))
hasAsync = afd->hasAsync();
return Flags(kind).withIsInstance(!fn->isStatic()).withIsAsync(hasAsync);
}
static void buildMethodDescriptorFields(IRGenModule &IGM,
const SILVTable *VTable,
SILDeclRef fn,
ConstantStructBuilder &descriptor,
ClassDecl *classDecl) {
auto *func = cast<AbstractFunctionDecl>(fn.getDecl());
// Classify the method.
using Flags = MethodDescriptorFlags;
auto flags = getMethodDescriptorFlags<Flags>(func);
// Remember if the declaration was dynamic.
if (func->shouldUseObjCDispatch())
flags = flags.withIsDynamic(true);
auto *accessor = dyn_cast<AccessorDecl>(func);
// Include the pointer-auth discriminator.
if (auto &schema =
func->hasAsync() ? IGM.getOptions().PointerAuth.AsyncSwiftClassMethods
: accessor &&
requiresFeatureCoroutineAccessors(accessor->getAccessorKind())
? IGM.getOptions().PointerAuth.CoroSwiftClassMethods
: IGM.getOptions().PointerAuth.SwiftClassMethods) {
auto discriminator =
PointerAuthInfo::getOtherDiscriminator(IGM, schema, fn);
flags = flags.withExtraDiscriminator(discriminator->getZExtValue());
}
// TODO: final? open?
descriptor.addInt(IGM.Int32Ty, flags.getIntValue());
if (auto entry = VTable->getEntry(IGM.getSILModule(), fn)) {
assert(entry->getKind() == SILVTable::Entry::Kind::Normal);
auto *impl = entry->getImplementation();
if (impl->isAsync()) {
llvm::Constant *implFn = IGM.getAddrOfAsyncFunctionPointer(impl);
descriptor.addRelativeAddress(implFn);
} else if (impl->getLoweredFunctionType()->isCalleeAllocatedCoroutine()) {
llvm::Constant *implFn = IGM.getAddrOfCoroFunctionPointer(impl);
descriptor.addRelativeAddress(implFn);
} else {
llvm::Function *implFn = IGM.getAddrOfSILFunction(impl, NotForDefinition);
if (IGM.getOptions().UseProfilingMarkerThunks &&
classDecl->getSelfNominalTypeDecl()->isGenericContext() &&
!impl->getLoweredFunctionType()->isCoroutine()) {
implFn = IGM.getAddrOfVTableProfilingThunk(implFn, classDecl);
}
descriptor.addCompactFunctionReference(implFn);
}
} else {
// The method is removed by dead method elimination.
// It should be never called. We add a pointer to an error function.
descriptor.addRelativeAddressOrNull(nullptr);
}
}
void IRGenModule::emitNonoverriddenMethodDescriptor(const SILVTable *VTable,
SILDeclRef declRef,
ClassDecl *classDecl) {
auto entity = LinkEntity::forMethodDescriptor(declRef);
auto *var = cast<llvm::GlobalVariable>(
getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()));
if (!var->isDeclaration()) {
assert(IRGen.isLazilyReemittingNominalTypeDescriptor(VTable->getClass()));
return;
}
var->setConstant(true);
setTrueConstGlobal(var);
ConstantInitBuilder ib(*this);
ConstantStructBuilder sb(ib.beginStruct(MethodDescriptorStructTy));
buildMethodDescriptorFields(*this, VTable, declRef, sb, classDecl);
auto init = sb.finishAndCreateFuture();
getAddrOfLLVMVariable(entity, init, DebugTypeInfo());
}
void IRGenModule::setVCallVisibility(llvm::GlobalVariable *var,
llvm::GlobalObject::VCallVisibility vis,
std::pair<uint64_t, uint64_t> range) {
// Insert attachment of !vcall_visibility !{ vis, range.first, range.second }
var->addMetadata(
llvm::LLVMContext::MD_vcall_visibility,
*llvm::MDNode::get(getLLVMContext(),
{
llvm::ConstantAsMetadata::get(
llvm::ConstantInt::get(Int64Ty, vis)),
llvm::ConstantAsMetadata::get(
llvm::ConstantInt::get(Int64Ty, range.first)),
llvm::ConstantAsMetadata::get(
llvm::ConstantInt::get(Int64Ty, range.second)),
}));
// Insert attachment of !typed_global_not_for_cfi !{}
var->addMetadata("typed_global_not_for_cfi",
*llvm::MDNode::get(getLLVMContext(), {}));
}
void IRGenModule::addVTableTypeMetadata(
ClassDecl *decl, llvm::GlobalVariable *var,
SmallVector<std::pair<Size, SILDeclRef>, 8> vtableEntries) {
if (vtableEntries.empty())
return;
uint64_t minOffset = UINT64_MAX;
uint64_t maxOffset = 0;
for (auto ventry : vtableEntries) {
auto method = ventry.second;
auto offset = ventry.first.getValue();
var->addTypeMetadata(offset, typeIdForMethod(*this, method));
minOffset = std::min(minOffset, offset);
maxOffset = std::max(maxOffset, offset);
}
using VCallVisibility = llvm::GlobalObject::VCallVisibility;
VCallVisibility vis = VCallVisibility::VCallVisibilityPublic;
auto AS = decl->getFormalAccessScope();
if (decl->isObjC()) {
// Swift methods are called from Objective-C via objc_MsgSend
// and thus such call sites are not taken into consideration
// by VFE in GlobalDCE. We cannot for the timebeing at least
// safely eliminate a virtual function that might be called from
// Objective-C. Setting vcall_visibility to public ensures this is
// prevented.
vis = VCallVisibility::VCallVisibilityPublic;
} else if (AS.isFileScope()) {
vis = VCallVisibility::VCallVisibilityTranslationUnit;
} else if (AS.isPrivate() || AS.isInternal()) {
vis = VCallVisibility::VCallVisibilityLinkageUnit;
} else if (getOptions().InternalizeAtLink) {
vis = VCallVisibility::VCallVisibilityLinkageUnit;
}
auto relptrSize = DataLayout.getTypeAllocSize(Int32Ty).getKnownMinValue();
setVCallVisibility(var, vis,
std::make_pair(minOffset, maxOffset + relptrSize));
}
static void addPaddingAfterGenericParamDescriptors(IRGenModule &IGM,
ConstantStructBuilder &b,
unsigned numDescriptors) {
unsigned padding = (unsigned) -numDescriptors & 3;
for (unsigned i = 0; i < padding; ++i)
b.addInt(IGM.Int8Ty, 0);
}
namespace {
struct GenericSignatureHeaderBuilder {
using PlaceholderPosition =
ConstantAggregateBuilderBase::PlaceholderPosition;
PlaceholderPosition NumParamsPP;
PlaceholderPosition NumRequirementsPP;
PlaceholderPosition NumGenericKeyArgumentsPP;
PlaceholderPosition FlagsPP;
unsigned NumParams = 0;
unsigned NumRequirements = 0;
unsigned NumGenericKeyArguments = 0;
SmallVector<CanType, 2> ShapeClasses;
SmallVector<GenericPackArgument, 2> GenericPackArguments;
InvertibleProtocolSet ConditionalInvertedProtocols;
SmallVector<GenericValueArgument, 2> GenericValueArguments;
GenericSignatureHeaderBuilder(IRGenModule &IGM,
ConstantStructBuilder &builder)
: NumParamsPP(builder.addPlaceholderWithSize(IGM.Int16Ty)),
NumRequirementsPP(builder.addPlaceholderWithSize(IGM.Int16Ty)),
NumGenericKeyArgumentsPP(builder.addPlaceholderWithSize(IGM.Int16Ty)),
FlagsPP(builder.addPlaceholderWithSize(IGM.Int16Ty)) {}
void add(const GenericArgumentMetadata &info) {
ShapeClasses.append(info.ShapeClasses.begin(),
info.ShapeClasses.end());
NumParams += info.NumParams;
NumRequirements += info.NumRequirements;
for (auto pack : info.GenericPackArguments) {
// Compute the final index.
pack.Index += NumGenericKeyArguments + ShapeClasses.size();
GenericPackArguments.push_back(pack);
}
NumGenericKeyArguments += info.NumGenericKeyArguments;
for (auto value : info.GenericValueArguments) {
GenericValueArguments.push_back(value);
}
}
void finish(IRGenModule &IGM, ConstantStructBuilder &b) {
assert(GenericPackArguments.empty() == ShapeClasses.empty() &&
"Can't have one without the other");
assert(NumParams <= UINT16_MAX && "way too generic");
b.fillPlaceholderWithInt(NumParamsPP, IGM.Int16Ty, NumParams);
assert(NumRequirements <= UINT16_MAX && "way too generic");
b.fillPlaceholderWithInt(NumRequirementsPP, IGM.Int16Ty,
NumRequirements);
assert(NumGenericKeyArguments <= UINT16_MAX && "way too generic");
b.fillPlaceholderWithInt(NumGenericKeyArgumentsPP, IGM.Int16Ty,
NumGenericKeyArguments + ShapeClasses.size());
bool hasTypePacks = !GenericPackArguments.empty();
bool hasConditionalInvertedProtocols =
!ConditionalInvertedProtocols.empty();
bool hasValues = !GenericValueArguments.empty();
GenericContextDescriptorFlags flags(
hasTypePacks, hasConditionalInvertedProtocols, hasValues);
b.fillPlaceholderWithInt(FlagsPP, IGM.Int16Ty,
flags.getIntValue());
}
};
template<class Impl>
class ContextDescriptorBuilderBase {
protected:
Impl &asImpl() { return *static_cast<Impl*>(this); }
IRGenModule &IGM;
private:
ConstantInitBuilder InitBuilder;
protected:
ConstantStructBuilder B;
std::optional<GenericSignatureHeaderBuilder> SignatureHeader;
ContextDescriptorBuilderBase(IRGenModule &IGM)
: IGM(IGM), InitBuilder(IGM), B(InitBuilder.beginStruct()) {
B.setPacked(true);
}
public:
void layout() {
asImpl().addFlags();
asImpl().addParent();
}
void addFlags() {
B.addInt32(
ContextDescriptorFlags(asImpl().getContextKind(),
!asImpl().getGenericSignature().isNull(),
asImpl().isUniqueDescriptor(),
!asImpl().getInvertedProtocols().empty(),
asImpl().getKindSpecificFlags())
.getIntValue());
}
void addParent() {
ConstantReference parent = asImpl().getParent();
if (parent.getValue()) {
B.addRelativeAddress(parent);
} else {
B.addInt32(0); // null offset
}
}
void addGenericSignature() {
if (!asImpl().getGenericSignature())
return;
asImpl().addGenericParametersHeader();
asImpl().addGenericParameters();
asImpl().addGenericRequirements();
asImpl().addGenericPackShapeDescriptors();
asImpl().addConditionalInvertedProtocols();
asImpl().addGenericValueDescriptors();
asImpl().finishGenericParameters();
}
void addGenericParametersHeader() {
// Drop placeholders for the counts. We'll fill these in when we emit
// the related sections.
SignatureHeader.emplace(IGM, B);
}
void addGenericParameters() {
GenericSignature sig = asImpl().getGenericSignature();
auto metadata =
irgen::addGenericParameters(IGM, B,
asImpl().getGenericSignature(),
/*implicit=*/false);
assert(metadata.NumParams == metadata.NumParamsEmitted &&
"We can't use implicit GenericParamDescriptors here");
SignatureHeader->add(metadata);
// Pad the structure up to four bytes for the following requirements.
addPaddingAfterGenericParamDescriptors(IGM, B,
SignatureHeader->NumParams);
}
void addGenericRequirements() {
auto metadata =
irgen::addGenericRequirements(IGM, B, asImpl().getGenericSignature());
SignatureHeader->add(metadata);
}
/// Adds the set of suppressed protocols, which must be explicitly called
/// by the concrete subclasses.
void addInvertedProtocols() {
auto protocols = asImpl().getInvertedProtocols();
if (protocols.empty())
return;
B.addInt(IGM.Int16Ty, protocols.rawBits());
}
InvertibleProtocolSet getConditionalInvertedProtocols() {
return InvertibleProtocolSet();
}
void addConditionalInvertedProtocols() {
assert(asImpl().getConditionalInvertedProtocols().empty() &&
"Subclass must implement this operation");
}
void finishGenericParameters() {
SignatureHeader->finish(IGM, B);
}
void addGenericPackShapeDescriptors() {
const auto &shapes = SignatureHeader->ShapeClasses;
const auto &packArgs = SignatureHeader->GenericPackArguments;
assert(shapes.empty() == packArgs.empty() &&
"Can't have one without the other");
// If we don't have any pack arguments, there is nothing to emit.
if (packArgs.empty())
return;
// Emit the GenericPackShapeHeader first.
// NumPacks
B.addInt(IGM.Int16Ty, packArgs.size());
// NumShapes
B.addInt(IGM.Int16Ty, shapes.size());
// Emit each GenericPackShapeDescriptor collected previously.
irgen::addGenericPackShapeDescriptors(IGM, B, shapes, packArgs);
}
void addGenericValueDescriptors() {
auto values = SignatureHeader->GenericValueArguments;
// If we don't have any value arguments, there is nothing to emit.
if (values.empty())
return;
// NumValues
B.addInt(IGM.Int32Ty, values.size());
// Emit each GenericValueDescriptor collected previously.
irgen::addGenericValueDescriptors(IGM, B, values);
}
/// Retrieve the set of protocols that are suppressed in this context.
InvertibleProtocolSet getInvertedProtocols() {
return InvertibleProtocolSet();
}
uint16_t getKindSpecificFlags() {
return 0;
}
// Subclasses should provide:
//
// bool isUniqueDescriptor();
// llvm::Constant *getParent();
// ContextDescriptorKind getContextKind();
// GenericSignature getGenericSignature();
// void emit();
};
class ModuleContextDescriptorBuilder
: public ContextDescriptorBuilderBase<ModuleContextDescriptorBuilder> {
using super = ContextDescriptorBuilderBase;
ModuleDecl *M;
public:
ModuleContextDescriptorBuilder(IRGenModule &IGM, ModuleDecl *M)
: super(IGM), M(M)
{}
void layout() {
super::layout();
addName();
}
void addName() {
B.addRelativeAddress(IGM.getAddrOfGlobalIdentifierString(
M->getABIName().str(),
/*willBeRelativelyAddressed*/ true));
}
bool isUniqueDescriptor() {
return false;
}
ConstantReference getParent() {
return {nullptr, ConstantReference::Direct};
}
ContextDescriptorKind getContextKind() {
return ContextDescriptorKind::Module;
}
GenericSignature getGenericSignature() {
return nullptr;
}
void emit() {
asImpl().layout();
auto addr = IGM.getAddrOfModuleContextDescriptor(M,
B.finishAndCreateFuture());
auto var = cast<llvm::GlobalVariable>(addr);
var->setConstant(true);
IGM.setColocateTypeDescriptorSection(var);
}
};
class ExtensionContextDescriptorBuilder
: public ContextDescriptorBuilderBase<ExtensionContextDescriptorBuilder> {
using super = ContextDescriptorBuilderBase;
ExtensionDecl *E;
public:
ExtensionContextDescriptorBuilder(IRGenModule &IGM, ExtensionDecl *E)
: super(IGM), E(E)
{}
void layout() {
super::layout();
addExtendedContext();
addGenericSignature();
}
void addExtendedContext() {
auto string = IGM.getTypeRef(E->getSelfInterfaceType(),
E->getGenericSignature(),
MangledTypeRefRole::Metadata).first;
B.addRelativeAddress(string);
}
ConstantReference getParent() {
return {IGM.getAddrOfModuleContextDescriptor(E->getParentModule()),
ConstantReference::Direct};
}
bool isUniqueDescriptor() {
// Extensions generated by the Clang importer will be emitted into any
// binary that uses the Clang module. Otherwise, we can guarantee that
// an extension (and any of its possible sub-contexts) belong to one
// translation unit.
return !isa<ClangModuleUnit>(E->getModuleScopeContext());
}
ContextDescriptorKind getContextKind() {
return ContextDescriptorKind::Extension;
}
GenericSignature getGenericSignature() {
return E->getGenericSignature();
}
void emit() {
asImpl().layout();
auto addr = IGM.getAddrOfExtensionContextDescriptor(E,
B.finishAndCreateFuture());
auto var = cast<llvm::GlobalVariable>(addr);
var->setConstant(true);
IGM.setColocateTypeDescriptorSection(var);
}
};
class AnonymousContextDescriptorBuilder
: public ContextDescriptorBuilderBase<AnonymousContextDescriptorBuilder> {
using super = ContextDescriptorBuilderBase;
PointerUnion<DeclContext *, VarDecl *> Name;
DeclContext *getInnermostDeclContext() {
if (auto DC = Name.dyn_cast<DeclContext *>()) {
return DC;
}
if (auto VD = Name.dyn_cast<VarDecl *>()) {
return VD->getInnermostDeclContext();
}
llvm_unreachable("unknown name kind");
}
public:
AnonymousContextDescriptorBuilder(IRGenModule &IGM,
PointerUnion<DeclContext *, VarDecl *> Name)
: super(IGM), Name(Name)
{
}
void layout() {
super::layout();
asImpl().addGenericSignature();
asImpl().addMangledName();
}
ConstantReference getParent() {
return IGM.getAddrOfParentContextDescriptor(
getInnermostDeclContext(), /*fromAnonymousContext=*/true);
}
ContextDescriptorKind getContextKind() {
return ContextDescriptorKind::Anonymous;
}
GenericSignature getGenericSignature() {
return getInnermostDeclContext()->getGenericSignatureOfContext();
}
bool isUniqueDescriptor() {
return true;
}
uint16_t getKindSpecificFlags() {
AnonymousContextDescriptorFlags flags{};
flags.setHasMangledName(
IGM.IRGen.Opts.EnableAnonymousContextMangledNames);
return flags.getOpaqueValue();
}
void addMangledName() {
if (!IGM.IRGen.Opts.EnableAnonymousContextMangledNames)
return;
IRGenMangler mangler(IGM.Context);
auto mangledName = mangler.mangleAnonymousDescriptorName(Name);
auto mangledNameConstant =
IGM.getAddrOfGlobalString(mangledName,
/*willBeRelativelyAddressed*/ true);
B.addRelativeAddress(mangledNameConstant);
}
void emit() {
asImpl().layout();
auto addr = IGM.getAddrOfAnonymousContextDescriptor(Name,
B.finishAndCreateFuture());
auto var = cast<llvm::GlobalVariable>(addr);
var->setConstant(true);
IGM.setColocateTypeDescriptorSection(var);
}
};
class ProtocolDescriptorBuilder
: public ContextDescriptorBuilderBase<ProtocolDescriptorBuilder> {
using super = ContextDescriptorBuilderBase;
ProtocolDecl *Proto;
SILDefaultWitnessTable *DefaultWitnesses;
std::optional<ConstantAggregateBuilderBase::PlaceholderPosition>
NumRequirementsInSignature, NumRequirements;
bool Resilient;
public:
ProtocolDescriptorBuilder(IRGenModule &IGM, ProtocolDecl *Proto,
SILDefaultWitnessTable *defaultWitnesses)
: super(IGM), Proto(Proto), DefaultWitnesses(defaultWitnesses),
Resilient(IGM.getSwiftModule()->isResilient()) {}
void layout() {
super::layout();
}
ConstantReference getParent() {
return IGM.getAddrOfParentContextDescriptor(
Proto, /*fromAnonymousContext=*/false);
}
ContextDescriptorKind getContextKind() {
return ContextDescriptorKind::Protocol;
}
GenericSignature getGenericSignature() {
return nullptr;
}
bool isUniqueDescriptor() {
return true;
}
uint16_t getKindSpecificFlags() {
ProtocolContextDescriptorFlags flags;
flags.setClassConstraint(Proto->requiresClass()
? ProtocolClassConstraint::Class
: ProtocolClassConstraint::Any);
flags.setSpecialProtocol(getSpecialProtocolID(Proto));
flags.setIsResilient(DefaultWitnesses != nullptr);
return flags.getOpaqueValue();
}
void emit() {
asImpl().layout();
asImpl().addName();
NumRequirementsInSignature = B.addPlaceholderWithSize(IGM.Int32Ty);
NumRequirements = B.addPlaceholderWithSize(IGM.Int32Ty);
asImpl().addAssociatedTypeNames();
asImpl().addRequirementSignature();
asImpl().addRequirements();
auto addr = IGM.getAddrOfProtocolDescriptor(Proto,
B.finishAndCreateFuture());
auto var = cast<llvm::GlobalVariable>(addr);
var->setConstant(true);
IGM.setColocateTypeDescriptorSection(var);
}
void addName() {
auto nameStr = IGM.getAddrOfGlobalIdentifierString(Proto->getName().str(),
/*willBeRelativelyAddressed*/ true);
B.addRelativeAddress(nameStr);
}
void addRequirementSignature() {
SmallVector<Requirement, 2> requirements;
SmallVector<InverseRequirement, 2> inverses;
Proto->getRequirementSignature().getRequirementsWithInverses(
Proto, requirements, inverses);
auto metadata =
irgen::addGenericRequirements(IGM, B, Proto->getGenericSignature(),
requirements, inverses);
B.fillPlaceholderWithInt(*NumRequirementsInSignature, IGM.Int32Ty,
metadata.NumRequirements);
}
struct RequirementInfo {
ProtocolRequirementFlags Flags;
llvm::Constant *DefaultImpl;
};
/// Build the information which will go into a ProtocolRequirement entry.
RequirementInfo getRequirementInfo(const WitnessTableEntry &entry) {
using Flags = ProtocolRequirementFlags;
if (entry.isBase()) {
assert(entry.isOutOfLineBase());
auto flags = Flags(Flags::Kind::BaseProtocol);
return { flags, nullptr };
}
if (entry.isAssociatedType()) {
auto flags = Flags(Flags::Kind::AssociatedTypeAccessFunction);
if (auto &schema = IGM.getOptions().PointerAuth
.ProtocolAssociatedTypeAccessFunctions) {
addDiscriminator(flags, schema,
AssociatedType(entry.getAssociatedType()));
}
// Look for a default witness.
llvm::Constant *defaultImpl =
findDefaultTypeWitness(entry.getAssociatedType());
return { flags, defaultImpl };
}
if (entry.isAssociatedConformance()) {
auto flags = Flags(Flags::Kind::AssociatedConformanceAccessFunction);
if (auto &schema = IGM.getOptions().PointerAuth
.ProtocolAssociatedTypeWitnessTableAccessFunctions) {
addDiscriminator(flags, schema,
AssociatedConformance(Proto,
entry.getAssociatedConformancePath(),
entry.getAssociatedConformanceRequirement()));
}
// Look for a default witness.
llvm::Constant *defaultImpl =
findDefaultAssociatedConformanceWitness(
entry.getAssociatedConformancePath(),
entry.getAssociatedConformanceRequirement());
return { flags, defaultImpl };
}
assert(entry.isFunction());
SILDeclRef func(entry.getFunction());
// Emit the dispatch thunk.
auto shouldEmitDispatchThunk =
(Resilient || IGM.getOptions().WitnessMethodElimination) &&
!func.isDistributed();
if (shouldEmitDispatchThunk) {
IGM.emitDispatchThunk(func);
}
{
auto *requirement = cast<AbstractFunctionDecl>(func.getDecl());
if (requirement->isDistributedThunk()) {
// when thunk, because in protocol we want access of for the thunk