-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathJVPCloner.cpp
1755 lines (1585 loc) · 74.3 KB
/
JVPCloner.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
//===--- JVPCloner.cpp - JVP function generation --------------*- C++ -*---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 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 a helper class for generating JVP functions for automatic
// differentiation.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "differentiation"
#include "swift/SILOptimizer/Differentiation/JVPCloner.h"
#include "swift/SILOptimizer/Analysis/DifferentiableActivityAnalysis.h"
#include "swift/SILOptimizer/Differentiation/ADContext.h"
#include "swift/SILOptimizer/Differentiation/AdjointValue.h"
#include "swift/SILOptimizer/Differentiation/DifferentiationInvoker.h"
#include "swift/SILOptimizer/Differentiation/LinearMapInfo.h"
#include "swift/SILOptimizer/Differentiation/PullbackCloner.h"
#include "swift/SILOptimizer/Differentiation/Thunk.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/LoopInfo.h"
#include "swift/SIL/TypeSubstCloner.h"
#include "swift/SILOptimizer/Analysis/LoopAnalysis.h"
#include "swift/SILOptimizer/PassManager/PrettyStackTrace.h"
#include "swift/SILOptimizer/Utils/DifferentiationMangler.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "llvm/ADT/DenseMap.h"
using namespace swift;
using namespace autodiff;
namespace swift {
namespace autodiff {
class JVPCloner::Implementation final
: public TypeSubstCloner<JVPCloner::Implementation, SILOptFunctionBuilder> {
private:
/// The global context.
ADContext &context;
/// The original function.
SILFunction *const original;
/// The witness.
SILDifferentiabilityWitness *const witness;
/// The JVP function.
SILFunction *const jvp;
llvm::BumpPtrAllocator allocator;
/// The differentiation invoker.
DifferentiationInvoker invoker;
/// Info from activity analysis on the original function.
const DifferentiableActivityInfo &activityInfo;
/// The loop info.
SILLoopInfo *loopInfo;
/// The differential info.
LinearMapInfo differentialInfo;
bool errorOccurred = false;
//--------------------------------------------------------------------------//
// Differential generation related fields
//--------------------------------------------------------------------------//
/// The builder for the differential function.
TangentBuilder differentialBuilder;
/// Mapping from original basic blocks to corresponding differential basic
/// blocks.
llvm::DenseMap<SILBasicBlock *, SILBasicBlock *> diffBBMap;
/// Mapping from original basic blocks and original values to corresponding
/// tangent values.
llvm::DenseMap<SILValue, AdjointValue> tangentValueMap;
/// Mapping from original basic blocks and original buffers to corresponding
/// tangent buffers.
llvm::DenseMap<std::pair<SILBasicBlock *, SILValue>, SILValue> bufferMap;
/// Mapping from differential basic blocks to differential struct arguments.
llvm::DenseMap<SILBasicBlock *, SILArgument *> differentialStructArguments;
/// Mapping from differential struct field declarations to differential struct
/// elements destructured from the linear map basic block argument. In the
/// beginning of each differential basic block, the block's differential
/// struct is destructured into the individual elements stored here.
llvm::DenseMap<SILBasicBlock *, SILInstructionResultArray> differentialTupleElements;
/// An auxiliary differential local allocation builder.
TangentBuilder diffLocalAllocBuilder;
/// Stack buffers allocated for storing local tangent values.
SmallVector<SILValue, 8> differentialLocalAllocations;
/// Mapping from original blocks to differential values. Used to build
/// differential struct instances.
llvm::DenseMap<SILBasicBlock *, SmallVector<SILValue, 8>> differentialValues;
//--------------------------------------------------------------------------//
// Getters
//--------------------------------------------------------------------------//
ASTContext &getASTContext() const { return jvp->getASTContext(); }
SILModule &getModule() const { return jvp->getModule(); }
const AutoDiffConfig getConfig() const { return witness->getConfig(); }
TangentBuilder &getDifferentialBuilder() { return differentialBuilder; }
SILFunction &getDifferential() { return differentialBuilder.getFunction(); }
SILArgument *getDifferentialStructArgument(SILBasicBlock *origBB) {
return differentialStructArguments[origBB];
}
//--------------------------------------------------------------------------//
// Differential tuple mapping
//--------------------------------------------------------------------------//
void initializeDifferentialTupleElements(SILBasicBlock *origBB,
SILInstructionResultArray values);
SILValue getDifferentialTupleElement(ApplyInst *ai);
//--------------------------------------------------------------------------//
// General utilities
//--------------------------------------------------------------------------//
/// Get the lowered SIL type of the given AST type.
SILType getLoweredType(Type type) {
auto jvpGenSig = jvp->getLoweredFunctionType()->getSubstGenericSignature();
Lowering::AbstractionPattern pattern(jvpGenSig,
type->getReducedType(jvpGenSig));
return jvp->getLoweredType(pattern, type);
}
/// Get the lowered SIL type of the given nominal type declaration.
SILType getNominalDeclLoweredType(NominalTypeDecl *nominal) {
auto nominalType =
getOpASTType(nominal->getDeclaredInterfaceType()->getCanonicalType());
return getLoweredType(nominalType);
}
/// Build a differential struct value for the original block corresponding to
/// the given terminator.
TupleInst *buildDifferentialValueStructValue(TermInst *termInst) {
assert(termInst->getFunction() == original);
auto loc = termInst->getFunction()->getLocation();
auto *origBB = termInst->getParent();
auto *jvpBB = BBMap[origBB];
assert(jvpBB && "Basic block mapping should exist");
auto tupleLoweredTy =
remapType(differentialInfo.getLinearMapTupleLoweredType(origBB));
auto bbDifferentialValues = differentialValues[origBB];
if (!origBB->isEntry()) {
auto *enumArg = jvpBB->getArguments().back();
bbDifferentialValues.insert(bbDifferentialValues.begin(), enumArg);
}
return getBuilder().createTuple(loc, tupleLoweredTy,
bbDifferentialValues);
}
//--------------------------------------------------------------------------//
// Tangent value factory methods
//--------------------------------------------------------------------------//
AdjointValue makeZeroTangentValue(SILType type) {
return AdjointValue::createZero(allocator,
remapSILTypeInDifferential(type));
}
AdjointValue makeConcreteTangentValue(SILValue value) {
return AdjointValue::createConcrete(allocator, value);
}
//--------------------------------------------------------------------------//
// Tangent materialization
//--------------------------------------------------------------------------//
void emitZeroIndirect(CanType type, SILValue buffer, SILLocation loc) {
auto builder = getDifferentialBuilder();
auto tangentSpace = getTangentSpace(type);
assert(tangentSpace && "No tangent space for this type");
switch (tangentSpace->getKind()) {
case TangentSpace::Kind::TangentVector:
builder.emitZeroIntoBuffer(loc, buffer, IsInitialization);
return;
case TangentSpace::Kind::Tuple: {
auto tupleType = tangentSpace->getTuple();
SmallVector<SILValue, 8> zeroElements;
for (unsigned i : range(tupleType->getNumElements())) {
auto eltAddr = builder.createTupleElementAddr(loc, buffer, i);
emitZeroIndirect(tupleType->getElementType(i)->getCanonicalType(),
eltAddr, loc);
}
return;
}
}
}
SILValue emitZeroDirect(CanType type, SILLocation loc) {
auto diffBuilder = getDifferentialBuilder();
auto silType = getModule().Types.getLoweredLoadableType(
type, TypeExpansionContext::minimal(), getModule());
auto *buffer = diffBuilder.createAllocStack(loc, silType);
emitZeroIndirect(type, buffer, loc);
auto loaded = diffBuilder.emitLoadValueOperation(
loc, buffer, LoadOwnershipQualifier::Take);
diffBuilder.createDeallocStack(loc, buffer);
return loaded;
}
SILValue materializeTangentDirect(AdjointValue val, SILLocation loc) {
assert(val.getType().isObject());
LLVM_DEBUG(getADDebugStream()
<< "Materializing tangents for " << val << '\n');
switch (val.getKind()) {
case AdjointValueKind::Zero: {
auto zeroVal = emitZeroDirect(val.getSwiftType(), loc);
return zeroVal;
}
case AdjointValueKind::Concrete:
return val.getConcreteValue();
case AdjointValueKind::Aggregate:
case AdjointValueKind::AddElement:
llvm_unreachable(
"Tuples and structs are not supported in forward mode yet.");
}
llvm_unreachable("Invalid adjoint value kind"); // silences MSVC C4715
}
SILValue materializeTangent(AdjointValue val, SILLocation loc) {
if (val.isConcrete()) {
LLVM_DEBUG(getADDebugStream()
<< "Materializing tangent: Value is concrete.\n");
return val.getConcreteValue();
}
LLVM_DEBUG(getADDebugStream() << "Materializing tangent: Value is "
"non-concrete. Materializing directly.\n");
return materializeTangentDirect(val, loc);
}
//--------------------------------------------------------------------------//
// Tangent value mapping
//--------------------------------------------------------------------------//
/// Get the tangent for an original value. The given value must be in the
/// original function.
///
/// This method first tries to find an entry in `tangentValueMap`. If an entry
/// doesn't exist, create a zero tangent.
AdjointValue getTangentValue(SILValue originalValue) {
assert(originalValue->getType().isObject());
assert(originalValue->getFunction() == original);
auto insertion = tangentValueMap.try_emplace(
originalValue,
makeZeroTangentValue(getRemappedTangentType(originalValue->getType())));
return insertion.first->getSecond();
}
/// Map the tangent value to the given original value.
void setTangentValue(SILBasicBlock *origBB, SILValue originalValue,
AdjointValue newTangentValue) {
#ifndef NDEBUG
if (auto *defInst = originalValue->getDefiningInstruction()) {
bool isTupleTypedApplyResult =
isa<ApplyInst>(defInst) && originalValue->getType().is<TupleType>();
assert(!isTupleTypedApplyResult &&
"Should not set tangent value for tuple-typed result from `apply` "
"instruction; use `destructure_tuple` on `apply` result and set "
"tangent value for `destructure_tuple` results instead.");
}
#endif
assert(originalValue->getType().isObject());
assert(newTangentValue.getType().isObject());
assert(originalValue->getFunction() == original);
LLVM_DEBUG(getADDebugStream()
<< "Setting tangent value for " << originalValue);
// The tangent value must be in the tangent space.
assert(newTangentValue.getType() ==
getRemappedTangentType(originalValue->getType()));
auto insertion =
tangentValueMap.try_emplace(originalValue, newTangentValue);
(void)insertion;
assert(insertion.second && "The tangent value should not already exist.");
}
//--------------------------------------------------------------------------//
// Tangent buffer mapping
//--------------------------------------------------------------------------//
/// Sets the tangent buffer for the original buffer. Asserts that the
/// original buffer does not already have a tangent buffer.
void setTangentBuffer(SILBasicBlock *origBB, SILValue originalBuffer,
SILValue tangentBuffer) {
assert(originalBuffer->getType().isAddress());
auto insertion =
bufferMap.try_emplace({origBB, originalBuffer}, tangentBuffer);
assert(insertion.second && "Tangent buffer already exists");
(void)insertion;
}
/// Returns the tangent buffer for the original buffer. Asserts that the
/// original buffer has a tangent buffer.
SILValue &getTangentBuffer(SILBasicBlock *origBB, SILValue originalBuffer) {
assert(originalBuffer->getType().isAddress());
assert(originalBuffer->getFunction() == original);
auto it = bufferMap.find({origBB, originalBuffer});
assert(it != bufferMap.end() && "Tangent buffer should already exist");
return it->getSecond();
}
//--------------------------------------------------------------------------//
// Differential type calculations
//--------------------------------------------------------------------------//
/// Substitutes all replacement types of the given substitution map using the
/// tangent function's substitution map.
SubstitutionMap remapSubstitutionMapInDifferential(SubstitutionMap substMap) {
return substMap.subst(getDifferential().getForwardingSubstitutionMap());
}
/// Remap any archetypes into the differential function's context.
Type remapTypeInDifferential(Type ty) {
if (ty->hasArchetype())
return getDifferential().mapTypeIntoContext(ty->mapTypeOutOfContext());
return getDifferential().mapTypeIntoContext(ty);
}
/// Remap any archetypes into the differential function's context.
SILType remapSILTypeInDifferential(SILType ty) {
if (ty.hasArchetype())
return getDifferential().mapTypeIntoContext(ty.mapTypeOutOfContext());
return getDifferential().mapTypeIntoContext(ty);
}
/// Find the tangent space of a given canonical type.
std::optional<TangentSpace> getTangentSpace(CanType type) {
// Use witness generic signature to remap types.
type = witness->getDerivativeGenericSignature().getReducedType(
type);
return type->getAutoDiffTangentSpace(
LookUpConformanceInModule());
}
/// Assuming the given type conforms to `Differentiable` after remapping,
/// returns the associated tangent space SIL type.
SILType getRemappedTangentType(SILType type) {
return SILType::getPrimitiveType(
getTangentSpace(remapSILTypeInDifferential(type).getASTType())
->getCanonicalType(),
type.getCategory());
}
/// Set up the differential function. This includes:
/// - Creating all differential blocks.
/// - Creating differential entry block arguments based on the function type.
/// - Creating tangent value mapping for original/differential parameters.
/// - Checking for unvaried result and emitting related warnings.
void prepareForDifferentialGeneration();
public:
explicit Implementation(ADContext &context,
SILDifferentiabilityWitness *witness,
SILFunction *jvp, DifferentiationInvoker invoker);
static SILFunction *
createEmptyDifferential(ADContext &context,
SILDifferentiabilityWitness *witness,
LinearMapInfo *linearMapInfo);
/// Run JVP generation. Returns true on error.
bool run();
SILFunction &getJVP() const { return *jvp; }
void postProcess(SILInstruction *orig, SILInstruction *cloned) {
if (errorOccurred)
return;
SILClonerWithScopes::postProcess(orig, cloned);
}
/// Remap original basic blocks.
SILBasicBlock *remapBasicBlock(SILBasicBlock *bb) {
auto *jvpBB = BBMap[bb];
return jvpBB;
}
/// General visitor for all instructions. If any error is emitted by previous
/// visits, bail out.
void visit(SILInstruction *inst) {
if (errorOccurred)
return;
if (differentialInfo.shouldDifferentiateInstruction(inst)) {
LLVM_DEBUG(getADDebugStream() << "JVPCloner visited:\n[ORIG]" << *inst);
#ifndef NDEBUG
auto diffBuilder = getDifferentialBuilder();
auto beforeInsertion = std::prev(diffBuilder.getInsertionPoint());
#endif
TypeSubstCloner::visit(inst);
LLVM_DEBUG({
auto &s = llvm::dbgs() << "[TAN] Emitted in differential:\n";
auto afterInsertion = diffBuilder.getInsertionPoint();
for (auto it = ++beforeInsertion; it != afterInsertion; ++it)
s << *it;
});
} else {
TypeSubstCloner::visit(inst);
}
}
void visitSILInstruction(SILInstruction *inst) {
context.emitNondifferentiabilityError(
inst, invoker, diag::autodiff_expression_not_differentiable_note);
errorOccurred = true;
}
void visitInstructionsInBlock(SILBasicBlock *bb) {
// Destructure the differential struct to get the elements.
auto &diffBuilder = getDifferentialBuilder();
auto diffLoc = getDifferential().getLocation();
auto *diffBB = diffBBMap.lookup(bb);
auto *mainDifferentialStruct = diffBB->getArguments().back();
diffBuilder.setInsertionPoint(diffBB);
auto *dsi =
diffBuilder.createDestructureTuple(diffLoc, mainDifferentialStruct);
initializeDifferentialTupleElements(bb, dsi->getResults());
TypeSubstCloner::visitInstructionsInBlock(bb);
}
// If an `apply` has active results or active inout parameters, replace it
// with an `apply` of its JVP.
void visitApplyInst(ApplyInst *ai) {
bool shouldDifferentiate =
differentialInfo.shouldDifferentiateApplySite(ai);
// If the function has no active arguments or results, zero-initialize the
// tangent buffers of the active indirect results.
if (!shouldDifferentiate) {
for (auto indResult : ai->getIndirectSILResults())
if (activityInfo.isActive(indResult, getConfig())) {
auto &tanBuf = getTangentBuffer(ai->getParent(), indResult);
emitZeroIndirect(tanBuf->getType().getASTType(), tanBuf,
tanBuf.getLoc());
}
}
// If the function should not be differentiated or its the array literal
// initialization intrinsic, just do standard cloning.
if (!shouldDifferentiate ||
ArraySemanticsCall(ai, semantics::ARRAY_UNINITIALIZED_INTRINSIC)) {
LLVM_DEBUG(getADDebugStream() << "No active results:\n" << *ai << '\n');
TypeSubstCloner::visitApplyInst(ai);
return;
}
auto loc = ai->getLoc();
auto &builder = getBuilder();
auto origCallee = getOpValue(ai->getCallee());
auto originalFnTy = origCallee->getType().castTo<SILFunctionType>();
LLVM_DEBUG(getADDebugStream() << "JVP-transforming:\n" << *ai << '\n');
// Get the minimal parameter and result indices required for differentiating
// this `apply`.
SmallVector<SILValue, 4> allResults;
SmallVector<unsigned, 8> activeParamIndices;
SmallVector<unsigned, 8> activeResultIndices;
collectMinimalIndicesForFunctionCall(ai, getConfig(), activityInfo,
allResults, activeParamIndices,
activeResultIndices);
assert(!activeParamIndices.empty() && "Parameter indices cannot be empty");
assert(!activeResultIndices.empty() && "Result indices cannot be empty");
LLVM_DEBUG(auto &s = getADDebugStream() << "Active indices: params={";
llvm::interleave(
activeParamIndices.begin(), activeParamIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << "}, results={"; llvm::interleave(
activeResultIndices.begin(), activeResultIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << "}\n";);
// Form expected indices.
auto numResults =
ai->getSubstCalleeType()->getNumResults() +
ai->getSubstCalleeType()->getNumIndirectMutatingParameters();
AutoDiffConfig config(
IndexSubset::get(getASTContext(),
ai->getArgumentsWithoutIndirectResults().size(),
activeParamIndices),
IndexSubset::get(getASTContext(), numResults, activeResultIndices));
// Emit the JVP.
SILValue jvpValue;
// If functionSource is a `@differentiable` function, just extract it.
if (originalFnTy->isDifferentiable()) {
auto paramIndices = originalFnTy->getDifferentiabilityParameterIndices();
for (auto i : config.parameterIndices->getIndices()) {
if (!paramIndices->contains(i)) {
context.emitNondifferentiabilityError(
origCallee, invoker,
diag::
autodiff_function_noderivative_parameter_not_differentiable);
errorOccurred = true;
return;
}
}
builder.emitScopedBorrowOperation(
loc, origCallee, [&](SILValue borrowedDiffFunc) {
jvpValue = builder.createDifferentiableFunctionExtract(
loc, NormalDifferentiableFunctionTypeComponent::JVP,
borrowedDiffFunc);
jvpValue = builder.emitCopyValueOperation(loc, jvpValue);
});
}
// If JVP has not yet been found, emit an `differentiable_function`
// instruction on the remapped function operand and
// an `differentiable_function_extract` instruction to get the JVP.
// The `differentiable_function` instruction will be canonicalized during
// the transform main loop.
if (!jvpValue) {
// FIXME: Handle indirect differentiation invokers. This may require some
// redesign: currently, each original function + witness pair is mapped
// only to one invoker.
/*
DifferentiationInvoker indirect(ai, attr);
auto insertion =
context.getInvokers().try_emplace({original, attr}, indirect);
auto &invoker = insertion.first->getSecond();
invoker = indirect;
*/
// If the original `apply` instruction has a substitution map, then the
// applied function is specialized.
// In the JVP, specialization is also necessary for parity. The original
// function operand is specialized with a remapped version of same
// substitution map using an argument-less `partial_apply`.
if (ai->getSubstitutionMap().empty()) {
origCallee = builder.emitCopyValueOperation(loc, origCallee);
} else {
auto substMap = getOpSubstitutionMap(ai->getSubstitutionMap());
auto jvpPartialApply = getBuilder().createPartialApply(
ai->getLoc(), origCallee, substMap, {},
ParameterConvention::Direct_Guaranteed);
origCallee = jvpPartialApply;
}
// Check and diagnose non-differentiable original function type.
auto diagnoseNondifferentiableOriginalFunctionType =
[&](CanSILFunctionType origFnTy) {
// Check and diagnose non-differentiable arguments.
for (auto paramIndex : config.parameterIndices->getIndices()) {
if (!originalFnTy->getParameters()[paramIndex]
.getSILStorageInterfaceType()
.isDifferentiable(getModule())) {
auto arg = ai->getArgumentsWithoutIndirectResults()[paramIndex];
auto startLoc = arg.getLoc().getStartSourceLoc();
auto endLoc = arg.getLoc().getEndSourceLoc();
context
.emitNondifferentiabilityError(
arg, invoker, diag::autodiff_nondifferentiable_argument)
.fixItInsert(startLoc, "withoutDerivative(at: ")
.fixItInsertAfter(endLoc, ")");
errorOccurred = true;
return true;
}
}
// Check and diagnose non-differentiable results.
for (auto resultIndex : config.resultIndices->getIndices()) {
SILType remappedResultType;
if (resultIndex >= originalFnTy->getNumResults()) {
auto inoutArgIdx = resultIndex - originalFnTy->getNumResults();
auto inoutArg =
*std::next(ai->getInoutArguments().begin(), inoutArgIdx);
remappedResultType = inoutArg->getType();
} else {
remappedResultType = originalFnTy->getResults()[resultIndex]
.getSILStorageInterfaceType();
}
if (!remappedResultType.isDifferentiable(getModule())) {
auto startLoc = ai->getLoc().getStartSourceLoc();
auto endLoc = ai->getLoc().getEndSourceLoc();
context
.emitNondifferentiabilityError(
origCallee, invoker,
diag::autodiff_nondifferentiable_result)
.fixItInsert(startLoc, "withoutDerivative(at: ")
.fixItInsertAfter(endLoc, ")");
errorOccurred = true;
return true;
}
}
return false;
};
if (diagnoseNondifferentiableOriginalFunctionType(originalFnTy))
return;
auto *diffFuncInst = context.createDifferentiableFunction(
builder, loc, config.parameterIndices, config.resultIndices,
origCallee);
// Record the `differentiable_function` instruction.
context.getDifferentiableFunctionInstWorklist().push_back(diffFuncInst);
builder.emitScopedBorrowOperation(
loc, diffFuncInst, [&](SILValue borrowedADFunc) {
auto extractedJVP = builder.createDifferentiableFunctionExtract(
loc, NormalDifferentiableFunctionTypeComponent::JVP,
borrowedADFunc);
jvpValue = builder.emitCopyValueOperation(loc, extractedJVP);
});
builder.emitDestroyValueOperation(loc, diffFuncInst);
}
// Call the JVP using the original parameters.
SmallVector<SILValue, 8> jvpArgs;
auto jvpFnTy = getOpType(jvpValue->getType()).castTo<SILFunctionType>();
auto numJVPArgs =
jvpFnTy->getNumParameters() + jvpFnTy->getNumIndirectFormalResults();
jvpArgs.reserve(numJVPArgs);
// Collect substituted arguments.
for (auto origArg : ai->getArguments())
jvpArgs.push_back(getOpValue(origArg));
assert(jvpArgs.size() == numJVPArgs);
// Apply the JVP.
// The JVP should be specialized, so no substitution map is necessary.
auto *jvpCall = getBuilder().createApply(loc, jvpValue, SubstitutionMap(),
jvpArgs, ai->getApplyOptions());
LLVM_DEBUG(getADDebugStream() << "Applied jvp function\n" << *jvpCall);
// Release the differentiable function.
builder.emitDestroyValueOperation(loc, jvpValue);
// Get the JVP results (original results and differential).
SmallVector<SILValue, 8> jvpDirectResults;
extractAllElements(jvpCall, builder, jvpDirectResults);
auto originalDirectResults =
ArrayRef<SILValue>(jvpDirectResults).drop_back(1);
auto originalDirectResult =
joinElements(originalDirectResults, getBuilder(), jvpCall->getLoc());
mapValue(ai, originalDirectResult);
// Some instructions that produce the callee may have been cloned.
// If the original callee did not have any users beyond this `apply`,
// recursively kill the cloned callee.
if (auto *origCallee = cast_or_null<SingleValueInstruction>(
ai->getCallee()->getDefiningInstruction()))
if (origCallee->hasOneUse())
recursivelyDeleteTriviallyDeadInstructions(
getOpValue(origCallee)->getDefiningInstruction());
// Add the differential function for when we create the struct we partially
// apply to the differential we are generating.
auto differential = jvpDirectResults.back();
auto differentialType = differentialInfo.lookUpLinearMapType(ai);
auto originalDifferentialType =
getOpType(differential->getType()).getAs<SILFunctionType>();
auto loweredDifferentialType =
getOpType(getLoweredType(differentialType)).castTo<SILFunctionType>();
// If actual differential type does not match lowered differential type,
// reabstract the differential using a thunk.
if (!loweredDifferentialType->isEqual(originalDifferentialType)) {
SILOptFunctionBuilder fb(context.getTransform());
differential = reabstractFunction(
builder, fb, loc, differential, loweredDifferentialType,
[this](SubstitutionMap subs) -> SubstitutionMap {
return this->getOpSubstitutionMap(subs);
});
}
differentialValues[ai->getParent()].push_back(differential);
// Differential emission.
emitTangentForApplyInst(ai, config, originalDifferentialType);
}
void visitReturnInst(ReturnInst *ri) {
auto loc = ri->getOperand().getLoc();
auto *origExit = ri->getParent();
auto &builder = getBuilder();
auto *diffStructVal = buildDifferentialValueStructValue(ri);
// Get the JVP value corresponding to the original functions's return value.
auto *origRetInst = cast<ReturnInst>(origExit->getTerminator());
auto origResult = getOpValue(origRetInst->getOperand());
SmallVector<SILValue, 8> origResults;
extractAllElements(origResult, builder, origResults);
// Get and partially apply the differential.
auto jvpSubstMap = jvp->getForwardingSubstitutionMap();
auto *differentialRef = builder.createFunctionRef(loc, &getDifferential());
auto *differentialPartialApply = builder.createPartialApply(
loc, differentialRef, jvpSubstMap, {diffStructVal},
ParameterConvention::Direct_Guaranteed);
auto differentialType = jvp->mapTypeIntoContext(
jvp->getConventions().getSILType(
jvp->getLoweredFunctionType()->getResults().back(),
jvp->getTypeExpansionContext()));
auto differentialFnType = differentialType.castTo<SILFunctionType>();
auto differentialSubstType =
differentialPartialApply->getType().castTo<SILFunctionType>();
// If necessary, convert the differential value to the returned differential
// function type.
SILValue differentialValue;
if (differentialSubstType == differentialFnType) {
differentialValue = differentialPartialApply;
} else if (differentialSubstType
->isABICompatibleWith(differentialFnType, *jvp)
.isCompatible()) {
differentialValue = builder.createConvertFunction(
loc, differentialPartialApply, differentialType,
/*withoutActuallyEscaping*/ false);
} else {
llvm::report_fatal_error("Differential value type is not ABI-compatible "
"with the returned differential type");
}
// Return a tuple of the original result and differential.
SmallVector<SILValue, 8> directResults;
directResults.append(origResults.begin(), origResults.end());
directResults.push_back(differentialValue);
builder.createReturn(ri->getLoc(),
joinElements(directResults, builder, loc));
}
void visitBranchInst(BranchInst *bi) {
llvm_unreachable("Unsupported SIL instruction.");
}
void visitCondBranchInst(CondBranchInst *cbi) {
llvm_unreachable("Unsupported SIL instruction.");
}
void visitSwitchEnumInst(SwitchEnumInst *sei) {
llvm_unreachable("Unsupported SIL instruction.");
}
void visitDifferentiableFunctionInst(DifferentiableFunctionInst *dfi) {
// Clone `differentiable_function` from original to JVP, then add the cloned
// instruction to the `differentiable_function` worklist.
TypeSubstCloner::visitDifferentiableFunctionInst(dfi);
auto *newDFI = cast<DifferentiableFunctionInst>(getOpValue(dfi));
context.getDifferentiableFunctionInstWorklist().push_back(newDFI);
}
void visitLinearFunctionInst(LinearFunctionInst *lfi) {
// Clone `linear_function` from original to JVP, then add the cloned
// instruction to the `linear_function` worklist.
TypeSubstCloner::visitLinearFunctionInst(lfi);
auto *newLFI = cast<LinearFunctionInst>(getOpValue(lfi));
context.getLinearFunctionInstWorklist().push_back(newLFI);
}
//--------------------------------------------------------------------------//
// Tangent emission helpers
//--------------------------------------------------------------------------//
#define CLONE_AND_EMIT_TANGENT(INST, ID) \
void visit##INST##Inst(INST##Inst *inst) { \
TypeSubstCloner::visit##INST##Inst(inst); \
if (differentialInfo.shouldDifferentiateInstruction(inst)) \
emitTangentFor##INST##Inst(inst); \
} \
void emitTangentFor##INST##Inst(INST##Inst *(ID))
CLONE_AND_EMIT_TANGENT(BeginBorrow, bbi) {
auto &diffBuilder = getDifferentialBuilder();
auto loc = bbi->getLoc();
auto tanVal = materializeTangent(getTangentValue(bbi->getOperand()), loc);
auto tanValBorrow = diffBuilder.emitBeginBorrowOperation(
loc, tanVal, bbi->isLexical(), bbi->hasPointerEscape(),
bbi->isFromVarDecl());
setTangentValue(bbi->getParent(), bbi,
makeConcreteTangentValue(tanValBorrow));
}
CLONE_AND_EMIT_TANGENT(EndBorrow, ebi) {
auto &diffBuilder = getDifferentialBuilder();
auto loc = ebi->getLoc();
auto tanVal = materializeTangent(getTangentValue(ebi->getOperand()), loc);
diffBuilder.emitEndBorrowOperation(loc, tanVal);
}
CLONE_AND_EMIT_TANGENT(DestroyValue, dvi) {
auto &diffBuilder = getDifferentialBuilder();
auto loc = dvi->getLoc();
auto tanVal = materializeTangent(getTangentValue(dvi->getOperand()), loc);
diffBuilder.emitDestroyValueOperation(loc, tanVal);
}
CLONE_AND_EMIT_TANGENT(CopyValue, cvi) {
auto &diffBuilder = getDifferentialBuilder();
auto tan = getTangentValue(cvi->getOperand());
auto tanVal = materializeTangent(tan, cvi->getLoc());
auto tanValCopy = diffBuilder.emitCopyValueOperation(cvi->getLoc(), tanVal);
setTangentValue(cvi->getParent(), cvi,
makeConcreteTangentValue(tanValCopy));
}
CLONE_AND_EMIT_TANGENT(MoveValue, mvi) {
auto &diffBuilder = getDifferentialBuilder();
auto tan = getTangentValue(mvi->getOperand());
auto tanVal = materializeTangent(tan, mvi->getLoc());
auto tanValMove = diffBuilder.emitMoveValueOperation(
mvi->getLoc(), tanVal, mvi->isLexical(), mvi->hasPointerEscape(),
mvi->isFromVarDecl());
setTangentValue(mvi->getParent(), mvi,
makeConcreteTangentValue(tanValMove));
}
/// Handle `load` instruction.
/// Original: y = load x
/// Tangent: tan[y] = load tan[x]
void visitLoadInst(LoadInst *li) {
TypeSubstCloner::visitLoadInst(li);
// If an active buffer is loaded with take to a non-active value, destroy
// the active buffer's tangent buffer.
if (!differentialInfo.shouldDifferentiateInstruction(li)) {
auto isTake =
(li->getOwnershipQualifier() == LoadOwnershipQualifier::Take);
if (isTake && activityInfo.isActive(li->getOperand(), getConfig())) {
auto &tanBuf = getTangentBuffer(li->getParent(), li->getOperand());
getDifferentialBuilder().emitDestroyOperation(tanBuf.getLoc(), tanBuf);
}
return;
}
// Otherwise, do standard differential cloning.
auto &diffBuilder = getDifferentialBuilder();
auto *bb = li->getParent();
auto loc = li->getLoc();
auto tanBuf = getTangentBuffer(bb, li->getOperand());
auto tanVal = diffBuilder.emitLoadValueOperation(
loc, tanBuf, li->getOwnershipQualifier());
setTangentValue(bb, li, makeConcreteTangentValue(tanVal));
}
/// Handle `load_borrow` instruction.
/// Original: y = load_borrow x
/// Tangent: tan[y] = load_borrow tan[x]
CLONE_AND_EMIT_TANGENT(LoadBorrow, lbi) {
auto &diffBuilder = getDifferentialBuilder();
auto *bb = lbi->getParent();
auto loc = lbi->getLoc();
auto tanBuf = getTangentBuffer(bb, lbi->getOperand());
auto tanVal = diffBuilder.emitLoadBorrowOperation(loc, tanBuf);
setTangentValue(bb, lbi, makeConcreteTangentValue(tanVal));
}
/// Handle `store` instruction in the differential.
/// Original: store x to y
/// Tangent: store tan[x] to tan[y]
void visitStoreInst(StoreInst *si) {
TypeSubstCloner::visitStoreInst(si);
// If a non-active value is stored into an active buffer, zero-initialize
// the active buffer's tangent buffer.
if (!differentialInfo.shouldDifferentiateInstruction(si)) {
if (activityInfo.isActive(si->getDest(), getConfig())) {
auto &tanBufDest = getTangentBuffer(si->getParent(), si->getDest());
emitZeroIndirect(tanBufDest->getType().getASTType(), tanBufDest,
tanBufDest.getLoc());
}
return;
}
// Otherwise, do standard differential cloning.
auto &diffBuilder = getDifferentialBuilder();
auto loc = si->getLoc();
auto tanValSrc = materializeTangent(getTangentValue(si->getSrc()), loc);
auto &tanValDest = getTangentBuffer(si->getParent(), si->getDest());
diffBuilder.emitStoreValueOperation(loc, tanValSrc, tanValDest,
si->getOwnershipQualifier());
}
/// Handle `store_borrow` instruction in the differential.
/// Original: store_borrow x to y
/// Tangent: store_borrow tan[x] to tan[y]
void visitStoreBorrowInst(StoreBorrowInst *sbi) {
TypeSubstCloner::visitStoreBorrowInst(sbi);
// If a non-active value is stored into an active buffer, zero-initialize
// the active buffer's tangent buffer.
if (!differentialInfo.shouldDifferentiateInstruction(sbi)) {
if (activityInfo.isActive(sbi->getDest(), getConfig())) {
auto &tanBufDest = getTangentBuffer(sbi->getParent(), sbi->getDest());
emitZeroIndirect(tanBufDest->getType().getASTType(), tanBufDest,
tanBufDest.getLoc());
}
return;
}
// Otherwise, do standard differential cloning.
auto &diffBuilder = getDifferentialBuilder();
auto loc = sbi->getLoc();
auto tanValSrc = materializeTangent(getTangentValue(sbi->getSrc()), loc);
auto &tanValDest = getTangentBuffer(sbi->getParent(), sbi->getDest());
diffBuilder.createStoreBorrow(loc, tanValSrc, tanValDest);
}
/// Handle `copy_addr` instruction.
/// Original: copy_addr x to y
/// Tangent: copy_addr tan[x] to tan[y]
void visitCopyAddrInst(CopyAddrInst *cai) {
TypeSubstCloner::visitCopyAddrInst(cai);
// If a non-active buffer is copied into an active buffer, zero-initialize
// the destination buffer's tangent buffer.
// If an active buffer is copied with take into a non-active buffer, destroy
// the source buffer's tangent buffer.
if (!differentialInfo.shouldDifferentiateInstruction(cai)) {
if (activityInfo.isActive(cai->getDest(), getConfig())) {
auto &tanBufDest = getTangentBuffer(cai->getParent(), cai->getDest());
emitZeroIndirect(tanBufDest->getType().getASTType(), tanBufDest,
tanBufDest.getLoc());
}
if (cai->isTakeOfSrc() &&
activityInfo.isActive(cai->getSrc(), getConfig())) {
auto &tanBufSrc = getTangentBuffer(cai->getParent(), cai->getSrc());
getDifferentialBuilder().emitDestroyOperation(tanBufSrc.getLoc(),
tanBufSrc);
}
return;
}
// Otherwise, do standard differential cloning.
auto diffBuilder = getDifferentialBuilder();
auto loc = cai->getLoc();
auto *bb = cai->getParent();
auto &tanSrc = getTangentBuffer(bb, cai->getSrc());
auto tanDest = getTangentBuffer(bb, cai->getDest());
diffBuilder.createCopyAddr(loc, tanSrc, tanDest, cai->isTakeOfSrc(),
cai->isInitializationOfDest());
}
/// Handle `unconditional_checked_cast_addr` instruction.
/// Original: unconditional_checked_cast_addr $X in x to $Y in y
/// Tangent: unconditional_checked_cast_addr $X.Tan in tan[x]
/// to $Y.Tan in tan[y]
CLONE_AND_EMIT_TANGENT(UnconditionalCheckedCastAddr, uccai) {
auto diffBuilder = getDifferentialBuilder();
auto loc = uccai->getLoc();
auto *bb = uccai->getParent();
auto &tanSrc = getTangentBuffer(bb, uccai->getSrc());
auto tanDest = getTangentBuffer(bb, uccai->getDest());
diffBuilder.createUnconditionalCheckedCastAddr(
loc, tanSrc, tanSrc->getType().getASTType(), tanDest,
tanDest->getType().getASTType());
}
/// Handle `begin_access` instruction (and do differentiability checks).
/// Original: y = begin_access x
/// Tangent: tan[y] = begin_access tan[x]
CLONE_AND_EMIT_TANGENT(BeginAccess, bai) {
// Check for non-differentiable writes.
if (bai->getAccessKind() == SILAccessKind::Modify) {
if (isa<GlobalAddrInst>(bai->getSource())) {
context.emitNondifferentiabilityError(
bai, invoker,
diag::autodiff_cannot_differentiate_writes_to_global_variables);
errorOccurred = true;
return;
}
if (isa<ProjectBoxInst>(bai->getSource())) {
context.emitNondifferentiabilityError(
bai, invoker,
diag::autodiff_cannot_differentiate_writes_to_mutable_captures);
errorOccurred = true;
return;
}
}
auto &diffBuilder = getDifferentialBuilder();
auto *bb = bai->getParent();
auto tanSrc = getTangentBuffer(bb, bai->getSource());
auto *tanDest = diffBuilder.createBeginAccess(
bai->getLoc(), tanSrc, bai->getAccessKind(), bai->getEnforcement(),
bai->hasNoNestedConflict(), bai->isFromBuiltin());
setTangentBuffer(bb, bai, tanDest);
}
/// Handle `end_access` instruction.
/// Original: begin_access x
/// Tangent: end_access tan[x]
CLONE_AND_EMIT_TANGENT(EndAccess, eai) {
auto &diffBuilder = getDifferentialBuilder();
auto *bb = eai->getParent();
auto loc = eai->getLoc();
auto tanOperand = getTangentBuffer(bb, eai->getOperand());
diffBuilder.createEndAccess(loc, tanOperand, eai->isAborting());
}
/// Handle `alloc_stack` instruction.
/// Original: y = alloc_stack $T