forked from vgvassilev/clad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseForwardModeVisitor.cpp
More file actions
2415 lines (2193 loc) · 95.3 KB
/
Copy pathBaseForwardModeVisitor.cpp
File metadata and controls
2415 lines (2193 loc) · 95.3 KB
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
//--------------------------------------------------------------------*- C++ -*-
// clad - the C++ Clang-based Automatic Differentiator
// version: $Id: ClangPlugin.cpp 7 2013-06-01 22:48:03Z v.g.vassilev@gmail.com $
// author: Vassil Vassilev <vvasilev-at-cern.ch>
//------------------------------------------------------------------------------
#include "clad/Differentiator/BaseForwardModeVisitor.h"
#include "ConstantFolder.h"
#include "clad/Differentiator/CladUtils.h"
#include "clad/Differentiator/DerivativeBuilder.h"
#include "clad/Differentiator/DiffMode.h"
#include "clad/Differentiator/DiffPlanner.h"
#include "clad/Differentiator/ErrorEstimator.h"
#include "clad/Differentiator/ParseDiffArgsTypes.h"
#include "clad/Differentiator/VisitorBase.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Basic/Version.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <cassert>
#include <string>
#include <vector>
#include "clad/Differentiator/Compatibility.h"
using namespace clang;
namespace clad {
BaseForwardModeVisitor::BaseForwardModeVisitor(DerivativeBuilder& builder,
const DiffRequest& request)
: VisitorBase(builder, request) {}
BaseForwardModeVisitor::~BaseForwardModeVisitor() {}
bool IsRealNonReferenceType(QualType T) {
return T.getNonReferenceType()->isRealType();
}
DerivativeAndOverload BaseForwardModeVisitor::Derive() {
const FunctionDecl* FD = m_DiffReq.Function;
assert(m_DiffReq.Mode == DiffMode::forward ||
m_DiffReq.Mode == DiffMode::pushforward ||
m_DiffReq.Mode == DiffMode::vector_pushforward);
assert(!m_DerivativeInFlight &&
"Doesn't support recursive diff. Use DiffPlan.");
PrettyStackTraceDerivative CrashInfo(m_DiffReq, m_Blocks, m_Sema,
&m_CurVisitedStmt);
llvm::SaveAndRestore<bool> saveInFlight(m_DerivativeInFlight,
/*NewValue=*/true);
if (m_DiffReq.Mode == DiffMode::forward) {
DiffInputVarsInfo DVI = m_DiffReq.DVI;
// FIXME: Shouldn't we give error here that no arg is specified?
if (DVI.empty())
return {};
DiffInputVarInfo diffVarInfo = DVI.back();
// Check that only one arg is requested and if the arg requested is of array
// or pointer type, only one of the indices have been requested
if (DVI.size() > 1 || (isArrayOrPointerType(diffVarInfo.param->getType()) &&
(diffVarInfo.paramIndexInterval.size() != 1))) {
SourceLocation L = m_DiffReq.Args ? m_DiffReq.Args->getBeginLoc() : noLoc;
diag(DiagnosticsEngine::Error, L,
"forward mode differentiation w.r.t. several parameters at once is "
"not supported; call 'clad::differentiate' for each parameter")
<< L;
return {};
}
// FIXME: implement gradient-vector products to fix the issue.
assert((DVI.size() == 1) &&
"nested forward mode differentiation for several args is broken");
// FIXME: Differentiation variable cannot always be represented just by
// `ValueDecl*` variable. For example -- `u.mem1.mem2,`, `arr[7]` etc.
// FIXME: independent variable is misleading terminology, what we actually
// mean here is 'variable' with respect to which differentiation is being
// performed. Mathematically, independent variables are all the function
// parameters, thus, does not convey the intendend meaning.
m_IndependentVar = DVI.back().param;
// If param is not real (i.e. floating point or integral), a pointer to a
// real type, or an array of a real type we cannot differentiate it.
// FIXME: we should support custom numeric types in the future.
if (isArrayOrPointerType(m_IndependentVar->getType())) {
if (!m_IndependentVar->getType()
->getPointeeOrArrayElementType()
->isRealType()) {
SourceLocation L = m_IndependentVar->getBeginLoc();
diag(DiagnosticsEngine::Error, L,
"attempted differentiation w.r.t. parameter %0 which is not"
" array or pointer of real type")
<< m_IndependentVar << L;
return {};
}
m_IndependentVarIndex = diffVarInfo.paramIndexInterval.Start;
} else {
QualType T = m_IndependentVar->getType();
bool isField = false;
if (auto* RD = diffVarInfo.param->getType()->getAsCXXRecordDecl()) {
llvm::SmallVector<llvm::StringRef, 4> ref(diffVarInfo.fields.begin(),
diffVarInfo.fields.end());
T = utils::ComputeMemExprPathType(m_Sema, RD, ref);
isField = true;
}
if (!IsRealNonReferenceType(T)) {
SourceLocation L = m_DiffReq.Args->getBeginLoc();
diag(DiagnosticsEngine::Error, L,
"attempted differentiation w.r.t. %select{member|parameter}0 '%1' "
"which is not of real type")
<< isField << diffVarInfo.source << L;
return {};
}
}
}
// Check if the function is already declared as a custom derivative.
std::string gradientName = m_DiffReq.ComputeDerivativeName();
// FIXME: We should not use const_cast to get the decl context here.
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
auto* DC = const_cast<DeclContext*>(m_DiffReq->getDeclContext());
IdentifierInfo* II = &m_Context.Idents.get(gradientName);
SourceLocation validLoc{m_DiffReq->getLocation()};
DeclarationNameInfo name(II, validLoc);
llvm::SaveAndRestore<DeclContext*> SaveContext(m_Sema.CurContext);
llvm::SaveAndRestore<Scope*> SaveScope(getCurrentScope());
m_Sema.CurContext = DC;
QualType derivedFnType = GetDerivativeType();
// `result` owns the namespace Scopes cloneFunction opens; its
// destructor pops them before SaveScope restores.
ClonedFunction result =
m_Builder.cloneFunction(FD, *this, DC, validLoc, name, derivedFnType);
FunctionDecl* derivedFD = result.fd;
m_Derivative = derivedFD;
// Function declaration scope
beginScope(Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope |
Scope::DeclScope);
m_Sema.PushFunctionScope();
m_Sema.PushDeclContext(getCurrentScope(), m_Derivative);
llvm::SmallVector<ParmVarDecl*, 16> params;
SetupDerivativeParameters(params);
m_Derivative->setParams(params);
m_Derivative->setBody(nullptr);
m_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
if (!m_DiffReq.DeclarationOnly) {
m_Sema.ActOnStartOfFunctionDef(getCurrentScope(), m_Derivative);
// Function body scope
beginScope(Scope::FnScope | Scope::DeclScope);
m_DerivativeFnScope = getCurrentScope();
beginBlock();
// FIXME: Remove the override in VectorPushForwardModeVisitor.
if (m_DiffReq.Mode == DiffMode::vector_pushforward)
ExecuteInsidePushforwardFunctionBlock();
if (m_DiffReq.Mode == DiffMode::forward)
GenerateSeeds(derivedFD);
Stmt* BodyDiff = Visit(FD->getBody()).getStmt();
if (auto* CS = dyn_cast<CompoundStmt>(BodyDiff))
for (Stmt* S : CS->body())
addToCurrentBlock(S);
else
addToCurrentBlock(BodyDiff);
Stmt* fnBody = endBlock();
// FIXME: Enable this when we vgvassilev/clad#367 (removing goto stmts).
// // If ActOnFinishFunctionBody should pop the current DeclContext.
// bool IsInstantiation = false;
// m_Sema.ActOnFinishFunctionBody(m_Derivative, fnBody, IsInstantiation);
m_Derivative->setBody(fnBody);
m_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
endScope(); // Function body scope
}
// FIXME: Drop the static specifier for the out-of-line definitions.
if (auto* RD = dyn_cast<RecordDecl>(m_Derivative->getDeclContext())) {
DeclContext::lookup_result R =
RD->getPrimaryContext()->lookup(m_Derivative->getDeclName());
FunctionDecl* FoundFD =
R.empty() ? nullptr : dyn_cast<FunctionDecl>(R.front());
if (!RD->isLambda() && !R.empty() &&
!m_Builder.m_Scheduler.getDerivedFns().IsCladDerivative(FoundFD)) {
Sema::NestedNameSpecInfo IdInfo(RD->getIdentifier(), noLoc, noLoc,
/*ObjectType=*/nullptr);
// FIXME: Address nested classes where SS should be set.
CXXScopeSpec SS;
m_Sema.BuildCXXNestedNameSpecifier(getCurrentScope(), IdInfo,
/*EnteringContext=*/true, SS,
/*ScopeLookupResult=*/nullptr,
/*ErrorRecoveryLookup=*/false);
m_Derivative->setQualifierInfo(SS.getWithLocInContext(m_Context));
m_Derivative->setLexicalDeclContext(RD->getParent());
}
}
endScope(); // Function decl scope
return DerivativeAndOverload{result.fd,
/*OverloadFunctionDecl=*/nullptr};
}
void BaseForwardModeVisitor::SetupDerivativeParameters(
llvm::SmallVectorImpl<ParmVarDecl*>& params) {
const FunctionDecl* FD = m_DiffReq.Function;
const FunctionDecl* FDPattern = nullptr;
unsigned FDPatternNumParams = 0;
if (FD->isTemplateInstantiation()) {
FDPattern = FD->getTemplateInstantiationPattern();
FDPatternNumParams = FDPattern->getNumParams();
}
for (unsigned i = 0, n = FD->getNumParams(); i < n; ++i) {
const ParmVarDecl* PVD = FD->getParamDecl(i);
IdentifierInfo* PVDII = PVD->getIdentifier();
// Implicitly created special member functions have no parameter names.
if (!PVD->getDeclName())
PVDII = CreateUniqueIdentifier("param");
if (FDPattern) {
const ParmVarDecl* OrigPVD =
i >= FDPatternNumParams
? FDPattern->getParamDecl(FDPatternNumParams - 1)
: FDPattern->getParamDecl(i);
if (OrigPVD->isParameterPack())
PVDII = CreateUniqueIdentifier(PVDII->getName());
}
auto* newPVD = CloneParmVarDecl(PVD, PVDII,
/*pushOnScopeChains=*/true,
/*cloneDefaultArg=*/false);
// Point m_IndependentVar to the argument of the newly created param.
if (PVD == m_IndependentVar)
m_IndependentVar = newPVD;
// We can't use lookup-based replacements
if (PVD->getDeclName() != newPVD->getDeclName())
m_DeclReplacements[PVD] = newPVD;
params.push_back(newPVD);
}
if (m_DiffReq.Mode == DiffMode::forward)
return;
bool HasThis = false;
// If we are differentiating an instance member function then create a
// parameter for representing derivative of `this` pointer with respect to the
// independent parameter.
if (const auto* MD = dyn_cast<CXXMethodDecl>(FD)) {
const CXXRecordDecl* RD = MD->getParent();
if (MD->isInstance() && !RD->isLambda()) {
IdentifierInfo* dThisII = &m_Context.Idents.get("_d_this");
auto* dPVD = utils::BuildParmVarDecl(m_Sema, m_Sema.CurContext, dThisII,
MD->getThisType());
m_Sema.PushOnScopeChains(dPVD, getCurrentScope(), /*AddToContext=*/false);
params.push_back(dPVD);
// FIXME: Replace m_ThisExprDerivative in favor of lookups of _d_this.
m_ThisExprDerivative = BuildDeclRef(dPVD);
HasThis = true;
}
}
for (size_t i = 0, e = params.size() - HasThis; i < e; ++i) {
const ParmVarDecl* PVD = params[i];
if (!utils::IsDifferentiableType(PVD->getType()))
continue;
IdentifierInfo* II = &m_Context.Idents.get("_d_" + PVD->getNameAsString());
QualType diffTy = utils::GetParameterDerivativeType(m_Sema, m_DiffReq.Mode,
PVD->getType());
auto* dPVD = utils::BuildParmVarDecl(m_Sema, m_Derivative, II, diffTy,
PVD->getStorageClass());
params.push_back(dPVD);
m_Variables[PVD] = {dPVD};
}
}
void BaseForwardModeVisitor::GenerateSeeds(const clang::FunctionDecl* dFD) {
// For each function parameter variable, store its derivative value.
for (const ParmVarDecl* param : dFD->parameters()) {
// We cannot create derivatives of reference type since seed value is
// always a constant (r-value). We assume that all the arguments have no
// relation among them, thus it is safe (correct) to use the corresponding
// non-reference type for creating the derivatives.
QualType dParamType = param->getType().getNonReferenceType();
Expr* dParam = nullptr;
if (!utils::IsDifferentiableType(dParamType))
continue;
// If the parameter type decayed const array type, we can still initialize
// it. Therefore, we don't have to produce the error.
if (const auto* DT = dyn_cast<DecayedType>(dParamType))
dParamType = DT->getOriginalType();
if (dParamType->isConstantArrayType()) {
if (param == m_IndependentVar)
continue;
dParam = getZeroInit(dParamType);
} else if (dParamType->isRealType()) {
// If param is independent variable, its derivative is 1, otherwise 0.
int dValue = (param == m_IndependentVar);
dParam =
ConstantFolder::synthesizeLiteral(m_Context.IntTy, m_Context, dValue);
} else if (utils::isArrayOrPointerType(dParamType)) {
// We cannot initialize a pointer array adjoint ourselves.
// Produce an error.
if (param != m_IndependentVar &&
!utils::GetValueType(dParamType).isConstQualified()) {
SourceLocation L = param->getLocation();
diag(DiagnosticsEngine::Error, L,
"dependent non-const pointer and array parameters "
"are not supported; differentiate w.r.t. %0 or mark it const")
<< param << L;
}
continue;
}
// For each function arg, create a variable _d_arg to store derivatives
// of potential reassignments, e.g.:
// double f_darg0(double x, double y) {
// double _d_x = 1;
// double _d_y = 0;
// ...
auto* dParamDecl =
BuildVarDecl(dParamType, "_d_" + param->getNameAsString(), dParam);
addToCurrentBlock(BuildDeclStmt(dParamDecl));
dParam = BuildDeclRef(dParamDecl);
if (dParamType->isRecordType() && param == m_IndependentVar) {
DiffInputVarInfo diffVarInfo = m_DiffReq.DVI.back();
llvm::SmallVector<llvm::StringRef, 4> ref(diffVarInfo.fields.begin(),
diffVarInfo.fields.end());
Expr* memRef =
utils::BuildMemberExpr(m_Sema, getCurrentScope(), dParam, ref);
assert(memRef->getType()->isRealType() &&
"Forward mode can only differentiate w.r.t builtin scalar "
"numerical types.");
addToCurrentBlock(BuildOp(BinaryOperatorKind::BO_Assign, memRef,
ConstantFolder::synthesizeLiteral(
m_Context.IntTy, m_Context, /*val=*/1)));
}
// Memorize the derivative of param, i.e. whenever the param is visited
// in the future, it's derivative dParam is found (unless reassigned with
// something new).
m_Variables[param] = {dParamDecl};
}
if (const auto* MD = dyn_cast<CXXMethodDecl>(dFD)) {
// We cannot create derivative of lambda yet because lambdas default
// constructor is deleted.
if (MD->isInstance() && !MD->getParent()->isLambda()) {
QualType thisObjectType =
clad_compat::CXXMethodDecl_GetThisObjectType(m_Sema, MD);
QualType thisType = MD->getThisType();
// Here we are effectively doing:
// ```
// Class _d_this_obj;
// Class* _d_this = &_d_this_obj;
// ```
// We are not creating `this` expression derivative using `new` because
// then we would be responsible for freeing the memory as well and its
// more convenient to let compiler handle the object lifecycle.
VarDecl* derivativeVD = BuildVarDecl(thisObjectType, "_d_this_obj");
DeclRefExpr* derivativeE = BuildDeclRef(derivativeVD);
VarDecl* thisExprDerivativeVD =
BuildVarDecl(thisType, "_d_this",
BuildOp(UnaryOperatorKind::UO_AddrOf, derivativeE));
addToCurrentBlock(BuildDeclStmt(derivativeVD));
addToCurrentBlock(BuildDeclStmt(thisExprDerivativeVD));
m_ThisExprDerivative = BuildDeclRef(thisExprDerivativeVD);
}
}
SourceLocation validLoc{m_DiffReq->getLocation()};
// Create derived variable for each member variable if we are
// differentiating a call operator.
if (m_DiffReq.Functor) {
for (FieldDecl* fieldDecl : m_DiffReq.Functor->fields()) {
Expr* dInitializer = nullptr;
QualType fieldType = fieldDecl->getType();
if (const auto* arrType = dyn_cast<ConstantArrayType>(fieldType)) {
if (!arrType->getElementType()->isRealType())
continue;
auto arrSize = arrType->getSize().getZExtValue();
std::vector<Expr*> dArrVal;
// Create an initializer list to initialize derived variable created
// for array member variable.
// For example, if we are differentiating wrt arr[3], then
// ```
// double arr[7];
// ```
// will get differentiated to,
//
// ```
// double _d_arr[7] = {0, 0, 0, 1, 0, 0, 0};
// ```
for (size_t i = 0; i < arrSize; ++i) {
int dValue =
(fieldDecl == m_IndependentVar && i == m_IndependentVarIndex);
auto* dValueLiteral = ConstantFolder::synthesizeLiteral(
m_Context.IntTy, m_Context, dValue);
dArrVal.push_back(dValueLiteral);
}
dInitializer = m_Sema.ActOnInitList(validLoc, dArrVal, validLoc).get();
} else if (const auto* ptrType =
dyn_cast<PointerType>(fieldType.getTypePtr())) {
if (!ptrType->getPointeeType()->isRealType())
continue;
// Pointer member variables should be initialised by `nullptr`.
dInitializer = m_Sema.ActOnCXXNullPtrLiteral(validLoc).get();
} else {
int dValue = (fieldDecl == m_IndependentVar);
dInitializer = ConstantFolder::synthesizeLiteral(m_Context.IntTy,
m_Context, dValue);
}
VarDecl* derivedFieldDecl =
BuildVarDecl(fieldType.getNonReferenceType(),
"_d_" + fieldDecl->getNameAsString(), dInitializer);
addToCurrentBlock(BuildDeclStmt(derivedFieldDecl));
m_Variables.emplace(fieldDecl, AdjointInfo{derivedFieldDecl});
}
}
}
StmtDiff BaseForwardModeVisitor::VisitStmt(const Stmt* S) {
diagUnsupported(S);
// Unknown stmt, just clone it.
return StmtDiff(Clone(S));
}
StmtDiff BaseForwardModeVisitor::VisitCompoundStmt(const CompoundStmt* CS) {
ScopeRAII compoundScope(*this, Scope::DeclScope);
beginBlock();
for (Stmt* S : CS->body()) {
StmtDiff SDiff = Visit(S);
addToCurrentBlock(SDiff.getStmt_dx());
addToCurrentBlock(SDiff.getStmt());
}
CompoundStmt* Result = endBlock();
// Differentation of CompundStmt produces another CompoundStmt with both
// original and derived statements, i.e. Stmt() is Result and Stmt_dx() is
// null.
return StmtDiff(Result);
}
StmtDiff BaseForwardModeVisitor::VisitIfStmt(const IfStmt* If) {
// Control scope of the IfStmt. E.g., in if (double x = ...) {...}, x goes
// to this scope.
ScopeRAII ifScope(*this, Scope::DeclScope | Scope::ControlScope);
// Create a block "around" if statement, e.g:
// {
// ...
// if (...) {...}
// }
beginBlock();
const Stmt* init = If->getInit();
StmtDiff initResult = init ? Visit(init) : StmtDiff{};
// If there is Init, it's derivative will be output in the block before if:
// E.g., for:
// if (int x = 1; ...) {...}
// result will be:
// {
// int _d_x = 0;
// if (int x = 1; ...) {...}
// }
// This is done to avoid variable names clashes.
addToCurrentBlock(initResult.getStmt_dx());
VarDecl* condVarClone = nullptr;
if (const VarDecl* condVarDecl = If->getConditionVariable()) {
DeclDiff<VarDecl> condVarDeclDiff = DifferentiateVarDecl(condVarDecl);
condVarClone = condVarDeclDiff.getDecl();
if (condVarDeclDiff.getDecl_dx())
addToCurrentBlock(BuildDeclStmt(condVarDeclDiff.getDecl_dx()));
}
// Condition is just cloned as it is, not derived.
// FIXME: if condition changes one of the variables, it may be reasonable
// to derive it, e.g.
// if (x += x) {...}
// should result in:
// {
// _d_y += _d_x
// if (y += x) {...}
// }
Expr* cond = Clone(If->getCond());
auto VisitBranch = [this](const Stmt* Branch) -> Stmt* {
if (!Branch)
return nullptr;
if (isa<CompoundStmt>(Branch)) {
StmtDiff BranchDiff = Visit(Branch);
return BranchDiff.getStmt();
} else {
beginBlock();
ScopeRAII branchScope(*this, Scope::DeclScope);
StmtDiff BranchDiff = Visit(Branch);
for (Stmt* S : BranchDiff.getBothStmts())
addToCurrentBlock(S);
CompoundStmt* Block = endBlock();
if (Block->size() == 1)
return Block->body_front();
else
return Block;
}
};
Stmt* thenDiff = VisitBranch(If->getThen());
Stmt* elseDiff = VisitBranch(If->getElse());
Stmt* ifDiff = clad_compat::IfStmt_Create(
m_Context, noLoc, If->isConstexpr(), initResult.getStmt(), condVarClone,
cond, noLoc, noLoc, thenDiff, noLoc, elseDiff);
addToCurrentBlock(ifDiff);
CompoundStmt* Block = endBlock();
// If IfStmt is the only statement in the block, remove the block:
// {
// if (...) {...}
// }
// ->
// if (...) {...}
StmtDiff Result = (Block->size() == 1) ? StmtDiff(ifDiff) : StmtDiff(Block);
return Result;
}
StmtDiff BaseForwardModeVisitor::VisitConditionalOperator(
const ConditionalOperator* CO) {
Expr* cond = Clone(CO->getCond());
// FIXME: fix potential side-effects from evaluating both sides of
// conditional.
StmtDiff ifTrueDiff = Visit(CO->getTrueExpr());
StmtDiff ifFalseDiff = Visit(CO->getFalseExpr());
cond = StoreAndRef(cond);
cond = m_Sema
.ActOnCondition(getCurrentScope(), noLoc, cond,
Sema::ConditionKind::Boolean)
.get()
.second;
Expr* condExpr =
m_Sema
.ActOnConditionalOp(noLoc, noLoc, cond, ifTrueDiff.getExpr(),
ifFalseDiff.getExpr())
.get();
if (condExpr->getType()->isVoidType())
return StmtDiff(condExpr, nullptr);
// cond is already used by the value conditional above; clone it for the
// derivative conditional so the two do not share the stored condition.
Expr* condExprDiff =
m_Sema
.ActOnConditionalOp(noLoc, noLoc, CloneNode(cond),
ifTrueDiff.getExpr_dx(), ifFalseDiff.getExpr_dx())
.get();
return StmtDiff(condExpr, condExprDiff);
}
StmtDiff
BaseForwardModeVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt* FRS) {
ScopeRAII rangeScope(*this, Scope::DeclScope | Scope::ControlScope |
Scope::BreakScope | Scope::ContinueScope);
// Visiting for range-based ststement produces __range1, __begin1 and __end1
// variables, so for(auto i: a){
// ...
//}
//
// is equivalent to
//
// auto&& __range1 = a
// auto __begin1 = __range1;
// auto __end1 = __range1 + OUL
// for(;__begin != __end1; ++__begin){
// auto i = *__begin1;
// ...
//}
const Stmt* RangeDecl = FRS->getRangeStmt();
const Stmt* BeginDecl = FRS->getBeginStmt();
const Stmt* EndDecl = FRS->getEndStmt();
StmtDiff VisitRange = Visit(RangeDecl);
StmtDiff VisitBegin = Visit(BeginDecl);
StmtDiff VisitEnd = Visit(EndDecl);
addToCurrentBlock(VisitRange.getStmt_dx());
addToCurrentBlock(VisitRange.getStmt());
addToCurrentBlock(VisitBegin.getStmt_dx());
addToCurrentBlock(VisitBegin.getStmt());
addToCurrentBlock(VisitEnd.getStmt());
// Build d_begin preincrementation.
auto* BeginAdjExpr = BuildDeclRef(
cast<VarDecl>(cast<DeclStmt>(VisitBegin.getStmt_dx())->getSingleDecl()));
// Build begin preincrementation.
Expr* IncAdjBegin = BuildOp(UO_PreInc, BeginAdjExpr);
auto* BeginVarDecl =
cast<VarDecl>(cast<DeclStmt>(VisitBegin.getStmt())->getSingleDecl());
DeclRefExpr* BeginExpr = BuildDeclRef(BeginVarDecl);
Expr* IncBegin = BuildOp(UO_PreInc, BeginExpr);
Expr* Inc = BuildOp(BO_Comma, IncAdjBegin, IncBegin);
auto* EndExpr = BuildDeclRef(
cast<VarDecl>(cast<DeclStmt>(VisitEnd.getStmt())->getSingleDecl()));
// Build begin != end condition. BeginExpr is already used by the increment
// above, so build a fresh reference to the begin iterator here.
Expr* cond = BuildOp(BO_NE, BuildDeclRef(BeginVarDecl), EndExpr);
const VarDecl* VD = FRS->getLoopVariable();
DeclDiff<VarDecl> VDDiff = DifferentiateVarDecl(VD);
// Differentiate body and add both Item and it's derivative.
Stmt* body = Clone(FRS->getBody());
Stmt* bodyResult = Visit(body).getStmt();
Visit(body).getStmt();
Stmt* bodyWithItem = utils::PrependAndCreateCompoundStmt(
m_Sema.getASTContext(), bodyResult, BuildDeclStmt(VDDiff.getDecl()));
bodyResult = utils::PrependAndCreateCompoundStmt(
m_Sema.getASTContext(), bodyWithItem, BuildDeclStmt(VDDiff.getDecl_dx()));
Stmt* forStmtDiff = new (m_Context)
ForStmt(m_Context, nullptr, cond, /*condVar=*/nullptr, Inc, bodyResult,
FRS->getForLoc(), FRS->getBeginLoc(), FRS->getEndLoc());
return StmtDiff(forStmtDiff);
}
StmtDiff BaseForwardModeVisitor::VisitForStmt(const ForStmt* FS) {
ScopeRAII forScope(*this, Scope::DeclScope | Scope::ControlScope |
Scope::BreakScope | Scope::ContinueScope);
beginBlock();
const Stmt* init = FS->getInit();
StmtDiff initDiff = init ? Visit(init) : StmtDiff{};
addToCurrentBlock(initDiff.getStmt_dx());
StmtDiff condDiff = Clone(FS->getCond());
Expr* cond = condDiff.getExpr();
// The declaration in the condition needs to be differentiated.
if (VarDecl* condVarDecl = FS->getConditionVariable()) {
// Here we create a fictional cond that is equal to the assignment used in
// the declaration. The declaration itself is thrown before the for-loop
// without any init value. The fictional condition is then differentiated as
// a normal condition would be (see below). For example, the declaration
// inside `for (;double t = x;) {}` will be first processed into the
// following code:
// ```
// {
// double t;
// for (;t = x;) {}
// }
// ```
// which will then get differentiated normally as a for-loop with a
// differentiable condition in the next section.
DeclDiff<VarDecl> condVarResult =
DifferentiateVarDecl(condVarDecl, /*ignoreInit=*/true);
VarDecl* condVarClone = condVarResult.getDecl();
if (condVarResult.getDecl_dx())
addToCurrentBlock(BuildDeclStmt(condVarResult.getDecl_dx()));
auto condInit = condVarClone->getInit();
SetDeclInit(condVarClone);
cond = BuildOp(BO_Assign, BuildDeclRef(condVarClone), condInit);
addToCurrentBlock(BuildDeclStmt(condVarClone));
}
// Condition differentiation.
// This adds support for assignments in conditions.
if (cond) {
cond = cond->IgnoreParenImpCasts();
// If it's a supported differentiable operator we wrap it back into
// parentheses and then visit. To ensure the correctness, a comma operator
// expression (cond_dx, cond) is generated and put instead of the condition.
// FIXME: Add support for other expressions in cond (comparisons, function
// calls, etc.). Ideally, we should be able to simply always call
// Visit(cond)
auto* condBO = dyn_cast<BinaryOperator>(cond);
auto* condUO = dyn_cast<UnaryOperator>(cond);
// FIXME: Currently we only support logical and assignment operators.
if ((condBO && (condBO->isLogicalOp() || condBO->isAssignmentOp())) ||
condUO) {
condDiff = Visit(cond);
if (condDiff.getExpr_dx() && (!isUnusedResult(condDiff.getExpr_dx())))
cond = BuildOp(BO_Comma, BuildParens(condDiff.getExpr_dx()),
BuildParens(condDiff.getExpr()));
else
cond = condDiff.getExpr();
}
}
// Differentiate the increment expression of the for loop
const Expr* inc = FS->getInc();
beginBlock();
StmtDiff incDiff = inc ? Visit(inc) : StmtDiff{};
CompoundStmt* decls = endBlock();
Expr* incResult = nullptr;
if (decls->size()) {
// If differentiation of the increment produces a statement for
// temporary variable declaration, enclose the increment in lambda
// since only expressions are allowed in the increment part of the for
// loop. E.g.:
// for (...; ...; x = x * std::sin(x))
// ->
// for (int i = 0; i < 10; [&] {
// double _t1 = std::sin(x);
// _d_x = _d_x * _t1 + x * custom_derivatives::sin_darg0(x) * (_d_x);
// x = x * _t1;
// }())
incResult = wrapInLambda(*this, m_Sema, inc, [&] {
StmtDiff incDiff = inc ? Visit(inc) : StmtDiff{};
addToCurrentBlock(incDiff.getStmt_dx());
addToCurrentBlock(incDiff.getStmt());
});
} else if (incDiff.getExpr_dx() && incDiff.getExpr()) {
// If no declarations are required and only two Expressions are produced,
// join them with comma expression.
if (!isUnusedResult(incDiff.getExpr_dx()))
incResult = BuildOp(BO_Comma, BuildParens(incDiff.getExpr_dx()),
BuildParens(incDiff.getExpr()));
else
incResult = incDiff.getExpr();
} else if (incDiff.getExpr()) {
incResult = incDiff.getExpr();
}
// Build the derived for loop body.
const Stmt* body = FS->getBody();
Stmt* bodyResult = nullptr;
{
ScopeRAII bodyScope(*this, Scope::DeclScope);
beginBlock();
StmtDiff bodyVisited = Visit(body);
for (Stmt* S : bodyVisited.getBothStmts())
addToCurrentBlock(S);
bodyResult = utils::unwrapIfSingleStmt(endBlock());
}
Stmt* forStmtDiff = new (m_Context)
ForStmt(m_Context, initDiff.getStmt(), cond, /*condVar=*/nullptr,
incResult, bodyResult, noLoc, noLoc, noLoc);
addToCurrentBlock(forStmtDiff);
CompoundStmt* Block = endBlock();
StmtDiff Result =
(Block->size() == 1) ? StmtDiff(forStmtDiff) : StmtDiff(Block);
return Result;
}
StmtDiff BaseForwardModeVisitor::VisitReturnStmt(const ReturnStmt* RS) {
// If there is no return value, we must not attempt to differentiate
if (!RS->getRetValue())
return nullptr;
StmtDiff retValDiff = Visit(RS->getRetValue());
Stmt* returnStmt =
m_Sema.ActOnReturnStmt(noLoc, retValDiff.getExpr_dx(), getCurrentScope())
.get();
return StmtDiff(returnStmt);
}
StmtDiff BaseForwardModeVisitor::VisitParenExpr(const ParenExpr* PE) {
StmtDiff subStmtDiff = Visit(PE->getSubExpr());
return StmtDiff(BuildParens(subStmtDiff.getExpr()),
BuildParens(subStmtDiff.getExpr_dx()));
}
StmtDiff BaseForwardModeVisitor::VisitMemberExpr(const MemberExpr* ME) {
auto clonedME = dyn_cast<MemberExpr>(Clone(ME));
// Currently, we only differentiate member variables if we are
// differentiating a call operator.
if (m_DiffReq.Functor) {
if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) {
// Try to find the derivative of the member variable wrt independent
// variable
auto memberDecl = ME->getMemberDecl();
auto it = m_Variables.find(memberDecl);
if (it != std::end(m_Variables))
return StmtDiff(clonedME, buildAdjoint(it->second));
}
// Is not a real variable. Therefore, derivative is 0.
auto zero =
ConstantFolder::synthesizeLiteral(m_Context.IntTy, m_Context, 0);
return StmtDiff(clonedME, zero);
} else {
auto zero =
ConstantFolder::synthesizeLiteral(m_Context.DoubleTy, m_Context, 0);
if (clad::utils::hasNonDifferentiableAttribute(ME))
return {clonedME, zero};
auto baseDiff = Visit(ME->getBase());
// No derivative found for base. Therefore, derivative is 0.
if (baseDiff.getExpr_dx()->getType()->isVoidType())
return {clonedME, zero};
auto field = ME->getMemberDecl();
assert(!isa<FunctionDecl>(field) &&
"Member functions are not supported yet!");
auto clonedME = utils::BuildMemberExpr(
m_Sema, getCurrentScope(), baseDiff.getExpr(), field->getName());
// Here we are implicitly assuming that the derived type and the original
// types are same. This may not be necessarily true in the future.
auto derivedME = utils::BuildMemberExpr(
m_Sema, getCurrentScope(), baseDiff.getExpr_dx(), field->getName());
return {clonedME, derivedME};
}
}
StmtDiff BaseForwardModeVisitor::VisitInitListExpr(const InitListExpr* ILE) {
llvm::SmallVector<Expr*, 16> clonedExprs(ILE->getNumInits());
llvm::SmallVector<Expr*, 16> derivedExprs(ILE->getNumInits());
for (unsigned i = 0, e = ILE->getNumInits(); i < e; i++) {
StmtDiff ResultI = Visit(ILE->getInit(i));
clonedExprs[i] = ResultI.getExpr();
derivedExprs[i] = ResultI.getExpr_dx();
}
Expr* clonedILE = m_Sema.ActOnInitList(noLoc, clonedExprs, noLoc).get();
Expr* derivedILE = m_Sema.ActOnInitList(noLoc, derivedExprs, noLoc).get();
return StmtDiff(clonedILE, derivedILE);
}
StmtDiff
BaseForwardModeVisitor::VisitArraySubscriptExpr(const ArraySubscriptExpr* ASE) {
auto ASI = SplitArraySubscript(ASE);
QualType ExprTy = ASE->getType();
if (ExprTy->isPointerType())
ExprTy = ExprTy->getPointeeType();
ExprTy = ExprTy->getCanonicalTypeInternal();
const Expr* base = ASI.first;
const auto& Indices = ASI.second;
StmtDiff cloneDiff = Visit(base);
Expr* clonedBase = cloneDiff.getExpr();
llvm::SmallVector<Expr*, 4> clonedIndices(Indices.size());
std::transform(std::begin(Indices), std::end(Indices),
std::begin(clonedIndices),
[this](const Expr* E) { return Clone(E); });
Expr* cloned = BuildArraySubscript(clonedBase, clonedIndices);
// The index exprs are consumed by the primal subscript above; the derivative
// subscript below needs its own copies so the two do not share index nodes.
auto derivedIndices = [&]() {
llvm::SmallVector<Expr*, 4> V(clonedIndices.size());
std::transform(clonedIndices.begin(), clonedIndices.end(), V.begin(),
[this](Expr* E) { return CloneNode(E); });
return V;
};
Expr* zero = getZeroInit(ExprTy);
ValueDecl* VD = nullptr;
// Derived variables for member variables are also created when we are
// differentiating a call operator.
if (m_DiffReq.Functor) {
if (auto ME = dyn_cast<MemberExpr>(clonedBase->IgnoreParenImpCasts())) {
ValueDecl* decl = ME->getMemberDecl();
auto it = m_Variables.find(decl);
// If the original field is of constant array type, then,
// the derived variable of `arr[i]` is `_d_arr[i]`.
if (it != m_Variables.end() && decl->getType()->isConstantArrayType()) {
auto* result_at_i =
BuildArraySubscript(buildAdjoint(it->second), derivedIndices());
return StmtDiff{cloned, result_at_i};
}
VD = decl;
}
} else if (isa<MemberExpr>(clonedBase->IgnoreParenImpCasts())) {
auto derivedME = cloneDiff.getExpr_dx();
if (!isa<MemberExpr>(derivedME->IgnoreParenImpCasts())) {
return {cloned, zero};
}
auto* derivedAS = BuildArraySubscript(derivedME, derivedIndices());
return {cloned, derivedAS};
} else {
if (!isa<DeclRefExpr>(clonedBase->IgnoreParenImpCasts()))
return StmtDiff(cloned, zero);
auto DRE = cast<DeclRefExpr>(clonedBase->IgnoreParenImpCasts());
assert(isa<VarDecl>(DRE->getDecl()) &&
"declaration represented by clonedBase Should always be VarDecl "
"when clonedBase is DeclRefExpr");
VD = DRE->getDecl();
}
if (VD == m_IndependentVar) {
llvm::APSInt index;
Expr* diffExpr = nullptr;
Expr::EvalResult res;
Expr::SideEffectsKind AllowSideEffects =
Expr::SideEffectsKind::SE_NoSideEffects;
if (!clonedIndices.back()->EvaluateAsInt(res, m_Context,
AllowSideEffects)) {
diffExpr =
BuildParens(BuildOp(BO_EQ, CloneNode(clonedIndices.back()),
ConstantFolder::synthesizeLiteral(
ExprTy, m_Context, m_IndependentVarIndex)));
} else if (res.Val.getInt().getExtValue() == m_IndependentVarIndex) {
diffExpr = ConstantFolder::synthesizeLiteral(ExprTy, m_Context, 1);
} else {
diffExpr = zero;
}
return StmtDiff(cloned, diffExpr);
}
// Check DeclRefExpr is a reference to an independent variable.
auto it = m_Variables.find(VD);
if (it == std::end(m_Variables))
// Is not an independent variable, ignored.
return StmtDiff(cloned, zero);
// FIXME: fix when adding array inputs. Forward-mode adjoints are plain refs,
// so the decl's type is the adjoint's -- check it before building anything.
if (!isArrayOrPointerType(it->second.Decl->getType().getNonReferenceType()))
return StmtDiff(cloned, zero);
auto* result_at_is =
BuildArraySubscript(buildAdjoint(it->second), derivedIndices());
return StmtDiff(cloned, result_at_is);
}
StmtDiff BaseForwardModeVisitor::VisitDeclRefExpr(const DeclRefExpr* DRE) {
DeclRefExpr* clonedDRE = nullptr;
// Check if referenced Decl was "replaced" with another identifier inside
// the derivative
if (auto VD = dyn_cast<VarDecl>(DRE->getDecl())) {
auto it = m_DeclReplacements.find(VD);
if (it != std::end(m_DeclReplacements))
clonedDRE = BuildDeclRef(it->second);
else
clonedDRE = cast<DeclRefExpr>(Clone(DRE));
// If current context is different than the context of the original
// declaration (e.g. we are inside lambda), rebuild the DeclRefExpr
// with Sema::BuildDeclRefExpr. This is required in some cases, e.g.
// Sema::BuildDeclRefExpr is responsible for adding captured fields
// to the underlying struct of a lambda.
if (clonedDRE->getDecl()->getDeclContext() != m_Sema.CurContext) {
// clang<22: getQualifier() returns NNS*, null on unqualified.
// clang>=22: it returns NNS-by-value; the unqualified case is
// Invalid (StoredOrFlag==4) -- bool-true under operator bool().
// Funnel through hasQualifier() so the "no qualifier" path stays
// consistent across versions.
clad_compat::NestedNameSpecifierTy NNS = DRE->getQualifier();
auto* referencedDecl = cast<VarDecl>(clonedDRE->getDecl());
clonedDRE = BuildDeclRef(referencedDecl, clad_compat::hasQualifier(NNS)
? NNS
: clad_compat::nullNNS());
}
} else
clonedDRE = cast<DeclRefExpr>(Clone(DRE));
if (auto VD = dyn_cast<VarDecl>(clonedDRE->getDecl())) {
// If DRE references a variable, try to find if we know something about
// how it is related to the independent variable.
auto it = m_Variables.find(VD);
if (it != std::end(m_Variables))
return StmtDiff(clonedDRE, buildAdjoint(it->second, DRE));
}
// Is not a variable or is a reference to something unrelated to independent
// variable. Derivative is 0.
// If DRE is of type pointer, then the derivative is a null pointer.
if (clonedDRE->getType()->isPointerType())
return StmtDiff(clonedDRE, nullptr);
if (const auto* decl = dyn_cast<VarDecl>(DRE->getDecl()))
if (!m_DiffReq.shouldHaveAdjointForw(decl))
return StmtDiff(clonedDRE, nullptr);
return StmtDiff(clonedDRE, getZeroInit(clonedDRE->getType()));
}
StmtDiff BaseForwardModeVisitor::VisitIntegerLiteral(const IntegerLiteral* IL) {