forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILFunctionType.cpp
5186 lines (4547 loc) · 208 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/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/ForeignInfo.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LocalArchetypeRequirementCollector.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/AbstractionPatternGenerators.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.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::substInterfaceType(SILModule &M,
SILType interfaceType,
TypeExpansionContext context) const {
// Apply pattern substitutions first, then invocation substitutions.
if (auto subs = getPatternSubstitutions())
interfaceType = interfaceType.subst(M, subs, context);
if (auto subs = getInvocationSubstitutions())
interfaceType = interfaceType.subst(M, subs, context);
return interfaceType;
}
CanSILFunctionType SILFunctionType::getUnsubstitutedType(SILModule &M) const {
auto mutableThis = const_cast<SILFunctionType*>(this);
// If we have no substitutions, there's nothing to do.
if (!hasPatternSubstitutions() && !hasInvocationSubstitutions())
return CanSILFunctionType(mutableThis);
// Otherwise, substitute the component types.
SmallVector<SILParameterInfo, 4> params;
SmallVector<SILYieldInfo, 4> yields;
SmallVector<SILResultInfo, 4> results;
std::optional<SILResultInfo> errorResult;
auto subs = getCombinedSubstitutions();
auto substComponentType = [&](CanType type) {
if (!type->hasTypeParameter()) return type;
return SILType::getPrimitiveObjectType(type)
.subst(M, subs).getASTType();
};
for (auto param : getParameters()) {
params.push_back(param.map(substComponentType));
}
for (auto yield : getYields()) {
yields.push_back(yield.map(substComponentType));
}
for (auto result : getResults()) {
results.push_back(result.map(substComponentType));
}
if (auto error = getOptionalErrorResult()) {
errorResult = error->map(substComponentType);
}
auto signature = isPolymorphic() ? getInvocationGenericSignature()
: CanGenericSignature();
return SILFunctionType::get(signature,
getExtInfo(),
getCoroutineKind(),
getCalleeConvention(),
params, yields, results, errorResult,
SubstitutionMap(),
SubstitutionMap(),
mutableThis->getASTContext(),
getWitnessMethodConformanceOrInvalid());
}
CanType SILParameterInfo::getArgumentType(SILFunction *fn) const {
return getArgumentType(fn->getModule(), fn->getLoweredFunctionType(),
fn->getTypeExpansionContext());
}
CanType SILParameterInfo::getArgumentType(SILModule &M,
const SILFunctionType *t,
TypeExpansionContext context) const {
// TODO: We should always require a function type.
if (t)
return t
->substInterfaceType(
M, SILType::getPrimitiveAddressType(getInterfaceType()), context)
.getASTType();
return getInterfaceType();
}
CanType SILResultInfo::getReturnValueType(SILModule &M,
const SILFunctionType *t,
TypeExpansionContext context) const {
// TODO: We should always require a function type.
if (t)
return t
->substInterfaceType(
M, SILType::getPrimitiveAddressType(getInterfaceType()), context)
.getASTType();
return getInterfaceType();
}
SILType
SILFunctionType::getDirectFormalResultsType(SILModule &M,
TypeExpansionContext context) {
CanType type;
if (getNumDirectFormalResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumDirectFormalResults() == 1) {
type = getSingleDirectFormalResult().getReturnValueType(M, this, context);
} else {
auto &cache = getMutableFormalResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
if (!result.isFormalIndirect())
elts.push_back(result.getReturnValueType(M, this, context));
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getAllResultsInterfaceType() {
CanType type;
if (getNumResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumResults() == 1) {
type = getResults()[0].getInterfaceType();
} else {
auto &cache = getMutableAllResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
elts.push_back(result.getInterfaceType());
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getAllResultsSubstType(SILModule &M,
TypeExpansionContext context) {
return substInterfaceType(M, getAllResultsInterfaceType(), context);
}
SILType SILFunctionType::getFormalCSemanticResult(SILModule &M) {
assert(getLanguage() == SILFunctionLanguage::C);
assert(getNumResults() <= 1);
return getDirectFormalResultsType(M, TypeExpansionContext::minimal());
}
CanType
SILFunctionType::getSelfInstanceType(SILModule &M,
TypeExpansionContext context) const {
auto selfTy = getSelfParameter().getArgumentType(M, this, context);
// If this is a static method, get the instance type.
if (auto metaTy = dyn_cast<AnyMetatypeType>(selfTy))
return metaTy.getInstanceType();
return selfTy;
}
ClassDecl *
SILFunctionType::getWitnessMethodClass(SILModule &M,
TypeExpansionContext context) const {
// TODO: When witnesses use substituted types, we'd get this from the
// substitution map.
auto selfTy = getSelfInstanceType(M, context);
auto genericSig = getSubstGenericSignature();
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;
}
IndexSubset *
SILFunctionType::getDifferentiabilityParameterIndices() {
assert(isDifferentiable() && "Must be a differentiable function");
SmallVector<unsigned, 8> paramIndices;
for (auto paramAndIndex : enumerate(getParameters()))
if (!paramAndIndex.value().hasOption(SILParameterInfo::NotDifferentiable))
paramIndices.push_back(paramAndIndex.index());
return IndexSubset::get(getASTContext(), getNumParameters(), paramIndices);
}
IndexSubset *SILFunctionType::getDifferentiabilityResultIndices() {
assert(isDifferentiable() && "Must be a differentiable function");
SmallVector<unsigned, 8> resultIndices;
// Check formal results.
for (auto resultAndIndex : enumerate(getResults()))
if (!resultAndIndex.value().hasOption(SILResultInfo::NotDifferentiable))
resultIndices.push_back(resultAndIndex.index());
auto numSemanticResults = getNumResults();
// Check semantic results (`inout`) parameters.
for (auto resultParamAndIndex : enumerate(getAutoDiffSemanticResultsParameters()))
// Currently, an `inout` parameter can either be:
// 1. Both a differentiability parameter and a differentiability result.
// 2. `@noDerivative`: neither a differentiability parameter nor a
// differentiability result.
// However, there is no way to represent an `inout` parameter that:
// 3. Is a differentiability result but not a differentiability parameter.
// 4. Is a differentiability parameter but not a differentiability result.
// This case is not currently expressible and does not yet have clear use
// cases, so supporting it is a non-goal.
//
// See TF-1305 for solution ideas. For now, `@noDerivative` `inout`
// parameters are not treated as differentiability results.
if (!resultParamAndIndex.value().hasOption(
SILParameterInfo::NotDifferentiable))
resultIndices.push_back(getNumResults() + resultParamAndIndex.index());
numSemanticResults += getNumAutoDiffSemanticResultsParameters();
// Check yields.
for (auto yieldAndIndex : enumerate(getYields()))
if (!yieldAndIndex.value().hasOption(
SILParameterInfo::NotDifferentiable))
resultIndices.push_back(numSemanticResults + yieldAndIndex.index());
numSemanticResults += getNumYields();
return IndexSubset::get(getASTContext(), numSemanticResults, resultIndices);
}
CanSILFunctionType SILFunctionType::getDifferentiableComponentType(
NormalDifferentiableFunctionTypeComponent component, SILModule &module) {
assert(getDifferentiabilityKind() == DifferentiabilityKind::Reverse &&
"Must be a `@differentiable(reverse)` function");
auto originalFnTy = getWithoutDifferentiability();
if (auto derivativeKind = component.getAsDerivativeFunctionKind()) {
return originalFnTy->getAutoDiffDerivativeFunctionType(
getDifferentiabilityParameterIndices(),
getDifferentiabilityResultIndices(), *derivativeKind, module.Types,
LookUpConformanceInModule());
}
return originalFnTy;
}
CanSILFunctionType SILFunctionType::getLinearComponentType(
LinearDifferentiableFunctionTypeComponent component, SILModule &module) {
assert(getDifferentiabilityKind() == DifferentiabilityKind::Linear &&
"Must be a `@differentiable(linear)` function");
auto originalFnTy = getWithoutDifferentiability();
switch (component) {
case LinearDifferentiableFunctionTypeComponent::Original:
return originalFnTy;
case LinearDifferentiableFunctionTypeComponent::Transpose:
return originalFnTy->getAutoDiffTransposeFunctionType(
getDifferentiabilityParameterIndices(), module.Types,
LookUpConformanceInModule());
}
}
CanSILFunctionType
SILFunctionType::getWithDifferentiability(DifferentiabilityKind kind,
IndexSubset *parameterIndices,
IndexSubset *resultIndices) {
assert(kind != DifferentiabilityKind::NonDifferentiable &&
"Differentiability kind must be normal or linear");
SmallVector<SILParameterInfo, 8> newParameters;
for (auto paramAndIndex : enumerate(getParameters())) {
auto param = paramAndIndex.value();
unsigned index = paramAndIndex.index();
newParameters.push_back(index < parameterIndices->getCapacity() &&
parameterIndices->contains(index)
? param - SILParameterInfo::NotDifferentiable
: param | SILParameterInfo::NotDifferentiable);
}
SmallVector<SILResultInfo, 8> newResults;
for (auto resultAndIndex : enumerate(getResults())) {
auto result = resultAndIndex.value();
unsigned index = resultAndIndex.index();
newResults.push_back(index < resultIndices->getCapacity() &&
resultIndices->contains(index)
? result - SILResultInfo::NotDifferentiable
: result | SILResultInfo::NotDifferentiable);
}
auto newExtInfo =
getExtInfo().intoBuilder().withDifferentiabilityKind(kind).build();
return get(getInvocationGenericSignature(), newExtInfo, getCoroutineKind(),
getCalleeConvention(), newParameters, getYields(), newResults,
getOptionalErrorResult(), getPatternSubstitutions(),
getInvocationSubstitutions(), getASTContext(),
getWitnessMethodConformanceOrInvalid());
}
CanSILFunctionType SILFunctionType::getWithoutDifferentiability() {
if (!isDifferentiable())
return CanSILFunctionType(this);
auto nondiffExtInfo =
getExtInfo()
.intoBuilder()
.withDifferentiabilityKind(DifferentiabilityKind::NonDifferentiable)
.build();
SmallVector<SILParameterInfo, 8> newParams;
for (SILParameterInfo param : getParameters())
newParams.push_back(param - SILParameterInfo::NotDifferentiable);
SmallVector<SILResultInfo, 8> newResults;
for (SILResultInfo result : getResults())
newResults.push_back(result - SILResultInfo::NotDifferentiable);
return SILFunctionType::get(
getInvocationGenericSignature(), nondiffExtInfo, getCoroutineKind(),
getCalleeConvention(), newParams, getYields(), newResults,
getOptionalErrorResult(), getPatternSubstitutions(),
getInvocationSubstitutions(), getASTContext());
}
/// Collects the differentiability parameters of the given original function
/// type in `diffParams`.
static void
getDifferentiabilityParameters(SILFunctionType *originalFnTy,
IndexSubset *parameterIndices,
SmallVectorImpl<SILParameterInfo> &diffParams) {
// Returns true if `index` is a differentiability parameter index.
auto isDiffParamIndex = [&](unsigned index) -> bool {
return index < parameterIndices->getCapacity() &&
parameterIndices->contains(index);
};
// Calculate differentiability parameter infos.
for (auto valueAndIndex : enumerate(originalFnTy->getParameters()))
if (isDiffParamIndex(valueAndIndex.index()))
diffParams.push_back(valueAndIndex.value());
}
static CanGenericSignature buildDifferentiableGenericSignature(CanGenericSignature sig,
CanType tanType,
CanType origTypeOfAbstraction) {
if (!sig)
return sig;
llvm::DenseSet<CanType> types;
auto &ctx = tanType->getASTContext();
(void) tanType.findIf([&](Type t) -> bool {
if (auto *dmt = t->getAs<DependentMemberType>()) {
if (dmt->getName() == ctx.Id_TangentVector)
types.insert(dmt->getBase()->getCanonicalType());
}
return false;
});
SmallVector<Requirement, 2> reqs;
auto *proto = ctx.getProtocol(KnownProtocolKind::Differentiable);
assert(proto != nullptr);
for (auto type : types) {
if (!sig->requiresProtocol(type, proto)) {
reqs.push_back(Requirement(RequirementKind::Conformance, type,
proto->getDeclaredInterfaceType()));
}
}
if (origTypeOfAbstraction) {
(void) origTypeOfAbstraction.findIf([&](Type t) -> bool {
if (auto *at = t->getAs<ArchetypeType>()) {
auto interfaceTy = at->getInterfaceType();
auto genericParams = sig.getGenericParams();
// The GSB used to drop requirements which reference non-existent
// generic parameters, whereas the RequirementMachine asserts now.
// Filter these requirements out explicitly to preserve the old
// behavior.
if (std::find_if(genericParams.begin(), genericParams.end(),
[interfaceTy](CanGenericTypeParamType t) -> bool {
return t->isEqual(interfaceTy->getRootGenericParam());
}) != genericParams.end()) {
types.insert(interfaceTy->getCanonicalType());
for (auto *proto : at->getConformsTo()) {
reqs.push_back(Requirement(RequirementKind::Conformance,
interfaceTy,
proto->getDeclaredInterfaceType()));
}
// The GSB would add conformance requirements if a nested type
// requirement involving a resolved DependentMemberType was added;
// eg, if you start with <T> and add T.[P]A == Int, it would also
// add the conformance requirement T : P.
//
// This was not an intended behavior on the part of the GSB, and the
// logic here is a complete mess, so just simulate the old behavior
// here.
auto parentTy = interfaceTy;
while (parentTy) {
if (auto memberTy = parentTy->getAs<DependentMemberType>()) {
parentTy = memberTy->getBase();
if (auto *assocTy = memberTy->getAssocType()) {
reqs.push_back(Requirement(RequirementKind::Conformance,
parentTy,
assocTy->getProtocol()->getDeclaredInterfaceType()));
}
} else
parentTy = Type();
}
}
}
return false;
});
}
return buildGenericSignature(ctx, sig, {}, reqs, /*allowInverses=*/false)
.getCanonicalSignature();
}
/// Given an original type, computes its tangent type for the purpose of
/// building a linear map using this type. When the original type is an
/// archetype or contains a type parameter, appends a new generic parameter and
/// a corresponding replacement type to the given containers.
static CanType getAutoDiffTangentTypeForLinearMap(
Type originalType,
LookupConformanceFn lookupConformance,
SmallVectorImpl<GenericTypeParamType *> &substGenericParams,
SmallVectorImpl<Type> &substReplacements,
ASTContext &context
) {
auto maybeTanType = originalType->getAutoDiffTangentSpace(lookupConformance);
assert(maybeTanType && "Type does not have a tangent space?");
auto tanType = maybeTanType->getCanonicalType();
// If concrete, the tangent type is concrete.
if (!tanType->hasArchetype() && !tanType->hasTypeParameter())
return tanType;
// Otherwise, the tangent type is a new generic parameter substituted for the
// tangent type.
auto gpIndex = substGenericParams.size();
auto gpType = CanGenericTypeParamType::getType(0, gpIndex, context);
substGenericParams.push_back(gpType);
substReplacements.push_back(tanType);
return gpType;
}
/// Returns the differential type for the given original function type,
/// parameter indices, and result index.
static CanSILFunctionType getAutoDiffDifferentialType(
SILFunctionType *originalFnTy, IndexSubset *parameterIndices,
IndexSubset *resultIndices, LookupConformanceFn lookupConformance,
CanType origTypeOfAbstraction,
TypeConverter &TC) {
// Given the tangent type and the corresponding original parameter's
// convention, returns the tangent parameter's convention.
auto getTangentParameterConvention =
[&](CanType tanType,
ParameterConvention origParamConv) -> ParameterConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
// When the tangent type is address only, we must ensure that the tangent
// parameter's convention is indirect.
if (tl.isAddressOnly() && !isIndirectFormalParameter(origParamConv)) {
switch (origParamConv) {
case ParameterConvention::Direct_Guaranteed:
return ParameterConvention::Indirect_In_Guaranteed;
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned:
return ParameterConvention::Indirect_In;
default:
llvm_unreachable("unhandled parameter convention");
}
}
return origParamConv;
};
// Given the tangent type and the corresponding original result's convention,
// returns the tangent result's convention.
auto getTangentResultConvention =
[&](CanType tanType,
ResultConvention origResConv) -> ResultConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
// When the tangent type is address only, we must ensure that the tangent
// result's convention is indirect.
if (tl.isAddressOnly() && !isIndirectFormalResult(origResConv)) {
switch (origResConv) {
case ResultConvention::Unowned:
case ResultConvention::Owned:
return ResultConvention::Indirect;
default:
llvm_unreachable("unhandled result convention");
}
}
return origResConv;
};
auto &ctx = originalFnTy->getASTContext();
SmallVector<GenericTypeParamType *, 4> substGenericParams;
SmallVector<Requirement, 4> substRequirements;
SmallVector<Type, 4> substReplacements;
SmallVector<ProtocolConformanceRef, 4> substConformances;
SmallVector<SILResultInfo, 2> originalResults;
autodiff::getSemanticResults(originalFnTy, parameterIndices, originalResults);
SmallVector<SILParameterInfo, 4> diffParams;
getDifferentiabilityParameters(originalFnTy, parameterIndices, diffParams);
SmallVector<SILParameterInfo, 8> differentialParams;
for (auto ¶m : diffParams) {
auto paramTanType = getAutoDiffTangentTypeForLinearMap(
param.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto paramConv = getTangentParameterConvention(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
param.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
param.getConvention());
differentialParams.push_back({paramTanType, paramConv});
}
SmallVector<SILResultInfo, 1> differentialResults;
unsigned firstSemanticParamResultIdx = originalFnTy->getNumResults();
unsigned firstYieldResultIndex = originalFnTy->getNumResults() +
originalFnTy->getNumAutoDiffSemanticResultsParameters();
for (auto resultIndex : resultIndices->getIndices()) {
// Handle formal original result.
if (resultIndex < firstSemanticParamResultIdx) {
auto &result = originalResults[resultIndex];
auto resultTanType = getAutoDiffTangentTypeForLinearMap(
result.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto resultConv = getTangentResultConvention(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
result.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
result.getConvention());
differentialResults.push_back({resultTanType, resultConv});
continue;
} else if (resultIndex < firstYieldResultIndex) {
// Handle original semantic result parameters.
auto resultParamIndex = resultIndex - originalFnTy->getNumResults();
auto resultParamIt = std::next(
originalFnTy->getAutoDiffSemanticResultsParameters().begin(),
resultParamIndex);
auto paramIndex =
std::distance(originalFnTy->getParameters().begin(), &*resultParamIt);
// If the original semantic result parameter is a differentiability
// parameter, then it already has a corresponding differential
// parameter. Skip adding a corresponding differential result.
if (parameterIndices->contains(paramIndex))
continue;
auto resultParam = originalFnTy->getParameters()[paramIndex];
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
resultParam.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
differentialResults.emplace_back(resultParamTanType,
ResultConvention::Indirect);
} else {
assert(originalFnTy->isCoroutine());
assert(originalFnTy->getCoroutineKind() == SILCoroutineKind::YieldOnce);
auto yieldResultIndex = resultIndex - firstYieldResultIndex;
auto yieldResult = originalFnTy->getYields()[yieldResultIndex];
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
yieldResult.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
ParameterConvention paramTanConvention = yieldResult.getConvention();
assert(yieldResult.getConvention() == ParameterConvention::Indirect_Inout);
differentialParams.emplace_back(resultParamTanType, paramTanConvention);
}
}
SubstitutionMap substitutions;
if (!substGenericParams.empty()) {
auto genericSig =
GenericSignature::get(substGenericParams, substRequirements)
.getCanonicalSignature();
substitutions =
SubstitutionMap::get(genericSig, llvm::ArrayRef(substReplacements),
llvm::ArrayRef(substConformances));
}
return SILFunctionType::get(
GenericSignature(), SILFunctionType::ExtInfo(), SILCoroutineKind::None,
ParameterConvention::Direct_Guaranteed, differentialParams, {},
differentialResults, std::nullopt, substitutions,
/*invocationSubstitutions*/ SubstitutionMap(), ctx);
}
/// Returns the pullback type for the given original function type, parameter
/// indices, and result index.
static CanSILFunctionType getAutoDiffPullbackType(
SILFunctionType *originalFnTy, IndexSubset *parameterIndices,
IndexSubset *resultIndices, LookupConformanceFn lookupConformance,
CanType origTypeOfAbstraction, TypeConverter &TC) {
auto &ctx = originalFnTy->getASTContext();
SmallVector<GenericTypeParamType *, 4> substGenericParams;
SmallVector<Requirement, 4> substRequirements;
SmallVector<Type, 4> substReplacements;
SmallVector<ProtocolConformanceRef, 4> substConformances;
SmallVector<SILResultInfo, 2> originalResults;
autodiff::getSemanticResults(originalFnTy, parameterIndices, originalResults);
// Given a type, returns its formal SIL parameter info.
auto getTangentParameterConventionForOriginalResult =
[&](CanType tanType,
ResultConvention origResConv) -> ParameterConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
ParameterConvention conv;
switch (origResConv) {
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
case ResultConvention::Owned:
case ResultConvention::Autoreleased:
if (tl.isAddressOnly()) {
conv = ParameterConvention::Indirect_In_Guaranteed;
} else {
conv = tl.isTrivial() ? ParameterConvention::Direct_Unowned
: ParameterConvention::Direct_Guaranteed;
}
break;
case ResultConvention::Pack:
conv = ParameterConvention::Pack_Guaranteed;
break;
case ResultConvention::Indirect:
conv = ParameterConvention::Indirect_In_Guaranteed;
break;
}
return conv;
};
// Given a type, returns its formal SIL result info.
auto getTangentResultConventionForOriginalParameter =
[&](CanType tanType,
ParameterConvention origParamConv) -> ResultConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
ResultConvention conv;
switch (origParamConv) {
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Direct_Unowned:
if (tl.isAddressOnly()) {
conv = ResultConvention::Indirect;
} else {
conv = tl.isTrivial() ? ResultConvention::Unowned
: ResultConvention::Owned;
}
break;
case ParameterConvention::Pack_Owned:
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Pack_Inout:
conv = ResultConvention::Pack;
break;
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_In_CXX:
conv = ResultConvention::Indirect;
break;
}
return conv;
};
// Collect pullback parameters & yields
SmallVector<SILParameterInfo, 1> pullbackParams;
SmallVector<SILYieldInfo, 1> pullbackYields;
unsigned firstSemanticParamResultIdx = originalFnTy->getNumResults();
unsigned firstYieldResultIndex = originalFnTy->getNumResults() +
originalFnTy->getNumAutoDiffSemanticResultsParameters();
for (auto resultIndex : resultIndices->getIndices()) {
// Handle formal original result.
if (resultIndex < firstSemanticParamResultIdx) {
auto &origRes = originalResults[resultIndex];
auto resultTanType = getAutoDiffTangentTypeForLinearMap(
origRes.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto paramConv = getTangentParameterConventionForOriginalResult(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
origRes.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
origRes.getConvention());
pullbackParams.emplace_back(resultTanType, paramConv);
} else if (resultIndex < firstYieldResultIndex) {
// Handle original semantic result parameters.
auto resultParamIndex = resultIndex - firstSemanticParamResultIdx;
auto resultParamIt = std::next(
originalFnTy->getAutoDiffSemanticResultsParameters().begin(),
resultParamIndex);
auto paramIndex =
std::distance(originalFnTy->getParameters().begin(), &*resultParamIt);
auto resultParam = originalFnTy->getParameters()[paramIndex];
// The pullback parameter convention depends on whether the original `inout`
// parameter is a differentiability parameter.
// - If yes, the pullback parameter convention is `@inout`.
// - If no, the pullback parameter convention is `@in_guaranteed`.
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
resultParam.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
ParameterConvention paramTanConvention = resultParam.getConvention();
if (!parameterIndices->contains(paramIndex))
paramTanConvention = ParameterConvention::Indirect_In_Guaranteed;
pullbackParams.emplace_back(resultParamTanType, paramTanConvention);
} else {
assert(originalFnTy->isCoroutine());
assert(originalFnTy->getCoroutineKind() == SILCoroutineKind::YieldOnce);
auto yieldResultIndex = resultIndex - firstYieldResultIndex;
auto yieldResult = originalFnTy->getYields()[yieldResultIndex];
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
yieldResult.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
ParameterConvention paramTanConvention = yieldResult.getConvention();
assert(yieldResult.getConvention() == ParameterConvention::Indirect_Inout);
pullbackYields.emplace_back(resultParamTanType, paramTanConvention);
}
}
// Collect pullback results.
SmallVector<SILParameterInfo, 4> diffParams;
getDifferentiabilityParameters(originalFnTy, parameterIndices, diffParams);
SmallVector<SILResultInfo, 8> pullbackResults;
for (auto ¶m : diffParams) {
// Skip semantic result parameters, which semantically behave as original
// results and always appear as pullback parameters.
if (param.isAutoDiffSemanticResult())
continue;
auto paramTanType = getAutoDiffTangentTypeForLinearMap(
param.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto resultTanConvention = getTangentResultConventionForOriginalParameter(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
param.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
param.getConvention());
pullbackResults.push_back({paramTanType, resultTanConvention});
}
SubstitutionMap substitutions;
if (!substGenericParams.empty()) {
auto genericSig =
GenericSignature::get(substGenericParams, substRequirements)
.getCanonicalSignature();
substitutions =
SubstitutionMap::get(genericSig, llvm::ArrayRef(substReplacements),
llvm::ArrayRef(substConformances));
}
return SILFunctionType::get(
GenericSignature(), SILFunctionType::ExtInfo(), originalFnTy->getCoroutineKind(),
ParameterConvention::Direct_Guaranteed,
pullbackParams, pullbackYields, pullbackResults, std::nullopt, substitutions,
/*invocationSubstitutions*/ SubstitutionMap(), ctx);
}
/// Constrains the `original` function type according to differentiability
/// requirements:
/// - All differentiability parameters are constrained to conform to
/// `Differentiable`.
/// - The invocation generic signature is replaced by the
/// `constrainedInvocationGenSig` argument.
static SILFunctionType *getConstrainedAutoDiffOriginalFunctionType(
SILFunctionType *original, IndexSubset *parameterIndices, IndexSubset *resultIndices,
LookupConformanceFn lookupConformance,
CanGenericSignature constrainedInvocationGenSig) {
auto originalInvocationGenSig = original->getInvocationGenericSignature();
if (!originalInvocationGenSig) {
assert(!constrainedInvocationGenSig ||
constrainedInvocationGenSig->areAllParamsConcrete() &&
"derivative function cannot have invocation generic signature "
"when original function doesn't");
if (auto patternSig = original->getPatternGenericSignature()) {
auto constrainedPatternSig =
autodiff::getConstrainedDerivativeGenericSignature(
original, parameterIndices, resultIndices,
patternSig, lookupConformance).getCanonicalSignature();
auto constrainedPatternSubs =
SubstitutionMap::get(constrainedPatternSig,
QuerySubstitutionMap{original->getPatternSubstitutions()},
lookupConformance);
return SILFunctionType::get(GenericSignature(),
original->getExtInfo(), original->getCoroutineKind(),
original->getCalleeConvention(),
original->getParameters(), original->getYields(),
original->getResults(), original->getOptionalErrorResult(),
constrainedPatternSubs,
/*invocationSubstitutions*/ SubstitutionMap(), original->getASTContext(),
original->getWitnessMethodConformanceOrInvalid());
}
return original;
}
assert(!original->getPatternSubstitutions() &&
"cannot constrain substituted function type");
if (!constrainedInvocationGenSig)
constrainedInvocationGenSig = originalInvocationGenSig;
if (!constrainedInvocationGenSig)
return original;
constrainedInvocationGenSig =
autodiff::getConstrainedDerivativeGenericSignature(
original, parameterIndices, resultIndices,
constrainedInvocationGenSig,
lookupConformance).getCanonicalSignature();
SmallVector<SILParameterInfo, 4> newParameters;
newParameters.reserve(original->getNumParameters());
for (auto ¶m : original->getParameters()) {
newParameters.push_back(
param.getWithInterfaceType(param.getInterfaceType()->getReducedType(
constrainedInvocationGenSig)));
}
SmallVector<SILResultInfo, 4> newResults;
newResults.reserve(original->getNumResults());
for (auto &result : original->getResults()) {
newResults.push_back(
result.getWithInterfaceType(result.getInterfaceType()->getReducedType(
constrainedInvocationGenSig)));
}
return SILFunctionType::get(
constrainedInvocationGenSig->areAllParamsConcrete()
? GenericSignature()
: constrainedInvocationGenSig,
original->getExtInfo(), original->getCoroutineKind(),
original->getCalleeConvention(), newParameters, original->getYields(),
newResults, original->getOptionalErrorResult(),
original->getPatternSubstitutions(),
/*invocationSubstitutions*/ SubstitutionMap(), original->getASTContext(),
original->getWitnessMethodConformanceOrInvalid());
}
CanSILFunctionType SILFunctionType::getAutoDiffDerivativeFunctionType(
IndexSubset *parameterIndices, IndexSubset *resultIndices,
AutoDiffDerivativeFunctionKind kind, TypeConverter &TC,
LookupConformanceFn lookupConformance,
CanGenericSignature derivativeFnInvocationGenSig,
bool isReabstractionThunk,
CanType origTypeOfAbstraction) {
assert(parameterIndices);
assert(!parameterIndices->isEmpty() && "Parameter indices must not be empty");
assert(resultIndices);
assert(!resultIndices->isEmpty() && "Result indices must not be empty");
auto &ctx = getASTContext();
// Look up result in cache.
SILAutoDiffDerivativeFunctionKey key{this,
parameterIndices,
resultIndices,
kind,
derivativeFnInvocationGenSig,
isReabstractionThunk};
auto insertion =
ctx.SILAutoDiffDerivativeFunctions.try_emplace(key, CanSILFunctionType());
auto &cachedResult = insertion.first->getSecond();
if (!insertion.second)
return cachedResult;
SILFunctionType *constrainedOriginalFnTy =
getConstrainedAutoDiffOriginalFunctionType(this, parameterIndices, resultIndices,
lookupConformance,
derivativeFnInvocationGenSig);
// Compute closure type.
CanSILFunctionType closureType;
switch (kind) {
case AutoDiffDerivativeFunctionKind::JVP:
closureType =
getAutoDiffDifferentialType(constrainedOriginalFnTy, parameterIndices,
resultIndices, lookupConformance,
origTypeOfAbstraction, TC);
break;
case AutoDiffDerivativeFunctionKind::VJP:
closureType =
getAutoDiffPullbackType(constrainedOriginalFnTy, parameterIndices,
resultIndices, lookupConformance,
origTypeOfAbstraction, TC);
break;
}
// Compute the derivative function parameters.
SmallVector<SILParameterInfo, 4> newParameters;
newParameters.reserve(constrainedOriginalFnTy->getNumParameters());
for (auto ¶m : constrainedOriginalFnTy->getParameters()) {
newParameters.push_back(param);
}
// Reabstraction thunks have a function-typed parameter (the function to
// reabstract) as their last parameter. Reabstraction thunk JVPs/VJPs have a
// `@differentiable` function-typed last parameter instead.
if (isReabstractionThunk) {
assert(!parameterIndices->contains(getNumParameters() - 1) &&
"Function-typed parameter should not be wrt");
auto fnParam = newParameters.back();
auto fnParamType = dyn_cast<SILFunctionType>(fnParam.getInterfaceType());
assert(fnParamType);
auto diffFnType = fnParamType->getWithDifferentiability(
DifferentiabilityKind::Reverse, parameterIndices, resultIndices);
newParameters.back() = fnParam.getWithInterfaceType(diffFnType);
}
// Compute the derivative function results.
SmallVector<SILResultInfo, 4> newResults;
newResults.reserve(getNumResults() + 1);
for (auto &result : constrainedOriginalFnTy->getResults())
newResults.push_back(result);
newResults.emplace_back(closureType, ResultConvention::Owned);
// Compute the derivative function ExtInfo.
// If original function is `@convention(c)`, the derivative function should
// have `@convention(thin)`. IRGen does not support `@convention(c)` functions
// with multiple results.
auto extInfo = constrainedOriginalFnTy->getExtInfo();
if (getRepresentation() == SILFunctionTypeRepresentation::CFunctionPointer)
extInfo = extInfo.withRepresentation(SILFunctionTypeRepresentation::Thin);
// Put everything together to get the derivative function type. Then, store in
// cache and return.
cachedResult = SILFunctionType::get(
constrainedOriginalFnTy->getInvocationGenericSignature(), extInfo,
constrainedOriginalFnTy->getCoroutineKind(),
constrainedOriginalFnTy->getCalleeConvention(), newParameters,
constrainedOriginalFnTy->getYields(), newResults,
constrainedOriginalFnTy->getOptionalErrorResult(),
constrainedOriginalFnTy->getPatternSubstitutions(),
/*invocationSubstitutions*/ SubstitutionMap(),
constrainedOriginalFnTy->getASTContext(),
constrainedOriginalFnTy->getWitnessMethodConformanceOrInvalid());
return cachedResult;
}
CanSILFunctionType SILFunctionType::getAutoDiffTransposeFunctionType(
IndexSubset *parameterIndices, Lowering::TypeConverter &TC,
LookupConformanceFn lookupConformance,
CanGenericSignature transposeFnGenSig) {
auto &ctx = getASTContext();