forked from vgvassilev/clad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseModeVisitor.cpp
More file actions
5565 lines (5103 loc) · 238 KB
/
Copy pathReverseModeVisitor.cpp
File metadata and controls
5565 lines (5103 loc) · 238 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/ReverseModeVisitor.h"
#include "ASTIntegrity.h"
#include "ConstantFolder.h"
#include "TBRAnalyzer.h"
#include "clad/Differentiator/DerivativeBuilder.h"
#include "clad/Differentiator/DiffPlanner.h"
#include "clad/Differentiator/ErrorEstimator.h"
#include "clad/Differentiator/ExternalRMVSource.h"
#include "clad/Differentiator/MultiplexExternalRMVSource.h"
#include "clad/Differentiator/VisitorBase.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/LLVM.h" // for clang::isa
#include "clang/Basic/Lambda.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Basic/Version.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/ParsedAttr.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/APSInt.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <memory>
#include <numeric>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "clad/Differentiator/CladUtils.h"
#include "clad/Differentiator/Compatibility.h"
using namespace clang;
namespace clad {
Expr* ReverseModeVisitor::getStdInitListSizeExpr(const Expr* E) {
if (E)
if (const auto* CXXILE =
dyn_cast<CXXStdInitializerListExpr>(E->IgnoreImplicit()))
if (const auto* ILE =
dyn_cast<InitListExpr>(CXXILE->getSubExpr()->IgnoreImplicit())) {
unsigned numInits = ILE->getNumInits();
return ConstantFolder::synthesizeLiteral(
clad_compat::getSizeType(m_Context), m_Context, numInits);
}
return nullptr;
}
Expr* ReverseModeVisitor::CladTapeResult::Last() {
LookupResult& Back = V.GetCladTapeBack();
CXXScopeSpec CSS;
CSS.Extend(V.m_Context, utils::GetCladNamespace(V.m_Sema), noLoc, noLoc);
Expr* BackDRE = V.m_Sema
.BuildDeclarationNameExpr(CSS, Back,
/*AcceptInvalidDecl=*/false)
.get();
// Ref is reused by every push and back call on this tape; clone so each
// call owns its tape reference. A local lvalue is required: the single
// element is passed as a MultiExprArg, which stores a pointer to it.
Expr* RefClone = V.CloneNode(Ref);
Expr* Call =
V.m_Sema
.ActOnCallExpr(V.getCurrentScope(), BackDRE, noLoc, RefClone, noLoc)
.get();
return Call;
}
ReverseModeVisitor::CladTapeResult
ReverseModeVisitor::MakeCladTapeFor(Expr* E, llvm::StringRef prefix,
clang::QualType type) {
assert(E && "must be provided");
E = E->IgnoreImplicit();
if (type.isNull())
type = E->getType();
type.removeLocalConst();
QualType TapeType = GetCladTapeOfType(type);
LookupResult& Push = GetCladTapePush();
LookupResult& Pop = GetCladTapePop();
// Threadprivate tapes must be static
StorageClass SC = isInsideOMPBlock ? SC_Static : SC_None;
Expr* TapeRef = BuildDeclRef(
GlobalStoreImpl(TapeType, prefix, getZeroInit(TapeType), SC));
auto* VD = cast<VarDecl>(cast<DeclRefExpr>(TapeRef)->getDecl());
// Add fake location, since Clang AST does assert(Loc.isValid()) somewhere.
VD->setLocation(m_DiffReq->getLocation());
CXXScopeSpec CSS;
CSS.Extend(m_Context, utils::GetCladNamespace(m_Sema), noLoc, noLoc);
auto* PopDRE = m_Sema
.BuildDeclarationNameExpr(CSS, Pop,
/*AcceptInvalidDecl=*/false)
.get();
auto* PushDRE = m_Sema
.BuildDeclarationNameExpr(CSS, Push,
/*AcceptInvalidDecl=*/false)
.get();
Expr* PopExpr =
m_Sema.ActOnCallExpr(getCurrentScope(), PopDRE, noLoc, TapeRef, noLoc)
.get();
// pop, push and the returned last-ref each get their own tape DeclRef so
// the same node is not parented by both the push and pop CallExprs.
Expr* CallArgs[] = {CloneNode(TapeRef), E};
Expr* PushExpr =
m_Sema.ActOnCallExpr(getCurrentScope(), PushDRE, noLoc, CallArgs, noLoc)
.get();
if (isInsideOMPBlock)
MarkDeclThreadPrivate(VD);
return CladTapeResult{*this, PushExpr, PopExpr, CloneNode(TapeRef)};
}
bool ReverseModeVisitor::shouldUseCudaAtomicOps(const Expr* E) {
if (!m_Context.getLangOpts().CUDA)
return false;
if (const auto* DRE = dyn_cast<DeclRefExpr>(E)) {
if (const auto* PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
if (m_DiffReq->hasAttr<clang::CUDAGlobalAttr>())
// Check whether this param is in the global memory of the GPU
return m_DiffReq.HasIndependentParameter(PVD);
if (m_DiffReq->hasAttr<clang::CUDADeviceAttr>()) {
for (auto index : m_DiffReq.CUDAGlobalArgsIndexes) {
const auto* PVDOrig = m_DiffReq->getParamDecl(index);
if ("_d_" + PVDOrig->getNameAsString() == PVD->getNameAsString() &&
(utils::isArrayOrPointerType(PVDOrig->getType()) ||
PVDOrig->getType()->isReferenceType()))
return true;
}
}
}
} else if (const auto* ASE = dyn_cast<ArraySubscriptExpr>(E)) {
const auto* base =
dyn_cast<DeclRefExpr>(ASE->getBase()->IgnoreImpCasts());
if (const auto* PVD = dyn_cast<ParmVarDecl>(base->getDecl())) {
const auto* idx = ASE->getIdx();
if (m_DiffReq->hasAttr<clang::CUDAGlobalAttr>())
// Check whether this param is in the global memory of the GPU and
// if index is injective.
return m_DiffReq.HasIndependentParameter(PVD) &&
!clad::utils::isInjective(idx, m_DiffReq.m_AnalysisDC);
if (m_DiffReq->hasAttr<clang::CUDADeviceAttr>()) {
for (auto index : m_DiffReq.CUDAGlobalArgsIndexes) {
const auto* PVDOrig = m_DiffReq->getParamDecl(index);
if ("_d_" + PVDOrig->getNameAsString() == PVD->getNameAsString() &&
(utils::isArrayOrPointerType(PVDOrig->getType()) ||
PVDOrig->getType()->isReferenceType()))
return !clad::utils::isInjective(idx, m_DiffReq.m_AnalysisDC);
}
}
}
}
return false;
}
clang::Expr* ReverseModeVisitor::BuildCallToCudaAtomicAdd(clang::Expr* LHS,
clang::Expr* RHS) {
DeclarationName atomicAddId = &m_Context.Idents.get("atomicAdd");
LookupResult lookupResult(m_Sema, atomicAddId, SourceLocation(),
Sema::LookupOrdinaryName);
m_Sema.LookupQualifiedName(lookupResult,
m_Context.getTranslationUnitDecl());
CXXScopeSpec SS;
Expr* UnresolvedLookup =
m_Sema.BuildDeclarationNameExpr(SS, lookupResult, /*ADL=*/true).get();
Expr* finalLHS = LHS;
if (auto* UO = dyn_cast<UnaryOperator>(LHS)) {
if (UO->getOpcode() == UnaryOperatorKind::UO_Deref)
finalLHS = UO->getSubExpr()->IgnoreImplicit();
} else if (!LHS->getType()->isPointerType() &&
!LHS->getType()->isReferenceType())
finalLHS = BuildOp(UnaryOperatorKind::UO_AddrOf, LHS);
llvm::SmallVector<Expr*, 2> atomicArgs = {finalLHS, RHS};
assert(!m_Builder.noOverloadExists(UnresolvedLookup, atomicArgs) &&
"atomicAdd function not found");
Expr* atomicAddCall =
m_Sema
.ActOnCallExpr(
getCurrentScope(),
/*Fn=*/UnresolvedLookup,
/*LParenLoc=*/noLoc,
/*ArgExprs=*/llvm::MutableArrayRef<Expr*>(atomicArgs),
/*RParenLoc=*/m_DiffReq->getLocation())
.get();
return atomicAddCall;
}
// Both LHS (the memset destination) and the size expression are cloned here:
// callers pass the derived pointer they also assign to and the malloc/realloc
// size they also pass to that call, so cloning keeps the memset a distinct
// subtree.
Expr* ReverseModeVisitor::CheckAndBuildCallToMemset(Expr* LHS, Expr* RHS) {
Expr* size = nullptr;
if (auto* callExpr = dyn_cast_or_null<CallExpr>(RHS))
if (auto* declRef =
dyn_cast<DeclRefExpr>(callExpr->getCallee()->IgnoreImpCasts()))
if (auto* FD = dyn_cast<FunctionDecl>(declRef->getDecl())) {
if (FD->getNameAsString() == "malloc")
size = callExpr->getArg(0);
else if (FD->getNameAsString() == "realloc")
size = callExpr->getArg(1);
}
if (size) {
llvm::SmallVector<Expr*, 3> args = {
CloneNode(LHS), getZeroInit(m_Context.IntTy), CloneNode(size)};
return GetFunctionCall("memset", "", args);
}
return nullptr;
}
ReverseModeVisitor::ReverseModeVisitor(DerivativeBuilder& builder,
const DiffRequest& request)
: VisitorBase(builder, request) {}
ReverseModeVisitor::~ReverseModeVisitor() = default;
DerivativeAndOverload ReverseModeVisitor::Derive() {
assert(m_DiffReq.Function && "Must not be null.");
PrettyStackTraceDerivative CrashInfo(m_DiffReq, m_Blocks, m_Sema,
&m_CurVisitedStmt);
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerive();
QualType returnTy = m_DiffReq->getReturnType();
// If reverse mode differentiates only part of the arguments it needs to
// generate an overload that can take in all the diff variables
bool shouldCreateOverload = false;
// FIXME: Gradient overload doesn't know how to handle additional parameters
// added by the plugins yet.
if (m_DiffReq.Mode == DiffMode::reverse) {
if (returnTy->isRealType())
m_Pullback.push_back(ConstantFolder::synthesizeLiteral(m_Context.IntTy,
m_Context,
/*val=*/1));
else if (!returnTy->isVoidType()) {
diag(DiagnosticsEngine::Warning, m_DiffReq.Function->getBeginLoc(),
"clad::gradient only supports differentiation functions of real "
"return types. Return stmt ignored")
<< m_DiffReq.Function->getReturnTypeSourceRange();
diag(DiagnosticsEngine::Note, m_DiffReq.CallContext->getBeginLoc(),
"use clad::jacobian to compute derivatives of multiple real "
"outputs w.r.t. multiple real inputs");
}
shouldCreateOverload = !m_ExternalSource;
if (!m_DiffReq.DeclarationOnly && !m_DiffReq.DerivedFDPrototypes.empty())
// If the overload is already created, we don't need to create it again.
shouldCreateOverload = false;
}
QualType dFnType = GetDerivativeType();
// Check if the function is already declared as a custom derivative.
std::string name = 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());
// Create the gradient function declaration.
llvm::SaveAndRestore<DeclContext*> SaveContext(m_Sema.CurContext);
llvm::SaveAndRestore<Scope*> SaveScope(getCurrentScope(),
getEnclosingNamespaceOrTUScope());
m_Sema.CurContext = DC;
SourceLocation loc = m_DiffReq->getLocation();
DeclarationNameInfo DNI = utils::BuildDeclarationNameInfo(m_Sema, name);
// `result` owns the namespace Scopes cloneFunction opens; its
// destructor pops them before SaveScope restores -- declaration order
// gives the correct LIFO unwind.
ClonedFunction result = m_Builder.cloneFunction(m_DiffReq.Function, *this,
DC, loc, DNI, dFnType);
m_Derivative = result.fd;
// Function declaration scope
beginScope(Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope |
Scope::DeclScope);
m_Sema.PushFunctionScope();
m_Sema.PushDeclContext(getCurrentScope(), m_Derivative);
llvm::SmallVector<ParmVarDecl*, 8> params;
BuildParams(params);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnParams(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();
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerivedFnBody(m_DiffReq);
if (m_DiffReq.use_enzyme) {
assert(m_DiffReq.Mode == DiffMode::reverse && "Not in reverse?");
DifferentiateWithEnzyme();
} else {
DifferentiateWithClad();
}
Stmt* fnBody = endBlock();
m_Derivative->setBody(fnBody);
// 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_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
endScope(); // Function body scope
}
endScope(); // Function decl scope
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());
}
}
if (!shouldCreateOverload)
return DerivativeAndOverload{result.fd, /*overload=*/nullptr};
return DerivativeAndOverload{result.fd, CreateDerivativeOverload()};
}
void ReverseModeVisitor::DifferentiateWithClad() {
if (m_DiffReq.Mode == DiffMode::reverse && !m_ExternalSource) {
// create derived variables for parameters which are not part of
// independent variables (args).
for (const ParmVarDecl* param : m_NonIndepParams) {
QualType paramTy = param->getType();
if (const auto* DT = dyn_cast<DecayedType>(paramTy))
paramTy = DT->getOriginalType();
if (utils::isArrayOrPointerType(paramTy) &&
!paramTy->isConstantArrayType()) {
// We cannot initialize derived variable for pointer types because
// we do not know the correct size.
if (!utils::GetValueType(paramTy).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;
return;
}
continue;
}
auto VDDerivedType = utils::getNonConstType(paramTy, m_Sema);
VDDerivedType = VDDerivedType.getNonReferenceType();
Expr* initExpr = nullptr;
// We initialize adjoints with original variables as part of
// the strategy to maintain the structure of the original variable.
// After that, we'll zero-initialize the adjoint. e.g.
// ```
// std::vector<...> v{x, y, z};
// std::vector<...> _d_v{v}; // The length of the vector is preserved
// clad::zero_init(_d_v);
// ```
// Also, if the original is initialized with a zero-constructor, it can
// be used for the adjoint as well.
const CXXRecordDecl* RD = VDDerivedType->getAsCXXRecordDecl();
bool isNonAggrClass = RD && !RD->isAggregate();
auto hasDangerousFields = [](const CXXRecordDecl* Record) {
bool result = false;
for (const clang::FieldDecl* FD : Record->fields())
result = result || FD->getType()->isPointerType() ||
FD->getType()->isReferenceType();
return result;
};
bool isDirectInit = false;
if (isNonAggrClass && utils::isCopyable(RD) &&
!hasDangerousFields(RD)) {
ParmVarDecl* newFuncParam = nullptr;
for (auto* p : m_Derivative->parameters()) {
if (p->getName() == param->getName()) {
newFuncParam = p;
break;
}
}
assert(
newFuncParam &&
"Could not find corresponding parameter in derivative function");
initExpr = BuildDeclRef(newFuncParam->getDefinition());
isDirectInit = true;
} else {
// If the type is not a tensor, we can use zero initialization.
initExpr = getZeroInit(VDDerivedType);
}
auto* VDDerived = BuildGlobalVarDecl(
VDDerivedType, "_d_" + param->getName().ltrim('_').str(), initExpr,
isDirectInit);
m_Variables[param] = {VDDerived};
addToBlock(BuildDeclStmt(VDDerived), m_Globals);
}
}
// If we the differentiated function is a constructor, generate `this`
// object and differentiate its inits.
Stmts initsDiff;
if (const auto* CD = dyn_cast<CXXConstructorDecl>(m_DiffReq.Function)) {
StmtDiff thisObj;
// Constructors with only linear operations do not require
// `_this` in the reverse sweep.
// FIXME: remove this check when our analysis is powerful enough.
if (!utils::isLinearConstructor(CD, m_Context)) {
QualType thisTy = CD->getThisType();
thisObj = BuildThisExpr(thisTy);
initsDiff.push_back(thisObj.getStmt_dx());
}
for (CXXCtorInitializer* CI : CD->inits()) {
// _this is reused by every initializer; clone so each owns its node.
StmtDiff CI_diff =
DifferentiateCtorInit(CI, CloneNode(thisObj.getExpr()));
addToCurrentBlock(CI_diff.getStmt(), direction::forward);
if (Stmt* unwrappedCIDiff =
utils::unwrapIfSingleStmt(CI_diff.getRevSweepStmt()))
initsDiff.push_back(unwrappedCIDiff);
}
}
// Start the visitation process which outputs the statements in the
// current block.
StmtDiff BodyDiff = Visit(m_DiffReq->getBody());
Stmt* Forward = BodyDiff.getStmt();
Stmt* Reverse = BodyDiff.getStmt_dx();
// Create the body of the function.
// Firstly, all "global" Stmts are put into fn's body.
for (Stmt* S : m_Globals)
addToCurrentBlock(S, direction::forward);
if (!m_DiffReq.hasEarlyReturns()) {
// Forward pass.
if (auto* CS = dyn_cast_or_null<CompoundStmt>(Forward))
for (Stmt* S : CS->body())
addToCurrentBlock(S, direction::forward);
else
addToCurrentBlock(Forward, direction::forward);
// Reverse pass.
if (auto* RCS = dyn_cast_or_null<CompoundStmt>(Reverse))
for (Stmt* S : RCS->body())
addToCurrentBlock(S, direction::forward);
else
addToCurrentBlock(Reverse, direction::forward);
} else {
// Function has early returns. Wrap the master reverse in a [&] lambda
// and call it from each early-return path (via marker patching) plus
// once at the natural tail. This replaces the previous goto/label
// encoding which violated [stmt.dcl]/2 in the presence of locals with
// non-trivial initializers/destructors (vgvassilev/clad#367).
//
// Source-order matters: the lambda's [&] capture-default binds names
// looked up at the lambda's definition point, so every captured local
// must be declared before the lambda. Split the forward sweep into
// its leading run of DeclStmts and the rest; emit those decls, then
// the lambda binding, then the computation tail (which may contain
// markers that resolve to calls into the now-declared lambda).
llvm::SmallVector<Stmt*, 8> ForwardDeclPrefix;
llvm::SmallVector<Stmt*, 16> ForwardCompSuffix;
auto* FwdCS = dyn_cast_or_null<CompoundStmt>(Forward);
bool inDecls = true;
auto classify = [&](Stmt* S) {
if (inDecls && isa<DeclStmt>(S))
ForwardDeclPrefix.push_back(S);
else {
inDecls = false;
ForwardCompSuffix.push_back(S);
}
};
if (FwdCS)
for (Stmt* S : FwdCS->body())
classify(S);
else if (Forward)
classify(Forward);
// An ExternalSource (error estimation) appends an epilogue after the
// reverse sweep — e.g. `_final_error += ...` for each parameter and the
// return value. It must run on every return path, but emitting it after
// the lambda would make it unreachable once an early return fires (which
// calls the lambda and returns). Materialize it now into its own block
// so it can be folded into the lambda body and captured together with
// the reverse. ActOnEndOfDerivedFnBody is a no-op without such a source,
// yielding an empty block that folds to nothing.
CompoundStmt* Epilogue = nullptr;
if (m_ExternalSource) {
beginBlock(direction::forward);
m_ExternalSource->ActOnEndOfDerivedFnBody();
Epilogue = endBlock(direction::forward);
}
// The reverse sweep and the epilogue become the lambda body; collect
// their captures now so the hoister below can place the captured decls
// before the lambda.
llvm::SmallVector<Stmt*, 2> LambdaBody;
if (Reverse)
LambdaBody.push_back(Reverse);
if (Epilogue)
LambdaBody.push_back(Epilogue);
LambdaCaptures Captures(*this);
Captures.collect(LambdaBody);
// clad emits a zero-initialized adjoint (`double _d_b = 0.;`) lazily,
// next to the primal it shadows, so a captured adjoint decl can land in
// the computation suffix -- after the lambda. Move such decls before it.
Captures.orderCaptureDecls(ForwardDeclPrefix, ForwardCompSuffix,
m_Globals);
for (Stmt* S : ForwardDeclPrefix)
addToCurrentBlock(S, direction::forward);
// The reverse-pass lambda captures by reference, so every captured local
// must be declared before it. That invariant is enforced globally by
// findUseBeforeDecl (ASTIntegrity), which flags a lambda-body reference
// to a local not yet in scope at the lambda's definition point.
VarDecl* RevVD = buildAndBindLambda(
m_DiffReq.Function->getBody(), "_rev", Captures, [&] {
// Emit the master reverse into the closure. clad no longer reuses
// AST nodes across the forward/reverse sweeps (b75bba2c), so the
// reverse's nodes are closure-unique and need no clone.
if (auto* RCS = dyn_cast_or_null<CompoundStmt>(Reverse))
for (Stmt* S : RCS->body())
addToCurrentBlock(S, direction::forward);
else if (Reverse)
addToCurrentBlock(Reverse, direction::forward);
// Fold the ExternalSource epilogue in after the reverse sweep so it
// runs on every return path; emitting it after the lambda would
// make it unreachable once an early return fires.
if (Epilogue)
for (Stmt* S : Epilogue->body())
addToCurrentBlock(S, direction::forward);
});
addToCurrentBlock(BuildDeclStmt(RevVD), direction::forward);
for (Stmt* S : ForwardCompSuffix)
addToCurrentBlock(S, direction::forward);
// Patch each marker with its own fresh `{ _rev(); return; }`. A single
// shared replacement would land under several parents and violate the
// single-parent AST invariant, so build one per marker site.
patchEarlyReturnMarkers([&]() -> Stmt* {
Expr* RevCallEarly =
m_Sema
.ActOnCallExpr(getCurrentScope(), BuildDeclRef(RevVD), noLoc,
{}, noLoc)
.get();
Stmt* RetStmt = m_Sema
.ActOnReturnStmt(noLoc, /*RetValExpr=*/nullptr,
getCurrentScope())
.get();
return MakeCompoundStmt({RevCallEarly, RetStmt});
});
// Natural-tail path: the tail-return seed was already emitted into the
// forward sweep as the last statement before this point
// (VisitReturnStmt), so it runs only on fall-through. Follow it with the
// lambda call; the function's implicit fall-off-end serves as the natural
// return.
Expr* RevCallTail =
m_Sema
.ActOnCallExpr(getCurrentScope(), BuildDeclRef(RevVD), noLoc, {},
noLoc)
.get();
addToCurrentBlock(RevCallTail, direction::forward);
}
for (auto S = initsDiff.rbegin(), S_end = initsDiff.rend(); S != S_end; ++S)
addToCurrentBlock(*S, direction::forward);
// Add delete statements present in m_DeallocExprs to the current block.
for (auto* S : m_DeallocExprs)
if (auto* CS = dyn_cast<CompoundStmt>(S))
for (Stmt* S : CS->body())
addToCurrentBlock(S, direction::forward);
else
addToCurrentBlock(S, direction::forward);
// For early-return functions the epilogue was already folded into the
// lambda (above) so it runs on every return path; emit it at the tail
// only when there is no lambda.
if (m_ExternalSource && !m_DiffReq.hasEarlyReturns())
m_ExternalSource->ActOnEndOfDerivedFnBody();
}
StmtDiff ReverseModeVisitor::BuildThisExpr(QualType thisTy,
bool isDerivedThis /*=false*/) {
// Build `sizeof(T)`
QualType recordTy = thisTy->getPointeeType();
TypeSourceInfo* TSI = m_Context.getTrivialTypeSourceInfo(recordTy, noLoc);
Expr* size = new (m_Context) UnaryExprOrTypeTraitExpr(
UETT_SizeOf, TSI, clad_compat::getSizeType(m_Context), noLoc, noLoc);
// Build `malloc(sizeof(T))`
llvm::SmallVector<clang::Expr*, 1> param{size};
Expr* init = GetFunctionCall("malloc", "", param);
// Build `(T*)malloc(sizeof(T))`
TypeSourceInfo* ptr_TSI = m_Context.getTrivialTypeSourceInfo(thisTy, noLoc);
init = m_Sema.BuildCStyleCastExpr(noLoc, ptr_TSI, noLoc, init).get();
// Build T* _this = (T*)malloc(sizeof(T));
std::string name = isDerivedThis ? "_d_this" : "_this";
VarDecl* thisDecl = BuildGlobalVarDecl(thisTy, name, init);
addToCurrentBlock(BuildDeclStmt(thisDecl), direction::forward);
param[0] = BuildDeclRef(thisDecl);
Expr* setCall = nullptr;
if (isDerivedThis) {
// size already parents the malloc call above; clone for the memset.
llvm::SmallVector<Expr*, 3> args = {BuildDeclRef(thisDecl),
getZeroInit(m_Context.IntTy),
CloneNode(size)};
setCall = GetFunctionCall("memset", "", args);
} else
setCall = GetFunctionCall("free", "", param);
return {BuildDeclRef(thisDecl), setCall};
}
StmtDiff ReverseModeVisitor::VisitCXXTryStmt(const CXXTryStmt* TS) {
// FIXME: Add support for try statements.
diagUnsupported(TS);
return StmtDiff();
}
StmtDiff ReverseModeVisitor::DifferentiateCtorInit(CXXCtorInitializer* CI,
Expr* thisExpr) {
// If we're dealing with a delegating constructor or a
// base initializer, we need to differentiate it as
// ```
// new (_this) ClassTy(args...);
// ...
// ClassTy::constructor_pullback(args..., _d_this, _d_args...);
// ```
if (!CI->isMemberInitializer()) {
beginBlock(direction::reverse);
Expr* dthisObj = BuildOp(UO_Deref, cloneThisExprDerivative());
StmtDiff initDiff = Visit(CI->getInit(), dthisObj);
// Build the placement new.
Expr* initCall = nullptr;
if (thisExpr) {
TypeSourceInfo* baseTSI = CI->getTypeSourceInfo();
QualType baseTy = baseTSI->getType();
if (CI->isBaseInitializer()) {
Expr* placementArg = thisExpr;
// If a base initializer is used, we need to explicitly cast the
// pointer to the base type. new (static_cast<BaseTy*>(derived_ptr))
// BaseTy(args...); Note: `derived_ptr` might not be the same memory
// address as after the cast, e.g. when having multiple inheritances.
QualType ptrBaseTy = m_Context.getPointerType(baseTy);
TypeSourceInfo* ptrTSI =
m_Context.getTrivialTypeSourceInfo(ptrBaseTy);
placementArg =
m_Sema
.BuildCXXNamedCast(noLoc, tok::TokenKind::kw_static_cast,
ptrTSI, thisExpr, noLoc, noLoc)
.get();
initCall = utils::BuildCXXNewExpr(m_Sema, baseTy, nullptr,
initDiff.getExpr(), baseTSI,
{placementArg});
} else if (CI->isDelegatingInitializer()) {
auto* thisDRE = cast<DeclRefExpr>(thisExpr);
auto* thisVD = cast<VarDecl>(thisDRE->getDecl());
Expr* newInit = utils::BuildCXXNewExpr(m_Sema, baseTy, nullptr,
initDiff.getExpr(), baseTSI);
SetDeclInit(thisVD, newInit);
}
}
CompoundStmt* block = endBlock(direction::reverse);
std::reverse(block->body_begin(), block->body_end());
return {initCall, nullptr, block};
}
llvm::StringRef fieldName = CI->getMember()->getName();
Expr* memberDiff = utils::BuildMemberExpr(
m_Sema, getCurrentScope(), cloneThisExprDerivative(), fieldName);
beginBlock(direction::reverse);
QualType memberTy = CI->getMember()->getType();
if (memberTy->isRealType()) {
Stmt* assign_zero = BuildOp(BO_Assign, CloneNode(memberDiff),
getZeroInit(memberDiff->getType()));
addToCurrentBlock(assign_zero, direction::reverse);
}
StmtDiff initDiff = Visit(CI->getInit(), memberDiff);
addToCurrentBlock(initDiff.getStmt_dx(), direction::reverse);
Stmt* init = nullptr;
Stmt* initDx = nullptr;
if (thisExpr) {
Expr* member = utils::BuildMemberExpr(m_Sema, getCurrentScope(), thisExpr,
fieldName);
init = BuildOp(BO_Assign, member, initDiff.getExpr());
Expr* memberDx = utils::BuildMemberExpr(
m_Sema, getCurrentScope(), cloneThisExprDerivative(), fieldName);
if (!memberDx->getType()->isRealType())
initDx = BuildOp(BO_Assign, memberDx, initDiff.getExpr_dx());
}
return {init, initDx, endBlock(direction::reverse)};
}
void ReverseModeVisitor::DifferentiateWithEnzyme() {
unsigned numParams = m_DiffReq->getNumParams();
auto origParams = m_DiffReq->parameters();
llvm::ArrayRef<ParmVarDecl*> paramsRef = m_Derivative->parameters();
const auto* originalFnType =
dyn_cast<FunctionProtoType>(m_DiffReq->getType());
// Prepare Arguments and Parameters to enzyme_autodiff
llvm::SmallVector<Expr*, 16> enzymeArgs;
llvm::SmallVector<ParmVarDecl*, 16> enzymeParams;
llvm::SmallVector<ParmVarDecl*, 16> enzymeRealParams;
llvm::SmallVector<ParmVarDecl*, 16> enzymeRealParamsDerived;
// First add the function itself as a parameter/argument
// FIXME: We should not use const_cast to get the decl context here.
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
enzymeArgs.push_back(
BuildDeclRef(const_cast<FunctionDecl*>(m_DiffReq.Function)));
// FIXME: We should not use const_cast to get the decl context here.
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
auto* fdDeclContext = const_cast<DeclContext*>(m_DiffReq->getDeclContext());
enzymeParams.push_back(m_Sema.BuildParmVarDeclForTypedef(
fdDeclContext, noLoc, m_DiffReq->getType()));
// Add rest of the parameters/arguments
for (unsigned i = 0; i < numParams; i++) {
// First Add the original parameter
enzymeArgs.push_back(BuildDeclRef(paramsRef[i]));
enzymeParams.push_back(m_Sema.BuildParmVarDeclForTypedef(
fdDeclContext, noLoc, paramsRef[i]->getType()));
QualType paramType = origParams[i]->getOriginalType();
// If original parameter is of a differentiable real type(but not
// array/pointer), then add it to the list of params whose gradient must
// be extracted later from the EnzymeGradient structure
if (paramType->isRealFloatingType()) {
enzymeRealParams.push_back(paramsRef[i]);
enzymeRealParamsDerived.push_back(paramsRef[numParams + i]);
} else if (utils::isArrayOrPointerType(paramType)) {
// Add the corresponding array/pointer variable
enzymeArgs.push_back(BuildDeclRef(paramsRef[numParams + i]));
enzymeParams.push_back(m_Sema.BuildParmVarDeclForTypedef(
fdDeclContext, noLoc, paramsRef[numParams + i]->getType()));
}
}
llvm::SmallVector<QualType, 16> enzymeParamsType;
for (auto* i : enzymeParams)
enzymeParamsType.push_back(i->getType());
QualType QT;
if (!enzymeRealParams.empty()) {
// Find the EnzymeGradient datastructure
auto* gradDecl =
utils::LookupTemplateDeclInCladNamespace(m_Sema, "EnzymeGradient");
TemplateArgumentListInfo TLI{};
llvm::APSInt argValue = m_Context.MakeIntValue(enzymeRealParams.size(),
m_Context.UnsignedIntTy);
TemplateArgument TA(m_Context, argValue, m_Context.UnsignedIntTy);
TLI.addArgument(TemplateArgumentLoc(TA, TemplateArgumentLocInfo()));
QT = utils::InstantiateTemplate(m_Sema, gradDecl, TLI);
} else {
QT = m_Context.VoidTy;
}
// Prepare Function call
std::string enzymeCallName =
"__enzyme_autodiff_" + m_DiffReq->getNameAsString();
IdentifierInfo* IIEnzyme = &m_Context.Idents.get(enzymeCallName);
DeclarationName nameEnzyme(IIEnzyme);
QualType enzymeFunctionType =
m_Sema.BuildFunctionType(QT, enzymeParamsType, noLoc, nameEnzyme,
originalFnType->getExtProtoInfo());
SourceLocation loc = m_DiffReq->getLocation();
FunctionDecl* enzymeCallFD = FunctionDecl::Create(
m_Context, fdDeclContext, loc, loc, nameEnzyme, enzymeFunctionType,
m_DiffReq->getTypeSourceInfo(), SC_Extern);
enzymeCallFD->setParams(enzymeParams);
Expr* enzymeCall = BuildCallExprToFunction(enzymeCallFD, enzymeArgs);
// Prepare the statements that assign the gradients to
// non array/pointer type parameters of the original function
if (!enzymeRealParams.empty()) {
VarDecl* gradVD = BuildVarDecl(QT, "grad", enzymeCall);
addToCurrentBlock(BuildDeclStmt(gradVD), direction::forward);
for (unsigned i = 0; i < enzymeRealParams.size(); i++) {
auto* LHSExpr =
BuildOp(UO_Deref, BuildDeclRef(enzymeRealParamsDerived[i]));
auto* ME = utils::BuildMemberExpr(m_Sema, getCurrentScope(),
BuildDeclRef(gradVD), "d_arr");
llvm::APSInt V = m_Context.MakeIntValue(i, m_Context.UnsignedIntTy);
Expr* gradIndex = dyn_cast<Expr>(IntegerLiteral::Create(
m_Context, V, m_Context.UnsignedIntTy, noLoc));
Expr* RHSExpr =
m_Sema.CreateBuiltinArraySubscriptExpr(ME, noLoc, gradIndex, noLoc)
.get();
auto* assignExpr = BuildOp(BO_Assign, LHSExpr, RHSExpr);
addToCurrentBlock(assignExpr, direction::forward);
}
} else {
// Add Function call to block
Expr* enzymeCall = BuildCallExprToFunction(enzymeCallFD, enzymeArgs);
addToCurrentBlock(enzymeCall);
}
}
StmtDiff ReverseModeVisitor::VisitCXXStdInitializerListExpr(
const clang::CXXStdInitializerListExpr* ILE) {
return Visit(ILE->getSubExpr(), dfdx());
}
StmtDiff
ReverseModeVisitor::VisitArrayInitLoopExpr(const ArrayInitLoopExpr* AILE) {
// Since ArrayInitLoopExpr is not possible to express with regular syntax,
// we have to replicate it with loops.
// The code we're differentiated is of the form
// res = ArrayInitLoopExpr(arr[ArrayInitIndexExpr])
// We have to replace ArrayInitIndexExpr with an actual index `i`
// and wrap the code in a for loop to compute the derivative as follows:
// for (int i = 0; i < N; ++i)
// _d_arr[i] += _d_res[i];
ScopeRAII arrayInitScope(*this, Scope::DeclScope);
VarDecl* idxDecl = BuildVarDecl(m_Context.UnsignedIntTy, "i",
getZeroInit(m_Context.IntTy));
// Push the index to the queue so that we can replace ArrayInitIndexExpr
// when we encounter it.
m_ArrayInitLoopIdx.push(idxDecl);
Expr* idx = BuildDeclRef(idxDecl);
// Build `_d_res[i]`
Expr* diff = BuildArraySubscript(dfdx(), {idx});
beginBlock(direction::reverse);
Visit(AILE->getSubExpr(), diff);
Stmt* block = utils::unwrapIfSingleStmt(endBlock(direction::reverse));
Stmt* loopDiff = BuildStandardForLoop(
idxDecl, AILE->getArraySize().getZExtValue(), block);
addToCurrentBlock(loopDiff, direction::reverse);
// We cannot clone ArrayInitLoopExpr because it's not possible to express
// with standard c++ syntax.
return {};
}
StmtDiff
ReverseModeVisitor::VisitArrayInitIndexExpr(const ArrayInitIndexExpr* AIIE) {
VarDecl* idxDecl = m_ArrayInitLoopIdx.front();
m_ArrayInitLoopIdx.pop();
return {BuildDeclRef(idxDecl)};
}
StmtDiff
ReverseModeVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
return Visit(OVE->getSourceExpr(), dfdx());
}
StmtDiff ReverseModeVisitor::VisitStmt(const Stmt* S) {
diagUnsupported(S);
// Unknown stmt, just clone it.
return StmtDiff(Clone(S));
}
StmtDiff
ReverseModeVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CLE) {
StmtDiff result = Visit(CLE->getInitializer());
ParsedType PT = ParsedType::make(CLE->getType());
result.updateStmt(
m_Sema.ActOnCompoundLiteral(noLoc, PT, noLoc, result.getExpr()).get());
result.updateStmtDx(
m_Sema.ActOnCompoundLiteral(noLoc, PT, noLoc, result.getExpr_dx())
.get());
return result;
}
StmtDiff ReverseModeVisitor::VisitCompoundStmt(const CompoundStmt* CS) {
int scopeFlags = Scope::DeclScope;
// If this is the outermost compound statement of the function,
// propagate the function scope.
if (getCurrentScope() == m_DerivativeFnScope)
scopeFlags |= Scope::FnScope;
ScopeRAII compoundScope(*this, scopeFlags);
beginBlock(direction::forward);
beginBlock(direction::reverse);
for (Stmt* S : CS->body()) {
if (m_ExternalSource)
m_ExternalSource->ActBeforeDifferentiatingStmtInVisitCompoundStmt();
StmtDiff SDiff = DifferentiateSingleStmt(S);
addToCurrentBlock(SDiff.getStmt(), direction::forward);
addToCurrentBlock(SDiff.getStmt_dx(), direction::reverse);
if (m_ExternalSource)
m_ExternalSource->ActAfterProcessingStmtInVisitCompoundStmt();
}
CompoundStmt* Forward = endBlock(direction::forward);
CompoundStmt* Reverse = endBlock(direction::reverse);
return StmtDiff(Forward, Reverse);
}
StmtDiff ReverseModeVisitor::VisitIfStmt(const clang::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(direction::forward);
beginBlock(direction::reverse);
StmtDiff condDiff;
// if the statement has an init, we process it
if (If->hasInitStorage()) {
StmtDiff initDiff = Visit(If->getInit());
addToCurrentBlock(initDiff.getStmt(), direction::forward);
addToCurrentBlock(initDiff.getStmt_dx(), direction::reverse);
}
// this ensures we can differentiate conditions that affect the derivatives
// as well as declarations inside the condition:
beginBlock(direction::reverse);
if (const auto* condDeclStmt = If->getConditionVariableDeclStmt())
condDiff = Visit(condDeclStmt);
else
condDiff = Visit(If->getCond());