-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenClass.cpp
3159 lines (2707 loc) · 120 KB
/
GenClass.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
//===--- GenClass.cpp - Swift IR Generation For 'class' Types -------------===//
//
// 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 class types.
//
//===----------------------------------------------------------------------===//
#include "GenClass.h"
#include "swift/ABI/Class.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AttrKind.h"
#include "swift/AST/Decl.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/TypeMemberVisitor.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILVTableVisitor.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/RecordLayout.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/Support/raw_ostream.h"
#include "Callee.h"
#include "ClassLayout.h"
#include "ClassTypeInfo.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenObjC.h"
#include "GenPointerAuth.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "MemberAccessStrategy.h"
#include "MetadataLayout.h"
#include "MetadataRequest.h"
using namespace swift;
using namespace irgen;
/// Return the lowered type for the class's 'self' type within its context.
SILType irgen::getSelfType(const ClassDecl *base) {
auto loweredTy = base->getDeclaredTypeInContext()->getCanonicalType();
return SILType::getPrimitiveObjectType(loweredTy);
}
/// If the superclass came from another module, we may have dropped
/// stored properties due to the Swift language version availability of
/// their types. In these cases we can't precisely lay out the ivars in
/// the class object at compile time so we need to do runtime layout.
static bool classHasIncompleteLayout(IRGenModule &IGM,
ClassDecl *theClass) {
if (theClass->getParentModule() == IGM.getSwiftModule())
return false;
for (auto field : theClass->getStoredPropertiesAndMissingMemberPlaceholders())
if (isa<MissingMemberDecl>(field))
return true;
return false;
}
namespace {
class ClassLayoutBuilder : public StructLayoutBuilder {
SmallVector<ElementLayout, 8> Elements;
SmallVector<Field, 8> AllStoredProperties;
SmallVector<FieldAccess, 8> AllFieldAccesses;
// If we're building a layout with tail-allocated elements, we do
// things slightly differently; all fields from the superclass are
// added before the class fields, and the tail elements themselves
// come after. We don't make a ClassLayout in this case, only a
// StructLayout.
std::optional<ArrayRef<SILType>> TailTypes;
// Normally, Swift only emits static metadata for a class if it has no
// generic ancestry and no fields with resilient value types, which
// require dynamic layout.
//
// However, for interop with Objective-C, where the runtime does not
// know how to invoke arbitrary code to initialize class metadata, we
// ignore resilience and emit a static layout and metadata for classes
// that would otherwise have static metadata, were it not for any
// resilient fields.
//
// This enables two things:
//
// - Objective-C can reference the class symbol by calling a static
// method on it, for example +alloc, which requires the InstanceSize
// to be known, except for possibly sliding ivars.
//
// - Objective-C message sends can call methods defined in categories
// emitted by Swift, which again require the class metadata symbol
// to have a static address.
//
// Note that we don't do this if the class is generic, has generic
// ancestry, or has a superclass that is itself resilient.
bool CompletelyFragileLayout;
ClassMetadataOptions Options;
Size HeaderSize;
public:
ClassLayoutBuilder(
IRGenModule &IGM, SILType classType, ReferenceCounting refcounting,
bool completelyFragileLayout,
std::optional<ArrayRef<SILType>> tailTypes = std::nullopt)
: StructLayoutBuilder(IGM), TailTypes(tailTypes),
CompletelyFragileLayout(completelyFragileLayout) {
// Start by adding a heap header.
switch (refcounting) {
case ReferenceCounting::Native:
// For native classes, place a full object header.
addHeapHeader();
HeaderSize = CurSize;
break;
case ReferenceCounting::ObjC:
// For ObjC-inheriting classes, we don't reliably know the size of the
// base class, but NSObject only has an `isa` pointer at most.
addNSObjectHeader();
HeaderSize = CurSize;
break;
case ReferenceCounting::None:
case ReferenceCounting::Custom:
break;
case ReferenceCounting::Block:
case ReferenceCounting::Unknown:
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("not a class refcounting kind");
}
// Next, add the fields for the given class.
auto theClass = classType.getClassOrBoundGenericClass();
assert(theClass);
if (theClass->getObjCImplementationDecl())
Options |= ClassMetadataFlags::ClassHasObjCImplementation;
if (theClass->isGenericContext() && !theClass->hasClangNode())
Options |= ClassMetadataFlags::ClassIsGeneric;
addFieldsForClass(theClass, classType, /*superclass=*/false);
if (TailTypes) {
// Add the tail elements.
for (SILType TailTy : *TailTypes) {
const TypeInfo &tailTI = IGM.getTypeInfo(TailTy);
addTailElement(ElementLayout::getIncomplete(tailTI));
}
}
}
/// Return the element layouts.
ArrayRef<ElementLayout> getElements() const {
return Elements;
}
ClassLayout getClassLayout(llvm::Type *classTy) const {
assert(!TailTypes);
auto allStoredProps = IGM.Context.AllocateCopy(AllStoredProperties);
auto allFieldAccesses = IGM.Context.AllocateCopy(AllFieldAccesses);
auto allElements = IGM.Context.AllocateCopy(Elements);
return ClassLayout(*this, Options, classTy,
allStoredProps, allFieldAccesses, allElements, HeaderSize);
}
private:
/// Adds a layout of a tail-allocated element.
void addTailElement(const ElementLayout &Elt) {
Elements.push_back(Elt);
if (!addField(Elements.back(), LayoutStrategy::Universal)) {
// For empty tail allocated elements we still add 1 padding byte.
assert(cast<FixedTypeInfo>(Elt.getType()).getFixedStride() == Size(1) &&
"empty elements should have stride 1");
StructFields.push_back(llvm::ArrayType::get(IGM.Int8Ty, 1));
CurSize += Size(1);
}
}
/// If 'superclass' is true, we're adding fields for one of our
/// superclasses, which means they become part of the struct
/// layout calculation, but are not actually added to any of
/// the vectors like AllStoredProperties, etc. Also, we don't need
/// to compute FieldAccesses for them.
void addFieldsForClass(ClassDecl *theClass, SILType classType,
bool superclass) {
addFieldsForClassImpl(theClass, classType, theClass, classType,
superclass);
}
void addFieldsForClassImpl(ClassDecl *rootClass, SILType rootClassType,
ClassDecl *theClass, SILType classType,
bool superclass) {
if (theClass->hasClangNode() && !theClass->isForeignReferenceType()) {
Options |= ClassMetadataFlags::ClassHasObjCAncestry;
if (!theClass->getObjCImplementationDecl())
return;
}
if (theClass->isNativeNSObjectSubclass()) {
// For layout purposes, we don't have ObjC ancestry.
} else if (theClass->hasSuperclass()) {
SILType superclassType = classType.getSuperclass();
auto superclassDecl = superclassType.getClassOrBoundGenericClass();
assert(superclassType && superclassDecl);
if (IGM.hasResilientMetadata(superclassDecl,
ResilienceExpansion::Maximal,
rootClass))
Options |= ClassMetadataFlags::ClassHasResilientAncestry;
// If the superclass has resilient storage, don't walk its fields.
if (IGM.isResilient(superclassDecl, ResilienceExpansion::Maximal,
rootClass)) {
Options |= ClassMetadataFlags::ClassHasResilientMembers;
// If the superclass is generic, we have to assume that its layout
// depends on its generic parameters. But this only propagates down to
// subclasses whose superclass type depends on the subclass's generic
// context.
if (superclassType.hasArchetype())
Options |= ClassMetadataFlags::ClassHasGenericLayout;
// Since we're not going to visit the superclass, make sure that we still
// set ClassHasObjCAncestry correctly.
if (superclassType.getASTType()->getReferenceCounting()
== ReferenceCounting::ObjC) {
Options |= ClassMetadataFlags::ClassHasObjCAncestry;
}
} else {
// Otherwise, we are allowed to have total knowledge of the superclass
// fields, so walk them to compute the layout.
addFieldsForClassImpl(rootClass, rootClassType, superclassDecl,
superclassType, /*superclass=*/true);
}
}
if (theClass->isGenericContext())
Options |= ClassMetadataFlags::ClassHasGenericAncestry;
if (classHasIncompleteLayout(IGM, theClass))
Options |= ClassMetadataFlags::ClassHasMissingMembers;
if (IGM.hasResilientMetadata(theClass, ResilienceExpansion::Maximal,
rootClass))
Options |= ClassMetadataFlags::ClassHasResilientAncestry;
if (IGM.isResilient(theClass, ResilienceExpansion::Maximal, rootClass)) {
Options |= ClassMetadataFlags::ClassHasResilientMembers;
return;
}
// Collect fields from this class and add them to the layout as a chunk.
addDirectFieldsFromClass(rootClass, rootClassType, theClass, classType,
superclass);
}
void maybeAddCxxRecordBases(ClassDecl *cd) {
auto cxxRecord = dyn_cast_or_null<clang::CXXRecordDecl>(cd->getClangDecl());
if (!cxxRecord)
return;
auto bases = getBasesAndOffsets(cxxRecord);
for (auto base : bases) {
if (base.offset != CurSize) {
assert(base.offset > CurSize);
auto paddingSize = base.offset - CurSize;
auto &opaqueTI =
IGM.getOpaqueStorageTypeInfo(paddingSize, Alignment(1));
auto element = ElementLayout::getIncomplete(opaqueTI);
addField(element, LayoutStrategy::Universal);
}
auto &opaqueTI = IGM.getOpaqueStorageTypeInfo(base.size, Alignment(1));
auto element = ElementLayout::getIncomplete(opaqueTI);
addField(element, LayoutStrategy::Universal);
}
}
void addPaddingBeforeClangField(const clang::FieldDecl *fd) {
auto offset = Size(fd->getASTContext().toCharUnitsFromBits(
fd->getASTContext().getFieldOffset(fd)).getQuantity());
if (offset != CurSize) {
assert(offset > CurSize);
auto paddingSize = offset - CurSize;
auto &opaqueTI = IGM.getOpaqueStorageTypeInfo(paddingSize, Alignment(1));
auto element = ElementLayout::getIncomplete(opaqueTI);
addField(element, LayoutStrategy::Universal);
}
}
void addDirectFieldsFromClass(ClassDecl *rootClass, SILType rootClassType,
ClassDecl *theClass, SILType classType,
bool superclass) {
bool collectStoredProperties =
!superclass ||
(rootClass->isGenericContext() && !rootClassType.getASTType()
->getRecursiveProperties()
.hasUnboundGeneric());
maybeAddCxxRecordBases(theClass);
auto fn = [&](Field field) {
// Ignore missing properties here; we should have flagged these
// with the classHasIncompleteLayout call above.
if (!field.isConcrete()) {
assert(Options & ClassMetadataFlags::ClassHasMissingMembers);
return;
}
// Lower the field type.
SILType type = field.getType(IGM, classType);
auto *eltType = &IGM.getTypeInfo(type);
if (CompletelyFragileLayout && !eltType->isFixedSize()) {
LoweringModeScope scope(IGM, TypeConverter::Mode::Legacy);
eltType = &IGM.getTypeInfo(type);
}
if (!eltType->isFixedSize()) {
if (type.hasArchetype())
Options |= ClassMetadataFlags::ClassHasGenericLayout;
else
Options |= ClassMetadataFlags::ClassHasResilientMembers;
}
auto element = ElementLayout::getIncomplete(*eltType);
bool isKnownEmpty = !addField(element, LayoutStrategy::Universal);
// The 'Elements' list only contains superclass fields when we're
// building a layout for tail allocation.
if (collectStoredProperties || TailTypes)
Elements.push_back(element);
if (collectStoredProperties) {
AllStoredProperties.push_back(field);
AllFieldAccesses.push_back(getFieldAccess(isKnownEmpty));
}
};
auto classDecl = dyn_cast<ClassDecl>(theClass);
if (classDecl) {
if (classDecl->isRootDefaultActor()) {
fn(Field::DefaultActorStorage);
} else if (classDecl->isNonDefaultExplicitDistributedActor()) {
fn(Field::NonDefaultDistributedActorStorage);
}
}
for (auto decl :
theClass->getStoredPropertiesAndMissingMemberPlaceholders()) {
if (decl->getClangDecl())
if (auto clangField = cast<clang::FieldDecl>(decl->getClangDecl()))
addPaddingBeforeClangField(clangField);
if (auto var = dyn_cast<VarDecl>(decl)) {
fn(var);
} else {
fn(cast<MissingMemberDecl>(decl));
}
}
if (!superclass) {
// If we're calculating the layout of a specialized generic class type,
// we cannot use field offset globals for dependently-typed fields,
// because they will not exist -- we only emit such globals for fields
// which are not dependent in all instantiations.
//
// So make sure to fall back to the fully unsubstituted 'abstract layout'
// for any fields whose offsets are not completely fixed.
auto *classTI = &IGM.getTypeInfo(classType).as<ClassTypeInfo>();
SILType selfType = getSelfType(theClass);
auto *selfTI = &IGM.getTypeInfo(selfType).as<ClassTypeInfo>();
// Only calculate an abstract layout if its different than the one
// being computed now.
if (classTI != selfTI) {
auto *abstractLayout = &selfTI->getClassLayout(IGM, selfType,
CompletelyFragileLayout);
for (unsigned index : indices(AllFieldAccesses)) {
auto &access = AllFieldAccesses[index];
auto field = AllStoredProperties[index];
if (access == FieldAccess::NonConstantDirect)
access = abstractLayout->getFieldAccessAndElement(field).first;
}
}
// If the class has Objective-C ancestry and we're doing runtime layout
// that depends on generic parameters, the Swift runtime will first
// layout the fields relative to the static instance start offset, and
// then ask the Objective-C runtime to slide them.
//
// However, this means that if some fields have a generic type, their
// alignment will change the instance start offset between generic
// instantiations, and we cannot use field offset global variables at
// all, even for fields that come before any generically-typed fields.
//
// For example, the alignment of 'x' and 'y' below might depend on 'T':
//
// class Foo<T> : NSFoobar {
// var x : AKlass = AKlass()
// var y : AKlass = AKlass()
// var t : T?
// }
if (Options.contains(ClassMetadataFlags::ClassHasGenericLayout) &&
Options.contains(ClassMetadataFlags::ClassHasObjCAncestry)) {
for (auto &access : AllFieldAccesses) {
if (access == FieldAccess::NonConstantDirect)
access = FieldAccess::ConstantIndirect;
}
}
}
}
FieldAccess getFieldAccess(bool isKnownEmpty) {
// If the field known empty, then its access pattern is always
// constant-direct.
if (isKnownEmpty)
return FieldAccess::ConstantDirect;
// If layout so far depends on generic parameters, we have to load the
// offset from the field offset vector in class metadata.
if (Options.contains(ClassMetadataFlags::ClassHasGenericLayout))
return FieldAccess::ConstantIndirect;
// If layout so far doesn't depend on any generic parameters, but it's
// nonetheless not statically known (because either the stored property
// layout of a superclass is resilient, or one of our own members is a
// resilient value type), then we can rely on the existence
// of a global field offset variable which will be initialized by
// either the Objective-C or Swift runtime, depending on the
// class's heritage.
if (Options.contains(ClassMetadataFlags::ClassHasMissingMembers) ||
Options.contains(ClassMetadataFlags::ClassHasResilientMembers) ||
Options.contains(ClassMetadataFlags::ClassHasObjCAncestry))
return FieldAccess::NonConstantDirect;
// If the layout so far has a fixed size, the field offset is known
// statically.
return FieldAccess::ConstantDirect;
}
};
} // end anonymous namespace
ClassLayout ClassTypeInfo::generateLayout(IRGenModule &IGM, SILType classType,
bool completelyFragileLayout) const {
ClassLayoutBuilder builder(IGM, classType, Refcount, completelyFragileLayout);
auto *classTy = classLayoutType;
if (completelyFragileLayout) {
// Create a name for the new llvm type.
SmallString<32> typeName = classTy->getName();
typeName += "_fragile";
// Create the llvm type.
classTy = llvm::StructType::create(IGM.getLLVMContext(), typeName.str());
}
builder.setAsBodyOfStruct(classTy);
return builder.getClassLayout(classTy);
}
StructLayout *
ClassTypeInfo::createLayoutWithTailElems(IRGenModule &IGM,
SILType classType,
ArrayRef<SILType> tailTypes) const {
// Add the elements for the class properties.
ClassLayoutBuilder builder(IGM, classType, Refcount,
/*CompletelyFragileLayout=*/false,
tailTypes);
// Create a name for the new llvm type.
SmallString<32> typeName;
llvm::raw_svector_ostream os(typeName);
os << classLayoutType->getName() << "_tailelems" << IGM.TailElemTypeID++;
// Create the llvm type.
llvm::StructType *ResultTy = llvm::StructType::create(IGM.getLLVMContext(),
os.str());
builder.setAsBodyOfStruct(ResultTy);
// Create the StructLayout, which is transferred to the caller (the caller is
// responsible for deleting it).
return new StructLayout(builder, classType.getClassOrBoundGenericClass(),
ResultTy, builder.getElements());
}
const ClassLayout &
ClassTypeInfo::getClassLayout(IRGenModule &IGM, SILType classType,
bool forBackwardDeployment) const {
// Perform fragile layout only if Objective-C interop is enabled.
bool completelyFragileLayout = (forBackwardDeployment &&
IGM.Context.LangOpts.EnableObjCInterop);
// Return the cached layout if available.
auto &Layout = completelyFragileLayout ? FragileLayout : ResilientLayout;
if (!Layout) {
auto NewLayout = generateLayout(IGM, classType, completelyFragileLayout);
assert(!Layout && "generateLayout() should not call itself recursively");
Layout = NewLayout;
}
return *Layout;
}
/// Cast the base to i8*, apply the given inbounds offset (in bytes,
/// as a size_t), and cast to a pointer to the given type.
llvm::Value *IRGenFunction::emitByteOffsetGEP(llvm::Value *base,
llvm::Value *offset,
llvm::Type *objectType,
const llvm::Twine &name) {
assert(offset->getType() == IGM.SizeTy || offset->getType() == IGM.Int32Ty);
auto addr = Builder.CreateBitCast(base, IGM.Int8PtrTy);
addr = Builder.CreateInBoundsGEP(IGM.Int8Ty, addr, offset);
return Builder.CreateBitCast(addr, objectType->getPointerTo(), name);
}
/// Cast the base to i8*, apply the given inbounds offset (in bytes,
/// as a size_t), and create an address in the given type.
Address IRGenFunction::emitByteOffsetGEP(llvm::Value *base,
llvm::Value *offset,
const TypeInfo &type,
const llvm::Twine &name) {
auto addr = emitByteOffsetGEP(base, offset, type.getStorageType(), name);
return type.getAddressForPointer(addr);
}
/// Emit a field l-value by applying the given offset to the given base.
static OwnedAddress emitAddressAtOffset(IRGenFunction &IGF, SILType baseType,
llvm::Value *base, llvm::Value *offset,
VarDecl *field) {
auto &fieldTI = IGF.getTypeInfo(baseType.getFieldType(
field, IGF.getSILModule(), IGF.IGM.getMaximalTypeExpansionContext()));
auto addr = IGF.emitByteOffsetGEP(base, offset, fieldTI,
base->getName() + "." + field->getName().str());
return OwnedAddress(addr, base);
}
llvm::Constant *irgen::tryEmitConstantClassFragilePhysicalMemberOffset(
IRGenModule &IGM, SILType baseType, VarDecl *field) {
auto fieldType = baseType.getFieldType(field, IGM.getSILModule(),
IGM.getMaximalTypeExpansionContext());
// If the field is empty, its address doesn't matter.
auto &fieldTI = IGM.getTypeInfo(fieldType);
if (fieldTI.isKnownEmpty(ResilienceExpansion::Maximal)) {
return llvm::ConstantInt::get(IGM.SizeTy, 0);
}
auto &baseClassTI = IGM.getTypeInfo(baseType).as<ClassTypeInfo>();
auto &classLayout = baseClassTI.getClassLayout(IGM, baseType,
/*forBackwardDeployment=*/false);
auto fieldInfo = classLayout.getFieldAccessAndElement(field);
switch (fieldInfo.first) {
case FieldAccess::ConstantDirect: {
auto element = fieldInfo.second;
return llvm::ConstantInt::get(IGM.SizeTy,
element.getByteOffset().getValue());
}
case FieldAccess::NonConstantDirect:
case FieldAccess::ConstantIndirect:
return nullptr;
}
llvm_unreachable("unhandled access");
}
FieldAccess
irgen::getClassFieldAccess(IRGenModule &IGM, SILType baseType, VarDecl *field) {
auto &baseClassTI = IGM.getTypeInfo(baseType).as<ClassTypeInfo>();
auto &classLayout = baseClassTI.getClassLayout(IGM, baseType,
/*forBackwardDeployment=*/false);
return classLayout.getFieldAccessAndElement(field).first;
}
Size
irgen::getClassFieldOffset(IRGenModule &IGM, SILType baseType, VarDecl *field) {
auto &baseClassTI = IGM.getTypeInfo(baseType).as<ClassTypeInfo>();
// FIXME: For now we just assume fragile layout here, because this is used as
// part of emitting class metadata.
auto &classLayout = baseClassTI.getClassLayout(IGM, baseType,
/*forBackwardDeployment=*/true);
auto fieldInfo = classLayout.getFieldAccessAndElement(field);
auto element = fieldInfo.second;
assert(element.hasByteOffset());
return element.getByteOffset();
}
StructLayout *
irgen::getClassLayoutWithTailElems(IRGenModule &IGM, SILType classType,
ArrayRef<SILType> tailTypes) {
auto &ClassTI = IGM.getTypeInfo(classType).as<ClassTypeInfo>();
return ClassTI.createLayoutWithTailElems(IGM, classType, tailTypes);
}
OwnedAddress irgen::projectPhysicalClassMemberAddress(IRGenFunction &IGF,
llvm::Value *base,
SILType baseType,
SILType fieldType,
VarDecl *field) {
// If the field is empty, its address doesn't matter.
auto &fieldTI = IGF.getTypeInfo(fieldType);
if (fieldTI.isKnownEmpty(ResilienceExpansion::Maximal)) {
return OwnedAddress(fieldTI.getUndefAddress(), base);
}
auto &baseClassTI = IGF.getTypeInfo(baseType).as<ClassTypeInfo>();
ClassDecl *baseClass = baseClassTI.getClass();
auto &classLayout = baseClassTI.getClassLayout(IGF.IGM, baseType,
/*forBackwardDeployment=*/false);
auto fieldInfo = classLayout.getFieldAccessAndElement(field);
switch (fieldInfo.first) {
case FieldAccess::ConstantDirect: {
Address baseAddr(base, classLayout.getType(), classLayout.getAlignment());
auto element = fieldInfo.second;
Address memberAddr = element.project(IGF, baseAddr, std::nullopt);
// We may need to bitcast the address if the field is of a generic type.
if (memberAddr.getElementType() != fieldTI.getStorageType())
memberAddr = IGF.Builder.CreateElementBitCast(memberAddr,
fieldTI.getStorageType());
return OwnedAddress(memberAddr, base);
}
case FieldAccess::NonConstantDirect: {
Address offsetA = IGF.IGM.getAddrOfFieldOffset(field, NotForDefinition);
auto offset = IGF.Builder.CreateLoad(offsetA, "offset");
return emitAddressAtOffset(IGF, baseType, base, offset, field);
}
case FieldAccess::ConstantIndirect: {
auto metadata = emitHeapMetadataRefForHeapObject(IGF, base, baseType);
auto offset = emitClassFieldOffset(IGF, baseClass, field, metadata);
return emitAddressAtOffset(IGF, baseType, base, offset, field);
}
}
llvm_unreachable("bad field-access strategy");
}
MemberAccessStrategy
irgen::getPhysicalClassMemberAccessStrategy(IRGenModule &IGM,
SILType baseType, VarDecl *field) {
auto &baseClassTI = IGM.getTypeInfo(baseType).as<ClassTypeInfo>();
ClassDecl *baseClass = baseType.getClassOrBoundGenericClass();
auto &classLayout = baseClassTI.getClassLayout(IGM, baseType,
/*forBackwardDeployment=*/false);
auto fieldInfo = classLayout.getFieldAccessAndElement(field);
switch (fieldInfo.first) {
case FieldAccess::ConstantDirect: {
auto element = fieldInfo.second;
return MemberAccessStrategy::getDirectFixed(element.getByteOffset());
}
case FieldAccess::NonConstantDirect: {
std::string symbol =
LinkEntity::forFieldOffset(field).mangleAsString(IGM.Context);
return MemberAccessStrategy::getDirectGlobal(std::move(symbol),
MemberAccessStrategy::OffsetKind::Bytes_Word);
}
case FieldAccess::ConstantIndirect: {
Size indirectOffset = getClassFieldOffsetOffset(IGM, baseClass, field);
return MemberAccessStrategy::getIndirectFixed(indirectOffset,
MemberAccessStrategy::OffsetKind::Bytes_Word);
}
}
llvm_unreachable("bad field-access strategy");
}
Address irgen::emitTailProjection(IRGenFunction &IGF, llvm::Value *Base,
SILType ClassType,
SILType TailType) {
const ClassTypeInfo &classTI = IGF.getTypeInfo(ClassType).as<ClassTypeInfo>();
llvm::Value *Offset = nullptr;
auto &layout = classTI.getClassLayout(IGF.IGM, ClassType,
/*forBackwardDeployment=*/false);
Alignment HeapObjAlign = IGF.IGM.TargetInfo.HeapObjectAlignment;
Alignment Align;
// Get the size of the class instance.
if (layout.isFixedLayout()) {
Size ClassSize = layout.getSize();
Offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, ClassSize.getValue());
Align = HeapObjAlign.alignmentAtOffset(ClassSize);
} else {
llvm::Value *metadata = emitHeapMetadataRefForHeapObject(IGF, Base,
ClassType);
Offset = emitClassResilientInstanceSizeAndAlignMask(IGF,
ClassType.getClassOrBoundGenericClass(),
metadata).first;
}
// Align up to the TailType.
assert(TailType.isObject());
const TypeInfo &TailTI = IGF.getTypeInfo(TailType);
llvm::Value *AlignMask = TailTI.getAlignmentMask(IGF, TailType);
Offset = IGF.Builder.CreateAdd(Offset, AlignMask);
llvm::Value *InvertedMask = IGF.Builder.CreateNot(AlignMask);
Offset = IGF.Builder.CreateAnd(Offset, InvertedMask);
Address Addr = IGF.emitByteOffsetGEP(Base, Offset, TailTI, "tailaddr");
if (auto *OffsetConst = dyn_cast<llvm::ConstantInt>(Offset)) {
// Try to get an accurate alignment (only possible if the Offset is a
// constant).
Size TotalOffset(OffsetConst->getZExtValue());
Align = HeapObjAlign.alignmentAtOffset(TotalOffset);
}
return Address(Addr.getAddress(), Addr.getElementType(), Align);
}
/// Try to stack promote a class instance with possible tail allocated arrays.
///
/// Returns the alloca if successful, or nullptr otherwise.
static llvm::Value *stackPromote(IRGenFunction &IGF,
const ClassLayout &FieldLayout,
int &StackAllocSize,
ArrayRef<std::pair<SILType, llvm::Value *>> TailArrays) {
if (StackAllocSize < 0)
return nullptr;
if (!FieldLayout.isFixedLayout())
return nullptr;
if (!FieldLayout.isFixedSize())
return nullptr;
// Calculate the total size needed.
// The first part is the size of the class itself.
Alignment ClassAlign = FieldLayout.getAlignment();
Size TotalSize = FieldLayout.getSize();
// Add size for tail-allocated arrays.
for (const auto &TailArray : TailArrays) {
SILType ElemTy = TailArray.first;
llvm::Value *Count = TailArray.second;
// We can only calculate a constant size if the tail-count is constant.
auto *CI = dyn_cast<llvm::ConstantInt>(Count);
if (!CI)
return nullptr;
const TypeInfo &ElemTI = IGF.getTypeInfo(ElemTy);
if (!ElemTI.isFixedSize())
return nullptr;
const FixedTypeInfo &ElemFTI = ElemTI.as<FixedTypeInfo>();
Alignment ElemAlign = ElemFTI.getFixedAlignment();
// This should not happen - just to be save.
if (ElemAlign > ClassAlign)
return nullptr;
TotalSize = TotalSize.roundUpToAlignment(ElemAlign);
TotalSize += ElemFTI.getFixedStride() * CI->getValue().getZExtValue();
}
if (TotalSize > Size(StackAllocSize))
return nullptr;
StackAllocSize = TotalSize.getValue();
if (TotalSize == FieldLayout.getSize()) {
// No tail-allocated arrays: we can use the llvm class type for alloca.
llvm::Type *ClassTy = FieldLayout.getType();
Address Alloca = IGF.createAlloca(ClassTy, ClassAlign, "reference.raw");
return Alloca.getAddress();
}
// Use a byte-array as type for alloca.
llvm::Value *SizeVal = llvm::ConstantInt::get(IGF.IGM.Int32Ty,
TotalSize.getValue());
Address Alloca = IGF.createAlloca(IGF.IGM.Int8Ty, SizeVal, ClassAlign,
"reference.raw");
return Alloca.getAddress();
}
std::pair<llvm::Value *, llvm::Value *>
irgen::appendSizeForTailAllocatedArrays(IRGenFunction &IGF,
llvm::Value *size, llvm::Value *alignMask,
TailArraysRef TailArrays) {
for (const auto &TailArray : TailArrays) {
SILType ElemTy = TailArray.first;
llvm::Value *Count = TailArray.second;
const TypeInfo &ElemTI = IGF.getTypeInfo(ElemTy);
// Align up to the tail-allocated array.
llvm::Value *ElemStride = ElemTI.getStride(IGF, ElemTy);
llvm::Value *ElemAlignMask = ElemTI.getAlignmentMask(IGF, ElemTy);
size = IGF.Builder.CreateAdd(size, ElemAlignMask);
llvm::Value *InvertedMask = IGF.Builder.CreateNot(ElemAlignMask);
size = IGF.Builder.CreateAnd(size, InvertedMask);
// Add the size of the tail allocated array.
llvm::Value *AllocSize = IGF.Builder.CreateMul(ElemStride, Count);
size = IGF.Builder.CreateAdd(size, AllocSize);
alignMask = IGF.Builder.CreateOr(alignMask, ElemAlignMask);
}
return {size, alignMask};
}
/// Emit an allocation of a class.
llvm::Value *irgen::emitClassAllocation(IRGenFunction &IGF, SILType selfType,
bool objc, bool isBare,
int &StackAllocSize,
TailArraysRef TailArrays) {
auto &classTI = IGF.getTypeInfo(selfType).as<ClassTypeInfo>();
auto classType = selfType.getASTType();
// If we need to use Objective-C allocation, do so.
// If the root class isn't known to use the Swift allocator, we need
// to call [self alloc].
if (objc) {
llvm::Value *metadata =
emitClassHeapMetadataRef(IGF, classType, MetadataValueType::ObjCClass,
MetadataState::Complete,
/*allow uninitialized*/ true);
StackAllocSize = -1;
return emitObjCAllocObjectCall(IGF, metadata, selfType);
}
auto &classLayout = classTI.getClassLayout(IGF.IGM, selfType,
/*forBackwardDeployment=*/false);
llvm::Type *destType = classLayout.getType()->getPointerTo();
llvm::Value *val = nullptr;
if (llvm::Value *Promoted = stackPromote(IGF, classLayout, StackAllocSize,
TailArrays)) {
if (isBare) {
val = Promoted;
} else {
llvm::Value *metadata =
emitClassHeapMetadataRef(IGF, classType, MetadataValueType::TypeMetadata,
MetadataState::Complete);
val = IGF.Builder.CreateBitCast(Promoted, IGF.IGM.RefCountedPtrTy);
val = IGF.emitInitStackObjectCall(metadata, val, "reference.new");
}
} else {
llvm::Value *metadata =
emitClassHeapMetadataRef(IGF, classType, MetadataValueType::TypeMetadata,
MetadataState::Complete);
llvm::Value *size, *alignMask;
if (classLayout.isFixedSize()) {
size = IGF.IGM.getSize(classLayout.getSize());
alignMask = IGF.IGM.getSize(classLayout.getAlignMask());
} else {
std::tie(size, alignMask)
= emitClassResilientInstanceSizeAndAlignMask(IGF,
selfType.getClassOrBoundGenericClass(),
metadata);
}
// Allocate the object on the heap.
std::tie(size, alignMask)
= appendSizeForTailAllocatedArrays(IGF, size, alignMask, TailArrays);
val = IGF.emitAllocObjectCall(metadata, size, alignMask, "reference.new");
StackAllocSize = -1;
}
return IGF.Builder.CreateBitCast(val, destType);
}
llvm::Value *irgen::emitClassAllocationDynamic(IRGenFunction &IGF,
llvm::Value *metadata,
SILType selfType,
bool objc,
int &StackAllocSize,
TailArraysRef TailArrays) {
// If we need to use Objective-C allocation, do so.
if (objc) {
StackAllocSize = -1;
return emitObjCAllocObjectCall(IGF, metadata, selfType);
}
llvm::Value *Promoted;
auto &classTI = IGF.getTypeInfo(selfType).as<ClassTypeInfo>();
auto &classLayout = classTI.getClassLayout(IGF.IGM, selfType,
/*forBackwardDeployment=*/false);
// If we are allowed to allocate on the stack we are allowed to use
// `selfType`'s size assumptions.
if (StackAllocSize >= 0 &&
(Promoted = stackPromote(IGF, classLayout, StackAllocSize,
TailArrays))) {
llvm::Value *val = IGF.Builder.CreateBitCast(Promoted,
IGF.IGM.RefCountedPtrTy);
val = IGF.emitInitStackObjectCall(metadata, val, "reference.new");
llvm::Type *destType = classLayout.getType()->getPointerTo();
return IGF.Builder.CreateBitCast(val, destType);
}
// Otherwise, allocate using Swift's routines.
llvm::Value *size, *alignMask;
std::tie(size, alignMask)
= emitClassResilientInstanceSizeAndAlignMask(IGF,
selfType.getClassOrBoundGenericClass(),
metadata);
std::tie(size, alignMask)
= appendSizeForTailAllocatedArrays(IGF, size, alignMask, TailArrays);
llvm::Value *val = IGF.emitAllocObjectCall(metadata, size, alignMask,
"reference.new");
StackAllocSize = -1;
llvm::Type *destType = classLayout.getType()->getPointerTo();
return IGF.Builder.CreateBitCast(val, destType);
}
/// Get the instance size and alignment mask for the given class
/// instance.
static void getInstanceSizeAndAlignMask(IRGenFunction &IGF,
SILType selfType,
ClassDecl *selfClass,
llvm::Value *selfValue,
llvm::Value *&size,
llvm::Value *&alignMask) {
// Try to determine the size of the object we're deallocating.
auto &info = IGF.IGM.getTypeInfo(selfType).as<ClassTypeInfo>();
auto &layout = info.getClassLayout(IGF.IGM, selfType,
/*forBackwardDeployment=*/false);
// If it's fixed, emit the constant size and alignment mask.
if (layout.isFixedLayout()) {
size = IGF.IGM.getSize(layout.getSize());
alignMask = IGF.IGM.getSize(layout.getAlignMask());
return;
}
// Otherwise, get them from the metadata.
llvm::Value *metadata =
emitHeapMetadataRefForHeapObject(IGF, selfValue, selfType);
std::tie(size, alignMask)
= emitClassResilientInstanceSizeAndAlignMask(IGF, selfClass, metadata);
}
static llvm::Value *emitCastToHeapObject(IRGenFunction &IGF,
llvm::Value *value) {
return IGF.Builder.CreateBitCast(value, IGF.IGM.RefCountedPtrTy);
}
void irgen::emitClassDeallocation(IRGenFunction &IGF,
SILType selfType,
llvm::Value *selfValue) {
auto *theClass = selfType.getClassOrBoundGenericClass();
// We want to deallocate default actors or potential default
// actors differently. We assume that being a default actor
// is purely a property of the root actor class, so just go to
// that class.
if (auto rootActorClass = theClass->getRootActorClass()) {
// If it's a default actor, use swift_deallocDefaultActor.
if (rootActorClass->isDefaultActor(IGF.IGM.getSwiftModule(),
ResilienceExpansion::Maximal)) {
selfValue = emitCastToHeapObject(IGF, selfValue);
IGF.Builder.CreateCall(IGF.IGM.getDefaultActorDeallocateFunctionPointer(),
{selfValue});
return;
}