forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenHeap.cpp
1652 lines (1438 loc) · 64.1 KB
/
GenHeap.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
//===--- GenHeap.cpp - Layout of heap objects and their metadata ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements routines for arbitrary Swift-native heap objects,
// such as layout and reference-counting.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ErrorHandling.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Intrinsics.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/IRGenOptions.h"
#include "Explosion.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "HeapTypeInfo.h"
#include "IndirectTypeInfo.h"
#include "WeakTypeInfo.h"
#include "GenHeap.h"
using namespace swift;
using namespace irgen;
/// Produce a constant to place in a metatype's isa field
/// corresponding to the given metadata kind.
static llvm::ConstantInt *getMetadataKind(IRGenModule &IGM,
MetadataKind kind) {
return llvm::ConstantInt::get(IGM.MetadataKindTy, uint8_t(kind));
}
/// Perform the layout required for a heap object.
HeapLayout::HeapLayout(IRGenModule &IGM, LayoutStrategy strategy,
ArrayRef<SILType> fieldTypes,
ArrayRef<const TypeInfo *> fieldTypeInfos,
llvm::StructType *typeToFill,
NecessaryBindings &&bindings)
: StructLayout(IGM, CanType(), LayoutKind::HeapObject, strategy,
fieldTypeInfos, typeToFill),
ElementTypes(fieldTypes.begin(), fieldTypes.end()),
Bindings(std::move(bindings))
{
#ifndef NDEBUG
assert(fieldTypeInfos.size() == fieldTypes.size()
&& "type infos don't match types");
if (!Bindings.empty()) {
assert(fieldTypeInfos.size() >= 1 && "no field for bindings");
auto fixedBindingsField = dyn_cast<FixedTypeInfo>(fieldTypeInfos[0]);
assert(fixedBindingsField
&& "bindings field is not fixed size");
assert(fixedBindingsField->getFixedSize()
== Bindings.getBufferSize(IGM)
&& fixedBindingsField->getFixedAlignment()
== IGM.getPointerAlignment()
&& "bindings field doesn't fit bindings");
}
#endif
}
HeapNonFixedOffsets::HeapNonFixedOffsets(IRGenFunction &IGF,
const HeapLayout &layout) {
if (!layout.isFixedLayout()) {
// Calculate all the non-fixed layouts.
// TODO: We could be lazier about this.
llvm::Value *offset = nullptr;
llvm::Value *totalAlign = llvm::ConstantInt::get(IGF.IGM.SizeTy,
layout.getAlignment().getMaskValue());
for (unsigned i : indices(layout.getElements())) {
auto &elt = layout.getElement(i);
auto eltTy = layout.getElementTypes()[i];
switch (elt.getKind()) {
case ElementLayout::Kind::InitialNonFixedSize:
// Factor the non-fixed-size field's alignment into the total alignment.
totalAlign = IGF.Builder.CreateOr(totalAlign,
elt.getType().getAlignmentMask(IGF, eltTy));
SWIFT_FALLTHROUGH;
case ElementLayout::Kind::Empty:
case ElementLayout::Kind::Fixed:
// Don't need to dynamically calculate this offset.
Offsets.push_back(nullptr);
break;
case ElementLayout::Kind::NonFixed:
// Start calculating non-fixed offsets from the end of the first fixed
// field.
assert(i > 0 && "shouldn't begin with a non-fixed field");
auto &prevElt = layout.getElement(i-1);
auto prevType = layout.getElementTypes()[i-1];
// Start calculating offsets from the last fixed-offset field.
if (!offset) {
Size lastFixedOffset = layout.getElement(i-1).getByteOffset();
if (auto *fixedType = dyn_cast<FixedTypeInfo>(&prevElt.getType())) {
// If the last fixed-offset field is also fixed-size, we can
// statically compute the end of the fixed-offset fields.
auto fixedEnd = lastFixedOffset + fixedType->getFixedSize();
offset
= llvm::ConstantInt::get(IGF.IGM.SizeTy, fixedEnd.getValue());
} else {
// Otherwise, we need to add the dynamic size to the fixed start
// offset.
offset
= llvm::ConstantInt::get(IGF.IGM.SizeTy,
lastFixedOffset.getValue());
offset = IGF.Builder.CreateAdd(offset,
prevElt.getType().getSize(IGF, prevType));
}
}
// Round up to alignment to get the offset.
auto alignMask = elt.getType().getAlignmentMask(IGF, eltTy);
auto notAlignMask = IGF.Builder.CreateNot(alignMask);
offset = IGF.Builder.CreateAdd(offset, alignMask);
offset = IGF.Builder.CreateAnd(offset, notAlignMask);
Offsets.push_back(offset);
// Advance by the field's size to start the next field.
offset = IGF.Builder.CreateAdd(offset,
elt.getType().getSize(IGF, eltTy));
totalAlign = IGF.Builder.CreateOr(totalAlign, alignMask);
break;
}
}
TotalSize = offset;
TotalAlignMask = totalAlign;
} else {
TotalSize = layout.emitSize(IGF.IGM);
TotalAlignMask = layout.emitAlignMask(IGF.IGM);
}
}
void irgen::emitDeallocateHeapObject(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocObjectFn(),
{object, size, alignMask});
}
void irgen::emitDeallocateClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocClassInstanceFn(),
{object, size, alignMask});
}
void irgen::emitDeallocatePartialClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *metadata,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocPartialClassInstanceFn(),
{object, metadata, size, alignMask});
}
/// Create the destructor function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
static llvm::Function *createDtorFn(IRGenModule &IGM,
const HeapLayout &layout) {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectdestroy", &IGM.Module);
fn->setAttributes(IGM.constructInitialAttributes());
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
Address structAddr = layout.emitCastTo(IGF, &*fn->arg_begin());
// Bind necessary bindings, if we have them.
if (layout.hasBindings()) {
// The type metadata bindings should be at a fixed offset, so we can pass
// None for NonFixedOffsets. If we didn't, we'd have a chicken-egg problem.
auto bindingsAddr = layout.getElement(0).project(IGF, structAddr, None);
layout.getBindings().restore(IGF, bindingsAddr);
}
// Figure out the non-fixed offsets.
HeapNonFixedOffsets offsets(IGF, layout);
// Destroy the fields.
for (unsigned i : indices(layout.getElements())) {
auto &field = layout.getElement(i);
auto fieldTy = layout.getElementTypes()[i];
if (field.isPOD())
continue;
field.getType().destroy(IGF, field.project(IGF, structAddr, offsets),
fieldTy);
}
emitDeallocateHeapObject(IGF, &*fn->arg_begin(), offsets.getSize(),
offsets.getAlignMask());
IGF.Builder.CreateRetVoid();
return fn;
}
/// Create the size function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
llvm::Constant *HeapLayout::createSizeFn(IRGenModule &IGM) const {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectsize", &IGM.Module);
fn->setAttributes(IGM.constructInitialAttributes());
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
// Ignore the object pointer; we aren't a dynamically-sized array,
// so it's pointless.
llvm::Value *size = emitSize(IGM);
IGF.Builder.CreateRet(size);
return fn;
}
static llvm::Constant *buildPrivateMetadata(IRGenModule &IGM,
const HeapLayout &layout,
llvm::Constant *dtorFn,
MetadataKind kind) {
// Build the fields of the private metadata.
SmallVector<llvm::Constant*, 4> fields;
fields.push_back(dtorFn);
fields.push_back(llvm::ConstantPointerNull::get(IGM.WitnessTablePtrTy));
fields.push_back(llvm::ConstantStruct::get(IGM.TypeMetadataStructTy,
getMetadataKind(IGM, kind)));
// Figure out the offset to the first element, which is necessary to be able
// to polymorphically project as a generic box.
auto elements = layout.getElements();
Size offset;
if (!elements.empty()
&& elements[0].getKind() == ElementLayout::Kind::Fixed)
offset = elements[0].getByteOffset();
else
offset = Size(0);
fields.push_back(llvm::ConstantInt::get(IGM.Int32Ty, offset.getValue()));
llvm::Constant *init =
llvm::ConstantStruct::get(IGM.FullBoxMetadataStructTy, fields);
llvm::GlobalVariable *var =
new llvm::GlobalVariable(IGM.Module, IGM.FullBoxMetadataStructTy,
/*constant*/ true,
llvm::GlobalVariable::PrivateLinkage, init,
"metadata");
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 2)
};
return llvm::ConstantExpr::getInBoundsGetElementPtr(
/*Ty=*/nullptr, var, indices);
}
llvm::Constant *HeapLayout::getPrivateMetadata(IRGenModule &IGM) const {
if (!privateMetadata)
privateMetadata = buildPrivateMetadata(IGM, *this, createDtorFn(IGM, *this),
MetadataKind::HeapLocalVariable);
return privateMetadata;
}
llvm::Value *IRGenFunction::emitUnmanagedAlloc(const HeapLayout &layout,
const llvm::Twine &name,
const HeapNonFixedOffsets *offsets) {
llvm::Value *metadata = layout.getPrivateMetadata(IGM);
llvm::Value *size, *alignMask;
if (offsets) {
size = offsets->getSize();
alignMask = offsets->getAlignMask();
} else {
size = layout.emitSize(IGM);
alignMask = layout.emitAlignMask(IGM);
}
return emitAllocObjectCall(metadata, size, alignMask, name);
}
namespace {
class BuiltinNativeObjectTypeInfo
: public HeapTypeInfo<BuiltinNativeObjectTypeInfo> {
public:
BuiltinNativeObjectTypeInfo(llvm::PointerType *storage,
Size size, SpareBitVector spareBits,
Alignment align)
: HeapTypeInfo(storage, size, spareBits, align) {}
/// Builtin.NativeObject uses Swift native reference-counting.
ReferenceCounting getReferenceCounting() const {
return ReferenceCounting::Native;
}
};
}
const LoadableTypeInfo *TypeConverter::convertBuiltinNativeObject() {
return new BuiltinNativeObjectTypeInfo(IGM.RefCountedPtrTy,
IGM.getPointerSize(),
IGM.getHeapObjectSpareBits(),
IGM.getPointerAlignment());
}
namespace {
/// A type implementation for an @unowned(unsafe) reference to an
/// object.
class UnmanagedReferenceTypeInfo
: public PODSingleScalarTypeInfo<UnmanagedReferenceTypeInfo,
LoadableTypeInfo> {
public:
UnmanagedReferenceTypeInfo(llvm::Type *type,
const SpareBitVector &spareBits,
Size size, Alignment alignment)
: PODSingleScalarTypeInfo(type, size, spareBits, alignment) {}
// Unmanaged types have the same spare bits as managed heap objects.
bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
return true;
}
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return getHeapObjectExtraInhabitantCount(IGM);
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const override {
return getHeapObjectFixedExtraInhabitantValue(IGM, bits, index, 0);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src,
SILType T)
const override {
return getHeapObjectExtraInhabitantIndex(IGF, src);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T) const override {
return storeHeapObjectExtraInhabitant(IGF, index, dest);
}
};
}
const LoadableTypeInfo *
TypeConverter::createUnmanagedStorageType(llvm::Type *valueType) {
return new UnmanagedReferenceTypeInfo(valueType,
IGM.getHeapObjectSpareBits(),
IGM.getPointerSize(),
IGM.getPointerAlignment());
}
namespace {
/// A type implementation for an [unowned] reference to an object
/// with a known-Swift reference count.
class NativeUnownedReferenceTypeInfo
: public SingleScalarTypeInfo<NativeUnownedReferenceTypeInfo,
LoadableTypeInfo> {
llvm::Type *ValueType;
public:
NativeUnownedReferenceTypeInfo(llvm::Type *valueType,
llvm::Type *unownedType,
SpareBitVector &&spareBits,
Size size, Alignment alignment)
: SingleScalarTypeInfo(unownedType, size, std::move(spareBits),
alignment, IsNotPOD, IsFixedSize),
ValueType(valueType) {}
enum { IsScalarPOD = false };
llvm::Type *getScalarType() const {
return ValueType;
}
Address projectScalar(IRGenFunction &IGF, Address addr) const {
return IGF.Builder.CreateBitCast(addr, ValueType->getPointerTo());
}
void emitScalarRetain(IRGenFunction &IGF, llvm::Value *value,
Atomicity atomicity) const {
IGF.emitNativeUnownedRetain(value);
}
void emitScalarRelease(IRGenFunction &IGF, llvm::Value *value,
Atomicity atomicity) const {
IGF.emitNativeUnownedRelease(value);
}
void emitScalarFixLifetime(IRGenFunction &IGF, llvm::Value *value) const {
IGF.emitFixLifetime(value);
}
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return IGM.getUnownedExtraInhabitantCount(ReferenceCounting::Native);
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const override {
return IGM.getUnownedExtraInhabitantValue(bits, index,
ReferenceCounting::Native);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src,
SILType T) const override {
return IGF.getUnownedExtraInhabitantIndex(src,
ReferenceCounting::Native);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T) const override {
return IGF.storeUnownedExtraInhabitant(index, dest,
ReferenceCounting::Native);
}
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override {
return IGM.getUnownedExtraInhabitantMask(ReferenceCounting::Native);
}
};
/// A type implementation for a [weak] reference to an object
/// with a known-Swift reference count.
class NativeWeakReferenceTypeInfo
: public IndirectTypeInfo<NativeWeakReferenceTypeInfo,
WeakTypeInfo> {
llvm::Type *ValueType;
public:
NativeWeakReferenceTypeInfo(llvm::Type *valueType,
llvm::Type *weakType,
Size size, Alignment alignment,
SpareBitVector &&spareBits)
: IndirectTypeInfo(weakType, size, alignment, std::move(spareBits)),
ValueType(valueType) {}
void initializeWithCopy(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitNativeWeakCopyInit(destAddr, srcAddr);
}
void initializeWithTake(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitNativeWeakTakeInit(destAddr, srcAddr);
}
void assignWithCopy(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitNativeWeakCopyAssign(destAddr, srcAddr);
}
void assignWithTake(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitNativeWeakTakeAssign(destAddr, srcAddr);
}
void destroy(IRGenFunction &IGF, Address addr, SILType T) const override {
IGF.emitNativeWeakDestroy(addr);
}
llvm::Type *getOptionalIntType() const {
return llvm::IntegerType::get(ValueType->getContext(),
getFixedSize().getValueInBits());
}
void weakLoadStrong(IRGenFunction &IGF, Address addr,
Explosion &out) const override {
auto value = IGF.emitNativeWeakLoadStrong(addr, ValueType);
// The optional will be lowered to an integer type the size of the word.
out.add(IGF.Builder.CreatePtrToInt(value, getOptionalIntType()));
}
void weakTakeStrong(IRGenFunction &IGF, Address addr,
Explosion &out) const override {
auto value = IGF.emitNativeWeakTakeStrong(addr, ValueType);
// The optional will be lowered to an integer type the size of the word.
out.add(IGF.Builder.CreatePtrToInt(value, getOptionalIntType()));
}
void weakInit(IRGenFunction &IGF, Explosion &in,
Address dest) const override {
llvm::Value *value = in.claimNext();
// The optional will be lowered to an integer type the size of the word.
assert(value->getType() == getOptionalIntType());
value = IGF.Builder.CreateIntToPtr(value, ValueType);
IGF.emitNativeWeakInit(value, dest);
}
void weakAssign(IRGenFunction &IGF, Explosion &in,
Address dest) const override {
llvm::Value *value = in.claimNext();
// The optional will be lowered to an integer type the size of the word.
assert(value->getType() == getOptionalIntType());
value = IGF.Builder.CreateIntToPtr(value, ValueType);
IGF.emitNativeWeakAssign(value, dest);
}
};
}
SpareBitVector IRGenModule::getWeakReferenceSpareBits() const {
// The runtime needs to be able to freely manipulate live weak
// references without worrying about us mucking around with their
// bits, so weak references are completely opaque.
return SpareBitVector::getConstant(getWeakReferenceSize().getValueInBits(),
false);
}
SpareBitVector
IRGenModule::getUnownedReferenceSpareBits(ReferenceCounting style) const {
// If unknown references don't exist, we can just use the same rules as
// regular pointers.
if (!ObjCInterop) {
assert(style == ReferenceCounting::Native);
return getHeapObjectSpareBits();
}
// Otherwise, we have to be conservative (even with native
// reference-counting) in order to interoperate with code that might
// be working more generically with the memory/type.
return SpareBitVector::getConstant(getPointerSize().getValueInBits(), false);
}
unsigned IRGenModule::getUnownedExtraInhabitantCount(ReferenceCounting style) {
if (!ObjCInterop) {
assert(style == ReferenceCounting::Native);
return getHeapObjectExtraInhabitantCount(*this);
}
return 1;
}
APInt IRGenModule::getUnownedExtraInhabitantValue(unsigned bits, unsigned index,
ReferenceCounting style) {
if (!ObjCInterop) {
assert(style == ReferenceCounting::Native);
return getHeapObjectFixedExtraInhabitantValue(*this, bits, index, 0);
}
assert(index == 0);
return APInt(bits, 0);
}
APInt IRGenModule::getUnownedExtraInhabitantMask(ReferenceCounting style) {
return APInt::getAllOnesValue(getPointerSize().getValueInBits());
}
llvm::Value *IRGenFunction::getUnownedExtraInhabitantIndex(Address src,
ReferenceCounting style) {
if (!IGM.ObjCInterop) {
assert(style == ReferenceCounting::Native);
return getHeapObjectExtraInhabitantIndex(*this, src);
}
assert(src.getAddress()->getType() == IGM.UnownedReferencePtrTy);
src = Builder.CreateStructGEP(src, 0, Size(0));
llvm::Value *ptr = Builder.CreateLoad(src);
llvm::Value *isNull = Builder.CreateIsNull(ptr);
llvm::Value *result =
Builder.CreateSelect(isNull, Builder.getInt32(0),
llvm::ConstantInt::getSigned(IGM.Int32Ty, -1));
return result;
}
void IRGenFunction::storeUnownedExtraInhabitant(llvm::Value *index,
Address dest,
ReferenceCounting style) {
if (!IGM.ObjCInterop) {
assert(style == ReferenceCounting::Native);
return storeHeapObjectExtraInhabitant(*this, index, dest);
}
// Since there's only one legal extra inhabitant, it has to have
// the null pattern.
assert(dest.getAddress()->getType() == IGM.UnownedReferencePtrTy);
dest = Builder.CreateStructGEP(dest, 0, Size(0));
llvm::Value *null = llvm::ConstantPointerNull::get(IGM.RefCountedPtrTy);
Builder.CreateStore(null, dest);
}
namespace {
/// A type implementation for an [unowned] reference to an object
/// that is not necessarily a Swift object.
class UnknownUnownedReferenceTypeInfo :
public IndirectTypeInfo<UnknownUnownedReferenceTypeInfo, FixedTypeInfo> {
public:
UnknownUnownedReferenceTypeInfo(llvm::Type *unownedType,
SpareBitVector &&spareBits,
Size size, Alignment alignment)
: IndirectTypeInfo(unownedType, size, std::move(spareBits), alignment,
IsNotPOD, IsNotBitwiseTakable, IsFixedSize) {
}
void assignWithCopy(IRGenFunction &IGF, Address dest,
Address src, SILType type) const override {
IGF.emitUnknownUnownedCopyAssign(dest, src);
}
void initializeWithCopy(IRGenFunction &IGF, Address dest,
Address src, SILType type) const override {
IGF.emitUnknownUnownedCopyInit(dest, src);
}
void assignWithTake(IRGenFunction &IGF, Address dest,
Address src, SILType type) const override {
IGF.emitUnknownUnownedTakeAssign(dest, src);
}
void initializeWithTake(IRGenFunction &IGF, Address dest,
Address src, SILType type) const override {
IGF.emitUnknownUnownedTakeInit(dest, src);
}
void destroy(IRGenFunction &IGF, Address addr,
SILType type) const override {
IGF.emitUnknownUnownedDestroy(addr);
}
// Unowned types have the same extra inhabitants as normal pointers.
// They do not, however, necessarily have any spare bits.
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return IGM.getUnownedExtraInhabitantCount(ReferenceCounting::Unknown);
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const override {
return IGM.getUnownedExtraInhabitantValue(bits, index,
ReferenceCounting::Unknown);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src,
SILType T) const override {
return IGF.getUnownedExtraInhabitantIndex(src,
ReferenceCounting::Unknown);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T) const override {
return IGF.storeUnownedExtraInhabitant(index, dest,
ReferenceCounting::Unknown);
}
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override {
return IGM.getUnownedExtraInhabitantMask(ReferenceCounting::Unknown);
}
};
/// A type implementation for a [weak] reference to an object
/// that is not necessarily a Swift object.
class UnknownWeakReferenceTypeInfo :
public IndirectTypeInfo<UnknownWeakReferenceTypeInfo,
WeakTypeInfo> {
/// We need to separately store the value type because we always
/// use the same type to store the weak reference struct.
llvm::Type *ValueType;
public:
UnknownWeakReferenceTypeInfo(llvm::Type *valueType,
llvm::Type *weakType,
Size size, Alignment alignment,
SpareBitVector &&spareBits)
: IndirectTypeInfo(weakType, size, alignment, std::move(spareBits)),
ValueType(valueType) {}
void initializeWithCopy(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitUnknownWeakCopyInit(destAddr, srcAddr);
}
void initializeWithTake(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitUnknownWeakTakeInit(destAddr, srcAddr);
}
void assignWithCopy(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitUnknownWeakCopyAssign(destAddr, srcAddr);
}
void assignWithTake(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
IGF.emitUnknownWeakTakeAssign(destAddr, srcAddr);
}
void destroy(IRGenFunction &IGF, Address addr, SILType T) const override {
IGF.emitUnknownWeakDestroy(addr);
}
llvm::Type *getOptionalIntType() const {
return llvm::IntegerType::get(ValueType->getContext(),
getFixedSize().getValueInBits());
}
void weakLoadStrong(IRGenFunction &IGF, Address addr,
Explosion &out) const override {
auto value = IGF.emitUnknownWeakLoadStrong(addr, ValueType);
// The optional will be lowered to an integer type the size of the word.
out.add(IGF.Builder.CreatePtrToInt(value, getOptionalIntType()));
}
void weakTakeStrong(IRGenFunction &IGF, Address addr,
Explosion &out) const override {
auto value = IGF.emitUnknownWeakTakeStrong(addr, ValueType);
// The optional will be lowered to an integer type the size of the word.
out.add(IGF.Builder.CreatePtrToInt(value, getOptionalIntType()));
}
void weakInit(IRGenFunction &IGF, Explosion &in,
Address dest) const override {
llvm::Value *value = in.claimNext();
// The optional will be lowered to an integer type the size of the word.
assert(value->getType() == getOptionalIntType());
value = IGF.Builder.CreateIntToPtr(value, ValueType);
IGF.emitUnknownWeakInit(value, dest);
}
void weakAssign(IRGenFunction &IGF, Explosion &in,
Address dest) const override {
llvm::Value *value = in.claimNext();
// The optional will be lowered to an integer type the size of the word.
assert(value->getType() == getOptionalIntType());
value = IGF.Builder.CreateIntToPtr(value, ValueType);
IGF.emitUnknownWeakAssign(value, dest);
}
};
}
const TypeInfo *TypeConverter::createUnownedStorageType(llvm::Type *valueType,
ReferenceCounting style) {
auto &&spareBits = IGM.getUnownedReferenceSpareBits(style);
switch (style) {
case ReferenceCounting::Native:
return new NativeUnownedReferenceTypeInfo(valueType,
IGM.UnownedReferencePtrTy->getElementType(),
std::move(spareBits),
IGM.getPointerSize(),
IGM.getPointerAlignment());
case ReferenceCounting::ObjC:
case ReferenceCounting::Block:
case ReferenceCounting::Unknown:
return new UnknownUnownedReferenceTypeInfo(
IGM.UnownedReferencePtrTy->getElementType(),
std::move(spareBits),
IGM.getPointerSize(),
IGM.getPointerAlignment());
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("not supported!");
}
llvm_unreachable("bad reference-counting style");
}
const WeakTypeInfo *TypeConverter::createWeakStorageType(llvm::Type *valueType,
ReferenceCounting style) {
switch (style) {
case ReferenceCounting::Native:
return new NativeWeakReferenceTypeInfo(valueType,
IGM.WeakReferencePtrTy->getElementType(),
IGM.getWeakReferenceSize(),
IGM.getWeakReferenceAlignment(),
IGM.getWeakReferenceSpareBits());
case ReferenceCounting::ObjC:
case ReferenceCounting::Block:
case ReferenceCounting::Unknown:
return new UnknownWeakReferenceTypeInfo(valueType,
IGM.WeakReferencePtrTy->getElementType(),
IGM.getWeakReferenceSize(),
IGM.getWeakReferenceAlignment(),
IGM.getWeakReferenceSpareBits());
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("not supported!");
}
llvm_unreachable("bad reference-counting style");
}
/// Does the given value superficially not require reference-counting?
static bool doesNotRequireRefCounting(llvm::Value *value) {
// Constants never require reference-counting.
return isa<llvm::ConstantPointerNull>(value);
}
static llvm::FunctionType *getTypeOfFunction(llvm::Constant *fn) {
return cast<llvm::FunctionType>(fn->getType()->getPointerElementType());
}
/// Emit a unary call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T)'
static void emitUnaryRefCountCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *value) {
auto cc = IGF.IGM.DefaultCC;
if (auto fun = dyn_cast<llvm::Function>(fn))
cc = fun->getCallingConv();
// Instead of casting the input, we cast the function type.
// This tends to produce less IR, but might be evil.
if (value->getType() != getTypeOfFunction(fn)->getParamType(0)) {
llvm::FunctionType *fnType =
llvm::FunctionType::get(IGF.IGM.VoidTy, value->getType(), false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, value);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a copy-like call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T, T)'
static void emitCopyLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *dest,
llvm::Value *src) {
assert(dest->getType() == src->getType() &&
"type mismatch in binary refcounting operation");
auto cc = IGF.IGM.DefaultCC;
if (auto fun = dyn_cast<llvm::Function>(fn))
cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
if (dest->getType() != getTypeOfFunction(fn)->getParamType(0)) {
llvm::Type *paramTypes[] = { dest->getType(), dest->getType() };
llvm::FunctionType *fnType =
llvm::FunctionType::get(IGF.IGM.VoidTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, {dest, src});
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to a function with a loadWeak-like signature.
///
/// \param fn - expected signature 'T (Weak*)'
static llvm::Value *emitLoadWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Type *resultType) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto cc = IGF.IGM.DefaultCC;
if (auto fun = dyn_cast<llvm::Function>(fn))
cc = fun->getCallingConv();
// Instead of casting the output, we cast the function type.
// This tends to produce less IR, but might be evil.
if (resultType != getTypeOfFunction(fn)->getReturnType()) {
llvm::Type *paramTypes[] = { addr->getType() };
llvm::FunctionType *fnType =
llvm::FunctionType::get(resultType, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, addr);
call->setCallingConv(cc);
call->setDoesNotThrow();
return call;
}
/// Emit a call to a function with a storeWeak-like signature.
///
/// \param fn - expected signature 'void (Weak*, T)'
static void emitStoreWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Value *value) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto cc = IGF.IGM.DefaultCC;
if (auto fun = dyn_cast<llvm::Function>(fn))
cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
if (value->getType() != getTypeOfFunction(fn)->getParamType(1)) {
llvm::Type *paramTypes[] = { addr->getType(), value->getType() };
llvm::FunctionType *fnType =
llvm::FunctionType::get(IGF.IGM.VoidTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, {addr, value});
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to swift_retain.
void IRGenFunction::emitNativeStrongRetain(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
// Make sure the input pointer is the right type.
if (value->getType() != IGM.RefCountedPtrTy)
value = Builder.CreateBitCast(value, IGM.RefCountedPtrTy);
// Emit the call.
llvm::CallInst *call = Builder.CreateCall(
(atomicity == Atomicity::Atomic) ? IGM.getNativeStrongRetainFn()
: IGM.getNativeNonAtomicStrongRetainFn(),
value);
call->setDoesNotThrow();
}
/// Emit a store of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongAssign(llvm::Value *newValue,
Address address) {
// Pull the old value out of the address.
llvm::Value *oldValue = Builder.CreateLoad(address);
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
// Release the old value.
emitNativeStrongRelease(oldValue);
}
/// Emit an initialize of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongInit(llvm::Value *newValue,
Address address) {
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
}
/// Emit a release of a live value with the given refcounting implementation.
void IRGenFunction::emitStrongRelease(llvm::Value *value,
ReferenceCounting refcounting,
Atomicity atomicity) {
switch (refcounting) {
case ReferenceCounting::Native:
return emitNativeStrongRelease(value, atomicity);
case ReferenceCounting::ObjC:
return emitObjCStrongRelease(value);
case ReferenceCounting::Block:
return emitBlockRelease(value);
case ReferenceCounting::Unknown:
return emitUnknownStrongRelease(value, atomicity);
case ReferenceCounting::Bridge:
return emitBridgeStrongRelease(value, atomicity);
case ReferenceCounting::Error:
return emitErrorStrongRelease(value);
}
}
void IRGenFunction::emitStrongRetain(llvm::Value *value,
ReferenceCounting refcounting,
Atomicity atomicity) {
switch (refcounting) {
case ReferenceCounting::Native:
emitNativeStrongRetain(value, atomicity);
return;
case ReferenceCounting::Bridge:
emitBridgeStrongRetain(value, atomicity);
return;
case ReferenceCounting::ObjC: