forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILFunctionType.cpp
3052 lines (2632 loc) · 115 KB
/
SILFunctionType.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
//===--- SILFunctionType.cpp - Giving SIL types to AST functions ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the native Swift ownership transfer conventions
// and works in concert with the importer to give the correct
// conventions to imported functions and types.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/ForeignInfo.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace swift::Lowering;
SILType SILFunctionType::getDirectFormalResultsType() {
CanType type;
if (getNumDirectFormalResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumDirectFormalResults() == 1) {
type = getSingleDirectFormalResult().getType();
} else {
auto &cache = getMutableFormalResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
if (!result.isFormalIndirect())
elts.push_back(result.getType());
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getAllResultsType() {
CanType type;
if (getNumResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumResults() == 1) {
type = getResults()[0].getType();
} else {
auto &cache = getMutableAllResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
elts.push_back(result.getType());
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getFormalCSemanticResult() {
assert(getLanguage() == SILFunctionLanguage::C);
assert(getNumResults() <= 1);
return getDirectFormalResultsType();
}
CanType SILFunctionType::getSelfInstanceType() const {
auto selfTy = getSelfParameter().getType();
// If this is a static method, get the instance type.
if (auto metaTy = dyn_cast<AnyMetatypeType>(selfTy))
return metaTy.getInstanceType();
return selfTy;
}
ProtocolDecl *
SILFunctionType::getDefaultWitnessMethodProtocol() const {
assert(getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod);
auto selfTy = getSelfInstanceType();
if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) {
assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0);
auto superclass = GenericSig->getSuperclassBound(paramTy);
if (superclass)
return nullptr;
auto protos = GenericSig->getConformsTo(paramTy);
assert(protos.size() == 1);
return protos[0];
}
return nullptr;
}
ClassDecl *
SILFunctionType::getWitnessMethodClass(ModuleDecl &M) const {
auto selfTy = getSelfInstanceType();
auto genericSig = getGenericSignature();
if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) {
assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0);
auto superclass = genericSig->getSuperclassBound(paramTy);
if (superclass)
return superclass->getClassOrBoundGenericClass();
}
return nullptr;
}
static CanType getKnownType(Optional<CanType> &cacheSlot, ASTContext &C,
StringRef moduleName, StringRef typeName) {
if (!cacheSlot) {
cacheSlot = ([&] {
ModuleDecl *mod = C.getLoadedModule(C.getIdentifier(moduleName));
if (!mod)
return CanType();
// Do a general qualified lookup instead of a direct lookupValue because
// some of the types we want are reexported through overlays and
// lookupValue would only give us types actually declared in the overlays
// themselves.
SmallVector<ValueDecl *, 2> decls;
mod->lookupQualified(mod, C.getIdentifier(typeName),
NL_QualifiedDefault | NL_KnownNonCascadingDependency,
decls);
if (decls.size() != 1)
return CanType();
const auto *typeDecl = dyn_cast<TypeDecl>(decls.front());
if (!typeDecl)
return CanType();
assert(typeDecl->hasInterfaceType() &&
"bridged type must be type-checked");
return typeDecl->getDeclaredInterfaceType()->getCanonicalType();
})();
}
CanType t = *cacheSlot;
// It is possible that we won't find a bridging type (e.g. String) when we're
// parsing the stdlib itself.
if (t) {
LLVM_DEBUG(llvm::dbgs() << "Bridging type " << moduleName << '.' << typeName
<< " mapped to ";
if (t)
t->print(llvm::dbgs());
else
llvm::dbgs() << "<null>";
llvm::dbgs() << '\n');
}
return t;
}
#define BRIDGING_KNOWN_TYPE(BridgedModule,BridgedType) \
CanType TypeConverter::get##BridgedType##Type() { \
return getKnownType(BridgedType##Ty, M.getASTContext(), \
#BridgedModule, #BridgedType); \
}
#include "swift/SIL/BridgedTypes.def"
/// Adjust a function type to have a slightly different type.
CanAnyFunctionType
Lowering::adjustFunctionType(CanAnyFunctionType t,
AnyFunctionType::ExtInfo extInfo) {
if (t->getExtInfo() == extInfo)
return t;
return CanAnyFunctionType(t->withExtInfo(extInfo));
}
/// Adjust a function type to have a slightly different type.
CanSILFunctionType Lowering::adjustFunctionType(
CanSILFunctionType type, SILFunctionType::ExtInfo extInfo,
ParameterConvention callee,
Optional<ProtocolConformanceRef> witnessMethodConformance) {
if (type->getExtInfo() == extInfo && type->getCalleeConvention() == callee &&
type->getWitnessMethodConformanceOrNone() == witnessMethodConformance)
return type;
return SILFunctionType::get(type->getGenericSignature(),
extInfo, type->getCoroutineKind(), callee,
type->getParameters(), type->getYields(),
type->getResults(),
type->getOptionalErrorResult(),
type->getASTContext(),
witnessMethodConformance);
}
CanSILFunctionType
SILFunctionType::getWithRepresentation(Representation repr) {
return getWithExtInfo(getExtInfo().withRepresentation(repr));
}
CanSILFunctionType SILFunctionType::getWithExtInfo(ExtInfo newExt) {
auto oldExt = getExtInfo();
if (newExt == oldExt)
return CanSILFunctionType(this);
auto calleeConvention =
(newExt.hasContext()
? (oldExt.hasContext()
? getCalleeConvention()
: Lowering::DefaultThickCalleeConvention)
: ParameterConvention::Direct_Unowned);
return get(getGenericSignature(), newExt, getCoroutineKind(),
calleeConvention, getParameters(), getYields(),
getResults(), getOptionalErrorResult(), getASTContext(),
getWitnessMethodConformanceOrNone());
}
namespace {
enum class ConventionsKind : uint8_t {
Default = 0,
DefaultBlock = 1,
ObjCMethod = 2,
CFunctionType = 3,
CFunction = 4,
SelectorFamily = 5,
Deallocator = 6,
Capture = 7,
};
class Conventions {
ConventionsKind kind;
protected:
virtual ~Conventions() = default;
public:
Conventions(ConventionsKind k) : kind(k) {}
ConventionsKind getKind() const { return kind; }
virtual ParameterConvention
getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const = 0;
virtual ParameterConvention
getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const = 0;
virtual ParameterConvention getCallee() const = 0;
virtual ResultConvention getResult(const TypeLowering &resultTL) const = 0;
virtual ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const = 0;
virtual ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const = 0;
// Helpers that branch based on a value ownership.
ParameterConvention getIndirect(ValueOwnership ownership, bool forSelf,
unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const {
switch (ownership) {
case ValueOwnership::Default:
if (forSelf)
return getIndirectSelfParameter(type);
return getIndirectParameter(index, type, substTL);
case ValueOwnership::InOut:
return ParameterConvention::Indirect_Inout;
case ValueOwnership::Shared:
return ParameterConvention::Indirect_In_Guaranteed;
case ValueOwnership::Owned:
return ParameterConvention::Indirect_In;
}
}
ParameterConvention getDirect(ValueOwnership ownership, bool forSelf,
unsigned index, const AbstractionPattern &type,
const TypeLowering &substTL) const {
switch (ownership) {
case ValueOwnership::Default:
if (forSelf)
return getDirectSelfParameter(type);
return getDirectParameter(index, type, substTL);
case ValueOwnership::InOut:
return ParameterConvention::Indirect_Inout;
case ValueOwnership::Shared:
return ParameterConvention::Direct_Guaranteed;
case ValueOwnership::Owned:
return ParameterConvention::Direct_Owned;
}
}
};
/// A visitor for breaking down formal result types into a SILResultInfo
/// and possibly some number of indirect-out SILParameterInfos,
/// matching the abstraction patterns of the original type.
class DestructureResults {
SILModule &M;
const Conventions &Convs;
SmallVectorImpl<SILResultInfo> &Results;
public:
DestructureResults(SILModule &M, const Conventions &conventions,
SmallVectorImpl<SILResultInfo> &results)
: M(M), Convs(conventions), Results(results) {}
void destructure(AbstractionPattern origType, CanType substType) {
// Recurse into tuples.
if (origType.isTuple()) {
auto substTupleType = cast<TupleType>(substType);
for (auto eltIndex : indices(substTupleType.getElementTypes())) {
AbstractionPattern origEltType =
origType.getTupleElementType(eltIndex);
CanType substEltType = substTupleType.getElementType(eltIndex);
destructure(origEltType, substEltType);
}
return;
}
auto &substResultTL = M.Types.getTypeLowering(origType, substType);
// Determine the result convention.
ResultConvention convention;
if (isFormallyReturnedIndirectly(origType, substType, substResultTL)) {
convention = ResultConvention::Indirect;
} else {
convention = Convs.getResult(substResultTL);
// Reduce conventions for trivial types to an unowned convention.
if (substResultTL.isTrivial()) {
switch (convention) {
case ResultConvention::Indirect:
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
// Leave these as-is.
break;
case ResultConvention::Autoreleased:
case ResultConvention::Owned:
// These aren't distinguishable from unowned for trivial types.
convention = ResultConvention::Unowned;
break;
}
}
}
SILResultInfo result(substResultTL.getLoweredType().getASTType(),
convention);
Results.push_back(result);
}
/// Query whether the original type is returned indirectly for the purpose
/// of reabstraction given complete lowering information about its
/// substitution.
bool isFormallyReturnedIndirectly(AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
// If the substituted type is returned indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter()
&& !origType.isConcreteType()
&& !origType.requiresClass())
|| substTL.isAddressOnly()) {
return true;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
// FIXME: Get expansion from SILDeclRef
return SILType::isFormallyReturnedIndirectly(
origType.getType(), M, origType.getGenericSignature(),
ResilienceExpansion::Minimal);
}
}
};
static bool isClangTypeMoreIndirectThanSubstType(SILModule &M,
const clang::Type *clangTy,
CanType substTy) {
// A const pointer argument might have been imported as
// UnsafePointer, COpaquePointer, or a CF foreign class.
// (An ObjC class type wouldn't be const-qualified.)
if (clangTy->isPointerType()
&& clangTy->getPointeeType().isConstQualified()) {
// Peek through optionals.
if (auto substObjTy = substTy.getOptionalObjectType())
substTy = substObjTy;
// Void pointers aren't usefully indirectable.
if (clangTy->isVoidPointerType())
return false;
if (auto eltTy = substTy->getAnyPointerElementType())
return isClangTypeMoreIndirectThanSubstType(M,
clangTy->getPointeeType().getTypePtr(), CanType(eltTy));
if (substTy->getAnyNominal() ==
M.getASTContext().getOpaquePointerDecl())
// TODO: We could conceivably have an indirect opaque ** imported
// as COpaquePointer. That shouldn't ever happen today, though,
// since we only ever indirect the 'self' parameter of functions
// imported as methods.
return false;
if (clangTy->getPointeeType()->getAs<clang::RecordType>()) {
// CF type as foreign class
if (substTy->getClassOrBoundGenericClass() &&
substTy->getClassOrBoundGenericClass()->getForeignClassKind() ==
ClassDecl::ForeignKind::CFType) {
return false;
}
}
// swift_newtypes are always passed directly
if (auto typedefTy = clangTy->getAs<clang::TypedefType>()) {
if (typedefTy->getDecl()->getAttr<clang::SwiftNewtypeAttr>())
return false;
}
return true;
}
return false;
}
static bool isFormallyPassedIndirectly(SILModule &M,
AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
// If the C type of the argument is a const pointer, but the Swift type
// isn't, treat it as indirect.
if (origType.isClangType()
&& isClangTypeMoreIndirectThanSubstType(M, origType.getClangType(),
substType)) {
return true;
}
// If the substituted type is passed indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter() && !origType.isConcreteType()
&& !origType.requiresClass())
|| substTL.isAddressOnly()) {
return true;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
// FIXME: Get expansion from SILDeclRef
return SILType::isFormallyPassedIndirectly(
origType.getType(), M, origType.getGenericSignature(),
ResilienceExpansion::Minimal);
}
}
/// A visitor for turning formal input types into SILParameterInfos,
/// matching the abstraction patterns of the original type.
///
/// If the original abstraction pattern is fully opaque, we must
/// pass the function's inputs as if the original type were the most
/// general function signature (expressed entirely in type
/// variables) which can be substituted to equal the given
/// signature.
///
/// The goal of the most general type is to be (1) unambiguous to
/// compute from the substituted type and (2) the same for every
/// possible generalization of that type. For example, suppose we
/// have a Vector<(Int,Int)->Bool>. Obviously, we would prefer to
/// store optimal function pointers directly in this array; and if
/// all uses of it are ungeneralized, we'd get away with that. But
/// suppose the vector is passed to a function like this:
/// func satisfiesAll<T>(v : Vector<(T,T)->Bool>, x : T, y : T) -> Bool
/// That function will expect to be able to pull values out with the
/// proper abstraction. The only type we can possibly expect to agree
/// upon is the most general form.
///
/// The precise way this works is that Vector's subscript operation
/// (assuming that's how it's being accessed) has this signature:
/// <X> Vector<X> -> Int -> X
/// which 'satisfiesAll' is calling with this substitution:
/// X := (T, T) -> Bool
/// Since 'satisfiesAll' has a function type substituting for an
/// unrestricted archetype, it expects the value returned to have the
/// most general possible form 'A -> B', which it will need to
/// de-generalize (by thunking) if it needs to pass it around as
/// a '(T, T) -> Bool' value.
///
/// It is only this sort of direct substitution in types that forces
/// the most general possible type to be selected; declarations will
/// generally provide a target generalization level. For example,
/// in a Vector<IntPredicate>, where IntPredicate is a struct (not a
/// tuple) with one field of type (Int, Int) -> Bool, all the
/// function pointers will be stored ungeneralized. Of course, such
/// a vector couldn't be passed to 'satisfiesAll'.
///
/// For most types, the most general type is simply a fresh,
/// unrestricted type variable. But unmaterializable types are not
/// valid results of substitutions, so this does not apply. The
/// most general form of an unmaterializable type preserves the
/// basic structure of the unmaterializable components, replacing
/// any materializable components with fresh type variables.
///
/// That is, if we have a substituted function type:
/// (UnicodeScalar, (Int, Float), Double) -> Bool
/// then its most general form is
/// A -> B
///
/// because there is a valid substitution
/// A := (UnicodeScalar, (Int, Float), Double)
/// B := Bool
///
/// But if we have a substituted function type:
/// (UnicodeScalar, (Int, Float), inout Double) -> Bool
/// then its most general form is
/// (A, B, inout C) -> D
/// because the substitution
/// X := (UnicodeScalar, (Int, Float), inout Double)
/// is invalid substitution, ultimately because 'inout Double'
/// is not materializable.
class DestructureInputs {
SILModule &M;
const Conventions &Convs;
const ForeignInfo &Foreign;
Optional<llvm::function_ref<void()>> HandleForeignSelf;
SmallVectorImpl<SILParameterInfo> &Inputs;
unsigned NextOrigParamIndex = 0;
public:
DestructureInputs(SILModule &M, const Conventions &conventions,
const ForeignInfo &foreign,
SmallVectorImpl<SILParameterInfo> &inputs)
: M(M), Convs(conventions), Foreign(foreign), Inputs(inputs) {}
void destructure(AbstractionPattern origType,
CanAnyFunctionType::CanParamArrayRef params,
AnyFunctionType::ExtInfo extInfo) {
visitTopLevelParams(origType, params, extInfo);
}
private:
/// Query whether the original type is address-only given complete
/// lowering information about its substitution.
bool isFormallyPassedIndirectly(AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
return ::isFormallyPassedIndirectly(M, origType, substType, substTL);
}
/// This is a special entry point that allows destructure inputs to handle
/// self correctly.
void visitTopLevelParams(AbstractionPattern origType,
CanAnyFunctionType::CanParamArrayRef params,
AnyFunctionType::ExtInfo extInfo) {
unsigned numEltTypes = params.size();
unsigned numNonSelfParams = numEltTypes - 1;
auto silRepresentation = extInfo.getSILRepresentation();
// We have to declare this out here so that the lambda scope lasts for
// the duration of the loop below.
auto handleForeignSelf = [&] {
// This is a "self", but it's not a Swift self, we handle it differently.
visit(ValueOwnership::Default,
/*forSelf=*/false, origType.getTupleElementType(numNonSelfParams),
params[numNonSelfParams].getType(), silRepresentation);
};
// If we have a foreign-self, install handleSelf as the handler.
if (Foreign.Self.isInstance()) {
assert(numEltTypes > 0);
// This is safe because function_ref just stores a pointer to the
// existing lambda object.
HandleForeignSelf = handleForeignSelf;
}
// Add any leading foreign parameters.
maybeAddForeignParameters();
// If we have no parameters, even 'self' parameters, bail unless we need
// to substitute.
if (params.empty()) {
if (origType.isTypeParameter())
visit(ValueOwnership::Default, /*forSelf=*/false, origType,
M.getASTContext().TheEmptyTupleType, silRepresentation);
return;
}
assert(numEltTypes > 0);
auto handleParameter = [&](AbstractionPattern pattern,
ParameterTypeFlags paramFlags, CanType ty) {
CanTupleType tty = dyn_cast<TupleType>(ty);
// If the abstraction pattern is opaque, and the tuple type is
// a valid target for substitution, don't expand it.
if (!tty ||
(pattern.isTypeParameter() &&
!shouldExpandTupleType(tty))) {
visit(paramFlags.getValueOwnership(), /*forSelf=*/false, pattern, ty,
silRepresentation);
return;
}
for (auto i : indices(tty.getElementTypes())) {
auto patternEltTy = pattern.getTupleElementType(i);
auto trueEltTy = tty.getElementType(i);
auto flags = tty->getElement(i).getParameterFlags();
visit(flags.getValueOwnership(), /*forSelf=*/false, patternEltTy,
trueEltTy, silRepresentation);
}
};
// If we don't have 'self', we don't need to do anything special.
if (!extInfo.hasSelfParam() && !Foreign.Self.isImportAsMember()) {
CanType ty = AnyFunctionType::composeInput(M.getASTContext(), params,
/*canonicalVararg*/true)
->getCanonicalType();
auto flags = (params.size() == 1) ? params.front().getParameterFlags()
: ParameterTypeFlags();
handleParameter(origType, flags, ty);
return;
}
// Okay, handle 'self'.
// Process all the non-self parameters.
for (unsigned i = 0; i != numNonSelfParams; ++i) {
CanType ty = params[i].getType();
AbstractionPattern eltPattern = origType.getTupleElementType(i);
auto flags = params[i].getParameterFlags();
handleParameter(eltPattern, flags, ty);
}
// Process the self parameter. Note that we implicitly drop self
// if this is a static foreign-self import.
if (!Foreign.Self.isImportAsMember()) {
visit(ValueOwnership::Default, /*forSelf=*/true,
origType.getTupleElementType(numNonSelfParams),
params[numNonSelfParams].getType(), silRepresentation);
}
// Clear the foreign-self handler for safety.
HandleForeignSelf.reset();
}
void visit(ValueOwnership ownership, bool forSelf,
AbstractionPattern origType, CanType substType,
SILFunctionTypeRepresentation rep) {
// Tuples get handled specially, in some cases:
CanTupleType substTupleTy = dyn_cast<TupleType>(substType);
if (substTupleTy && !origType.isTypeParameter()) {
assert(origType.getNumTupleElements() == substTupleTy->getNumElements());
switch (ownership) {
case ValueOwnership::Default:
case ValueOwnership::Owned:
// Expand the tuple.
for (auto i : indices(substTupleTy.getElementTypes())) {
visit(ownership, forSelf, origType.getTupleElementType(i),
substTupleTy.getElementType(i), rep);
}
return;
case ValueOwnership::Shared:
// Do not lower tuples @guaranteed. This can create conflicts with
// substitutions for witness thunks e.g. we take $*(T, T)
// @in_guaranteed and try to substitute it for $*T.
return visit(ValueOwnership::Default, forSelf, origType, substType,
rep);
case ValueOwnership::InOut:
// handled below
break;
}
}
unsigned origParamIndex = NextOrigParamIndex++;
bool isInout = false;
if (auto inoutType = dyn_cast<InOutType>(substType)) {
isInout = true;
substType = inoutType.getObjectType();
origType = origType.getWithoutSpecifierType();
}
auto &substTL = M.Types.getTypeLowering(origType, substType);
ParameterConvention convention;
if (isInout) {
convention = ParameterConvention::Indirect_Inout;
} else if (isFormallyPassedIndirectly(origType, substType, substTL)) {
if (forSelf && rep == SILFunctionTypeRepresentation::WitnessMethod)
convention = ParameterConvention::Indirect_In_Guaranteed;
else
convention = Convs.getIndirect(ownership, forSelf, origParamIndex,
origType, substTL);
assert(isIndirectFormalParameter(convention));
} else if (substTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = Convs.getDirect(ownership, forSelf, origParamIndex, origType,
substTL);
assert(!isIndirectFormalParameter(convention));
}
auto loweredType = substTL.getLoweredType().getASTType();
Inputs.push_back(SILParameterInfo(loweredType, convention));
maybeAddForeignParameters();
}
/// Given that we've just reached an argument index for the
/// first time, add any foreign parameters.
void maybeAddForeignParameters() {
while (maybeAddForeignErrorParameter() ||
maybeAddForeignSelfParameter()) {
// Continue to see, just in case there are more parameters to add.
}
}
bool maybeAddForeignErrorParameter() {
if (!Foreign.Error ||
NextOrigParamIndex != Foreign.Error->getErrorParameterIndex())
return false;
auto foreignErrorTy =
M.Types.getLoweredType(Foreign.Error->getErrorParameterType());
// Assume the error parameter doesn't have interesting lowering.
Inputs.push_back(SILParameterInfo(foreignErrorTy.getASTType(),
ParameterConvention::Direct_Unowned));
NextOrigParamIndex++;
return true;
}
bool maybeAddForeignSelfParameter() {
if (!Foreign.Self.isInstance() ||
NextOrigParamIndex != Foreign.Self.getSelfIndex())
return false;
(*HandleForeignSelf)();
return true;
}
};
} // end anonymous namespace
static bool isPseudogeneric(SILDeclRef c) {
// FIXME: should this be integrated in with the Sema check that prevents
// illegal use of type arguments in pseudo-generic method bodies?
// The implicitly-generated native initializer thunks for imported
// initializers are never pseudo-generic, because they may need
// to use their type arguments to bridge their value arguments.
if (!c.isForeign &&
(c.kind == SILDeclRef::Kind::Allocator ||
c.kind == SILDeclRef::Kind::Initializer) &&
c.getDecl()->hasClangNode())
return false;
// Otherwise, we have to look at the entity's context.
DeclContext *dc;
if (c.hasDecl()) {
dc = c.getDecl()->getDeclContext();
} else if (auto closure = c.getAbstractClosureExpr()) {
dc = closure->getParent();
} else {
return false;
}
dc = dc->getInnermostTypeContext();
if (!dc) return false;
auto classDecl = dc->getSelfClassDecl();
return (classDecl && classDecl->usesObjCGenericsModel());
}
/// Update the result type given the foreign error convention that we will be
/// using.
static std::pair<AbstractionPattern, CanType> updateResultTypeForForeignError(
ForeignErrorConvention convention, CanGenericSignature genericSig,
AbstractionPattern origResultType, CanType substFormalResultType) {
switch (convention.getKind()) {
// These conventions replace the result type.
case ForeignErrorConvention::ZeroResult:
case ForeignErrorConvention::NonZeroResult:
assert(substFormalResultType->isVoid());
substFormalResultType = convention.getResultType();
origResultType = AbstractionPattern(genericSig, substFormalResultType);
return {origResultType, substFormalResultType};
// These conventions wrap the result type in a level of optionality.
case ForeignErrorConvention::NilResult:
assert(!substFormalResultType->getOptionalObjectType());
substFormalResultType =
OptionalType::get(substFormalResultType)->getCanonicalType();
origResultType =
AbstractionPattern::getOptional(origResultType);
return {origResultType, substFormalResultType};
// These conventions don't require changes to the formal error type.
case ForeignErrorConvention::ZeroPreservedResult:
case ForeignErrorConvention::NonNilError:
return {origResultType, substFormalResultType};
}
}
/// Lower any/all capture context parameters.
///
/// *NOTE* Currently default arg generators can not capture anything.
/// If we ever add that ability, it will be a different capture list
/// from the function to which the argument is attached.
static void
lowerCaptureContextParameters(SILModule &M, AnyFunctionRef function,
CanGenericSignature genericSig,
SmallVectorImpl<SILParameterInfo> &inputs) {
// NB: The generic signature may be elided from the lowered function type
// if the function is in a fully-specialized context, but we still need to
// canonicalize references to the generic parameters that may appear in
// non-canonical types in that context. We need the original generic
// signature from the AST for that.
auto origGenericSig = function.getGenericSignature();
auto &Types = M.Types;
auto loweredCaptures = Types.getLoweredLocalCaptures(function);
for (auto capture : loweredCaptures.getCaptures()) {
if (capture.isDynamicSelfMetadata()) {
ParameterConvention convention = ParameterConvention::Direct_Unowned;
auto dynamicSelfInterfaceType =
loweredCaptures.getDynamicSelfType()->mapTypeOutOfContext();
auto selfMetatype = MetatypeType::get(dynamicSelfInterfaceType,
MetatypeRepresentation::Thick);
auto canSelfMetatype = selfMetatype->getCanonicalType(origGenericSig);
SILParameterInfo param(canSelfMetatype, convention);
inputs.push_back(param);
continue;
}
auto *VD = capture.getDecl();
auto type = VD->getInterfaceType();
auto canType = type->getCanonicalType(origGenericSig);
auto &loweredTL =
Types.getTypeLowering(AbstractionPattern(genericSig, canType), canType);
auto loweredTy = loweredTL.getLoweredType();
switch (Types.getDeclCaptureKind(capture)) {
case CaptureKind::None:
break;
case CaptureKind::Constant: {
// Constants are captured by value.
ParameterConvention convention;
if (loweredTL.isAddressOnly()) {
convention = ParameterConvention::Indirect_In_Guaranteed;
} else if (loweredTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = ParameterConvention::Direct_Guaranteed;
}
SILParameterInfo param(loweredTy.getASTType(), convention);
inputs.push_back(param);
break;
}
case CaptureKind::Box: {
// Lvalues are captured as a box that owns the captured value.
auto boxTy = Types.getInterfaceBoxTypeForCapture(
VD, loweredTy.getASTType(),
/*mutable*/ true);
auto convention = ParameterConvention::Direct_Guaranteed;
auto param = SILParameterInfo(boxTy, convention);
inputs.push_back(param);
break;
}
case CaptureKind::StorageAddress: {
// Non-escaping lvalues are captured as the address of the value.
SILType ty = loweredTy.getAddressType();
auto param =
SILParameterInfo(ty.getASTType(),
ParameterConvention::Indirect_InoutAliasable);
inputs.push_back(param);
break;
}
}
}
}
static void destructureYieldsForReadAccessor(SILModule &M,
AbstractionPattern origType,
CanType valueType,
SmallVectorImpl<SILYieldInfo> &yields) {
// Recursively destructure tuples.
if (origType.isTuple()) {
auto valueTupleType = cast<TupleType>(valueType);
for (auto i : indices(valueTupleType.getElementTypes())) {
auto origEltType = origType.getTupleElementType(i);
auto valueEltType = valueTupleType.getElementType(i);
destructureYieldsForReadAccessor(M, origEltType, valueEltType, yields);
}
return;
}
auto &tl = M.Types.getTypeLowering(origType, valueType);
auto convention = [&] {
if (isFormallyPassedIndirectly(M, origType, valueType, tl))
return ParameterConvention::Indirect_In_Guaranteed;
if (tl.isTrivial())
return ParameterConvention::Direct_Unowned;
return ParameterConvention::Direct_Guaranteed;
}();
yields.push_back(SILYieldInfo(tl.getLoweredType().getASTType(),
convention));
}
static void destructureYieldsForCoroutine(SILModule &M,
Optional<SILDeclRef> origConstant,
Optional<SILDeclRef> constant,
Optional<SubstitutionMap> reqtSubs,
SmallVectorImpl<SILYieldInfo> &yields,
SILCoroutineKind &coroutineKind) {
assert(coroutineKind == SILCoroutineKind::None);
assert(yields.empty());
if (!constant || !constant->hasDecl())
return;
auto accessor = dyn_cast<AccessorDecl>(constant->getDecl());
if (!accessor || !accessor->isCoroutine())
return;
auto origAccessor = cast<AccessorDecl>(origConstant->getDecl());
// Coroutine accessors are implicitly yield-once coroutines, despite
// their function type.
coroutineKind = SILCoroutineKind::YieldOnce;
// Coroutine accessors are always native, so fetch the native
// abstraction pattern.
auto origStorage = origAccessor->getStorage();
auto origType = M.Types.getAbstractionPattern(origStorage, /*nonobjc*/ true)
.getReferenceStorageReferentType();
auto storage = accessor->getStorage();
auto valueType = storage->getValueInterfaceType()
->getReferenceStorageReferent();
if (reqtSubs) {
valueType = valueType.subst(*reqtSubs);
}
// 'modify' yields an inout of the target type.
if (accessor->getAccessorKind() == AccessorKind::Modify) {
auto loweredValueTy = M.Types.getLoweredType(origType, valueType);
yields.push_back(SILYieldInfo(loweredValueTy.getASTType(),
ParameterConvention::Indirect_Inout));
return;
}
// 'read' yields a borrowed value of the target type, destructuring
// tuples as necessary.
assert(accessor->getAccessorKind() == AccessorKind::Read);
destructureYieldsForReadAccessor(M, origType, valueType->getCanonicalType(),
yields);
}
/// Create the appropriate SIL function type for the given formal type
/// and conventions.
///
/// The lowering of function types is generally sensitive to the
/// declared abstraction pattern. We want to be able to take
/// advantage of declared type information in order to, say, pass
/// arguments separately and directly; but we also want to be able to
/// call functions from generic code without completely embarrassing
/// performance. Therefore, different abstraction patterns induce
/// different argument-passing conventions, and we must introduce
/// implicit reabstracting conversions where necessary to map one
/// convention to another.
///
/// However, we actually can't reabstract arbitrary thin function
/// values while still leaving them thin, at least without costly
/// page-mapping tricks. Therefore, the representation must remain