forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILGenPoly.cpp
1991 lines (1742 loc) · 84.4 KB
/
SILGenPoly.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
//===--- SILGenPoly.cpp - Function Type Thunks ----------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// In Swift's AST-level type system, function types are allowed to be equivalent
// or have a subtyping relationship even if the SIL-level lowering of the
// calling convention is different. The routines in this file implement thunking
// between lowered function types.
//
//
// Re-abstraction thunks
// =====================
// After SIL type lowering, generic substitutions become explicit, for example
// the AST type Int -> Int passes the Ints directly, whereas T -> T with Int
// substituted for T will pass the Ints like a T, as an address-only value with
// opaque type metadata. Such a thunk is called a "re-abstraction thunk" -- the
// AST-level type of the function value does not change, only the manner in
// which parameters and results are passed.
//
// Function conversion thunks
// ==========================
// In Swift's AST-level type system, certain types have a subtype relation
// involving a representation change. For example, a concrete type is always
// a subtype of any protocol it conforms to. The upcast from the concrete
// type to an existential type for the protocol requires packaging the
// payload together with type metadata and witness tables.
//
// Between function types, the type A -> B is defined to be a subtype of
// A' -> B' iff A' is a subtype of A, and B is a subtype of B' -- parameters
// are contravariant, and results are covariant.
//
// A subtype conversion of a function value A -> B is performed by wrapping
// the function value in a thunk of type A' -> B'. The thunk takes an A' and
// converts it into an A, calls the inner function value, and converts the
// result from B to B'.
//
// VTable thunks
// =============
//
// If a base class is generic and a derived class substitutes some generic
// parameter of the base with a concrete type, the derived class can override
// methods in the base that involved generic types. In the derived class, a
// method override that involves substituted types will have a different
// SIL lowering than the base method. In this case, the overriden vtable entry
// will point to a thunk which transforms parameters and results and invokes
// the derived method.
//
// Some limited forms of subtyping are also supported for method overrides;
// namely, a derived method's parameter can be a superclass of, or more
// optional than, a parameter of the base, and result can be a subclass of,
// or less optional than, the result of the base.
//
// Witness thunks
// ==============
//
// Currently protocol witness methods are called with an additional generic
// parameter bound to the Self type, and thus always require a thunk.
//
// Thunks for class method witnesses dispatch through the vtable allowing
// inherited witnesses to be overridden in subclasses. Hence a witness thunk
// might require two levels of abstraction difference -- the method might
// override a base class method with more generic types, and the protocol
// requirement may involve associated types which are always concrete in the
// conforming class.
//
// Other thunks
// ============
//
// Foreign-to-native, native-to-foreign thunks for declarations and function
// values are implemented in SILGenBridging.cpp.
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "Scope.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/AST/AST.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/TypeLowering.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
using namespace swift;
using namespace Lowering;
namespace {
/// An abstract class for transforming first-class SIL values.
class Transform {
private:
SILGenFunction &SGF;
SILLocation Loc;
public:
Transform(SILGenFunction &SGF, SILLocation loc) : SGF(SGF), Loc(loc) {}
virtual ~Transform() = default;
/// Transform an arbitrary value.
ManagedValue transform(ManagedValue input,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt);
/// Transform a metatype value.
ManagedValue transformMetatype(ManagedValue fn,
AbstractionPattern inputOrigType,
CanMetatypeType inputSubstType,
AbstractionPattern outputOrigType,
CanMetatypeType outputSubstType);
/// Transform a tuple value.
ManagedValue transformTuple(ManagedValue input,
AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
SGFContext ctxt);
/// Transform a function value.
ManagedValue transformFunction(ManagedValue fn,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
AbstractionPattern outputOrigType,
CanAnyFunctionType outputSubstType,
const TypeLowering &expectedTL);
};
};
static ArrayRef<ProtocolConformance*>
collectExistentialConformances(Module *M, Type fromType, Type toType) {
assert(!fromType->isAnyExistentialType());
SmallVector<ProtocolDecl *, 4> protocols;
toType->getAnyExistentialTypeProtocols(protocols);
SmallVector<ProtocolConformance *, 4> conformances;
for (auto proto : protocols) {
ProtocolConformance *conformance =
M->lookupConformance(fromType, proto, nullptr).getPointer();
conformances.push_back(conformance);
}
return M->getASTContext().AllocateCopy(conformances);
}
static CanArchetypeType getOpenedArchetype(Type openedType) {
while (auto metatypeTy = openedType->getAs<MetatypeType>())
openedType = metatypeTy->getInstanceType();
return cast<ArchetypeType>(openedType->getCanonicalType());
}
static ManagedValue emitTransformExistential(SILGenFunction &SGF,
SILLocation loc,
ManagedValue input,
CanType inputType,
CanType outputType,
SGFContext ctxt) {
assert(inputType != outputType);
SILGenFunction::OpaqueValueState state;
CanArchetypeType openedArchetype;
if (inputType->isAnyExistentialType()) {
CanType openedType = ArchetypeType::getAnyOpened(inputType);
SILType loweredOpenedType = SGF.getLoweredType(openedType);
// Unwrap zero or more metatype levels
openedArchetype = getOpenedArchetype(openedType);
state = SGF.emitOpenExistential(loc, input,
openedArchetype, loweredOpenedType);
inputType = openedType;
}
// Build conformance table
Type fromInstanceType = inputType;
Type toInstanceType = outputType;
// Look through metatypes
while (fromInstanceType->is<AnyMetatypeType>() &&
toInstanceType->is<ExistentialMetatypeType>()) {
fromInstanceType = fromInstanceType->castTo<AnyMetatypeType>()
->getInstanceType();
toInstanceType = toInstanceType->castTo<ExistentialMetatypeType>()
->getInstanceType();
}
ArrayRef<ProtocolConformance *> conformances =
collectExistentialConformances(SGF.SGM.M.getSwiftModule(),
fromInstanceType,
toInstanceType);
// Build result existential
AbstractionPattern opaque = AbstractionPattern::getOpaque();
const TypeLowering &concreteTL = SGF.getTypeLowering(opaque, inputType);
const TypeLowering &expectedTL = SGF.getTypeLowering(outputType);
input = SGF.emitExistentialErasure(
loc, inputType, concreteTL, expectedTL,
conformances, ctxt,
[&](SGFContext C) -> ManagedValue {
if (openedArchetype)
return SGF.manageOpaqueValue(state, loc, C);
return input;
});
if (openedArchetype)
state.destroy(SGF, loc);
return input;
}
// Single @objc protocol value metatypes can be converted to the ObjC
// Protocol class type.
static bool isProtocolClass(Type t) {
auto classDecl = t->getClassOrBoundGenericClass();
if (!classDecl)
return false;
ASTContext &ctx = classDecl->getASTContext();
return (classDecl->getName() == ctx.Id_Protocol &&
classDecl->getModuleContext()->getName() == ctx.Id_ObjectiveC);
};
static ManagedValue emitManagedLoad(SILGenFunction &gen, SILLocation loc,
ManagedValue addr,
const TypeLowering &addrTL) {
auto loadedValue = gen.B.createLoad(loc, addr.forward(gen));
return gen.emitManagedRValueWithCleanup(loadedValue, addrTL);
}
/// Apply this transformation to an arbitrary value.
ManagedValue Transform::transform(ManagedValue v,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt) {
// Look through inout types.
if (isa<InOutType>(inputSubstType))
inputSubstType = CanType(inputSubstType->getInOutObjectType());
// Load if the result isn't address-only. All the translation routines
// expect this.
if (v.getType().isAddress()) {
auto &inputTL = SGF.getTypeLowering(v.getType());
if (!inputTL.isAddressOnly()) {
v = emitManagedLoad(SGF, Loc, v, inputTL);
}
}
const TypeLowering &expectedTL = SGF.getTypeLowering(outputOrigType,
outputSubstType);
auto loweredResultTy = expectedTL.getLoweredType();
// Nothing to convert
if (v.getType() == loweredResultTy)
return v;
OptionalTypeKind outputOTK, inputOTK;
CanType inputObjectType = inputSubstType.getAnyOptionalObjectType(inputOTK);
CanType outputObjectType = outputSubstType.getAnyOptionalObjectType(outputOTK);
// If the value is less optional than the desired formal type, wrap in
// an optional.
if (outputOTK != OTK_None && inputOTK == OTK_None) {
return SGF.emitInjectOptional(Loc, v,
inputSubstType, outputSubstType,
expectedTL, ctxt);
}
// If the value is IUO, but the desired formal type isn't optional, force it.
if (inputOTK == OTK_ImplicitlyUnwrappedOptional
&& outputOTK == OTK_None) {
v = SGF.emitCheckedGetOptionalValueFrom(Loc, v,
SGF.getTypeLowering(v.getType()),
SGFContext());
// Check if we have any more conversions remaining.
if (v.getType() == loweredResultTy)
return v;
inputOTK = OTK_None;
}
// Optional-to-optional conversion.
if (inputOTK != OTK_None && outputOTK != OTK_None &&
(inputOTK != outputOTK ||
inputObjectType != outputObjectType)) {
// If the conversion is trivial, just cast.
if (SGF.SGM.Types.checkForABIDifferences(v.getType().getSwiftRValueType(),
loweredResultTy.getSwiftRValueType())
== TypeConverter::ABIDifference::Trivial) {
SILValue result = v.getValue();
if (v.getType().isAddress())
result = SGF.B.createUncheckedAddrCast(Loc, result, loweredResultTy);
else
result = SGF.B.createUncheckedBitCast(Loc, result, loweredResultTy);
return ManagedValue(result, v.getCleanup());
}
auto transformOptionalPayload = [&](SILGenFunction &gen,
SILLocation loc,
ManagedValue input,
SILType loweredResultTy) -> ManagedValue {
return transform(input,
AbstractionPattern::getOpaque(), inputObjectType,
AbstractionPattern::getOpaque(), outputObjectType,
SGFContext());
};
return SGF.emitOptionalToOptional(Loc, v, loweredResultTy,
transformOptionalPayload);
}
// Abstraction changes:
// - functions
if (auto outputFnType = dyn_cast<AnyFunctionType>(outputSubstType)) {
auto inputFnType = cast<AnyFunctionType>(inputSubstType);
return transformFunction(v,
inputOrigType, inputFnType,
outputOrigType, outputFnType,
expectedTL);
}
// - tuples of transformable values
if (auto outputTupleType = dyn_cast<TupleType>(outputSubstType)) {
auto inputTupleType = cast<TupleType>(inputSubstType);
return transformTuple(v,
inputOrigType, inputTupleType,
outputOrigType, outputTupleType,
ctxt);
}
// - metatypes
if (auto outputMetaType = dyn_cast<MetatypeType>(outputSubstType)) {
auto inputMetaType = cast<MetatypeType>(inputSubstType);
return transformMetatype(v,
inputOrigType, inputMetaType,
outputOrigType, outputMetaType);
}
// Subtype conversions:
// - upcasts
if (outputSubstType->getClassOrBoundGenericClass() &&
inputSubstType->getClassOrBoundGenericClass()) {
auto class1 = inputSubstType->getClassOrBoundGenericClass();
auto class2 = outputSubstType->getClassOrBoundGenericClass();
// CF <-> Objective-C via toll-free bridging.
if (class1->isForeign() != class2->isForeign()) {
return ManagedValue(SGF.B.createUncheckedRefCast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
}
// Upcast to a superclass.
return ManagedValue(SGF.B.createUpcast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
}
// - upcasts from an archetype
if (outputSubstType->getClassOrBoundGenericClass()) {
if (auto archetypeType = dyn_cast<ArchetypeType>(inputSubstType)) {
if (archetypeType->getSuperclass()) {
// Replace the cleanup with a new one on the superclass value so we
// always use concrete retain/release operations.
return ManagedValue(SGF.B.createUpcast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
}
}
}
// - metatype to Protocol conversion
if (isProtocolClass(outputSubstType)) {
if (auto metatypeTy = dyn_cast<MetatypeType>(inputSubstType)) {
return SGF.emitProtocolMetatypeToObject(Loc, metatypeTy,
SGF.getLoweredLoadableType(outputSubstType));
}
}
// - metatype to AnyObject conversion
if (outputSubstType->isAnyObject() &&
isa<MetatypeType>(inputSubstType)) {
return SGF.emitClassMetatypeToObject(Loc, v,
SGF.getLoweredLoadableType(outputSubstType));
}
// - existential metatype to AnyObject conversion
if (outputSubstType->isAnyObject() &&
isa<ExistentialMetatypeType>(inputSubstType)) {
return SGF.emitExistentialMetatypeToObject(Loc, v,
SGF.getLoweredLoadableType(outputSubstType));
}
// - existentials
if (outputSubstType->isAnyExistentialType()) {
// We have to re-abstract payload if its a metatype or a function
v = SGF.emitSubstToOrigValue(Loc, v, AbstractionPattern::getOpaque(),
inputSubstType);
return emitTransformExistential(SGF, Loc, v,
inputSubstType, outputSubstType,
ctxt);
}
// Should have handled the conversion in one of the cases above.
llvm_unreachable("Unhandled transform?");
}
ManagedValue Transform::transformMetatype(ManagedValue meta,
AbstractionPattern inputOrigType,
CanMetatypeType inputSubstType,
AbstractionPattern outputOrigType,
CanMetatypeType outputSubstType) {
assert(!meta.hasCleanup() && "metatype with cleanup?!");
auto expectedType = SGF.getTypeLowering(outputOrigType,
outputSubstType).getLoweredType();
auto wasRepr = meta.getType().castTo<MetatypeType>()->getRepresentation();
auto willBeRepr = expectedType.castTo<MetatypeType>()->getRepresentation();
SILValue result;
if ((wasRepr == MetatypeRepresentation::Thick &&
willBeRepr == MetatypeRepresentation::Thin) ||
(wasRepr == MetatypeRepresentation::Thin &&
willBeRepr == MetatypeRepresentation::Thick)) {
// If we have a thin-to-thick abstraction change, cook up new a metatype
// value out of nothing -- thin metatypes carry no runtime state.
result = SGF.B.createMetatype(Loc, expectedType);
} else {
// Otherwise, we have a metatype subtype conversion of thick metatypes.
assert(wasRepr == willBeRepr && "Unhandled metatype conversion");
result = SGF.B.createUpcast(Loc, meta.getUnmanagedValue(), expectedType);
}
return ManagedValue::forUnmanaged(result);
}
/// Explode a managed tuple into a bunch of managed elements.
///
/// If the tuple is in memory, the result elements will also be in
/// memory.
typedef std::pair<ManagedValue, const TypeLowering *> ManagedValueAndType;
static void explodeTuple(SILGenFunction &gen,
SILLocation loc,
ManagedValue managedTuple,
SmallVectorImpl<ManagedValueAndType> &out) {
// None of the operations we do here can fail, so we can atomically
// disable the tuple's cleanup and then create cleanups for all the
// elements.
SILValue tuple = managedTuple.forward(gen);
auto tupleSILType = tuple.getType();
auto tupleType = tupleSILType.castTo<TupleType>();
out.reserve(tupleType->getNumElements());
for (auto index : indices(tupleType.getElementTypes())) {
// We're starting with a SIL-lowered tuple type, so the elements
// must also all be SIL-lowered.
SILType eltType = tupleSILType.getTupleElementType(index);
auto &eltTL = gen.getTypeLowering(eltType);
ManagedValue elt;
if (tupleSILType.isAddress()) {
auto addr = gen.B.createTupleElementAddr(loc, tuple, index, eltType);
elt = gen.emitManagedBufferWithCleanup(addr, eltTL);
} else {
auto value = gen.B.createTupleExtract(loc, tuple, index, eltType);
elt = gen.emitManagedRValueWithCleanup(value, eltTL);
}
out.push_back(ManagedValueAndType(elt, &eltTL));
}
}
/// Apply this transformation to all the elements of a tuple value,
/// which just entails mapping over each of its component elements.
ManagedValue Transform::transformTuple(ManagedValue inputTuple,
AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
SGFContext ctxt) {
const TypeLowering &outputTL =
SGF.getTypeLowering(outputOrigType, outputSubstType);
assert(outputTL.isAddressOnly() == inputTuple.getType().isAddress() &&
"expected loadable inputs to have been loaded");
// If there's no representation difference, we're done.
if (outputTL.getLoweredType() == inputTuple.getType())
return inputTuple;
assert(inputOrigType.matchesTuple(outputSubstType));
assert(outputOrigType.matchesTuple(outputSubstType));
auto inputType = inputTuple.getType().castTo<TupleType>();
assert(outputSubstType->getNumElements() == inputType->getNumElements());
// If the tuple is address only, we need to do the operation in memory.
SILValue outputAddr;
if (outputTL.isAddressOnly())
outputAddr = SGF.getBufferForExprResult(Loc, outputTL.getLoweredType(),
ctxt);
// Explode the tuple into individual managed values.
SmallVector<ManagedValueAndType, 4> inputElts;
explodeTuple(SGF, Loc, inputTuple, inputElts);
// Track all the managed elements whether or not we're actually
// emitting to an address, just so that we can disable them after.
SmallVector<ManagedValue, 4> outputElts;
for (auto index : indices(inputType->getElementTypes())) {
auto &inputEltTL = *inputElts[index].second;
ManagedValue inputElt = inputElts[index].first;
if (inputElt.getType().isAddress() && !inputEltTL.isAddressOnly()) {
inputElt = emitManagedLoad(SGF, Loc, inputElt, inputEltTL);
}
auto inputEltOrigType = inputOrigType.getTupleElementType(index);
auto inputEltSubstType = inputSubstType.getElementType(index);
auto outputEltOrigType = outputOrigType.getTupleElementType(index);
auto outputEltSubstType = outputSubstType.getElementType(index);
// If we're emitting to memory, project out this element in the
// destination buffer, then wrap that in an Initialization to
// track the cleanup.
Optional<TemporaryInitialization> outputEltTemp;
if (outputAddr) {
SILValue outputEltAddr =
SGF.B.createTupleElementAddr(Loc, outputAddr, index);
auto &outputEltTL = SGF.getTypeLowering(outputEltAddr.getType());
assert(outputEltTL.isAddressOnly() == inputEltTL.isAddressOnly());
auto cleanup =
SGF.enterDormantTemporaryCleanup(outputEltAddr, outputEltTL);
outputEltTemp.emplace(outputEltAddr, cleanup);
}
SGFContext eltCtxt =
(outputEltTemp ? SGFContext(&outputEltTemp.getValue()) : SGFContext());
auto outputElt = transform(inputElt,
inputEltOrigType, inputEltSubstType,
outputEltOrigType, outputEltSubstType,
eltCtxt);
// If we're not emitting to memory, remember this element for
// later assembly into a tuple.
if (!outputEltTemp) {
assert(outputElt);
assert(!inputEltTL.isAddressOnly());
outputElts.push_back(outputElt);
continue;
}
// Otherwise, make sure we emit into the slot.
auto &temp = outputEltTemp.getValue();
auto outputEltAddr = temp.getManagedAddress();
// That might involve storing directly.
if (outputElt) {
outputElt.forwardInto(SGF, Loc, outputEltAddr.getValue());
temp.finishInitialization(SGF);
}
outputElts.push_back(outputEltAddr);
}
// Okay, disable all the individual element cleanups and collect
// the values for a potential tuple aggregate.
SmallVector<SILValue, 4> outputEltValues;
for (auto outputElt : outputElts) {
SILValue value = outputElt.forward(SGF);
if (!outputAddr) outputEltValues.push_back(value);
}
// If we're emitting to an address, just manage that.
if (outputAddr)
return SGF.manageBufferForExprResult(outputAddr, outputTL, ctxt);
// Otherwise, assemble the tuple value and manage that.
auto outputTuple =
SGF.B.createTuple(Loc, outputTL.getLoweredType(), outputEltValues);
return SGF.emitManagedRValueWithCleanup(outputTuple, outputTL);
}
static ManagedValue manageParam(SILGenFunction &gen,
SILLocation loc,
SILValue paramValue,
SILParameterInfo info,
bool allowPlusZero) {
switch (info.getConvention()) {
// A deallocating parameter can always be accessed directly.
case ParameterConvention::Direct_Deallocating:
return ManagedValue::forUnmanaged(paramValue);
case ParameterConvention::Direct_Guaranteed:
if (allowPlusZero)
return ManagedValue::forUnmanaged(paramValue);
SWIFT_FALLTHROUGH;
// Unowned parameters are only guaranteed at the instant of the call, so we
// must retain them even if we're in a context that can accept a +0 value.
case ParameterConvention::Direct_Unowned:
gen.getTypeLowering(paramValue.getType())
.emitRetainValue(gen.B, loc, paramValue);
SWIFT_FALLTHROUGH;
case ParameterConvention::Direct_Owned:
return gen.emitManagedRValueWithCleanup(paramValue);
case ParameterConvention::Indirect_In_Guaranteed:
// FIXME: Avoid a behavior change while guaranteed self is disabled by
// default.
if (allowPlusZero) {
return ManagedValue::forUnmanaged(paramValue);
} else {
auto copy = gen.emitTemporaryAllocation(loc, paramValue.getType());
gen.B.createCopyAddr(loc, paramValue, copy, IsNotTake, IsInitialization);
return gen.emitManagedBufferWithCleanup(copy);
}
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
return ManagedValue::forLValue(paramValue);
case ParameterConvention::Indirect_In:
return gen.emitManagedBufferWithCleanup(paramValue);
case ParameterConvention::Indirect_Out:
llvm_unreachable("shouldn't be handled out-parameters here");
}
llvm_unreachable("bad parameter convention");
}
static void collectParams(SILGenFunction &gen,
SILLocation loc,
SmallVectorImpl<ManagedValue> ¶ms,
bool allowPlusZero) {
auto paramTypes =
gen.F.getLoweredFunctionType()->getParametersWithoutIndirectResult();
for (auto param : paramTypes) {
auto paramTy = gen.F.mapTypeIntoContext(param.getSILType());
auto paramValue = new (gen.SGM.M) SILArgument(gen.F.begin(),
paramTy);
params.push_back(manageParam(gen, loc, paramValue, param, allowPlusZero));
}
}
/// Force a ManagedValue to be stored into a temporary initialization
/// if it wasn't emitted that way directly.
static void emitForceInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue result, TemporaryInitialization &temp) {
if (result.isInContext()) return;
result.forwardInto(SGF, loc, temp.getAddress());
temp.finishInitialization(SGF);
}
namespace {
class TranslateArguments {
SILGenFunction &SGF;
SILLocation Loc;
ArrayRef<ManagedValue> Inputs;
SmallVectorImpl<ManagedValue> &Outputs;
ArrayRef<SILParameterInfo> OutputTypes;
public:
TranslateArguments(SILGenFunction &SGF, SILLocation loc,
ArrayRef<ManagedValue> inputs,
SmallVectorImpl<ManagedValue> &outputs,
ArrayRef<SILParameterInfo> outputTypes)
: SGF(SGF), Loc(loc), Inputs(inputs), Outputs(outputs),
OutputTypes(outputTypes) {}
void translate(AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType) {
// Most of this function is about tuples: tuples can be represented
// as one or many values, with varying levels of indirection.
auto inputTupleType = dyn_cast<TupleType>(inputSubstType);
auto outputTupleType = dyn_cast<TupleType>(outputSubstType);
// Look inside one-element exploded tuples, but not if both input
// and output types are *both* one-element tuples.
if (!(inputTupleType && outputTupleType &&
inputTupleType.getElementTypes().size() == 1 &&
outputTupleType.getElementTypes().size() == 1)) {
if (inputOrigType.isTuple() &&
inputOrigType.getNumTupleElements() == 1) {
inputOrigType = inputOrigType.getTupleElementType(0);
inputSubstType = cast<TupleType>(inputSubstType).getElementType(0);
return translate(inputOrigType, inputSubstType,
outputOrigType, outputSubstType);
}
if (outputOrigType.isTuple() &&
outputOrigType.getNumTupleElements() == 1) {
outputOrigType = outputOrigType.getTupleElementType(0);
outputSubstType = cast<TupleType>(outputSubstType).getElementType(0);
return translate(inputOrigType, inputSubstType,
outputOrigType, outputSubstType);
}
}
// Special-case: tuples containing inouts.
if (inputTupleType && inputTupleType->hasInOut()) {
// Non-materializable tuple types cannot be bound as generic
// arguments, so none of the remaining transformations apply.
// Instead, the outermost tuple layer is exploded, even when
// they are being passed opaquely. See the comment in
// AbstractionPattern.h for a discussion.
return translateParallelExploded(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType);
}
// Case where the input type is an exploded tuple.
if (inputOrigType.isTuple()) {
if (outputOrigType.isTuple()) {
// Both input and output are exploded tuples, easy case.
return translateParallelExploded(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType);
}
// Tuple types are subtypes of their optionals
OptionalTypeKind outputOTK;
if (auto outputObjectType = outputSubstType.getAnyOptionalObjectType(outputOTK)) {
// The input is exploded and the output is an optional tuple.
// Translate values and collect them into a single optional
// payload.
auto outputTupleType = cast<TupleType>(outputObjectType);
return translateAndImplodeIntoOptional(inputOrigType,
inputTupleType,
outputTupleType,
outputOTK);
// FIXME: optional of Any (ugh...)
}
if (outputTupleType) {
// The input is exploded and the output is not. Translate values
// and store them to a result tuple in memory.
assert(outputOrigType.isOpaque() &&
"Output is not a tuple and is not opaque?");
auto output = claimNextOutputType();
auto &outputTL = SGF.getTypeLowering(output.getSILType());
auto temp = SGF.emitTemporary(Loc, outputTL);
translateAndImplodeInto(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType,
*temp.get());
Outputs.push_back(temp->getManagedAddress());
return;
}
// FIXME: Tuple-to-Any conversions
llvm_unreachable("Unhandled conversion from exploded tuple");
}
// Handle output being an exploded tuple when the input is opaque.
if (outputOrigType.isTuple()) {
if (inputTupleType) {
// The input is exploded and the output is not. Translate values
// and store them to a result tuple in memory.
assert(inputOrigType.isOpaque() &&
"Input is not a tuple and is not opaque?");
return translateAndExplodeOutOf(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType,
claimNextInput());
}
// FIXME: IUO<Tuple> to Tuple
llvm_unreachable("Unhandled conversion to exploded tuple");
}
// Okay, we are now working with a single value turning into a
// single value.
auto inputElt = claimNextInput();
auto outputEltType = claimNextOutputType();
translateSingle(inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
inputElt, outputEltType);
}
private:
/// Handle a tuple that has been exploded in the input but wrapped in
/// an optional in the output.
void translateAndImplodeIntoOptional(AbstractionPattern inputOrigType,
CanTupleType inputTupleType,
CanTupleType outputTupleType,
OptionalTypeKind OTK) {
assert(!inputTupleType->hasInOut() &&
!outputTupleType->hasInOut());
assert(inputTupleType->getNumElements() ==
outputTupleType->getNumElements());
// Collect the tuple elements, which should all be maximally abstracted
// to go in the optional payload.
auto opaque = AbstractionPattern::getOpaque();
auto &loweredTL = SGF.getTypeLowering(opaque, outputTupleType);
auto loweredTy = loweredTL.getLoweredType();
auto optionalTy = claimNextOutputType().getSILType();
auto someDecl = SGF.getASTContext().getOptionalSomeDecl(OTK);
if (loweredTL.isLoadable()) {
// Implode into a maximally-abstracted value.
std::function<ManagedValue (CanTupleType, CanTupleType, CanTupleType)>
translateAndImplodeIntoValue
= [&](CanTupleType lowered, CanTupleType input, CanTupleType output) -> ManagedValue {
SmallVector<ManagedValue, 4> elements;
assert(output->getNumElements() == input->getNumElements());
for (unsigned i = 0, e = output->getNumElements(); i < e; ++i) {
auto inputTy = input.getElementType(i);
auto outputTy = output.getElementType(i);
ManagedValue arg;
if (auto outputTuple = dyn_cast<TupleType>(outputTy)) {
auto inputTuple = cast<TupleType>(inputTy);
arg = translateAndImplodeIntoValue(
cast<TupleType>(lowered.getElementType(i)),
inputTuple, outputTuple);
} else {
arg = claimNextInput();
}
if (arg.getType().isAddress())
arg = SGF.emitLoad(Loc, arg.forward(SGF),
SGF.getTypeLowering(arg.getType()),
SGFContext(), IsTake);
if (arg.getType().getSwiftRValueType() != lowered.getElementType(i))
arg = translatePrimitive(AbstractionPattern(inputTy), inputTy,
opaque, outputTy,
arg);
elements.push_back(arg);
}
SmallVector<SILValue, 4> forwarded;
for (auto element : elements)
forwarded.push_back(element.forward(SGF));
auto tuple = SGF.B.createTuple(Loc,
SILType::getPrimitiveObjectType(lowered),
forwarded);
return SGF.emitManagedRValueWithCleanup(tuple);
};
auto payload = translateAndImplodeIntoValue(
cast<TupleType>(loweredTy.getSwiftRValueType()),
inputTupleType,
outputTupleType);
optionalTy = SGF.F.mapTypeIntoContext(optionalTy);
auto optional = SGF.B.createEnum(Loc, payload.getValue(),
someDecl, optionalTy);
Outputs.push_back(ManagedValue(optional, payload.getCleanup()));
return;
} else {
// Implode into a maximally-abstracted indirect buffer.
auto optionalBuf = SGF.emitTemporaryAllocation(Loc, optionalTy);
auto tupleBuf = SGF.B.createInitEnumDataAddr(Loc, optionalBuf, someDecl,
loweredTy);
auto tupleTemp = SGF.useBufferAsTemporary(Loc, tupleBuf, loweredTL);
std::function<void (CanTupleType,
CanTupleType,
CanTupleType,
TemporaryInitialization&)>
translateAndImplodeIntoBuffer
= [&](CanTupleType lowered,
CanTupleType input,
CanTupleType output,
TemporaryInitialization &buf) {
auto tupleAddr = buf.getAddress();
SmallVector<CleanupHandle, 4> cleanups;
for (unsigned i = 0, e = output->getNumElements(); i < e; ++i) {
auto inputTy = input.getElementType(i);
auto outputTy = output.getElementType(i);
auto loweredOutputTy
= SILType::getPrimitiveAddressType(lowered.getElementType(i));
auto &loweredOutputTL = SGF.getTypeLowering(loweredOutputTy);
auto eltAddr = SGF.B.createTupleElementAddr(Loc, tupleAddr, i,
loweredOutputTy);
CleanupHandle eltCleanup
= SGF.enterDormantTemporaryCleanup(eltAddr, loweredOutputTL);
if (eltCleanup.isValid()) cleanups.push_back(eltCleanup);
TemporaryInitialization eltInit(eltAddr, eltCleanup);
if (auto outputTuple = dyn_cast<TupleType>(outputTy)) {
auto inputTuple = cast<TupleType>(inputTy);
translateAndImplodeIntoBuffer(
cast<TupleType>(loweredOutputTy.getSwiftRValueType()),
inputTuple, outputTuple, eltInit);
} else {
auto arg = claimNextInput();
auto &argTL = SGF.getTypeLowering(arg.getType());
if (arg.getType().isAddress() && argTL.isLoadable())
arg = SGF.emitLoad(Loc, arg.forward(SGF),
argTL, SGFContext(), IsTake);
if (arg.getType().getSwiftRValueType()
!= loweredOutputTy.getSwiftRValueType()) {
arg = translatePrimitive(AbstractionPattern(inputTy), inputTy,
opaque, outputTy,
arg);
}
emitForceInto(SGF, Loc, arg, eltInit);
}
}
// Deactivate the element cleanups and activate the tuple cleanup.
for (auto cleanup : cleanups)
SGF.Cleanups.forwardCleanup(cleanup);
buf.finishInitialization(SGF);
};
translateAndImplodeIntoBuffer(
cast<TupleType>(loweredTy.getSwiftRValueType()),
inputTupleType,
outputTupleType,
*tupleTemp.get());
SGF.B.createInjectEnumAddr(Loc, optionalBuf, someDecl);
auto payload = tupleTemp->getManagedAddress();
Outputs.push_back(ManagedValue(optionalBuf, payload.getCleanup()));
}
}
/// Handle a tuple that has been exploded in both the input and
/// the output.
void translateParallelExploded(AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType) {
assert(inputOrigType.matchesTuple(inputSubstType));
assert(outputOrigType.matchesTuple(outputSubstType));
// Non-materializable input and materializable output occurs
// when witness method thunks re-abstract a non-mutating
// witness for a mutating requirement. The inout self is just
// loaded to produce a value in this case.
assert(inputSubstType->hasInOut() ||
!outputSubstType->hasInOut());
assert(inputSubstType->getNumElements() ==
outputSubstType->getNumElements());
for (auto index : indices(outputSubstType.getElementTypes())) {
translate(inputOrigType.getTupleElementType(index),
inputSubstType.getElementType(index),
outputOrigType.getTupleElementType(index),
outputSubstType.getElementType(index));
}
}
/// Given that a tuple value is being passed indirectly in the
/// input, explode it and translate the elements.
void translateAndExplodeOutOf(AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
ManagedValue inputTupleAddr) {
assert(inputOrigType.isOpaque());
assert(outputOrigType.matchesTuple(outputSubstType));
assert(!inputSubstType->hasInOut() &&
!outputSubstType->hasInOut());
assert(inputSubstType->getNumElements() ==
outputSubstType->getNumElements());
SmallVector<ManagedValueAndType, 4> inputEltAddrs;
explodeTuple(SGF, Loc, inputTupleAddr, inputEltAddrs);
assert(inputEltAddrs.size() == outputSubstType->getNumElements());
for (auto index : indices(outputSubstType.getElementTypes())) {