-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDerivedConformanceDifferentiable.cpp
914 lines (829 loc) · 40.5 KB
/
DerivedConformanceDifferentiable.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
//===--- DerivedConformanceDifferentiable.cpp - Derived Differentiable ----===//
//
// 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 implements explicit derivation of the Differentiable protocol for
// struct and class types.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "TypeChecker.h"
#include "swift/AST/AutoDiff.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "DerivedConformances.h"
using namespace swift;
/// Get the stored properties of a nominal type that are relevant for
/// differentiation, except the ones tagged `@noDerivative`.
static void
getStoredPropertiesForDifferentiation(NominalTypeDecl *nominal, DeclContext *DC,
SmallVectorImpl<VarDecl *> &result,
bool includeLetProperties = false) {
auto &C = nominal->getASTContext();
auto *diffableProto = C.getProtocol(KnownProtocolKind::Differentiable);
for (auto *vd : nominal->getStoredProperties()) {
// Peer through property wrappers: use original wrapped properties instead.
if (auto *originalProperty = vd->getOriginalWrappedProperty()) {
// Skip immutable wrapped properties. `mutating func move(along:)` cannot
// be synthesized to update these properties.
if (!originalProperty->isSettable(DC))
continue;
// Use the original wrapped property.
vd = originalProperty;
}
// Skip stored properties with `@noDerivative` attribute.
if (vd->getAttrs().hasAttribute<NoDerivativeAttr>())
continue;
// Skip `let` stored properties if requested.
// `mutating func move(along:)` cannot be synthesized to update `let`
// properties.
if (!includeLetProperties && vd->isLet())
continue;
if (vd->getInterfaceType()->hasError())
continue;
auto varType = DC->mapTypeIntoContext(vd->getValueInterfaceType());
if (!TypeChecker::conformsToProtocol(varType, diffableProto, nominal))
continue;
result.push_back(vd);
}
}
/// Convert the given `ValueDecl` to a `StructDecl` if it is a `StructDecl` or a
/// `TypeDecl` with an underlying struct type. Otherwise, return `nullptr`.
static StructDecl *convertToStructDecl(ValueDecl *v) {
if (auto *structDecl = dyn_cast<StructDecl>(v))
return structDecl;
auto *typeDecl = dyn_cast<TypeDecl>(v);
if (!typeDecl)
return nullptr;
return dyn_cast_or_null<StructDecl>(
typeDecl->getDeclaredInterfaceType()->getAnyNominal());
}
/// Get the `Differentiable` protocol `TangentVector` associated type witness
/// for the given interface type and declaration context.
static Type getTangentVectorInterfaceType(Type contextualType,
DeclContext *DC) {
auto &C = contextualType->getASTContext();
auto *diffableProto = C.getProtocol(KnownProtocolKind::Differentiable);
assert(diffableProto && "`Differentiable` protocol not found");
auto conf =
TypeChecker::conformsToProtocol(contextualType, diffableProto, DC);
assert(conf && "Contextual type must conform to `Differentiable`");
if (!conf)
return nullptr;
auto tanType = conf.getTypeWitnessByName(contextualType, C.Id_TangentVector);
return tanType->hasArchetype() ? tanType->mapTypeOutOfContext() : tanType;
}
/// Returns true iff the given nominal type declaration can derive
/// `TangentVector` as `Self` in the given conformance context.
static bool canDeriveTangentVectorAsSelf(NominalTypeDecl *nominal,
DeclContext *DC) {
// `Self` must not be a class declaraiton.
if (nominal->getSelfClassDecl())
return false;
auto nominalTypeInContext =
DC->mapTypeIntoContext(nominal->getDeclaredInterfaceType());
auto &C = nominal->getASTContext();
auto *diffableProto = C.getProtocol(KnownProtocolKind::Differentiable);
auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic);
// `Self` must conform to `AdditiveArithmetic`.
if (!TypeChecker::conformsToProtocol(nominalTypeInContext, addArithProto, DC))
return false;
for (auto *field : nominal->getStoredProperties()) {
// `Self` must not have any `@noDerivative` stored properties.
if (field->getAttrs().hasAttribute<NoDerivativeAttr>())
return false;
// `Self` must have all stored properties satisfy `Self == TangentVector`.
auto fieldType = DC->mapTypeIntoContext(field->getValueInterfaceType());
auto conf = TypeChecker::conformsToProtocol(fieldType, diffableProto, DC);
if (!conf)
return false;
auto tangentType = conf.getTypeWitnessByName(fieldType, C.Id_TangentVector);
if (!fieldType->isEqual(tangentType))
return false;
}
return true;
}
// Synthesizable `Differentiable` protocol requirements.
enum class DifferentiableRequirement {
// associatedtype TangentVector
TangentVector,
// mutating func move(along direction: TangentVector)
MoveAlong,
// var zeroTangentVectorInitializer: () -> TangentVector
ZeroTangentVectorInitializer,
};
static DifferentiableRequirement
getDifferentiableRequirementKind(ValueDecl *requirement) {
auto &C = requirement->getASTContext();
if (requirement->getBaseName() == C.Id_TangentVector)
return DifferentiableRequirement::TangentVector;
if (requirement->getBaseName() == C.Id_move)
return DifferentiableRequirement::MoveAlong;
if (requirement->getBaseName() == C.Id_zeroTangentVectorInitializer)
return DifferentiableRequirement::ZeroTangentVectorInitializer;
llvm_unreachable("Invalid `Differentiable` protocol requirement");
}
bool DerivedConformance::canDeriveDifferentiable(NominalTypeDecl *nominal,
DeclContext *DC,
ValueDecl *requirement) {
// Experimental differentiable programming must be enabled.
if (auto *SF = DC->getParentSourceFile())
if (!isDifferentiableProgrammingEnabled(*SF))
return false;
auto reqKind = getDifferentiableRequirementKind(requirement);
auto &C = nominal->getASTContext();
// If there are any `TangentVector` type witness candidates, check whether
// there exists only a single valid candidate.
bool canUseTangentVectorAsSelf = canDeriveTangentVectorAsSelf(nominal, DC);
auto isValidTangentVectorCandidate = [&](ValueDecl *v) -> bool {
// If the requirement is `var zeroTangentVectorInitializer` and
// the candidate is a type declaration that conforms to
// `AdditiveArithmetic`, return true.
if (reqKind == DifferentiableRequirement::ZeroTangentVectorInitializer) {
if (auto *tangentVectorTypeDecl = dyn_cast<TypeDecl>(v)) {
auto tangentType = DC->mapTypeIntoContext(
tangentVectorTypeDecl->getDeclaredInterfaceType());
auto *addArithProto =
C.getProtocol(KnownProtocolKind::AdditiveArithmetic);
if (TypeChecker::conformsToProtocol(tangentType, addArithProto, DC))
return true;
}
}
// Valid candidate must be a struct or a typealias to a struct.
auto *structDecl = convertToStructDecl(v);
if (!structDecl)
return false;
// Valid candidate must either:
// 1. Be implicit (previously synthesized).
if (structDecl->isImplicit())
return true;
// 2. Equal nominal, when the nominal can derive `TangentVector` as `Self`.
// Nominal type must not customize `TangentVector` to anything other than
// `Self`. Otherwise, synthesis is semantically unsupported.
if (structDecl == nominal && canUseTangentVectorAsSelf)
return true;
// Otherwise, candidate is invalid.
return false;
};
auto tangentDecls = nominal->lookupDirect(C.Id_TangentVector);
// There can be at most one valid `TangentVector` type.
if (tangentDecls.size() > 1)
return false;
// There cannot be any invalid `TangentVector` types.
if (tangentDecls.size() == 1) {
auto *tangentDecl = tangentDecls.front();
if (!isValidTangentVectorCandidate(tangentDecl))
return false;
}
bool hasValidTangentDecl = !tangentDecls.empty();
// Check requirement-specific derivation conditions.
if (reqKind == DifferentiableRequirement::ZeroTangentVectorInitializer) {
// If there is a valid `TangentVector` type witness (conforming to
// `AdditiveArithmetic`), return true.
if (hasValidTangentDecl)
return true;
// Otherwise, fallback on `TangentVector` struct derivation conditions.
}
// Check `TangentVector` struct derivation conditions.
// Nominal type must be a struct or class. (No stored properties is okay.)
if (!isa<StructDecl>(nominal) && !isa<ClassDecl>(nominal))
return false;
// If there are no `TangentVector` candidates, derivation is possible if all
// differentiation stored properties conform to `Differentiable`.
SmallVector<VarDecl *, 16> diffProperties;
getStoredPropertiesForDifferentiation(nominal, DC, diffProperties);
auto *diffableProto = C.getProtocol(KnownProtocolKind::Differentiable);
return llvm::all_of(diffProperties, [&](VarDecl *v) {
if (v->getInterfaceType()->hasError())
return false;
auto varType = DC->mapTypeIntoContext(v->getValueInterfaceType());
return (bool)TypeChecker::conformsToProtocol(varType, diffableProto, DC);
});
}
/// Synthesize body for `move(along:)`.
static std::pair<BraceStmt *, bool>
deriveBodyDifferentiable_move(AbstractFunctionDecl *funcDecl, void *) {
auto &C = funcDecl->getASTContext();
auto *parentDC = funcDecl->getParent();
auto *nominal = parentDC->getSelfNominalTypeDecl();
// Get `Differentiable.move(along:)` protocol requirement.
auto *diffProto = C.getProtocol(KnownProtocolKind::Differentiable);
auto *requirement = getProtocolRequirement(diffProto, C.Id_move);
// Get references to `self` and parameter declarations.
auto *selfDecl = funcDecl->getImplicitSelfDecl();
auto *selfDRE =
new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true);
auto *paramDecl = funcDecl->getParameters()->get(0);
auto *paramDRE =
new (C) DeclRefExpr(paramDecl, DeclNameLoc(), /*Implicit*/ true);
SmallVector<VarDecl *, 8> diffProperties;
getStoredPropertiesForDifferentiation(nominal, parentDC, diffProperties);
// Create call expression applying a member `move(along:)` method to a
// parameter member: `self.<member>.move(along: direction.<member>)`.
auto createMemberMethodCallExpr = [&](VarDecl *member) -> Expr * {
auto *module = nominal->getModuleContext();
auto memberType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
auto confRef = module->lookupConformance(memberType, diffProto);
assert(confRef && "Member does not conform to `Differentiable`");
// Get member type's requirement witness: `<Member>.move(along:)`.
ValueDecl *memberWitnessDecl = requirement;
if (confRef.isConcrete())
if (auto *witness = confRef.getConcrete()->getWitnessDecl(requirement))
memberWitnessDecl = witness;
assert(memberWitnessDecl && "Member witness declaration must exist");
// Create reference to member method: `self.<member>.move(along:)`.
Expr *memberExpr =
new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(),
/*Implicit*/ true);
auto *memberMethodExpr =
new (C) MemberRefExpr(memberExpr, SourceLoc(), memberWitnessDecl,
DeclNameLoc(), /*Implicit*/ true);
// Create reference to parameter member: `direction.<member>`.
VarDecl *paramMember = nullptr;
auto *paramNominal = paramDecl->getType()->getAnyNominal();
assert(paramNominal && "Parameter should have a nominal type");
// Find parameter member corresponding to returned nominal member.
for (auto *candidate : paramNominal->getStoredProperties()) {
if (candidate->getName() == member->getName()) {
paramMember = candidate;
break;
}
}
assert(paramMember && "Could not find corresponding parameter member");
auto *paramMemberExpr =
new (C) MemberRefExpr(paramDRE, SourceLoc(), paramMember, DeclNameLoc(),
/*Implicit*/ true);
// Create expression: `self.<member>.move(along: direction.<member>)`.
return CallExpr::createImplicit(C, memberMethodExpr, {paramMemberExpr},
{C.Id_along});
};
// Collect member `move(along:)` method call expressions.
SmallVector<ASTNode, 2> memberMethodCallExprs;
SmallVector<Identifier, 2> memberNames;
for (auto *member : diffProperties) {
memberMethodCallExprs.push_back(createMemberMethodCallExpr(member));
memberNames.push_back(member->getName());
}
auto *braceStmt = BraceStmt::create(C, SourceLoc(), memberMethodCallExprs,
SourceLoc(), true);
return std::pair<BraceStmt *, bool>(braceStmt, false);
}
/// Synthesize body for `var zeroTangentVectorInitializer` getter.
static std::pair<BraceStmt *, bool>
deriveBodyDifferentiable_zeroTangentVectorInitializer(
AbstractFunctionDecl *funcDecl, void *) {
auto &C = funcDecl->getASTContext();
auto *parentDC = funcDecl->getParent();
auto *nominal = parentDC->getSelfNominalTypeDecl();
// Get method protocol requirement.
auto *diffProto = C.getProtocol(KnownProtocolKind::Differentiable);
auto *requirement =
getProtocolRequirement(diffProto, C.Id_zeroTangentVectorInitializer);
auto nominalType =
parentDC->mapTypeIntoContext(nominal->getDeclaredInterfaceType());
auto conf = TypeChecker::conformsToProtocol(nominalType, diffProto, parentDC);
auto tangentType = conf.getTypeWitnessByName(nominalType, C.Id_TangentVector);
auto *tangentTypeExpr = TypeExpr::createImplicit(tangentType, C);
// Get differentiation properties.
SmallVector<VarDecl *, 8> diffProperties;
getStoredPropertiesForDifferentiation(nominal, parentDC, diffProperties,
/*includeLetProperties*/ true);
// Check whether memberwise derivation of `zeroTangentVectorInitializer` is
// possible.
bool canPerformMemberwiseDerivation = [&]() -> bool {
// Memberwise derivation is possible only for struct `TangentVector` types.
auto *tangentTypeDecl = tangentType->getAnyNominal();
if (!tangentTypeDecl || !tangentTypeDecl->getSelfStructDecl())
return false;
// Get effective memberwise initializer.
auto *memberwiseInitDecl =
tangentTypeDecl->getEffectiveMemberwiseInitializer();
// Return false if number of memberwise initializer parameters does not
// equal number of differentiation properties.
if (memberwiseInitDecl->getParameters()->size() != diffProperties.size())
return false;
// Iterate over all initializer parameters and differentiation properties.
for (auto pair : llvm::zip(memberwiseInitDecl->getParameters()->getArray(),
diffProperties)) {
auto *initParam = std::get<0>(pair);
auto *diffProp = std::get<1>(pair);
// Return false if parameter label does not equal property name.
if (initParam->getParameterName() != diffProp->getName())
return false;
auto diffPropContextualType =
parentDC->mapTypeIntoContext(diffProp->getValueInterfaceType());
auto diffPropTangentType =
getTangentVectorInterfaceType(diffPropContextualType, parentDC);
// Return false if parameter type does not equal property tangent type.
if (!initParam->getValueInterfaceType()->isEqual(diffPropTangentType))
return false;
}
return true;
}();
// If memberwise derivation is not possible, synthesize
// `{ TangentVector.zero }` as a fallback.
if (!canPerformMemberwiseDerivation) {
auto *module = nominal->getModuleContext();
auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic);
auto confRef = module->lookupConformance(tangentType, addArithProto);
assert(confRef &&
"`TangentVector` does not conform to `AdditiveArithmetic`");
auto *zeroDecl = getProtocolRequirement(addArithProto, C.Id_zero);
// If conformance reference is concrete, then use concrete witness
// declaration for the operator.
if (confRef.isConcrete())
if (auto *witnessDecl = confRef.getConcrete()->getWitnessDecl(zeroDecl))
zeroDecl = witnessDecl;
assert(zeroDecl && "Member method declaration must exist");
auto *zeroExpr =
new (C) MemberRefExpr(tangentTypeExpr, SourceLoc(), zeroDecl,
DeclNameLoc(), /*Implicit*/ true);
// Create closure expression.
unsigned discriminator = 0;
auto resultTy = funcDecl->getMethodInterfaceType()
->castTo<AnyFunctionType>()
->getResult();
auto *closureParams = ParameterList::createEmpty(C);
auto *closure = new (C) ClosureExpr(
SourceRange(), /*capturedSelfDecl*/ nullptr, closureParams,
SourceLoc(), SourceLoc(), SourceLoc(), SourceLoc(),
TypeExpr::createImplicit(resultTy, C), discriminator, funcDecl);
closure->setImplicit();
auto *closureReturn = new (C) ReturnStmt(SourceLoc(), zeroExpr, true);
auto *closureBody =
BraceStmt::create(C, SourceLoc(), {closureReturn}, SourceLoc(), true);
closure->setBody(closureBody, /*isSingleExpression=*/true);
ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), closure, true);
auto *braceStmt =
BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true);
return std::pair<BraceStmt *, bool>(braceStmt, false);
}
// Otherwise, perform memberwise derivation.
// Get effective memberwise initializer: `Nominal.init(...)`.
auto *tangentTypeDecl = tangentType->getAnyNominal();
auto *memberwiseInitDecl =
tangentTypeDecl->getEffectiveMemberwiseInitializer();
assert(memberwiseInitDecl && "Memberwise initializer must exist");
auto *initDRE =
new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true);
initDRE->setFunctionRefKind(FunctionRefKind::SingleApply);
auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, tangentTypeExpr);
// Get references to `self` and parameter declarations.
auto *selfDecl = funcDecl->getImplicitSelfDecl();
// Create `self.<member>.zeroTangentVectorInitializer` capture list entry.
auto createMemberZeroTanInitCaptureListEntry =
[&](VarDecl *member) -> CaptureListEntry {
// Create `<member>_zeroTangentVectorInitializer` capture var declaration.
auto memberCaptureName = C.getIdentifier(std::string(member->getNameStr()) +
"_zeroTangentVectorInitializer");
auto *memberZeroTanInitCaptureDecl = new (C) VarDecl(
/*isStatic*/ false, VarDecl::Introducer::Let, /*isCaptureList*/ true,
SourceLoc(), memberCaptureName, funcDecl);
memberZeroTanInitCaptureDecl->setImplicit();
auto *memberZeroTanInitPattern =
NamedPattern::createImplicit(C, memberZeroTanInitCaptureDecl);
auto *module = nominal->getModuleContext();
auto memberType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
auto confRef = module->lookupConformance(memberType, diffProto);
assert(confRef && "Member does not conform to `Differentiable`");
// Get member type's `zeroTangentVectorInitializer` requirement witness.
ValueDecl *memberWitnessDecl = requirement;
if (confRef.isConcrete())
if (auto *witness = confRef.getConcrete()->getWitnessDecl(requirement))
memberWitnessDecl = witness;
assert(memberWitnessDecl && "Member witness declaration must exist");
// <member>.zeroTangentVectorInitializer
auto *selfDRE =
new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true);
auto *memberExpr =
new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(),
/*Implicit*/ true);
auto *memberZeroTangentVectorInitExpr =
new (C) MemberRefExpr(memberExpr, SourceLoc(), memberWitnessDecl,
DeclNameLoc(), /*Implicit*/ true);
auto *memberZeroTanInitPBD = PatternBindingDecl::createImplicit(
C, StaticSpellingKind::None, memberZeroTanInitPattern,
memberZeroTangentVectorInitExpr, funcDecl);
CaptureListEntry captureEntry(memberZeroTanInitCaptureDecl,
memberZeroTanInitPBD);
return captureEntry;
};
// Create `<member>_zeroTangentVectorInitializer()` call expression.
auto createMemberZeroTanInitCallExpr =
[&](CaptureListEntry memberZeroTanInitEntry) -> Expr * {
// <member>_zeroTangentVectorInitializer
auto *memberZeroTanInitDRE = new (C) DeclRefExpr(
memberZeroTanInitEntry.Var, DeclNameLoc(), /*Implicit*/ true);
// <member>_zeroTangentVectorInitializer()
auto *memberZeroTangentVector =
CallExpr::createImplicit(C, memberZeroTanInitDRE, {}, {});
return memberZeroTangentVector;
};
// Collect member zero tangent vector expressions.
SmallVector<Identifier, 4> memberNames;
SmallVector<Expr *, 4> memberZeroTanExprs;
SmallVector<CaptureListEntry, 2> memberZeroTanInitCaptures;
for (auto *member : diffProperties) {
memberNames.push_back(member->getName());
auto memberZeroTanInitCapture =
createMemberZeroTanInitCaptureListEntry(member);
memberZeroTanInitCaptures.push_back(memberZeroTanInitCapture);
memberZeroTanExprs.push_back(
createMemberZeroTanInitCallExpr(memberZeroTanInitCapture));
}
// Create `zeroTangentVectorInitializer` closure body:
// `TangentVector(x: x_zeroTangentVectorInitializer(), ...)`.
auto *callExpr =
CallExpr::createImplicit(C, initExpr, memberZeroTanExprs, memberNames);
// Create closure expression:
// `{ TangentVector(x: x_zeroTangentVectorInitializer(), ...) }`.
unsigned discriminator = 0;
auto resultTy = funcDecl->getMethodInterfaceType()
->castTo<AnyFunctionType>()
->getResult();
auto *closureParams = ParameterList::createEmpty(C);
auto *closure = new (C) ClosureExpr(
SourceRange(), /*capturedSelfDecl*/ nullptr, closureParams, SourceLoc(),
SourceLoc(), SourceLoc(), SourceLoc(),
TypeExpr::createImplicit(resultTy, C), discriminator, funcDecl);
closure->setImplicit();
auto *closureReturn = new (C) ReturnStmt(SourceLoc(), callExpr, true);
auto *closureBody =
BraceStmt::create(C, SourceLoc(), {closureReturn}, SourceLoc(), true);
closure->setBody(closureBody, /*isSingleExpression=*/true);
// Create capture list expression:
// ```
// { [x_zeroTangentVectorInitializer = x.zeroTangentVectorInitializer, ...] in
// TangentVector(x: x_zeroTangentVectorInitializer(), ...)
// }
// ```
auto *captureList =
CaptureListExpr::create(C, memberZeroTanInitCaptures, closure);
captureList->setImplicit();
ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), captureList, true);
auto *braceStmt =
BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true);
return std::pair<BraceStmt *, bool>(braceStmt, false);
}
/// Synthesize function declaration for a `Differentiable` method requirement.
static ValueDecl *deriveDifferentiable_method(
DerivedConformance &derived, Identifier methodName, Identifier argumentName,
Identifier parameterName, Type parameterType, Type returnType,
AbstractFunctionDecl::BodySynthesizer bodySynthesizer) {
auto *nominal = derived.Nominal;
auto &C = derived.Context;
auto *parentDC = derived.getConformanceContext();
auto *param = new (C) ParamDecl(SourceLoc(), SourceLoc(), argumentName,
SourceLoc(), parameterName, parentDC);
param->setSpecifier(ParamDecl::Specifier::Default);
param->setInterfaceType(parameterType);
ParameterList *params = ParameterList::create(C, {param});
DeclName declName(C, methodName, params);
auto *funcDecl = FuncDecl::create(C, SourceLoc(), StaticSpellingKind::None,
SourceLoc(), declName, SourceLoc(),
/*Async*/ false, SourceLoc(),
/*Throws*/ false, SourceLoc(),
/*GenericParams=*/nullptr, params,
TypeLoc::withoutLoc(returnType), parentDC);
if (!nominal->getSelfClassDecl())
funcDecl->setSelfAccessKind(SelfAccessKind::Mutating);
funcDecl->setImplicit();
funcDecl->setBodySynthesizer(bodySynthesizer.Fn, bodySynthesizer.Context);
funcDecl->setGenericSignature(parentDC->getGenericSignatureOfContext());
funcDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true);
derived.addMembersToConformanceContext({funcDecl});
return funcDecl;
}
/// Synthesize the `move(along:)` function declaration.
static ValueDecl *deriveDifferentiable_move(DerivedConformance &derived) {
auto &C = derived.Context;
auto *parentDC = derived.getConformanceContext();
auto tangentType =
getTangentVectorInterfaceType(parentDC->getSelfTypeInContext(), parentDC);
return deriveDifferentiable_method(
derived, C.Id_move, C.Id_along, C.Id_direction, tangentType,
C.TheEmptyTupleType, {deriveBodyDifferentiable_move, nullptr});
}
/// Synthesize the `zeroTangentVectorInitializer` computed property declaration.
static ValueDecl *
deriveDifferentiable_zeroTangentVectorInitializer(DerivedConformance &derived) {
auto &C = derived.Context;
auto *parentDC = derived.getConformanceContext();
auto tangentType =
getTangentVectorInterfaceType(parentDC->getSelfTypeInContext(), parentDC);
auto returnType = FunctionType::get({}, tangentType);
VarDecl *propDecl;
PatternBindingDecl *pbDecl;
std::tie(propDecl, pbDecl) = derived.declareDerivedProperty(
C.Id_zeroTangentVectorInitializer, returnType, returnType,
/*isStatic*/ false, /*isFinal*/ true);
// Define the getter.
auto *getterDecl =
derived.addGetterToReadOnlyDerivedProperty(propDecl, returnType);
// Add an implicit `@noDerivative` attribute.
// `zeroTangentVectorInitializer` getter calls should never be differentiated.
getterDecl->getAttrs().add(new (C) NoDerivativeAttr(/*Implicit*/ true));
getterDecl->setBodySynthesizer(
&deriveBodyDifferentiable_zeroTangentVectorInitializer);
derived.addMembersToConformanceContext({propDecl, pbDecl});
return propDecl;
}
/// Return associated `TangentVector` struct for a nominal type, if it exists.
/// If not, synthesize the struct.
static StructDecl *
getOrSynthesizeTangentVectorStruct(DerivedConformance &derived, Identifier id) {
auto *parentDC = derived.getConformanceContext();
auto *nominal = derived.Nominal;
auto &C = nominal->getASTContext();
// If the associated struct already exists, return it.
auto lookup = nominal->lookupDirect(C.Id_TangentVector);
assert(lookup.size() < 2 &&
"Expected at most one associated type named `TangentVector`");
if (lookup.size() == 1) {
auto *structDecl = convertToStructDecl(lookup.front());
assert(structDecl && "Expected lookup result to be a struct");
return structDecl;
}
// Otherwise, synthesize a new struct.
auto *diffableProto = C.getProtocol(KnownProtocolKind::Differentiable);
auto diffableType = TypeLoc::withoutLoc(diffableProto->getDeclaredInterfaceType());
auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic);
auto addArithType = TypeLoc::withoutLoc(addArithProto->getDeclaredInterfaceType());
// By definition, `TangentVector` must conform to `Differentiable` and
// `AdditiveArithmetic`.
SmallVector<TypeLoc, 4> inherited{diffableType, addArithType};
// Cache original members and their associated types for later use.
SmallVector<VarDecl *, 8> diffProperties;
getStoredPropertiesForDifferentiation(nominal, parentDC, diffProperties);
auto *structDecl =
new (C) StructDecl(SourceLoc(), C.Id_TangentVector, SourceLoc(),
/*Inherited*/ C.AllocateCopy(inherited),
/*GenericParams*/ {}, parentDC);
structDecl->setImplicit();
structDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true);
// Add stored properties to the `TangentVector` struct.
for (auto *member : diffProperties) {
// Add a tangent stored property to the `TangentVector` struct, with the
// name and `TangentVector` type of the original property.
auto *tangentProperty = new (C) VarDecl(
member->isStatic(), member->getIntroducer(), member->isCaptureList(),
/*NameLoc*/ SourceLoc(), member->getName(), structDecl);
// Note: `tangentProperty` is not marked as implicit here, because that
// incorrectly affects memberwise initializer synthesis.
auto memberContextualType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
auto memberTanType =
getTangentVectorInterfaceType(memberContextualType, parentDC);
tangentProperty->setInterfaceType(memberTanType);
Pattern *memberPattern = NamedPattern::createImplicit(C, tangentProperty);
memberPattern->setType(memberTanType);
memberPattern =
TypedPattern::createImplicit(C, memberPattern, memberTanType);
memberPattern->setType(memberTanType);
auto *memberBinding = PatternBindingDecl::createImplicit(
C, StaticSpellingKind::None, memberPattern, /*initExpr*/ nullptr,
structDecl);
structDecl->addMember(tangentProperty);
structDecl->addMember(memberBinding);
tangentProperty->copyFormalAccessFrom(member,
/*sourceIsParentContext*/ true);
tangentProperty->setSetterAccess(member->getFormalAccess());
// Cache the tangent property.
C.evaluator.cacheOutput(TangentStoredPropertyRequest{member, CanType()},
TangentPropertyInfo(tangentProperty));
// Now that the original property has a corresponding tangent property, it
// should be marked `@differentiable` so that the differentiation transform
// will synthesize derivative functions for its accessors. We only add this
// to public stored properties, because their access outside the module will
// go through accessor declarations.
if (member->getEffectiveAccess() > AccessLevel::Internal &&
!member->getAttrs().hasAttribute<DifferentiableAttr>()) {
auto *getter = member->getSynthesizedAccessor(AccessorKind::Get);
(void)getter->getInterfaceType();
// If member or its getter already has a `@differentiable` attribute,
// continue.
if (member->getAttrs().hasAttribute<DifferentiableAttr>() ||
getter->getAttrs().hasAttribute<DifferentiableAttr>())
continue;
GenericSignature derivativeGenericSignature =
getter->getGenericSignature();
// If the parent declaration context is an extension, the nominal type may
// conditionally conform to `Differentiable`. Use the extension generic
// requirements in getter `@differentiable` attributes.
if (auto *extDecl = dyn_cast<ExtensionDecl>(parentDC->getAsDecl()))
if (auto extGenSig = extDecl->getGenericSignature())
derivativeGenericSignature = extGenSig;
auto *diffableAttr = DifferentiableAttr::create(
getter, /*implicit*/ true, SourceLoc(), SourceLoc(),
/*linear*/ false, /*parameterIndices*/ IndexSubset::get(C, 1, {0}),
derivativeGenericSignature);
member->getAttrs().add(diffableAttr);
}
}
// If nominal type is `@_fixed_layout`, also mark `TangentVector` struct as
// `@_fixed_layout`.
if (nominal->getAttrs().hasAttribute<FixedLayoutAttr>())
addFixedLayoutAttr(structDecl);
// If nominal type is `@frozen`, also mark `TangentVector` struct as
// `@frozen`.
if (nominal->getAttrs().hasAttribute<FrozenAttr>())
structDecl->getAttrs().add(new (C) FrozenAttr(/*implicit*/ true));
// If nominal type is `@usableFromInline`, also mark `TangentVector` struct as
// `@usableFromInline`.
if (nominal->getAttrs().hasAttribute<UsableFromInlineAttr>())
structDecl->getAttrs().add(new (C) UsableFromInlineAttr(/*implicit*/ true));
// The implicit memberwise constructor must be explicitly created so that it
// can called in `AdditiveArithmetic` and `Differentiable` methods. Normally,
// the memberwise constructor is synthesized during SILGen, which is too late.
TypeChecker::addImplicitConstructors(structDecl);
// After memberwise initializer is synthesized, mark members as implicit.
for (auto *member : structDecl->getStoredProperties())
member->setImplicit();
derived.addMembersToConformanceContext({structDecl});
return structDecl;
}
/// Diagnose stored properties in the nominal that do not have an explicit
/// `@noDerivative` attribute, but either:
/// - Do not conform to `Differentiable`.
/// - Are a `let` stored property.
/// Emit a warning and a fixit so that users will make the attribute explicit.
static void checkAndDiagnoseImplicitNoDerivative(ASTContext &Context,
NominalTypeDecl *nominal,
DeclContext *DC) {
// If nominal type can conform to `AdditiveArithmetic`, suggest adding a
// conformance to `AdditiveArithmetic` in fix-its.
// `Differentiable` protocol requirements all have default implementations
// when `Self` conforms to `AdditiveArithmetic`, so `Differentiable`
// derived conformances will no longer be necessary.
bool nominalCanDeriveAdditiveArithmetic =
DerivedConformance::canDeriveAdditiveArithmetic(nominal, DC);
auto *diffableProto = Context.getProtocol(KnownProtocolKind::Differentiable);
// Check all stored properties.
for (auto *vd : nominal->getStoredProperties()) {
// Peer through property wrappers: use original wrapped properties.
if (auto *originalProperty = vd->getOriginalWrappedProperty()) {
// Skip wrapped properties with `@noDerivative` attribute.
if (originalProperty->getAttrs().hasAttribute<NoDerivativeAttr>())
continue;
// Diagnose wrapped properties whose property wrappers do not define
// `wrappedValue.set`. `mutating func move(along:)` cannot be synthesized
// to update these properties.
if (!originalProperty->isSettable(DC)) {
auto *wrapperDecl =
vd->getInterfaceType()->getNominalOrBoundGenericNominal();
auto loc =
originalProperty->getAttributeInsertionLoc(/*forModifier*/ false);
Context.Diags
.diagnose(
loc,
diag::
differentiable_immutable_wrapper_implicit_noderivative_fixit,
wrapperDecl->getName(), nominal->getName(),
nominalCanDeriveAdditiveArithmetic)
.fixItInsert(loc, "@noDerivative ");
// Add an implicit `@noDerivative` attribute.
originalProperty->getAttrs().add(
new (Context) NoDerivativeAttr(/*Implicit*/ true));
continue;
}
// Use the original wrapped property.
vd = originalProperty;
}
if (vd->getInterfaceType()->hasError())
continue;
// Skip stored properties with `@noDerivative` attribute.
if (vd->getAttrs().hasAttribute<NoDerivativeAttr>())
continue;
// Check whether to diagnose stored property.
auto varType = DC->mapTypeIntoContext(vd->getValueInterfaceType());
bool conformsToDifferentiable =
!TypeChecker::conformsToProtocol(varType, diffableProto, nominal)
.isInvalid();
// If stored property should not be diagnosed, continue.
if (conformsToDifferentiable && !vd->isLet())
continue;
// Otherwise, add an implicit `@noDerivative` attribute.
vd->getAttrs().add(new (Context) NoDerivativeAttr(/*Implicit*/ true));
auto loc = vd->getAttributeInsertionLoc(/*forModifier*/ false);
assert(loc.isValid() && "Expected valid source location");
// Diagnose properties that do not conform to `Differentiable`.
if (!conformsToDifferentiable) {
Context.Diags
.diagnose(
loc,
diag::differentiable_nondiff_type_implicit_noderivative_fixit,
vd->getName(), vd->getType(), nominal->getName(),
nominalCanDeriveAdditiveArithmetic)
.fixItInsert(loc, "@noDerivative ");
continue;
}
// Otherwise, diagnose `let` property.
Context.Diags
.diagnose(loc,
diag::differentiable_let_property_implicit_noderivative_fixit,
nominal->getName(), nominalCanDeriveAdditiveArithmetic)
.fixItInsert(loc, "@noDerivative ");
}
}
/// Get or synthesize `TangentVector` struct type.
static std::pair<Type, TypeDecl *>
getOrSynthesizeTangentVectorStructType(DerivedConformance &derived) {
auto *parentDC = derived.getConformanceContext();
auto *nominal = derived.Nominal;
auto &C = nominal->getASTContext();
// Get or synthesize `TangentVector` struct.
auto *tangentStruct =
getOrSynthesizeTangentVectorStruct(derived, C.Id_TangentVector);
if (!tangentStruct)
return std::make_pair(nullptr, nullptr);
// Check and emit warnings for implicit `@noDerivative` members.
checkAndDiagnoseImplicitNoDerivative(C, nominal, parentDC);
// Return the `TangentVector` struct type.
return std::make_pair(
parentDC->mapTypeIntoContext(
tangentStruct->getDeclaredInterfaceType()),
tangentStruct);
}
/// Synthesize the `TangentVector` struct type.
static std::pair<Type, TypeDecl *>
deriveDifferentiable_TangentVectorStruct(DerivedConformance &derived) {
auto *parentDC = derived.getConformanceContext();
auto *nominal = derived.Nominal;
// If nominal type can derive `TangentVector` as the contextual `Self` type,
// return it.
if (canDeriveTangentVectorAsSelf(nominal, parentDC))
return std::make_pair(parentDC->getSelfTypeInContext(), nullptr);
// Otherwise, get or synthesize `TangentVector` struct type.
return getOrSynthesizeTangentVectorStructType(derived);
}
ValueDecl *DerivedConformance::deriveDifferentiable(ValueDecl *requirement) {
// Diagnose unknown requirements.
if (requirement->getBaseName() != Context.Id_move &&
requirement->getBaseName() != Context.Id_zeroTangentVectorInitializer) {
Context.Diags.diagnose(requirement->getLoc(),
diag::broken_differentiable_requirement);
return nullptr;
}
// Diagnose conformances in disallowed contexts.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
// Start an error diagnostic before attempting derivation.
// If derivation succeeds, cancel the diagnostic.
DiagnosticTransaction diagnosticTransaction(Context.Diags);
ConformanceDecl->diagnose(diag::type_does_not_conform,
Nominal->getDeclaredType(), getProtocolType());
requirement->diagnose(diag::no_witnesses,
getProtocolRequirementKind(requirement),
requirement->getName(), getProtocolType(),
/*AddFixIt=*/false);
// If derivation is possible, cancel the diagnostic and perform derivation.
if (canDeriveDifferentiable(Nominal, getConformanceContext(), requirement)) {
diagnosticTransaction.abort();
if (requirement->getBaseName() == Context.Id_move)
return deriveDifferentiable_move(*this);
if (requirement->getBaseName() == Context.Id_zeroTangentVectorInitializer)
return deriveDifferentiable_zeroTangentVectorInitializer(*this);
}
// Otheriwse, return nullptr.
return nullptr;
}
std::pair<Type, TypeDecl *>
DerivedConformance::deriveDifferentiable(AssociatedTypeDecl *requirement) {
// Diagnose unknown requirements.
if (requirement->getBaseName() != Context.Id_TangentVector) {
Context.Diags.diagnose(requirement->getLoc(),
diag::broken_differentiable_requirement);
return std::make_pair(nullptr, nullptr);
}
// Start an error diagnostic before attempting derivation.
// If derivation succeeds, cancel the diagnostic.
DiagnosticTransaction diagnosticTransaction(Context.Diags);
ConformanceDecl->diagnose(diag::type_does_not_conform,
Nominal->getDeclaredType(), getProtocolType());
requirement->diagnose(diag::no_witnesses_type, requirement->getName());
// If derivation is possible, cancel the diagnostic and perform derivation.
if (canDeriveDifferentiable(Nominal, getConformanceContext(), requirement)) {
diagnosticTransaction.abort();
return deriveDifferentiable_TangentVectorStruct(*this);
}
// Otherwise, return nullptr.
return std::make_pair(nullptr, nullptr);
}