forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenType.cpp
1898 lines (1633 loc) · 67.7 KB
/
GenType.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
//===--- GenType.cpp - Swift IR Generation For Types ----------------------===//
//
// 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 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 types in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/Types.h"
#include "swift/SIL/SILModule.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
#include "clang/CodeGen/SwiftCallingConv.h"
#include "EnumPayload.h"
#include "LoadableTypeInfo.h"
#include "GenMeta.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "Address.h"
#include "Explosion.h"
#include "GenOpaque.h"
#include "HeapTypeInfo.h"
#include "IndirectTypeInfo.h"
#include "Linking.h"
#include "ProtocolInfo.h"
#include "ReferenceTypeInfo.h"
#include "ScalarTypeInfo.h"
#include "WeakTypeInfo.h"
using namespace swift;
using namespace irgen;
llvm::DenseMap<TypeBase*, TypeCacheEntry> &
TypeConverter::Types_t::getCacheFor(TypeBase *t) {
return t->hasTypeParameter() ? DependentCache : IndependentCache;
}
void TypeInfo:: assign(IRGenFunction &IGF, Address dest, Address src,
IsTake_t isTake, SILType T) const {
if (isTake) {
assignWithTake(IGF, dest, src, T);
} else {
assignWithCopy(IGF, dest, src, T);
}
}
void TypeInfo::initialize(IRGenFunction &IGF, Address dest, Address src,
IsTake_t isTake, SILType T) const {
if (isTake) {
initializeWithTake(IGF, dest, src, T);
} else {
initializeWithCopy(IGF, dest, src, T);
}
}
bool TypeInfo::isSingleRetainablePointer(ResilienceExpansion expansion,
ReferenceCounting *refcounting) const {
return false;
}
ExplosionSchema TypeInfo::getSchema() const {
ExplosionSchema schema;
getSchema(schema);
return schema;
}
Address TypeInfo::getAddressForPointer(llvm::Value *ptr) const {
assert(ptr->getType()->getPointerElementType() == StorageType);
return Address(ptr, StorageAlignment);
}
Address TypeInfo::getUndefAddress() const {
return Address(llvm::UndefValue::get(getStorageType()->getPointerTo(0)),
StorageAlignment);
}
/// Whether this type is known to be empty.
bool TypeInfo::isKnownEmpty(ResilienceExpansion expansion) const {
if (auto fixed = dyn_cast<FixedTypeInfo>(this))
return fixed->isKnownEmpty(expansion);
return false;
}
/// Copy a value from one object to a new object, directly taking
/// responsibility for anything it might have. This is like C++
/// move-initialization, except the old object will not be destroyed.
void FixedTypeInfo::initializeWithTake(IRGenFunction &IGF,
Address destAddr,
Address srcAddr,
SILType T) const {
assert(isBitwiseTakable(ResilienceExpansion::Maximal)
&& "non-bitwise-takable type must override default initializeWithTake");
// Prefer loads and stores if we won't make a million of them.
// Maybe this should also require the scalars to have a fixed offset.
ExplosionSchema schema = getSchema();
if (!schema.containsAggregate() && schema.size() <= 2) {
auto &loadableTI = cast<LoadableTypeInfo>(*this);
Explosion copy;
loadableTI.loadAsTake(IGF, srcAddr, copy);
loadableTI.initialize(IGF, copy, destAddr);
return;
}
// Otherwise, use a memcpy.
IGF.emitMemCpy(destAddr, srcAddr, getFixedSize());
}
/// Copy a value from one object to a new object. This is just the
/// default implementation.
void LoadableTypeInfo::initializeWithCopy(IRGenFunction &IGF,
Address destAddr,
Address srcAddr,
SILType T) const {
// Use memcpy if that's legal.
if (isPOD(ResilienceExpansion::Maximal)) {
return initializeWithTake(IGF, destAddr, srcAddr, T);
}
// Otherwise explode and re-implode.
Explosion copy;
loadAsCopy(IGF, srcAddr, copy);
initialize(IGF, copy, destAddr);
}
LoadedRef LoadableTypeInfo::loadRefcountedPtr(IRGenFunction &IGF,
SourceLoc loc,
Address addr) const {
IGF.IGM.error(loc, "Can only load from an address that holds a reference to "
"a refcounted type or an address of an optional reference.");
llvm::report_fatal_error("loadRefcountedPtr: Invalid SIL in IRGen");
}
void LoadableTypeInfo::addScalarToAggLowering(IRGenModule &IGM,
SwiftAggLowering &lowering,
llvm::Type *type, Size offset,
Size storageSize) {
lowering.addTypedData(type, offset.asCharUnits(), storageSize.asCharUnits());
}
static llvm::Constant *asSizeConstant(IRGenModule &IGM, Size size) {
return llvm::ConstantInt::get(IGM.SizeTy, size.getValue());
}
/// Return the size and alignment of this type.
std::pair<llvm::Value*,llvm::Value*>
FixedTypeInfo::getSizeAndAlignmentMask(IRGenFunction &IGF,
SILType T) const {
return {FixedTypeInfo::getSize(IGF, T),
FixedTypeInfo::getAlignmentMask(IGF, T)};
}
std::tuple<llvm::Value*,llvm::Value*,llvm::Value*>
FixedTypeInfo::getSizeAndAlignmentMaskAndStride(IRGenFunction &IGF,
SILType T) const {
return std::make_tuple(FixedTypeInfo::getSize(IGF, T),
FixedTypeInfo::getAlignmentMask(IGF, T),
FixedTypeInfo::getStride(IGF, T));
}
llvm::Value *FixedTypeInfo::getSize(IRGenFunction &IGF, SILType T) const {
return FixedTypeInfo::getStaticSize(IGF.IGM);
}
llvm::Constant *FixedTypeInfo::getStaticSize(IRGenModule &IGM) const {
return asSizeConstant(IGM, getFixedSize());
}
llvm::Value *FixedTypeInfo::getAlignmentMask(IRGenFunction &IGF,
SILType T) const {
return FixedTypeInfo::getStaticAlignmentMask(IGF.IGM);
}
llvm::Constant *FixedTypeInfo::getStaticAlignmentMask(IRGenModule &IGM) const {
return asSizeConstant(IGM, Size(getFixedAlignment().getValue() - 1));
}
llvm::Value *FixedTypeInfo::getStride(IRGenFunction &IGF, SILType T) const {
return FixedTypeInfo::getStaticStride(IGF.IGM);
}
llvm::Value *FixedTypeInfo::getIsPOD(IRGenFunction &IGF, SILType T) const {
return llvm::ConstantInt::get(IGF.IGM.Int1Ty,
isPOD(ResilienceExpansion::Maximal) == IsPOD);
}
llvm::Constant *FixedTypeInfo::getStaticStride(IRGenModule &IGM) const {
return asSizeConstant(IGM, getFixedStride());
}
llvm::Value *FixedTypeInfo::isDynamicallyPackedInline(IRGenFunction &IGF,
SILType T) const {
auto packing = getFixedPacking(IGF.IGM);
assert(packing == FixedPacking::Allocate ||
packing == FixedPacking::OffsetZero);
return llvm::ConstantInt::get(IGF.IGM.Int1Ty,
packing == FixedPacking::OffsetZero);
}
unsigned FixedTypeInfo::getSpareBitExtraInhabitantCount() const {
if (SpareBits.none())
return 0;
// The runtime supports a max of 0x7FFFFFFF extra inhabitants, which ought
// to be enough for anybody.
if (StorageSize.getValue() >= 4)
return 0x7FFFFFFF;
unsigned spareBitCount = SpareBits.count();
assert(spareBitCount <= StorageSize.getValueInBits()
&& "more spare bits than storage bits?!");
unsigned inhabitedBitCount = StorageSize.getValueInBits() - spareBitCount;
return ((1U << spareBitCount) - 1U) << inhabitedBitCount;
}
void FixedTypeInfo::applyFixedSpareBitsMask(SpareBitVector &mask,
const SpareBitVector &spareBits) {
// If the mask is no longer than the stored spare bits, we can just
// apply the stored spare bits.
if (mask.size() <= spareBits.size()) {
// Grow the mask out if necessary; the tail padding is all spare bits.
mask.extendWithSetBits(spareBits.size());
mask &= spareBits;
// Otherwise, we have to grow out the stored spare bits before we
// can intersect.
} else {
auto paddedSpareBits = spareBits;
paddedSpareBits.extendWithSetBits(mask.size());
mask &= paddedSpareBits;
}
}
void FixedTypeInfo::applyFixedSpareBitsMask(SpareBitVector &mask) const {
return applyFixedSpareBitsMask(mask, SpareBits);
}
APInt
FixedTypeInfo::getSpareBitFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const {
// Factor the index into the part that goes in the occupied bits and the
// part that goes in the spare bits.
unsigned occupiedIndex, spareIndex = 0;
unsigned spareBitCount = SpareBits.count();
unsigned occupiedBitCount = SpareBits.size() - spareBitCount;
if (occupiedBitCount >= 31) {
occupiedIndex = index;
// The spare bit value is biased by one because all zero spare bits
// represents a valid value of the type.
spareIndex = 1;
} else {
occupiedIndex = index & ((1 << occupiedBitCount) - 1);
// The spare bit value is biased by one because all zero spare bits
// represents a valid value of the type.
spareIndex = (index >> occupiedBitCount) + 1;
}
return interleaveSpareBits(IGM, SpareBits, bits, spareIndex, occupiedIndex);
}
llvm::Value *
FixedTypeInfo::getSpareBitExtraInhabitantIndex(IRGenFunction &IGF,
Address src) const {
assert(!SpareBits.none() && "no spare bits");
auto &C = IGF.IGM.getLLVMContext();
// Load the value.
auto payloadTy = llvm::IntegerType::get(C, StorageSize.getValueInBits());
src = IGF.Builder.CreateBitCast(src, payloadTy->getPointerTo());
auto val = IGF.Builder.CreateLoad(src);
// If the spare bits are all zero, then we have a valid value and not an
// extra inhabitant.
auto spareBitsMask
= llvm::ConstantInt::get(C, SpareBits.asAPInt());
auto valSpareBits = IGF.Builder.CreateAnd(val, spareBitsMask);
auto isValid = IGF.Builder.CreateICmpEQ(valSpareBits,
llvm::ConstantInt::get(payloadTy, 0));
auto *origBB = IGF.Builder.GetInsertBlock();
auto *endBB = llvm::BasicBlock::Create(C);
auto *spareBB = llvm::BasicBlock::Create(C);
IGF.Builder.CreateCondBr(isValid, endBB, spareBB);
IGF.Builder.emitBlock(spareBB);
ConditionalDominanceScope condition(IGF);
// Gather the occupied bits.
auto OccupiedBits = SpareBits;
OccupiedBits.flipAll();
llvm::Value *idx = emitGatherSpareBits(IGF, OccupiedBits, val, 0, 31);
// See if spare bits fit into the 31 bits of the index.
unsigned numSpareBits = SpareBits.count();
unsigned numOccupiedBits = StorageSize.getValueInBits() - numSpareBits;
if (numOccupiedBits < 31) {
// Gather the spare bits.
llvm::Value *spareIdx
= emitGatherSpareBits(IGF, SpareBits, val, numOccupiedBits, 31);
// Unbias by subtracting one.
uint64_t shifted = static_cast<uint64_t>(1) << numOccupiedBits;
spareIdx = IGF.Builder.CreateSub(spareIdx,
llvm::ConstantInt::get(spareIdx->getType(), shifted));
idx = IGF.Builder.CreateOr(idx, spareIdx);
}
idx = IGF.Builder.CreateZExt(idx, IGF.IGM.Int32Ty);
IGF.Builder.CreateBr(endBB);
IGF.Builder.emitBlock(endBB);
// If we had a valid value, return -1. Otherwise, return the index.
auto phi = IGF.Builder.CreatePHI(IGF.IGM.Int32Ty, 2);
phi->addIncoming(llvm::ConstantInt::get(IGF.IGM.Int32Ty, -1), origBB);
phi->addIncoming(idx, spareBB);
return phi;
}
void
FixedTypeInfo::storeSpareBitExtraInhabitant(IRGenFunction &IGF,
llvm::Value *index,
Address dest) const {
assert(!SpareBits.none() && "no spare bits");
auto &C = IGF.IGM.getLLVMContext();
auto payloadTy = llvm::IntegerType::get(C, StorageSize.getValueInBits());
unsigned spareBitCount = SpareBits.count();
unsigned occupiedBitCount = SpareBits.size() - spareBitCount;
llvm::Value *occupiedIndex;
llvm::Value *spareIndex;
// The spare bit value is biased by one because all zero spare bits
// represents a valid value of the type.
auto spareBitBias = llvm::ConstantInt::get(IGF.IGM.Int32Ty, 1U);
// Factor the spare and occupied bit values from the index.
if (occupiedBitCount >= 31) {
occupiedIndex = index;
spareIndex = spareBitBias;
} else {
auto occupiedBitMask = APInt::getAllOnesValue(occupiedBitCount);
occupiedBitMask = occupiedBitMask.zext(32);
auto occupiedBitMaskValue = llvm::ConstantInt::get(C, occupiedBitMask);
occupiedIndex = IGF.Builder.CreateAnd(index, occupiedBitMaskValue);
auto occupiedBitCountValue
= llvm::ConstantInt::get(IGF.IGM.Int32Ty, occupiedBitCount);
spareIndex = IGF.Builder.CreateLShr(index, occupiedBitCountValue);
spareIndex = IGF.Builder.CreateAdd(spareIndex, spareBitBias);
}
// Scatter the occupied bits.
auto OccupiedBits = SpareBits;
OccupiedBits.flipAll();
llvm::Value *occupied = emitScatterSpareBits(IGF, OccupiedBits,
occupiedIndex, 0);
// Scatter the spare bits.
llvm::Value *spare = emitScatterSpareBits(IGF, SpareBits, spareIndex, 0);
// Combine the values and store to the destination.
llvm::Value *inhabitant = IGF.Builder.CreateOr(occupied, spare);
dest = IGF.Builder.CreateBitCast(dest, payloadTy->getPointerTo());
IGF.Builder.CreateStore(inhabitant, dest);
}
namespace {
/// A TypeInfo implementation for empty types.
struct EmptyTypeInfo : ScalarTypeInfo<EmptyTypeInfo, LoadableTypeInfo> {
EmptyTypeInfo(llvm::Type *ty)
: ScalarTypeInfo(ty, Size(0), SpareBitVector{}, Alignment(1), IsPOD,
IsFixedSize) {}
unsigned getExplosionSize() const override { return 0; }
void getSchema(ExplosionSchema &schema) const override {}
void addToAggLowering(IRGenModule &IGM, SwiftAggLowering &lowering,
Size offset) const override {}
void loadAsCopy(IRGenFunction &IGF, Address addr,
Explosion &e) const override {}
void loadAsTake(IRGenFunction &IGF, Address addr,
Explosion &e) const override {}
void assign(IRGenFunction &IGF, Explosion &e,
Address addr) const override {}
void initialize(IRGenFunction &IGF, Explosion &e,
Address addr) const override {}
void copy(IRGenFunction &IGF, Explosion &src,
Explosion &dest, Atomicity atomicity) const override {}
void consume(IRGenFunction &IGF, Explosion &src,
Atomicity atomicity) const override {}
void fixLifetime(IRGenFunction &IGF, Explosion &src) const override {}
void destroy(IRGenFunction &IGF, Address addr, SILType T) const override {}
void packIntoEnumPayload(IRGenFunction &IGF, EnumPayload &payload,
Explosion &src, unsigned offset) const override {}
void unpackFromEnumPayload(IRGenFunction &IGF,
const EnumPayload &payload,
Explosion &dest,
unsigned offset) const override {}
};
/// A TypeInfo implementation for types represented as a single
/// scalar type.
class PrimitiveTypeInfo final :
public PODSingleScalarTypeInfo<PrimitiveTypeInfo, LoadableTypeInfo> {
public:
PrimitiveTypeInfo(llvm::Type *storage, Size size,
SpareBitVector &&spareBits,
Alignment align)
: PODSingleScalarTypeInfo(storage, size, std::move(spareBits), align) {}
};
/// A TypeInfo implementation for bare non-null pointers (like `void *`).
class RawPointerTypeInfo final :
public PODSingleScalarTypeInfo<RawPointerTypeInfo, LoadableTypeInfo> {
public:
RawPointerTypeInfo(llvm::Type *storage, Size size, Alignment align)
: PODSingleScalarTypeInfo(
storage, size,
SpareBitVector::getConstant(size.getValueInBits(), false),
align) {}
bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
return true;
}
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return 1;
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, unsigned bits,
unsigned index) const override {
assert(index == 0);
return APInt(bits, 0);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF,
Address src,
SILType T) const override {
// Copied from BridgeObjectTypeInfo.
src = IGF.Builder.CreateBitCast(src, IGF.IGM.IntPtrTy->getPointerTo());
auto val = IGF.Builder.CreateLoad(src);
auto zero = llvm::ConstantInt::get(IGF.IGM.IntPtrTy, 0);
auto isNonzero = IGF.Builder.CreateICmpNE(val, zero);
// We either have extra inhabitant 0 or no extra inhabitant (-1).
// Conveniently, this is just a sext i1 -> i32 away.
return IGF.Builder.CreateSExt(isNonzero, IGF.IGM.Int32Ty);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T) const override {
// Copied from BridgeObjectTypeInfo.
// There's only one extra inhabitant, 0.
dest = IGF.Builder.CreateBitCast(dest, IGF.IGM.IntPtrTy->getPointerTo());
IGF.Builder.CreateStore(llvm::ConstantInt::get(IGF.IGM.IntPtrTy, 0),dest);
}
};
/// A TypeInfo implementation for opaque storage. Swift will preserve any
/// data stored into this arbitrarily sized and aligned field, but doesn't
/// know anything about the data.
class OpaqueStorageTypeInfo final :
public ScalarTypeInfo<OpaqueStorageTypeInfo, LoadableTypeInfo>
{
llvm::IntegerType *ScalarType;
public:
OpaqueStorageTypeInfo(llvm::ArrayType *storage,
llvm::IntegerType *scalarType,
Size size,
SpareBitVector &&spareBits,
Alignment align)
: ScalarTypeInfo(storage, size, std::move(spareBits), align, IsPOD,
IsFixedSize),
ScalarType(scalarType)
{}
llvm::ArrayType *getStorageType() const {
return cast<llvm::ArrayType>(ScalarTypeInfo::getStorageType());
}
unsigned getExplosionSize() const override {
return 1;
}
void loadAsCopy(IRGenFunction &IGF, Address addr,
Explosion &explosion) const override {
loadAsTake(IGF, addr, explosion);
}
void loadAsTake(IRGenFunction &IGF, Address addr,
Explosion &explosion) const override {
addr = IGF.Builder.CreateElementBitCast(addr, ScalarType);
explosion.add(IGF.Builder.CreateLoad(addr));
}
void assign(IRGenFunction &IGF, Explosion &explosion,
Address addr) const override {
initialize(IGF, explosion, addr);
}
void initialize(IRGenFunction &IGF, Explosion &explosion,
Address addr) const override {
addr = IGF.Builder.CreateElementBitCast(addr, ScalarType);
IGF.Builder.CreateStore(explosion.claimNext(), addr);
}
void reexplode(IRGenFunction &IGF, Explosion &sourceExplosion,
Explosion &targetExplosion) const override {
targetExplosion.add(sourceExplosion.claimNext());
}
void copy(IRGenFunction &IGF, Explosion &sourceExplosion,
Explosion &targetExplosion, Atomicity atomicity) const override {
reexplode(IGF, sourceExplosion, targetExplosion);
}
void consume(IRGenFunction &IGF, Explosion &explosion,
Atomicity atomicity) const override {
explosion.claimNext();
}
void fixLifetime(IRGenFunction &IGF, Explosion &explosion) const override {
explosion.claimNext();
}
void destroy(IRGenFunction &IGF, Address address, SILType T) const override {
/* nop */
}
void getSchema(ExplosionSchema &schema) const override {
schema.add(ExplosionSchema::Element::forScalar(ScalarType));
}
void addToAggLowering(IRGenModule &IGM, SwiftAggLowering &lowering,
Size offset) const override {
lowering.addOpaqueData(offset.asCharUnits(),
getFixedSize().asCharUnits());
}
void packIntoEnumPayload(IRGenFunction &IGF,
EnumPayload &payload,
Explosion &source,
unsigned offset) const override {
payload.insertValue(IGF, source.claimNext(), offset);
}
void unpackFromEnumPayload(IRGenFunction &IGF,
const EnumPayload &payload,
Explosion &target,
unsigned offset) const override {
target.add(payload.extractValue(IGF, ScalarType, offset));
}
};
/// A TypeInfo implementation for address-only types which can never
/// be copied.
class ImmovableTypeInfo :
public IndirectTypeInfo<ImmovableTypeInfo, FixedTypeInfo> {
public:
ImmovableTypeInfo(llvm::Type *storage, Size size,
SpareBitVector &&spareBits,
Alignment align)
: IndirectTypeInfo(storage, size, std::move(spareBits), align,
IsNotPOD, IsNotBitwiseTakable, IsFixedSize) {}
void assignWithCopy(IRGenFunction &IGF, Address dest,
Address src, SILType T) const override {
llvm_unreachable("cannot opaquely manipulate immovable types!");
}
void assignWithTake(IRGenFunction &IGF, Address dest,
Address src, SILType T) const override {
llvm_unreachable("cannot opaquely manipulate immovable types!");
}
void initializeWithTake(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
llvm_unreachable("cannot opaquely manipulate immovable types!");
}
void initializeWithCopy(IRGenFunction &IGF, Address destAddr,
Address srcAddr, SILType T) const override {
llvm_unreachable("cannot opaquely manipulate immovable types!");
}
void destroy(IRGenFunction &IGF, Address address,
SILType T) const override {
llvm_unreachable("cannot opaquely manipulate immovable types!");
}
};
}
/// Constructs a type info which performs simple loads and stores of
/// the given IR type.
const LoadableTypeInfo *
TypeConverter::createPrimitive(llvm::Type *type, Size size, Alignment align) {
return new PrimitiveTypeInfo(type, size, IGM.getSpareBitsForType(type, size),
align);
}
/// Constructs a type info which performs simple loads and stores of
/// the given IR type, given that it's a pointer to an aligned pointer
/// type.
const LoadableTypeInfo *
TypeConverter::createPrimitiveForAlignedPointer(llvm::PointerType *type,
Size size,
Alignment align,
Alignment pointerAlignment) {
SpareBitVector spareBits = IGM.TargetInfo.PointerSpareBits;
for (unsigned bit = 0; Alignment(1 << bit) != pointerAlignment; ++bit) {
spareBits.setBit(bit);
}
return new PrimitiveTypeInfo(type, size, std::move(spareBits), align);
}
/// Constructs a fixed-size type info which asserts if you try to copy
/// or destroy it.
const FixedTypeInfo *
TypeConverter::createImmovable(llvm::Type *type, Size size, Alignment align) {
auto spareBits = SpareBitVector::getConstant(size.getValueInBits(), false);
return new ImmovableTypeInfo(type, size, std::move(spareBits), align);
}
static TypeInfo *invalidTypeInfo() { return (TypeInfo*) 1; }
static ProtocolInfo *invalidProtocolInfo() { return (ProtocolInfo*) 1; }
TypeConverter::TypeConverter(IRGenModule &IGM)
: IGM(IGM),
FirstType(invalidTypeInfo()),
FirstProtocol(invalidProtocolInfo()) {}
TypeConverter::~TypeConverter() {
// Delete all the converted type infos.
for (const TypeInfo *I = FirstType; I != invalidTypeInfo(); ) {
const TypeInfo *Cur = I;
I = Cur->NextConverted;
delete Cur;
}
for (const ProtocolInfo *I = FirstProtocol; I != invalidProtocolInfo(); ) {
const ProtocolInfo *Cur = I;
I = Cur->NextConverted;
delete Cur;
}
}
void TypeConverter::pushGenericContext(CanGenericSignature signature) {
if (!signature)
return;
// Push the generic context down to the SIL TypeConverter, so we can share
// archetypes with SIL.
IGM.getSILTypes().pushGenericContext(signature);
}
void TypeConverter::popGenericContext(CanGenericSignature signature) {
if (!signature)
return;
// Pop the SIL TypeConverter's generic context too.
IGM.getSILTypes().popGenericContext(signature);
Types.DependentCache.clear();
}
GenericEnvironment *TypeConverter::getGenericEnvironment() {
auto moduleDecl = IGM.getSwiftModule();
auto genericSig = IGM.getSILTypes().getCurGenericContext();
return genericSig->getCanonicalSignature().getGenericEnvironment(*moduleDecl);
}
GenericEnvironment *IRGenModule::getGenericEnvironment() {
return Types.getGenericEnvironment();
}
/// Add a temporary forward declaration for a type. This will live
/// only until a proper mapping is added.
void TypeConverter::addForwardDecl(TypeBase *key, llvm::Type *type) {
assert(key->isCanonical());
assert(!key->hasTypeParameter());
assert(!Types.IndependentCache.count(key) && "entry already exists for type!");
Types.IndependentCache.insert(std::make_pair(key, type));
}
const TypeInfo &IRGenModule::getWitnessTablePtrTypeInfo() {
return Types.getWitnessTablePtrTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getWitnessTablePtrTypeInfo() {
if (WitnessTablePtrTI) return *WitnessTablePtrTI;
WitnessTablePtrTI =
createPrimitiveForAlignedPointer(IGM.WitnessTablePtrTy,
IGM.getPointerSize(),
IGM.getPointerAlignment(),
IGM.getWitnessTableAlignment());
WitnessTablePtrTI->NextConverted = FirstType;
FirstType = WitnessTablePtrTI;
return *WitnessTablePtrTI;
}
const SpareBitVector &IRGenModule::getWitnessTablePtrSpareBits() const {
// Witness tables are pointers and have pointer spare bits.
return TargetInfo.PointerSpareBits;
}
const TypeInfo &IRGenModule::getTypeMetadataPtrTypeInfo() {
return Types.getTypeMetadataPtrTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getTypeMetadataPtrTypeInfo() {
if (TypeMetadataPtrTI) return *TypeMetadataPtrTI;
TypeMetadataPtrTI =
createUnmanagedStorageType(IGM.TypeMetadataPtrTy);
TypeMetadataPtrTI->NextConverted = FirstType;
FirstType = TypeMetadataPtrTI;
return *TypeMetadataPtrTI;
}
const LoadableTypeInfo &
IRGenModule::getReferenceObjectTypeInfo(ReferenceCounting refcounting) {
switch (refcounting) {
case ReferenceCounting::Native:
return getNativeObjectTypeInfo();
case ReferenceCounting::Unknown:
return getUnknownObjectTypeInfo();
case ReferenceCounting::Bridge:
return getBridgeObjectTypeInfo();
case ReferenceCounting::Block:
case ReferenceCounting::Error:
case ReferenceCounting::ObjC:
llvm_unreachable("not implemented");
}
llvm_unreachable("Not a valid ReferenceCounting.");
}
const LoadableTypeInfo &IRGenModule::getNativeObjectTypeInfo() {
return Types.getNativeObjectTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getNativeObjectTypeInfo() {
if (NativeObjectTI) return *NativeObjectTI;
NativeObjectTI = convertBuiltinNativeObject();
NativeObjectTI->NextConverted = FirstType;
FirstType = NativeObjectTI;
return *NativeObjectTI;
}
const LoadableTypeInfo &IRGenModule::getUnknownObjectTypeInfo() {
return Types.getUnknownObjectTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getUnknownObjectTypeInfo() {
if (UnknownObjectTI) return *UnknownObjectTI;
UnknownObjectTI = convertBuiltinUnknownObject();
UnknownObjectTI->NextConverted = FirstType;
FirstType = UnknownObjectTI;
return *UnknownObjectTI;
}
const LoadableTypeInfo &IRGenModule::getBridgeObjectTypeInfo() {
return Types.getBridgeObjectTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getBridgeObjectTypeInfo() {
if (BridgeObjectTI) return *BridgeObjectTI;
BridgeObjectTI = convertBuiltinBridgeObject();
BridgeObjectTI->NextConverted = FirstType;
FirstType = BridgeObjectTI;
return *BridgeObjectTI;
}
const LoadableTypeInfo &IRGenModule::getRawPointerTypeInfo() {
return Types.getRawPointerTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getRawPointerTypeInfo() {
if (RawPointerTI) return *RawPointerTI;
RawPointerTI = new RawPointerTypeInfo(IGM.Int8PtrTy,
IGM.getPointerSize(),
IGM.getPointerAlignment());
RawPointerTI->NextConverted = FirstType;
FirstType = RawPointerTI;
return *RawPointerTI;
}
const LoadableTypeInfo &TypeConverter::getEmptyTypeInfo() {
if (EmptyTI) return *EmptyTI;
EmptyTI = new EmptyTypeInfo(IGM.Int8Ty);
EmptyTI->NextConverted = FirstType;
FirstType = EmptyTI;
return *EmptyTI;
}
const TypeInfo &TypeConverter::getResilientStructTypeInfo() {
if (ResilientStructTI) return *ResilientStructTI;
ResilientStructTI = convertResilientStruct();
ResilientStructTI->NextConverted = FirstType;
FirstType = ResilientStructTI;
return *ResilientStructTI;
}
/// Get the fragile type information for the given type, which may not
/// have yet undergone SIL type lowering. The type can serve as its own
/// abstraction pattern.
const TypeInfo &IRGenFunction::getTypeInfoForUnlowered(Type subst) {
return IGM.getTypeInfoForUnlowered(subst);
}
/// Get the fragile type information for the given type, which may not
/// have yet undergone SIL type lowering.
const TypeInfo &
IRGenFunction::getTypeInfoForUnlowered(AbstractionPattern orig, Type subst) {
return IGM.getTypeInfoForUnlowered(orig, subst);
}
/// Get the fragile type information for the given type, which may not
/// have yet undergone SIL type lowering.
const TypeInfo &
IRGenFunction::getTypeInfoForUnlowered(AbstractionPattern orig, CanType subst) {
return IGM.getTypeInfoForUnlowered(orig, subst);
}
/// Get the fragile type information for the given type, which is known
/// to have undergone SIL type lowering (or be one of the types for
/// which that lowering is the identity function).
const TypeInfo &IRGenFunction::getTypeInfoForLowered(CanType T) {
return IGM.getTypeInfoForLowered(T);
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenFunction::getTypeInfo(SILType T) {
return IGM.getTypeInfo(T);
}
/// Return the SIL-lowering of the given type.
SILType IRGenModule::getLoweredType(AbstractionPattern orig, Type subst) {
return getSILTypes().getLoweredType(orig, subst);
}
/// Return the SIL-lowering of the given type.
SILType IRGenModule::getLoweredType(Type subst) {
return getSILTypes().getLoweredType(subst);
}
/// Get a pointer to the storage type for the given type. Note that,
/// unlike fetching the type info and asking it for the storage type,
/// this operation will succeed for forward-declarations.
llvm::PointerType *IRGenModule::getStoragePointerType(SILType T) {
return getStoragePointerTypeForLowered(T.getSwiftRValueType());
}
llvm::PointerType *IRGenModule::getStoragePointerTypeForUnlowered(Type T) {
return getStorageTypeForUnlowered(T)->getPointerTo();
}
llvm::PointerType *IRGenModule::getStoragePointerTypeForLowered(CanType T) {
return getStorageTypeForLowered(T)->getPointerTo();
}
llvm::Type *IRGenModule::getStorageTypeForUnlowered(Type subst) {
return getStorageType(getSILTypes().getLoweredType(subst));
}
llvm::Type *IRGenModule::getStorageType(SILType T) {
return getStorageTypeForLowered(T.getSwiftRValueType());
}
/// Get the storage type for the given type. Note that, unlike
/// fetching the type info and asking it for the storage type, this
/// operation will succeed for forward-declarations.
llvm::Type *IRGenModule::getStorageTypeForLowered(CanType T) {
// TODO: we can avoid creating entries for some obvious cases here.
auto entry = Types.getTypeEntry(T);
if (auto ti = entry.dyn_cast<const TypeInfo*>()) {
return ti->getStorageType();
} else {
return entry.get<llvm::Type*>();
}
}
/// Get the type information for the given type, which may not have
/// yet undergone SIL type lowering. The type can serve as its own
/// abstraction pattern.
const TypeInfo &IRGenModule::getTypeInfoForUnlowered(Type subst) {
return getTypeInfoForUnlowered(AbstractionPattern(subst), subst);
}
/// Get the type information for the given type, which may not
/// have yet undergone SIL type lowering.
const TypeInfo &
IRGenModule::getTypeInfoForUnlowered(AbstractionPattern orig, Type subst) {
return getTypeInfoForUnlowered(orig, subst->getCanonicalType());
}
/// Get the type information for the given type, which may not
/// have yet undergone SIL type lowering.
const TypeInfo &
IRGenModule::getTypeInfoForUnlowered(AbstractionPattern orig, CanType subst) {
return getTypeInfo(getSILTypes().getLoweredType(orig, subst));
}
/// Get the fragile type information for the given type, which is known
/// to have undergone SIL type lowering (or be one of the types for
/// which that lowering is the identity function).
const TypeInfo &IRGenModule::getTypeInfo(SILType T) {
return getTypeInfoForLowered(T.getSwiftRValueType());
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenModule::getTypeInfoForLowered(CanType T) {
return Types.getCompleteTypeInfo(T);
}
///
const TypeInfo &TypeConverter::getCompleteTypeInfo(CanType T) {
auto entry = getTypeEntry(T);
assert(entry.is<const TypeInfo*>() && "getting TypeInfo recursively!");
auto &ti = *entry.get<const TypeInfo*>();
assert(ti.isComplete());
return ti;
}
const TypeInfo *TypeConverter::tryGetCompleteTypeInfo(CanType T) {
auto entry = getTypeEntry(T);
if (!entry.is<const TypeInfo*>()) return nullptr;
auto &ti = *entry.get<const TypeInfo*>();
if (!ti.isComplete()) return nullptr;
return &ti;
}
/// Profile the archetype constraints that may affect type layout into a
/// folding set node ID.
static void profileArchetypeConstraints(
Type ty,
llvm::FoldingSetNodeID &ID,
llvm::DenseMap<ArchetypeType*, unsigned> &seen) {
// Helper.
class ProfileType : public CanTypeVisitor<ProfileType> {
llvm::FoldingSetNodeID &ID;
llvm::DenseMap<ArchetypeType *, unsigned> &seen;
public:
ProfileType(llvm::FoldingSetNodeID &ID,
llvm::DenseMap<ArchetypeType *, unsigned> &seen)
: ID(ID), seen(seen) {}
#define TYPE_WITHOUT_ARCHETYPE(KIND) \
void visit##KIND##Type(Can##KIND##Type type) { \
llvm_unreachable("does not contain an archetype"); \
}
TYPE_WITHOUT_ARCHETYPE(Builtin)
void visitNominalType(CanNominalType type) {
if (type.getParent())
profileArchetypeConstraints(type.getParent(), ID, seen);
ID.AddPointer(type->getDecl());
}
void visitTupleType(CanTupleType type) {
ID.AddInteger(type->getNumElements());
for (auto &elt : type->getElements()) {
ID.AddInteger(elt.isVararg());
profileArchetypeConstraints(elt.getType(), ID, seen);
}
}
void visitReferenceStorageType(CanReferenceStorageType type) {
profileArchetypeConstraints(type.getReferentType(), ID, seen);
}
void visitAnyMetatypeType(CanAnyMetatypeType type) {
profileArchetypeConstraints(type.getInstanceType(), ID, seen);
}
TYPE_WITHOUT_ARCHETYPE(Module)
void visitDynamicSelfType(CanDynamicSelfType type) {
profileArchetypeConstraints(type.getSelfType(), ID, seen);
}
void visitArchetypeType(CanArchetypeType type) {
profileArchetypeConstraints(type, ID, seen);
}
TYPE_WITHOUT_ARCHETYPE(GenericTypeParam)