forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeLowering.cpp
2632 lines (2229 loc) · 97.4 KB
/
TypeLowering.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
//===--- TypeLowering.cpp - Type information for SILGen ---------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "clang/AST/Type.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace Lowering;
namespace {
/// A CRTP type visitor for deciding whether the metatype for a type
/// is a singleton type, i.e. whether there can only ever be one
/// such value.
struct HasSingletonMetatype : CanTypeVisitor<HasSingletonMetatype, bool> {
/// Class metatypes have non-trivial representation due to the
/// possibility of subclassing.
bool visitClassType(CanClassType type) {
return false;
}
bool visitBoundGenericClassType(CanBoundGenericClassType type) {
return false;
}
bool visitDynamicSelfType(CanDynamicSelfType type) {
return false;
}
/// Dependent types have non-trivial representation in case they
/// instantiate to a class metatype.
bool visitGenericTypeParamType(CanGenericTypeParamType type) {
return false;
}
bool visitDependentMemberType(CanDependentMemberType type) {
return false;
}
/// Archetype metatypes have non-trivial representation in case
/// they instantiate to a class metatype.
bool visitArchetypeType(CanArchetypeType type) {
return false;
}
/// All levels of class metatypes support subtyping.
bool visitMetatypeType(CanMetatypeType type) {
return visit(type.getInstanceType());
}
/// Everything else is trivial. Note that ordinary metatypes of
/// existential types are still singleton.
bool visitType(CanType type) {
return true;
}
};
}
/// Does the metatype for the given type have a known-singleton
/// representation?
static bool hasSingletonMetatype(CanType instanceType) {
return HasSingletonMetatype().visit(instanceType);
}
CaptureKind TypeConverter::getDeclCaptureKind(CapturedValue capture) {
auto decl = capture.getDecl();
if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
switch (var->getStorageKind()) {
case VarDecl::StoredWithTrivialAccessors:
llvm_unreachable("stored local variable with trivial accessors?");
case VarDecl::InheritedWithObservers:
llvm_unreachable("inherited local variable?");
case VarDecl::Computed:
llvm_unreachable("computed captured property should have been lowered "
"away");
case VarDecl::StoredWithObservers:
case VarDecl::Addressed:
case VarDecl::AddressedWithTrivialAccessors:
case VarDecl::AddressedWithObservers:
case VarDecl::ComputedWithMutableAddress:
// Computed captures should have been lowered away.
assert(capture.isDirect()
&& "computed captured property should have been lowered away");
// If captured directly, the variable is captured by box or pointer.
assert(var->hasStorage());
return capture.isNoEscape() ?
CaptureKind::StorageAddress : CaptureKind::Box;
case VarDecl::Stored:
// If this is a non-address-only stored 'let' constant, we can capture it
// by value. If it is address-only, then we can't load it, so capture it
// by its address (like a var) instead.
if (var->isLet() && !getTypeLowering(var->getType()).isAddressOnly())
return CaptureKind::Constant;
// If we're capturing into a non-escaping closure, we can generally just
// capture the address of the value as no-escape.
return capture.isNoEscape() ?
CaptureKind::StorageAddress : CaptureKind::Box;
}
llvm_unreachable("bad storage kind");
}
// "Captured" local types require no context.
if (isa<TypeAliasDecl>(decl) || isa<GenericTypeParamDecl>(decl) ||
isa<AssociatedTypeDecl>(decl))
return CaptureKind::None;
llvm_unreachable("function-like captures should have been lowered away");
}
enum class LoweredTypeKind {
/// Trivial and loadable.
Trivial,
/// A reference type.
Reference,
/// An aggregate type that contains references (potentially recursively).
AggWithReference,
/// Non-trivial and not loadable.
AddressOnly
};
static LoweredTypeKind classifyType(CanType type, SILModule &M);
namespace {
/// A CRTP helper class for doing things that depends on type
/// classification.
template <class Impl, class RetTy>
class TypeClassifierBase : public CanTypeVisitor<Impl, RetTy> {
SILModule &M;
Impl &asImpl() { return *static_cast<Impl*>(this); }
protected:
TypeClassifierBase(SILModule &M) : M(M) {}
public:
// The subclass should implement:
// RetTy handleAddressOnly(CanType);
// RetTy handleReference(CanType);
// RetTy handleTrivial(CanType);
// In addition, if it does not override visitTupleType
// and visitAnyStructType, it should also implement:
// RetTy handleAggWithReference(CanType);
#define IMPL(TYPE, LOWERING) \
RetTy visit##TYPE##Type(Can##TYPE##Type type) { \
return asImpl().handle##LOWERING(type); \
}
IMPL(BuiltinInteger, Trivial)
IMPL(BuiltinFloat, Trivial)
IMPL(BuiltinRawPointer, Trivial)
IMPL(BuiltinNativeObject, Reference)
IMPL(BuiltinBridgeObject, Reference)
IMPL(BuiltinUnknownObject, Reference)
IMPL(BuiltinUnsafeValueBuffer, AddressOnly)
IMPL(BuiltinVector, Trivial)
IMPL(Class, Reference)
IMPL(BoundGenericClass, Reference)
IMPL(AnyMetatype, Trivial)
IMPL(Module, Trivial)
RetTy visitAnyFunctionType(CanAnyFunctionType type) {
switch (type->getRepresentation()) {
case AnyFunctionType::Representation::Swift:
case AnyFunctionType::Representation::Block:
return asImpl().handleReference(type);
case AnyFunctionType::Representation::CFunctionPointer:
case AnyFunctionType::Representation::Thin:
return asImpl().handleTrivial(type);
}
llvm_unreachable("bad function representation");
}
RetTy visitSILFunctionType(CanSILFunctionType type) {
if (type->getExtInfo().hasContext())
return asImpl().handleReference(type);
return asImpl().handleTrivial(type);
}
#undef IMPL
RetTy visitLValueType(CanLValueType type) {
llvm_unreachable("shouldn't get an l-value type here");
}
RetTy visitInOutType(CanInOutType type) {
llvm_unreachable("shouldn't get an inout type here");
}
// Dependent types should be contextualized before visiting.
RetTy visitGenericTypeParamType(CanGenericTypeParamType type) {
llvm_unreachable("should have substituted dependent type into context");
}
RetTy visitDependentMemberType(CanDependentMemberType type) {
llvm_unreachable("should have substituted dependent type into context");
}
RetTy visitUnmanagedStorageType(CanUnmanagedStorageType type) {
return asImpl().handleTrivial(type);
}
RetTy visitUnownedStorageType(CanUnownedStorageType type) {
return asImpl().handleReference(type);
}
RetTy visitWeakStorageType(CanWeakStorageType type) {
return asImpl().handleAddressOnly(type);
}
RetTy visitArchetypeType(CanArchetypeType type) {
if (type->requiresClass()) {
return asImpl().handleReference(type);
} else {
return asImpl().handleAddressOnly(type);
}
}
RetTy visitExistentialType(CanType type) {
switch (SILType::getPrimitiveObjectType(type)
.getPreferredExistentialRepresentation(M)) {
case ExistentialRepresentation::None:
llvm_unreachable("not an existential type?!");
// Opaque existentials are address-only.
case ExistentialRepresentation::Opaque:
return asImpl().handleAddressOnly(type);
// Class-constrained and boxed existentials are refcounted.
case ExistentialRepresentation::Class:
case ExistentialRepresentation::Boxed:
return asImpl().handleReference(type);
// Existential metatypes are trivial.
case ExistentialRepresentation::Metatype:
return asImpl().handleTrivial(type);
}
}
RetTy visitProtocolType(CanProtocolType type) {
return visitExistentialType(type);
}
RetTy visitProtocolCompositionType(CanProtocolCompositionType type) {
return visitExistentialType(type);
}
// Enums depend on their enumerators.
RetTy visitEnumType(CanEnumType type) {
return asImpl().visitAnyEnumType(type, type->getDecl());
}
RetTy visitBoundGenericEnumType(CanBoundGenericEnumType type) {
return asImpl().visitAnyEnumType(type, type->getDecl());
}
RetTy visitAnyEnumType(CanType type, EnumDecl *D) {
// Consult the type lowering.
auto &lowering = M.Types.getTypeLowering(type);
return handleClassificationFromLowering(type, lowering);
}
RetTy handleClassificationFromLowering(CanType type,
const TypeLowering &lowering) {
if (lowering.isAddressOnly())
return asImpl().handleAddressOnly(type);
if (lowering.isTrivial())
return asImpl().handleTrivial(type);
return asImpl().handleAggWithReference(type);
}
// Structs depend on their physical fields.
RetTy visitStructType(CanStructType type) {
return asImpl().visitAnyStructType(type, type->getDecl());
}
RetTy visitBoundGenericStructType(CanBoundGenericStructType type) {
return asImpl().visitAnyStructType(type, type->getDecl());
}
RetTy visitAnyStructType(CanType type, StructDecl *D) {
// Consult the type lowering. This means we implicitly get
// caching, but that type lowering needs to override this case.
auto &lowering = M.Types.getTypeLowering(type);
return handleClassificationFromLowering(type, lowering);
}
// Tuples depend on their elements.
RetTy visitTupleType(CanTupleType type) {
bool hasReference = false;
// TODO: We ought to be able to early-exit as soon as we've established
// that a type is address-only. However, we also currenty rely on
// SIL lowering to catch unsupported recursive value types.
bool isAddressOnly = false;
for (auto eltType : type.getElementTypes()) {
switch (classifyType(eltType, M)) {
case LoweredTypeKind::Trivial:
continue;
case LoweredTypeKind::AddressOnly:
isAddressOnly = true;
continue;
case LoweredTypeKind::Reference:
case LoweredTypeKind::AggWithReference:
hasReference = true;
continue;
}
llvm_unreachable("bad type classification");
}
if (isAddressOnly)
return asImpl().handleAddressOnly(type);
if (hasReference)
return asImpl().handleAggWithReference(type);
return asImpl().handleTrivial(type);
}
RetTy visitDynamicSelfType(CanDynamicSelfType type) {
return this->visit(type.getSelfType());
}
RetTy visitSILBlockStorageType(CanSILBlockStorageType type) {
// Should not be loaded.
return asImpl().handleAddressOnly(type);
}
RetTy visitSILBoxType(CanSILBoxType type) {
// Should not be loaded.
return asImpl().handleReference(type);
}
};
class TypeClassifier :
public TypeClassifierBase<TypeClassifier, LoweredTypeKind> {
public:
TypeClassifier(SILModule &M) : TypeClassifierBase(M) {}
LoweredTypeKind handleReference(CanType type) {
return LoweredTypeKind::Reference;
}
LoweredTypeKind handleAggWithReference(CanType type) {
return LoweredTypeKind::AggWithReference;
}
LoweredTypeKind handleTrivial(CanType type) {
return LoweredTypeKind::Trivial;
}
LoweredTypeKind handleAddressOnly(CanType type) {
return LoweredTypeKind::AddressOnly;
}
};
}
static LoweredTypeKind classifyType(CanType type, SILModule &M) {
if (type->hasTypeParameter())
type = M.Types.getArchetypes().substDependentType(type)->getCanonicalType();
return TypeClassifier(M).visit(type);
}
/// True if the type, or the referenced type of an address
/// type, is address-only. For example, it could be a resilient struct or
/// something of unknown size.
bool SILType::isAddressOnly(CanType type, SILModule &M) {
return classifyType(type, M) == LoweredTypeKind::AddressOnly;
}
namespace {
/// A class for loadable types.
class LoadableTypeLowering : public TypeLowering {
protected:
LoadableTypeLowering(SILType type, IsTrivial_t isTrivial,
IsReferenceCounted_t isRefCounted)
: TypeLowering(type, isTrivial, IsNotAddressOnly, isRefCounted) {}
public:
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
SILValue value = B.createLoad(loc, addr);
emitReleaseValue(B, loc, value);
}
void emitDestroyRValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
emitReleaseValue(B, loc, value);
}
void emitCopyInto(SILBuilder &B, SILLocation loc,
SILValue src, SILValue dest, IsTake_t isTake,
IsInitialization_t isInit) const override {
SILValue value = emitLoadOfCopy(B, loc, src, isTake);
emitStoreOfCopy(B, loc, value, dest, isInit);
}
};
/// A class for trivial, loadable types.
class TrivialTypeLowering final : public LoadableTypeLowering {
public:
TrivialTypeLowering(SILType type)
: LoadableTypeLowering(type, IsTrivial, IsNotReferenceCounted) {}
SILValue emitLoadOfCopy(SILBuilder &B, SILLocation loc, SILValue addr,
IsTake_t isTake) const override {
return B.createLoad(loc, addr);
}
void emitStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue value, SILValue addr,
IsInitialization_t isInit) const override {
B.createStore(loc, value, addr);
}
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
// Trivial
}
void emitLoweredReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle loweringStyle) const override {
// Trivial
}
void emitLoweredRetainValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
// Trivial
}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
// Trivial
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
// Trivial
}
};
class NonTrivialLoadableTypeLowering : public LoadableTypeLowering {
public:
NonTrivialLoadableTypeLowering(SILType type,
IsReferenceCounted_t isRefCounted)
: LoadableTypeLowering(type, IsNotTrivial, isRefCounted) {}
SILValue emitLoadOfCopy(SILBuilder &B, SILLocation loc,
SILValue addr, IsTake_t isTake) const override {
SILValue value = B.createLoad(loc, addr);
if (!isTake) emitRetainValue(B, loc, value);
return value;
}
void emitStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue newValue, SILValue addr,
IsInitialization_t isInit) const override {
SILValue oldValue;
if (!isInit) oldValue = B.createLoad(loc, addr);
B.createStore(loc, newValue, addr);
if (!isInit) emitReleaseValue(B, loc, oldValue);
}
};
/// A CRTP helper class for loadable but non-trivial aggregate types.
template <class Impl, class IndexType>
class LoadableAggTypeLowering : public NonTrivialLoadableTypeLowering {
public:
/// A child of this aggregate type.
class Child {
/// The index of this child, used to project it out.
IndexType Index;
/// The aggregate's type lowering.
const TypeLowering *Lowering;
public:
Child(IndexType index, const TypeLowering &lowering)
: Index(index), Lowering(&lowering) {}
const TypeLowering &getLowering() const { return *Lowering; }
IndexType getIndex() const { return Index; }
bool isTrivial() const { return Lowering->isTrivial(); }
};
private:
const Impl &asImpl() const { return static_cast<const Impl&>(*this); }
Impl &asImpl() { return static_cast<Impl&>(*this); }
// A reference to the lazily-allocated children vector.
mutable ArrayRef<Child> Children = {};
protected:
virtual void lowerChildren(SILModule &M, SmallVectorImpl<Child> &children)
const = 0;
public:
LoadableAggTypeLowering(CanType type)
: NonTrivialLoadableTypeLowering(SILType::getPrimitiveObjectType(type),
IsNotReferenceCounted) {
}
ArrayRef<Child> getChildren(SILModule &M) const {
if (Children.data() == nullptr) {
SmallVector<Child, 4> children;
lowerChildren(M, children);
auto isDependent = IsDependent_t(getLoweredType().hasTypeParameter());
auto buf = operator new(sizeof(Child) * children.size(), M.Types,
isDependent);
memcpy(buf, children.data(), sizeof(Child) * children.size());
Children = {reinterpret_cast<Child*>(buf), children.size()};
}
return Children;
}
template <class T>
void forEachNonTrivialChild(SILBuilder &B, SILLocation loc,
SILValue aggValue,
const T &operation) const {
for (auto &child : getChildren(B.getModule())) {
auto &childLowering = child.getLowering();
// Skip trivial children.
if (childLowering.isTrivial())
continue;
auto childIndex = child.getIndex();
auto childValue = asImpl().emitRValueProject(B, loc, aggValue,
childIndex, childLowering);
operation(B, loc, childIndex, childValue, childLowering);
}
}
using SimpleOperationTy = void (TypeLowering::*)(SILBuilder &B,
SILLocation loc,
SILValue value) const;
void forEachNonTrivialChild(SILBuilder &B, SILLocation loc,
SILValue aggValue,
SimpleOperationTy operation) const {
forEachNonTrivialChild(B, loc, aggValue,
[operation](SILBuilder &B, SILLocation loc, IndexType index,
SILValue childValue, const TypeLowering &childLowering) {
(childLowering.*operation)(B, loc, childValue);
});
}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue aggValue) const override {
B.createRetainValue(loc, aggValue);
}
void emitLoweredRetainValue(SILBuilder &B, SILLocation loc,
SILValue aggValue,
LoweringStyle style) const override {
for (auto &child : getChildren(B.getModule())) {
auto &childLowering = child.getLowering();
SILValue childValue = asImpl().emitRValueProject(B, loc, aggValue,
child.getIndex(),
childLowering);
if (!childLowering.isTrivial()) {
childLowering.emitLoweredCopyChildValue(B, loc, childValue, style);
}
}
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue aggValue) const override {
B.emitReleaseValueAndFold(loc, aggValue);
}
void emitLoweredReleaseValue(SILBuilder &B, SILLocation loc,
SILValue aggValue,
LoweringStyle loweringStyle) const override {
SimpleOperationTy Fn;
switch(loweringStyle) {
case LoweringStyle::Shallow:
Fn = &TypeLowering::emitReleaseValue;
break;
case LoweringStyle::Deep:
Fn = &TypeLowering::emitLoweredReleaseValueDeep;
break;
case LoweringStyle::DeepNoEnum:
Fn = &TypeLowering::emitLoweredReleaseValueDeepNoEnum;
break;
}
forEachNonTrivialChild(B, loc, aggValue, Fn);
}
};
/// A lowering for loadable but non-trivial tuple types.
class LoadableTupleTypeLowering final
: public LoadableAggTypeLowering<LoadableTupleTypeLowering, unsigned> {
public:
LoadableTupleTypeLowering(CanType type)
: LoadableAggTypeLowering(type) {}
SILValue emitRValueProject(SILBuilder &B, SILLocation loc,
SILValue tupleValue, unsigned index,
const TypeLowering &eltLowering) const {
return B.createTupleExtract(loc, tupleValue, index,
eltLowering.getLoweredType());
}
SILValue rebuildAggregate(SILBuilder &B, SILLocation loc,
ArrayRef<SILValue> values) const {
return B.createTuple(loc, getLoweredType(), values);
}
private:
void lowerChildren(SILModule &M, SmallVectorImpl<Child> &children)
const override {
// The children are just the elements of the lowered tuple.
auto silTy = getLoweredType();
auto tupleTy = silTy.castTo<TupleType>();
children.reserve(tupleTy->getNumElements());
unsigned index = 0;
for (auto elt : tupleTy.getElementTypes()) {
auto silElt = SILType::getPrimitiveType(elt, silTy.getCategory());
children.push_back(Child{index, M.Types.getTypeLowering(silElt)});
++index;
}
}
};
/// A lowering for loadable but non-trivial struct types.
class LoadableStructTypeLowering final
: public LoadableAggTypeLowering<LoadableStructTypeLowering, VarDecl*> {
public:
LoadableStructTypeLowering(CanType type)
: LoadableAggTypeLowering(type) {}
SILValue emitRValueProject(SILBuilder &B, SILLocation loc,
SILValue structValue, VarDecl *field,
const TypeLowering &fieldLowering) const {
return B.createStructExtract(loc, structValue, field,
fieldLowering.getLoweredType());
}
SILValue rebuildAggregate(SILBuilder &B, SILLocation loc,
ArrayRef<SILValue> values) const {
return B.createStruct(loc, getLoweredType(), values);
}
private:
void lowerChildren(SILModule &M, SmallVectorImpl<Child> &children)
const override {
auto silTy = getLoweredType();
auto structDecl = silTy.getStructOrBoundGenericStruct();
assert(structDecl);
for (auto prop : structDecl->getStoredProperties()) {
SILType propTy = silTy.getFieldType(prop, M);
children.push_back(Child{prop, M.Types.getTypeLowering(propTy)});
}
}
};
/// A lowering for loadable but non-trivial enum types.
class LoadableEnumTypeLowering final : public NonTrivialLoadableTypeLowering {
public:
/// A non-trivial case of the enum.
class NonTrivialElement {
/// The non-trivial element.
EnumElementDecl *element;
/// Its type lowering.
const TypeLowering *lowering;
public:
NonTrivialElement(EnumElementDecl *element, const TypeLowering &lowering)
: element(element), lowering(&lowering) {}
const TypeLowering &getLowering() const { return *lowering; }
EnumElementDecl *getElement() const { return element; }
};
private:
using SimpleOperationTy = void (*)(SILBuilder &B, SILLocation loc, SILValue value,
const TypeLowering &valueLowering,
SILBasicBlock *dest);
/// Emit a value semantics operation for each nontrivial case of the enum.
template <typename T>
void ifNonTrivialElement(SILBuilder &B, SILLocation loc, SILValue value,
const T &operation) const {
SmallVector<std::pair<EnumElementDecl*,SILBasicBlock*>, 4> nonTrivialBBs;
auto &M = B.getFunction().getModule();
// Create all the blocks up front, so we can set up our switch_enum.
auto nonTrivialElts = getNonTrivialElements(M);
for (auto &elt : nonTrivialElts) {
auto bb = new (M) SILBasicBlock(&B.getFunction());
auto argTy = elt.getLowering().getLoweredType();
new (M) SILArgument(bb, argTy);
nonTrivialBBs.push_back({elt.getElement(), bb});
}
// If we are appending to the end of a block being constructed, then we
// create a new basic block to continue cons'ing up code. If we're
// emitting this operation into the middle of existing code, we split the
// block.
SILBasicBlock *doneBB = B.splitBlockForFallthrough();
B.createSwitchEnum(loc, value, doneBB, nonTrivialBBs);
for (size_t i = 0; i < nonTrivialBBs.size(); ++i) {
SILBasicBlock *bb = nonTrivialBBs[i].second;
const TypeLowering &lowering = nonTrivialElts[i].getLowering();
B.emitBlock(bb);
operation(B, loc, bb->getBBArgs()[0], lowering, doneBB);
}
B.emitBlock(doneBB);
}
/// A reference to the lazily-allocated array of non-trivial enum cases.
mutable ArrayRef<NonTrivialElement> NonTrivialElements = {};
public:
LoadableEnumTypeLowering(CanType type)
: NonTrivialLoadableTypeLowering(SILType::getPrimitiveObjectType(type),
IsNotReferenceCounted)
{
}
ArrayRef<NonTrivialElement> getNonTrivialElements(SILModule &M) const {
SILType silTy = getLoweredType();
EnumDecl *enumDecl = silTy.getEnumOrBoundGenericEnum();
assert(enumDecl);
if (NonTrivialElements.data() == nullptr) {
SmallVector<NonTrivialElement, 4> elts;
for (auto elt : enumDecl->getAllElements()) {
if (!elt->hasArgumentType()) continue;
SILType substTy = silTy.getEnumElementType(elt, M);
elts.push_back(NonTrivialElement{elt,
M.Types.getTypeLowering(substTy)});
}
auto isDependent = IsDependent_t(silTy.hasTypeParameter());
auto buf = operator new(sizeof(NonTrivialElement) * elts.size(),
M.Types, isDependent);
memcpy(buf, elts.data(), sizeof(NonTrivialElement) * elts.size());
NonTrivialElements = {reinterpret_cast<NonTrivialElement*>(buf),
elts.size()};
}
return NonTrivialElements;
}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.createRetainValue(loc, value);
}
void emitLoweredRetainValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
if (style == LoweringStyle::Shallow ||
style == LoweringStyle::DeepNoEnum) {
B.createRetainValue(loc, value);
} else {
ifNonTrivialElement(B, loc, value,
[&](SILBuilder &B, SILLocation loc, SILValue child,
const TypeLowering &childLowering, SILBasicBlock *dest) {
childLowering.emitLoweredCopyChildValue(B, loc, child, style);
B.createBranch(loc, dest);
});
}
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.emitReleaseValueAndFold(loc, value);
}
void emitLoweredReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
assert(style != LoweringStyle::Shallow &&
"This method should never be called when performing a shallow "
"destroy value.");
if (style == LoweringStyle::DeepNoEnum)
B.emitReleaseValueAndFold(loc, value);
else
ifNonTrivialElement(B, loc, value,
[&](SILBuilder &B, SILLocation loc, SILValue child,
const TypeLowering &childLowering, SILBasicBlock *dest) {
childLowering.emitLoweredDestroyChildValue(B, loc, child, style);
B.createBranch(loc, dest);
});
}
};
class LeafLoadableTypeLowering : public NonTrivialLoadableTypeLowering {
public:
LeafLoadableTypeLowering(SILType type, IsReferenceCounted_t isRefCounted)
: NonTrivialLoadableTypeLowering(type, isRefCounted) {}
void emitLoweredRetainValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
emitRetainValue(B, loc, value);
}
void emitLoweredReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
emitReleaseValue(B, loc, value);
}
};
/// A class for reference types, which are all non-trivial but still
/// loadable.
class ReferenceTypeLowering : public LeafLoadableTypeLowering {
public:
ReferenceTypeLowering(SILType type)
: LeafLoadableTypeLowering(type, IsReferenceCounted) {}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (!isa<FunctionRefInst>(value))
B.createStrongRetain(loc, value);
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.emitStrongReleaseAndFold(loc, value);
}
};
/// A type lowering for @unowned types.
class UnownedTypeLowering final : public LeafLoadableTypeLowering {
public:
UnownedTypeLowering(SILType type)
: LeafLoadableTypeLowering(type, IsReferenceCounted) {}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.createUnownedRetain(loc, value);
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.createUnownedRelease(loc, value);
}
};
/// A class for non-trivial, address-only types.
class AddressOnlyTypeLowering : public TypeLowering {
public:
AddressOnlyTypeLowering(SILType type)
: TypeLowering(type, IsNotTrivial, IsAddressOnly, IsNotReferenceCounted)
{}
void emitCopyInto(SILBuilder &B, SILLocation loc,
SILValue src, SILValue dest, IsTake_t isTake,
IsInitialization_t isInit) const override {
B.createCopyAddr(loc, src, dest, isTake, isInit);
}
SILValue emitLoadOfCopy(SILBuilder &B, SILLocation loc,
SILValue addr, IsTake_t isTake) const override {
llvm_unreachable("calling emitLoadOfCopy on non-loadable type");
}
void emitStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue newValue, SILValue addr,
IsInitialization_t isInit) const override {
llvm_unreachable("calling emitStoreOfCopy on non-loadable type");
}
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
B.emitDestroyAddrAndFold(loc, addr);
}
void emitDestroyRValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
B.emitDestroyAddrAndFold(loc, value);
}
void emitRetainValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
llvm_unreachable("type is not loadable!");
}
void emitLoweredRetainValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
llvm_unreachable("type is not loadable!");
}
void emitReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
llvm_unreachable("type is not loadable!");
}
void emitLoweredReleaseValue(SILBuilder &B, SILLocation loc,
SILValue value,
LoweringStyle style) const override {
llvm_unreachable("type is not loadable!");
}
};
/// A class for Builtin.UnsafeValueBuffer. The only purpose here is
/// to catch obviously broken attempts to copy or destroy the buffer.
class UnsafeValueBufferTypeLowering : public AddressOnlyTypeLowering {
public:
UnsafeValueBufferTypeLowering(SILType type)
: AddressOnlyTypeLowering(type) {}
void emitCopyInto(SILBuilder &B, SILLocation loc,
SILValue src, SILValue dest, IsTake_t isTake,
IsInitialization_t isInit) const override {
llvm_unreachable("cannot copy an UnsafeValueBuffer!");
}
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
llvm_unreachable("cannot destroy an UnsafeValueBuffer!");
}
void emitDestroyRValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
llvm_unreachable("cannot destroy an UnsafeValueBuffer!");
}
};
/// A class that acts as a stand-in for improperly recursive types.
class RecursiveErrorTypeLowering : public AddressOnlyTypeLowering {
public:
RecursiveErrorTypeLowering(SILType type)
: AddressOnlyTypeLowering(type) {}
bool isValid() const override {
return false;
}
};
/// Build the appropriate TypeLowering subclass for the given type.
class LowerType
: public TypeClassifierBase<LowerType, const TypeLowering *>
{
TypeConverter &TC;
CanType OrigType;
IsDependent_t Dependent;
public:
LowerType(TypeConverter &TC, CanType OrigType, IsDependent_t Dependent)
: TypeClassifierBase(TC.M), TC(TC), OrigType(OrigType),
Dependent(Dependent) {}
const TypeLowering *handleTrivial(CanType type) {
auto silType = SILType::getPrimitiveObjectType(OrigType);
return new (TC, Dependent) TrivialTypeLowering(silType);
}
const TypeLowering *handleReference(CanType type) {
auto silType = SILType::getPrimitiveObjectType(OrigType);
return new (TC, Dependent) ReferenceTypeLowering(silType);
}
const TypeLowering *handleAddressOnly(CanType type) {
auto silType = SILType::getPrimitiveAddressType(OrigType);
return new (TC, Dependent) AddressOnlyTypeLowering(silType);
}
/// @unowned is basically like a reference type lowering except
/// it manipulates unowned reference counts instead of strong.
const TypeLowering *visitUnownedStorageType(CanUnownedStorageType type) {
// Lower 'Self' as if it were the base type.
if (auto dynamicSelfType
= dyn_cast<DynamicSelfType>(type.getReferentType())) {
auto unownedBaseType = CanUnownedStorageType::get(
dynamicSelfType.getSelfType());
return LowerType(TC, unownedBaseType, Dependent)
.visit(unownedBaseType);
}
return new (TC, Dependent) UnownedTypeLowering(
SILType::getPrimitiveObjectType(OrigType));
}