-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDifferentiation.cpp
6858 lines (6274 loc) · 285 KB
/
Differentiation.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
//===--- Differentiation.cpp - SIL Automatic Differentiation --*- C++ -*---===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// SWIFT_ENABLE_TENSORFLOW
//
// This file implements reverse-mode automatic differentiation.
//
// NOTE: Although the AD feature is developed as part of the Swift for
// TensorFlow project, it is completely independent from TensorFlow support.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "differentiation"
#include "Differentiation.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/AutoDiff.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/LoopInfo.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/TypeSubstCloner.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/LoopAnalysis.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/LoopUtils.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/BreadthFirstIterator.h"
#include "llvm/ADT/DenseSet.h"
using namespace swift;
using llvm::DenseMap;
using llvm::SmallDenseMap;
using llvm::SmallDenseSet;
using llvm::SmallMapVector;
using llvm::SmallSet;
/// This flag is used to disable `autodiff_function_extract` instruction folding
/// for SIL testing purposes.
static llvm::cl::opt<bool> SkipFoldingAutoDiffFunctionExtraction(
"differentiation-skip-folding-autodiff-function-extraction",
llvm::cl::init(true));
//===----------------------------------------------------------------------===//
// Helpers
//===----------------------------------------------------------------------===//
/// Prints an "[AD] " prefix to `llvm::dbgs()` and returns the debug stream.
/// This is being used to print short debug messages within the AD pass.
static raw_ostream &getADDebugStream() { return llvm::dbgs() << "[AD] "; }
/// Given a dumpable value, dumps it to `llvm::dbgs()`.
template <typename T> static inline void debugDump(T &v) {
LLVM_DEBUG(llvm::dbgs() << "\n==== BEGIN DEBUG DUMP ====\n"
<< v << "\n==== END DEBUG DUMP ====\n");
}
static bool isWithoutDerivative(SILValue v) {
if (auto *fnRef = dyn_cast<FunctionRefInst>(v))
return fnRef->getReferencedFunctionOrNull()->hasSemanticsAttr(
"autodiff.nonvarying");
return false;
}
static ApplyInst *getAllocateUninitializedArrayIntrinsic(SILValue v) {
if (auto *applyInst = dyn_cast<ApplyInst>(v))
if (applyInst->hasSemantics("array.uninitialized_intrinsic"))
return applyInst;
return nullptr;
}
/// Given a function, gather all of its formal results (both direct and
/// indirect) in an order defined by its result type. Note that "formal results"
/// refer to result values in the body of the function, not at call sites.
static void
collectAllFormalResultsInTypeOrder(SILFunction &function,
SmallVectorImpl<SILValue> &results) {
SILFunctionConventions convs(function.getLoweredFunctionType(),
function.getModule());
auto indResults = function.getIndirectResults();
auto *retInst = cast<ReturnInst>(function.findReturnBB()->getTerminator());
auto retVal = retInst->getOperand();
SmallVector<SILValue, 8> dirResults;
if (auto *tupleInst =
dyn_cast_or_null<TupleInst>(retVal->getDefiningInstruction()))
dirResults.append(tupleInst->getElements().begin(),
tupleInst->getElements().end());
else
dirResults.push_back(retVal);
unsigned indResIdx = 0, dirResIdx = 0;
for (auto &resInfo : convs.getResults())
results.push_back(resInfo.isFormalDirect() ? dirResults[dirResIdx++]
: indResults[indResIdx++]);
}
/// Given a function call site, gather all of its actual results (both direct
/// and indirect) in an order defined by its result type.
template <typename IndResRange>
static void collectAllActualResultsInTypeOrder(
ApplyInst *ai, ArrayRef<SILValue> extractedDirectResults,
IndResRange &&indirectResults, SmallVectorImpl<SILValue> &results) {
auto callee = ai->getCallee();
SILFunctionConventions calleeConvs(
callee->getType().castTo<SILFunctionType>(), ai->getModule());
unsigned indResIdx = 0, dirResIdx = 0;
for (auto &resInfo : calleeConvs.getResults()) {
results.push_back(resInfo.isFormalDirect()
? extractedDirectResults[dirResIdx++]
: indirectResults[indResIdx++]);
}
}
/// Given a range of types, joins these into a single type. If there's exactly
/// one element type, returns that element type. Otherwise, creates a tuple type
/// of all element types.
template <typename TypeRange>
static CanType joinElementTypes(TypeRange &&range, const ASTContext &ctx) {
if (range.size() == 1)
return range.front();
auto typeElts =
map<SmallVector<TupleTypeElt, 8>>(range, [&](Type type) { return type; });
return TupleType::get(typeElts, ctx);
}
/// Given a range of SIL values, retrieves the canonical types of these values,
/// and joins these types into a single type.
template <typename SILValueRange>
static CanType joinElementTypesFromValues(SILValueRange &&range,
const ASTContext &ctx) {
if (range.size() == 1)
return range.front()->getType().getASTType();
SmallVector<TupleTypeElt, 8> elts;
transform(range, elts.begin(),
[&](SILValue val) { return val->getType().getASTType(); });
return TupleType::get(elts, ctx)->getCanonicalType();
}
/// Given an operator name, such as '+', and a protocol, returns the '+'
/// operator. If the operator does not exist in the protocol, returns null.
static FuncDecl *findOperatorDeclInProtocol(DeclName operatorName,
ProtocolDecl *protocol) {
assert(operatorName.isOperator());
// Find the operator requirement in the `VectorProtocol` protocol
// declaration and cache it.
auto opLookup = protocol->lookupDirect(operatorName);
// Find the `+` with type siguature `(Self, Self) -> Self`.
for (auto *decl : opLookup) {
auto *fd = dyn_cast<FuncDecl>(decl);
if (!fd || !fd->isStatic() || !fd->isOperator())
continue;
return fd;
}
// Not found.
return nullptr;
}
/// Assuming the buffer is for indirect passing, returns the store ownership
/// qualifier for creating a `store` instruction into the buffer.
static StoreOwnershipQualifier getBufferSOQ(Type type, SILFunction &fn) {
if (fn.hasOwnership())
return fn.getModule().Types.getTypeLowering(
type, ResilienceExpansion::Minimal).isTrivial()
? StoreOwnershipQualifier::Trivial
: StoreOwnershipQualifier::Init;
return StoreOwnershipQualifier::Unqualified;
}
/// Assuming the buffer is for indirect passing, returns the load ownership
/// qualified for creating a `load` instruction from the buffer.
static LoadOwnershipQualifier getBufferLOQ(Type type, SILFunction &fn) {
if (fn.hasOwnership())
return fn.getModule().Types.getTypeLowering(
type, ResilienceExpansion::Minimal).isTrivial()
? LoadOwnershipQualifier::Trivial
: LoadOwnershipQualifier::Take;
return LoadOwnershipQualifier::Unqualified;
}
// Returns the generic signature for an autodiff associated function given a
// `SILDifferentiableAttr` and the original function. The associated function's
// generic signature is built from the original function's generic signature and
// the attribute's requirements. All differentiation parameters are constrained
// to conform to `Differentiable`.
static CanGenericSignature
getAssociatedFunctionGenericSignature(SILDifferentiableAttr *attr,
SILFunction *original) {
auto originalFnTy = original->getLoweredFunctionType();
auto originalGenSig = originalFnTy->getGenericSignature();
if (!originalGenSig)
return nullptr;
auto &ctx = original->getASTContext();
GenericSignatureBuilder builder(ctx);
// Add original generic signature.
builder.addGenericSignature(originalGenSig);
// Add where clause requirements.
auto source =
GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
for (auto &req : attr->getRequirements())
builder.addRequirement(req, source, original->getModule().getSwiftModule());
// Constrain all wrt parameters to conform to `Differentiable`.
auto *diffableProto = ctx.getProtocol(KnownProtocolKind::Differentiable);
auto paramIndexSet = attr->getIndices().parameters;
for (unsigned paramIdx : paramIndexSet->getIndices()) {
auto paramType = originalFnTy->getParameters()[paramIdx].getType();
Requirement req(RequirementKind::Conformance, paramType,
diffableProto->getDeclaredType());
builder.addRequirement(req, source, original->getModule().getSwiftModule());
}
return std::move(builder)
.computeGenericSignature(SourceLoc(), /*allowConcreteGenericParams*/ true)
->getCanonicalSignature();
}
// Clone the generic parameters of the given generic signature and return a new
// `GenericParamList`.
static GenericParamList *cloneGenericParameters(ASTContext &ctx,
DeclContext *dc,
CanGenericSignature sig) {
SmallVector<GenericTypeParamDecl *, 2> clonedParams;
for (auto paramType : sig->getGenericParams()) {
auto clonedParam = new (ctx) GenericTypeParamDecl(
dc, paramType->getName(), SourceLoc(), paramType->getDepth(),
paramType->getIndex());
clonedParam->setDeclContext(dc);
clonedParam->setImplicit(true);
clonedParams.push_back(clonedParam);
}
return GenericParamList::create(ctx, SourceLoc(), clonedParams, SourceLoc());
}
/// Given an `autodiff_function` instruction, find the corresponding
/// differential operator used in the AST. If no differential operator is found,
/// return nullptr.
static AutoDiffFunctionExpr *
findDifferentialOperator(AutoDiffFunctionInst *inst) {
return inst->getLoc().getAsASTNode<AutoDiffFunctionExpr>();
}
/// Returns the underlying instruction for the given SILValue, if it exists,
/// peering through function conversion instructions.
template<class Inst>
static Inst *peerThroughFunctionConversions(SILValue value) {
if (auto *inst = dyn_cast<Inst>(value))
return inst;
if (auto *thinToThick = dyn_cast<ThinToThickFunctionInst>(value))
return peerThroughFunctionConversions<Inst>(thinToThick->getOperand());
if (auto *convertFn = dyn_cast<ConvertFunctionInst>(value))
return peerThroughFunctionConversions<Inst>(convertFn->getOperand());
if (auto *partialApply = dyn_cast<PartialApplyInst>(value))
return peerThroughFunctionConversions<Inst>(partialApply->getCallee());
return nullptr;
}
//===----------------------------------------------------------------------===//
// Auxiliary data structures
//===----------------------------------------------------------------------===//
namespace {
class ADContext;
/// The invoker of a differentiation task. It can be some user syntax, e.g.
/// an `autodiff_function` instruction lowered from an `AutoDiffFunctionExpr`
/// expression, the differentiation pass, or nothing at all. This will be used
/// to emit informative diagnostics.
struct DifferentiationInvoker {
public:
/// The kind of the invoker of a differentiation task.
enum class Kind {
// Invoked by an `autodiff_function` instruction, which may or may not be
// linked to a Swift AST node (e.g. an `AutoDiffFunctionExpr` expression).
AutoDiffFunctionInst,
// Invoked by the indirect application of differentiation. This case has an
// associated original `apply` instruction and `[differentiable]` attribute.
IndirectDifferentiation,
// Invoker by a `[differentiable]` attribute in SIL **without** being linked
// to a Swift AST attribute. This case has an associated `[differentiable]`
// attribute.
SILDifferentiableAttribute
};
private:
Kind kind;
union Value {
/// The instruction associated with the `AutoDiffFunctionInst` case.
AutoDiffFunctionInst *adFuncInst;
Value(AutoDiffFunctionInst *inst) : adFuncInst(inst) {}
/// The parent `apply` instruction and `[differentiable]` attribute
/// associated with the `IndirectDifferentiation` case.
std::pair<ApplyInst *, SILDifferentiableAttr *>
indirectDifferentiation;
Value(ApplyInst *applyInst, SILDifferentiableAttr *attr)
: indirectDifferentiation({applyInst, attr}) {}
/// The `[differentiable]` attribute associated with the
/// `SILDifferentiableAttribute` case.
SILDifferentiableAttr *silDifferentiableAttribute;
Value(SILDifferentiableAttr *attr) : silDifferentiableAttribute(attr) {}
} value;
/*implicit*/
DifferentiationInvoker(Kind kind, Value value) : kind(kind), value(value) {}
public:
DifferentiationInvoker(AutoDiffFunctionInst *inst)
: kind(Kind::AutoDiffFunctionInst), value(inst) {}
DifferentiationInvoker(ApplyInst *applyInst, SILDifferentiableAttr *attr)
: kind(Kind::IndirectDifferentiation),
value({applyInst, attr}) {}
DifferentiationInvoker(SILDifferentiableAttr *attr)
: kind(Kind::SILDifferentiableAttribute), value(attr) {}
Kind getKind() const { return kind; }
AutoDiffFunctionInst *getAutoDiffFunctionInst() const {
assert(kind == Kind::AutoDiffFunctionInst);
return value.adFuncInst;
}
std::pair<ApplyInst *, SILDifferentiableAttr *>
getIndirectDifferentiation() const {
assert(kind == Kind::IndirectDifferentiation);
return value.indirectDifferentiation;
}
SILDifferentiableAttr *getSILDifferentiableAttribute() const {
assert(kind == Kind::SILDifferentiableAttribute);
return value.silDifferentiableAttribute;
}
SourceLoc getLocation() const {
switch (kind) {
case Kind::AutoDiffFunctionInst:
return getAutoDiffFunctionInst()->getLoc().getSourceLoc();
case Kind::IndirectDifferentiation:
return getIndirectDifferentiation().first->getLoc().getSourceLoc();
case Kind::SILDifferentiableAttribute:
return getSILDifferentiableAttribute()->getOriginal()
->getLocation().getSourceLoc();
}
}
void print(llvm::raw_ostream &os) const;
};
/// Information about the VJP function produced during VJP generation, e.g.
/// mappings from original values to corresponding values in the pullback
/// struct.
///
/// A pullback struct is an aggregate value containing pullbacks checkpointed
/// during the VJP computation. Pullback structs are generated for every
/// original function during VJP generation. Pullback struct values are
/// constructed by VJP functions and consumed by pullback functions.
class PullbackInfo {
private:
/// The original function.
SILFunction *const original;
/// Mapping from original basic blocks to pullback structs.
DenseMap<SILBasicBlock *, StructDecl *> pullbackStructs;
/// Mapping from original basic blocks to predecessor enums.
DenseMap<SILBasicBlock *, EnumDecl *> predecessorEnums;
/// Mapping from `apply` and `struct_extract` instructions in the original
/// function to the corresponding pullback declaration in the pullback struct.
DenseMap<SILInstruction *, VarDecl *> pullbackValueMap;
/// Mapping from predecessor+succcessor basic block pairs in original function
/// to the corresponding predecessor enum case.
DenseMap<std::pair<SILBasicBlock *, SILBasicBlock *>, EnumElementDecl *>
predecessorEnumCases;
/// Mapping from pullback structs to their predecessor enum fields.
DenseMap<StructDecl *, VarDecl *> pullbackStructPredecessorFields;
/// A type converter, used to compute struct/enum SIL types.
Lowering::TypeConverter &typeConverter;
private:
VarDecl *addVarDecl(NominalTypeDecl *nominal, StringRef name, Type type) {
auto &astCtx = nominal->getASTContext();
auto id = astCtx.getIdentifier(name);
auto *varDecl = new (astCtx) VarDecl(
/*IsStatic*/ false, VarDecl::Introducer::Var,
/*IsCaptureList*/ false, SourceLoc(), id, nominal);
varDecl->setAccess(nominal->getEffectiveAccess());
if (type->hasArchetype())
varDecl->setInterfaceType(type->mapTypeOutOfContext());
else
varDecl->setInterfaceType(type);
nominal->addMember(varDecl);
return varDecl;
}
/// Retrieves the file unit that contains implicit declarations in the
/// current Swift module. If it does not exist, create one.
///
// FIXME: Currently it defaults to the file containing `origFn`, if it can be
// determined. Otherwise, it defaults to any file unit in the module. To
// handle this more properly, we should make a DerivedFileUnit class to
// contain all synthesized implicit type declarations.
SourceFile &getDeclarationFileUnit() {
if (original->hasLocation())
if (auto *declContext = original->getLocation().getAsDeclContext())
if (auto *parentSourceFile = declContext->getParentSourceFile())
return *parentSourceFile;
for (auto *file : original->getModule().getSwiftModule()->getFiles())
if (auto *src = dyn_cast<SourceFile>(file))
return *src;
llvm_unreachable("No files?");
}
/// Compute and set the access level for the given pullback data structure,
/// given the original function linkage.
void computeAccessLevel(
NominalTypeDecl *nominal, SILLinkage originalLinkage) {
auto &astCtx = nominal->getASTContext();
switch (originalLinkage) {
case swift::SILLinkage::Public:
case swift::SILLinkage::PublicNonABI:
nominal->setAccess(AccessLevel::Internal);
nominal->getAttrs().add(
new (astCtx) UsableFromInlineAttr(/*Implicit*/ true));
break;
case swift::SILLinkage::Hidden:
case swift::SILLinkage::Shared:
nominal->setAccess(AccessLevel::Internal);
break;
case swift::SILLinkage::Private:
nominal->setAccess(AccessLevel::FilePrivate);
break;
default:
// When the original function has external linkage, we create an internal
// struct for use by our own module. This is necessary for cross-cell
// differentiation in Jupyter.
// TODO: Add a test in the compiler that exercises a similar situation as
// cross-cell differentiation in Jupyter.
nominal->setAccess(AccessLevel::Internal);
}
}
/// Creates an enum declaration with the given VJP generic signature, whose
/// cases represent the predecessors of the given original block.
EnumDecl *
createBasicBlockPredecessorEnum(SILBasicBlock *originalBB,
SILAutoDiffIndices indices,
CanGenericSignature vjpGenericSig) {
assert(originalBB->getParent() == original);
auto *moduleDecl = original->getModule().getSwiftModule();
auto &astCtx = original->getASTContext();
auto &file = getDeclarationFileUnit();
// Create a `_AD__<fn_name>_bb<bb_id>__Pred__` predecessor enum.
std::string predEnumName =
"_AD__" + original->getName().str() +
"_bb" + std::to_string(originalBB->getDebugID()) +
"__Pred__" + indices.mangle();
auto enumId = astCtx.getIdentifier(predEnumName);
auto loc = original->getLocation().getSourceLoc();
auto *predecessorEnum = new (astCtx) EnumDecl(
/*EnumLoc*/ loc, /*Name*/ enumId, /*NameLoc*/ loc, /*Inherited*/ {},
/*GenericParams*/ /*set later*/ nullptr, /*DC*/ &file);
if (vjpGenericSig) {
auto *genericParams =
cloneGenericParameters(astCtx, predecessorEnum, vjpGenericSig);
predecessorEnum->setGenericParams(genericParams);
predecessorEnum->setGenericEnvironment(
vjpGenericSig->createGenericEnvironment());
}
predecessorEnum->setBraces(loc);
computeAccessLevel(predecessorEnum, original->getEffectiveSymbolLinkage());
predecessorEnum->computeType();
assert(predecessorEnum->hasInterfaceType());
file.addVisibleDecl(predecessorEnum);
// Add predecessor block enum cases.
for (auto *predBB : originalBB->getPredecessorBlocks()) {
auto bbId = "bb" + std::to_string(predBB->getDebugID());
auto *predPBStruct = getPullbackStruct(predBB);
assert(predPBStruct);
auto predPBStructTy =
predPBStruct->getDeclaredInterfaceType()->getCanonicalType();
// Create dummy declaration representing enum case parameter.
auto *decl = new (astCtx)
ParamDecl(ParamDecl::Specifier::Default, loc, loc, Identifier(), loc,
Identifier(), moduleDecl);
if (predPBStructTy->hasArchetype())
decl->setInterfaceType(predPBStructTy->mapTypeOutOfContext());
else
decl->setInterfaceType(predPBStructTy);
// Create enum element and enum case declarations.
auto *paramList = ParameterList::create(astCtx, {decl});
auto *enumEltDecl = new (astCtx) EnumElementDecl(
/*IdentifierLoc*/ loc, DeclName(astCtx.getIdentifier(bbId)),
paramList, loc, /*RawValueExpr*/ nullptr, predecessorEnum);
enumEltDecl->setImplicit();
enumEltDecl->computeType();
auto *enumCaseDecl = EnumCaseDecl::create(
/*CaseLoc*/ loc, {enumEltDecl}, predecessorEnum);
enumCaseDecl->setImplicit();
predecessorEnum->addMember(enumEltDecl);
predecessorEnum->addMember(enumCaseDecl);
// Cache predecessor/successor enum element declarations.
predecessorEnumCases.insert({{predBB, originalBB}, enumEltDecl});
}
LLVM_DEBUG({
auto &s = getADDebugStream();
s << "Predecessor enum created for function @" << original->getName()
<< " bb" << originalBB->getDebugID() << '\n';
predecessorEnum->print(s);
s << '\n';
});
return predecessorEnum;
}
/// Creates a struct declaration with the given VJP generic signature, for
/// storing the pullback values and predecessor of the given original block.
StructDecl *
createPullbackStruct(SILBasicBlock *originalBB, SILAutoDiffIndices indices,
CanGenericSignature vjpGenericSig) {
auto *original = originalBB->getParent();
auto &astCtx = original->getASTContext();
auto &file = getDeclarationFileUnit();
// Create a `_AD__<fn_name>_bb<bb_id>__PB__` struct.
std::string pbStructName =
"_AD__" + original->getName().str() +
"_bb" + std::to_string(originalBB->getDebugID()) +
"__PB__" + indices.mangle();
auto structId = astCtx.getIdentifier(pbStructName);
SourceLoc loc = original->getLocation().getSourceLoc();
auto *pullbackStruct = new (astCtx) StructDecl(
/*StructLoc*/ loc, /*Name*/ structId, /*NameLoc*/ loc, /*Inherited*/ {},
/*GenericParams*/ /*set later*/ nullptr, /*DC*/ &file);
if (vjpGenericSig) {
auto *genericParams =
cloneGenericParameters(astCtx, pullbackStruct, vjpGenericSig);
pullbackStruct->setGenericParams(genericParams);
pullbackStruct->setGenericEnvironment(
vjpGenericSig->createGenericEnvironment());
}
pullbackStruct->setBraces(loc);
computeAccessLevel(
pullbackStruct, original->getEffectiveSymbolLinkage());
pullbackStruct->computeType();
assert(pullbackStruct->hasInterfaceType());
file.addVisibleDecl(pullbackStruct);
LLVM_DEBUG({
auto &s = getADDebugStream();
s << "Pullback struct created for function @" << original->getName()
<< " bb" << originalBB->getDebugID() << '\n';
pullbackStruct->print(s);
s << '\n';
});
return pullbackStruct;
}
public:
PullbackInfo(const PullbackInfo &) = delete;
PullbackInfo &operator=(const PullbackInfo &) = delete;
explicit PullbackInfo(ADContext &context, SILFunction *original,
SILFunction *vjp, const SILAutoDiffIndices &indices);
/// Returns the pullback struct associated with the given original block.
StructDecl *getPullbackStruct(SILBasicBlock *origBB) const {
return pullbackStructs.lookup(origBB);
}
/// Returns the lowered SIL type of the pullback struct associated with the
/// given original block.
SILType getPullbackStructLoweredType(SILBasicBlock *origBB) const {
auto *pbStruct = getPullbackStruct(origBB);
auto pbStructType =
pbStruct->getDeclaredInterfaceType()->getCanonicalType();
return typeConverter.getLoweredType(pbStructType,
ResilienceExpansion::Minimal);
}
/// Returns the predecessor enum associated with the given original block.
EnumDecl *getPredecessorEnum(SILBasicBlock *origBB) const {
return predecessorEnums.lookup(origBB);
}
/// Returns the lowered SIL type of the predecessor enum associated with the
/// given original block.
SILType getPredecessorEnumLoweredType(SILBasicBlock *origBB) const {
auto *predEnum = getPredecessorEnum(origBB);
auto predEnumType =
predEnum->getDeclaredInterfaceType()->getCanonicalType();
return typeConverter.getLoweredType(predEnumType,
ResilienceExpansion::Minimal);
}
/// Returns the enum element in the given successor block's predecessor enum
/// corresponding to the given predecessor block.
EnumElementDecl *
lookUpPredecessorEnumElement(SILBasicBlock *origPredBB,
SILBasicBlock *origSuccBB) const {
assert(origPredBB->getParent() == original);
return predecessorEnumCases.lookup({origPredBB, origSuccBB});
}
/// Returns the mapping from pullback structs to their predecessor enum
/// fields.
DenseMap<StructDecl *, VarDecl *> &getPullbackStructPredecessorFields() {
return pullbackStructPredecessorFields;
}
/// Returns the predecessor enum field for the pullback struct of the given
/// original block.
VarDecl *lookUpPullbackStructPredecessorField(SILBasicBlock *origBB) {
auto *pullbackStruct = getPullbackStruct(origBB);
return pullbackStructPredecessorFields.lookup(pullbackStruct);
}
/// Add a pullback to the pullback struct.
VarDecl *addPullbackDecl(SILInstruction *inst, SILType pullbackType) {
// IRGen requires decls to have AST types (not `SILFunctionType`), so we
// convert the `SILFunctionType` of the pullback to a `FunctionType` with
// the same parameters and results.
auto silFnTy = pullbackType.castTo<SILFunctionType>();
SmallVector<AnyFunctionType::Param, 8> params;
for (auto ¶m : silFnTy->getParameters())
params.push_back(AnyFunctionType::Param(param.getType()));
AnyFunctionType *astFnTy;
if (auto genSig = silFnTy->getGenericSignature())
astFnTy = GenericFunctionType::get(
genSig, params, silFnTy->getAllResultsType().getASTType());
else
astFnTy = FunctionType::get(
params, silFnTy->getAllResultsType().getASTType());
auto *origBB = inst->getParent();
auto *pbStruct = getPullbackStruct(origBB);
auto pullbackName = "pullback_" + llvm::itostr(pullbackValueMap.size());
auto *pullbackDecl = addVarDecl(pbStruct, pullbackName, astFnTy);
pullbackValueMap.insert({inst, pullbackDecl});
return pullbackDecl;
}
/// Finds the pullback declaration in the pullback struct for an `apply` or
/// `struct_extract` in the original function.
VarDecl *lookUpPullbackDecl(SILInstruction *inst) {
auto lookup = pullbackValueMap.find(inst);
return lookup == pullbackValueMap.end() ? nullptr
: lookup->getSecond();
}
};
/// Stores `apply` instruction information calculated by VJP generation.
struct NestedApplyInfo {
/// The differentiation indices that are used to differentiate this `apply`
/// instruction.
SILAutoDiffIndices indices;
/// The original pullback type before reabstraction. `None` if the pullback
/// type is not reabstracted.
Optional<CanSILFunctionType> originalPullbackType;
};
static inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
DifferentiationInvoker invoker) {
invoker.print(os);
return os;
}
void DifferentiationInvoker::print(llvm::raw_ostream &os) const {
os << "(differentiation_invoker ";
switch (kind) {
case Kind::AutoDiffFunctionInst:
os << "autodiff_function_inst=(" << *getAutoDiffFunctionInst() << ")";
break;
case Kind::IndirectDifferentiation: {
auto indDiff = getIndirectDifferentiation();
os << "indirect_differentiation=(" << *std::get<0>(indDiff) << ')';
// TODO: Enable printing parent invokers.
// May require storing a `DifferentiableInvoker *` in the
// `IndirectDifferentiation` case.
/*
SILInstruction *inst;
SILDifferentiableAttr *attr;
std::tie(inst, attr) = getIndirectDifferentiation();
auto invokerLookup = invokers.find(attr); // No access to ADContext?
assert(invokerLookup != invokers.end() && "Expected parent invoker");
*/
break;
}
case Kind::SILDifferentiableAttribute: {
auto diffAttr = getSILDifferentiableAttribute();
os << "sil_differentiable_attribute=(attr=(";
diffAttr->print(os);
os << ") function=" << diffAttr->getOriginal()->getName();
break;
}
}
os << ')';
}
//===----------------------------------------------------------------------===//
// ADContext - Per-module contextual information for the Differentiation pass.
//===----------------------------------------------------------------------===//
class ADContext {
private:
/// Reference to the main transform.
SILModuleTransform &transform;
/// The module where Differentiation is performed on.
SILModule &module;
/// AST context.
ASTContext &astCtx = module.getASTContext();
/// Shared pass manager.
SILPassManager &passManager;
/// The worklist (stack) of `autodiff_function` instructions to be processed.
SmallVector<AutoDiffFunctionInst *, 32> autoDiffFunctionInsts;
/// The set of `autodiff_function` instructions that have been processed.
/// Used to avoid reprocessing invalidated instructions.
SmallPtrSet<AutoDiffFunctionInst *, 32> processedAutoDiffFunctionInsts;
/// Mapping from `[differentiable]` attributes to invokers.
/// `SmallMapVector` is used for deterministic insertion order iteration.
SmallMapVector<SILDifferentiableAttr *, DifferentiationInvoker, 32>
invokers;
/// Mapping from `autodiff_function` instructions to result indices.
DenseMap<AutoDiffFunctionInst *, unsigned> resultIndices;
/// Mapping from original `apply` instructions to their corresponding
/// `NestedApplyInfo`s.
DenseMap<ApplyInst *, NestedApplyInfo> nestedApplyInfo;
/// List of generated functions (JVPs, VJPs, pullbacks, and thunks).
/// Saved for deletion during cleanup.
SmallVector<SILFunction *, 32> generatedFunctions;
/// List of associated function references, generated via
/// `emitAssociatedFunctionReference`.
/// Saved for deletion during cleanup.
SmallVector<SILValue, 32> generatedAssociatedFunctionReferences;
/// The AdditiveArithmetic protocol in the standard library.
ProtocolDecl *additiveArithmeticProtocol =
astCtx.getProtocol(KnownProtocolKind::AdditiveArithmetic);
/// The VectorProtocol protocol in the standard library.
ProtocolDecl *vectorProtocolProtocol =
astCtx.getProtocol(KnownProtocolKind::VectorProtocol);
/// `AdditiveArithmetic.+` declaration.
mutable FuncDecl *cachedPlusFn = nullptr;
/// `AdditiveArithmetic.+=` declaration.
mutable FuncDecl *cachedPlusEqualFn = nullptr;
public:
/// Construct an ADContext for the given module.
explicit ADContext(SILModuleTransform &transform);
//--------------------------------------------------------------------------//
// General utilities
//--------------------------------------------------------------------------//
SILModuleTransform &getTransform() const { return transform; }
SILModule &getModule() const { return module; }
ASTContext &getASTContext() const { return module.getASTContext(); }
SILPassManager &getPassManager() const { return passManager; }
Lowering::TypeConverter &getTypeConverter() { return module.Types; }
SmallVectorImpl<AutoDiffFunctionInst *> &getAutoDiffFunctionInsts() {
return autoDiffFunctionInsts;
}
SmallPtrSetImpl<AutoDiffFunctionInst *> &getProcessedAutoDiffFunctionInsts() {
return processedAutoDiffFunctionInsts;
}
llvm::SmallMapVector<SILDifferentiableAttr *, DifferentiationInvoker, 32> &
getInvokers() {
return invokers;
}
DenseMap<AutoDiffFunctionInst *, unsigned> &getResultIndices() {
return resultIndices;
}
DenseMap<ApplyInst *, NestedApplyInfo> &getNestedApplyInfo() {
return nestedApplyInfo;
}
SmallVector<SILFunction *, 32> &getGeneratedFunctions() {
return generatedFunctions;
}
SmallVector<SILValue, 32> &getGeneratedAssociatedFunctionReferences() {
return generatedAssociatedFunctionReferences;
}
ProtocolDecl *getAdditiveArithmeticProtocol() const {
return additiveArithmeticProtocol;
}
ProtocolDecl *getVectorProtocolProtocol() const {
return vectorProtocolProtocol;
}
FuncDecl *getPlusDecl() const {
if (!cachedPlusFn) {
cachedPlusFn = findOperatorDeclInProtocol(
astCtx.getIdentifier("+"), additiveArithmeticProtocol);
assert(cachedPlusFn && "AdditiveArithmetic.+ not found");
}
return cachedPlusFn;
}
FuncDecl *getPlusEqualDecl() const {
if (!cachedPlusEqualFn) {
cachedPlusEqualFn = findOperatorDeclInProtocol(
astCtx.getIdentifier("+="), additiveArithmeticProtocol);
assert(cachedPlusEqualFn && "AdditiveArithmetic.+= not found");
}
return cachedPlusEqualFn;
}
void cleanUp() {
for (auto invokerPair : invokers) {
auto *attr = std::get<0>(invokerPair);
auto *original = attr->getOriginal();
LLVM_DEBUG(getADDebugStream()
<< "Removing [differentiable] attribute for "
<< original->getName() << '\n');
original->removeDifferentiableAttr(attr);
}
// Delete all references to generated functions.
for (auto assocFn : generatedAssociatedFunctionReferences) {
if (auto *fnRef =
peerThroughFunctionConversions<FunctionRefInst>(assocFn)) {
LLVM_DEBUG(getADDebugStream()
<< "Deleting generated associated function reference:\n"
<< *fnRef);
fnRef->replaceAllUsesWithUndef();
fnRef->eraseFromParent();
}
}
// Delete all generated functions.
for (auto *generatedFunction : generatedFunctions) {
LLVM_DEBUG(getADDebugStream()
<< "Deleting generated function "
<< generatedFunction->getName() << '\n');
generatedFunction->dropAllReferences();
transform.notifyWillDeleteFunction(generatedFunction);
module.eraseFunction(generatedFunction);
}
}
//--------------------------------------------------------------------------//
// `[differentiable]` attribute lookup and registration
//--------------------------------------------------------------------------//
/// Finds the `[differentiable]` attribute on the specified original function
/// with the exact specified parameter indices. Returns nullptr if no such
/// attribute exists.
SILDifferentiableAttr *lookUpDifferentiableAttr(
SILFunction *original, const SILAutoDiffIndices &indices) const {
for (auto *attr : original->getDifferentiableAttrs())
if (attr->getIndices() == indices)
return attr;
return nullptr;
}
/// Finds the `[differentiable]` attribute on the specified original function
/// whose parameter indices are a minimal superset of the specified parameter
/// indices. Returns nullptr if no such attribute exists.
SILDifferentiableAttr *lookUpMinimalDifferentiableAttr(
SILFunction *original, const SILAutoDiffIndices &indices) const {
auto *minimalIndexSet = AutoDiffIndexSubset::getDefault(
getASTContext(),
original->getLoweredFunctionType()->getNumParameters(), false);
auto *indexSet = indices.parameters;
if (auto *exactAttr = lookUpDifferentiableAttr(original, indices))
return exactAttr;
SILDifferentiableAttr *minimalAttr = nullptr;
for (auto *da : original->getDifferentiableAttrs()) {
if (da->getIndices().source != indices.source)
continue;
auto *daIndexSet = da->getIndices().parameters;
// If all indices in `indexSet` are in `daIndexSet`, and it has fewer
// indices than our current candidate and a primitive VJP, then `da` is
// our new candidate.
//
// NOTE(TF-642): `da` may come from a un-partial-applied function and
// have larger capacity than the desired indices. We expect this logic to
// go away when `partial_apply` supports `@differentiable` callees.
if (daIndexSet->isSupersetOf(indexSet->extendingCapacity(
getASTContext(), daIndexSet->getCapacity())) &&
// fewer parameters than before
(minimalIndexSet->isEmpty() ||
daIndexSet->getNumIndices() < minimalIndexSet->getNumIndices())) {
minimalAttr = da;
minimalIndexSet = daIndexSet;
}
}
return minimalAttr;
}
/// Finds the `@differentiable` attribute (and its parameter indices) on the
/// specified original function whose parameter indices are a minimal
/// superset of the specified parameter indices. Returns nullptr if no such
/// attribute exists.
std::pair<const DifferentiableAttr *, AutoDiffIndexSubset *>
lookUpMinimalASTDifferentiableAttrAndIndexSubset(
SILDeclRef originalDeclRef, CanSILFunctionType originalFnType,
const SILAutoDiffIndices &indices) {
auto *original = originalDeclRef.getDecl();
const DifferentiableAttr *minimalAttr = nullptr;
auto *minimalIndexSet = AutoDiffIndexSubset::getDefault(
getASTContext(), originalFnType->getNumParameters(), false);
auto *indexSet = indices.parameters;
for (auto *da : original->getAttrs().getAttributes<DifferentiableAttr>()) {
auto *daParamIndices = da->getParameterIndices();
auto *daIndexSet = daParamIndices->getLowered(
getASTContext(),
original->getInterfaceType()->castTo<AnyFunctionType>());
// If all indices in `indexSet` are in `daIndexSet`, and it has fewer
// indices than our current candidate and a primitive VJP, then `da` is
// our new candidate.
//
// NOTE(TF-642): `da` may come from a un-partial-applied function and
// have larger capacity than the desired indices. We expect this logic to
// go away when `partial_apply` supports `@differentiable` callees.
if (daIndexSet->isSupersetOf(indexSet->extendingCapacity(getASTContext(),
daIndexSet->getCapacity())) &&
// fewer parameters than before
(minimalIndexSet->isEmpty() ||
daIndexSet->getNumIndices() < minimalIndexSet->getNumIndices())) {
minimalAttr = da;
minimalIndexSet = daIndexSet;
}
}
return std::make_pair(minimalAttr, minimalIndexSet);
}
/// Creates a `[differentiable]` attribute on the specified original function
/// with the specified parameter indices.
SILDifferentiableAttr *createDifferentiableAttr(
SILFunction *original, const SILAutoDiffIndices &indices,
ArrayRef<Requirement> contextualRequirements) const {
assert(!lookUpDifferentiableAttr(original, indices));
auto *attr = SILDifferentiableAttr::create(getModule(), indices,
contextualRequirements);
original->addDifferentiableAttr(attr);
return attr;
}
/// Finds or creates a `[differentiable]` attribute on the specified
/// original function corresponding to the specified parameter indices.
SILDifferentiableAttr *getOrCreateDifferentiableAttr(
SILFunction *original, const SILAutoDiffIndices &indices,
ArrayRef<Requirement> contextualRequirements) {
if (auto *attr = lookUpDifferentiableAttr(original, indices))
return attr;
assert(original->isDefinition());
return createDifferentiableAttr(original, indices, contextualRequirements);
}
/// Creates an `autodiff_function` instruction using the given builder and
/// arguments. Erase the newly created instruction from the processed set, if
/// it exists - it may exist in the processed set if it has the same pointer
/// value as a previously processed and deleted instruction.
AutoDiffFunctionInst *createAutoDiffFunction(
SILBuilder &builder, SILLocation loc,
AutoDiffIndexSubset *parameterIndices, unsigned differentiationOrder,
SILValue original, ArrayRef<SILValue> associatedFunctions = {}) {
auto *adfi = builder.createAutoDiffFunction(