Skip to content

Commit 18f7205

Browse files
Vedant2005goyalvgvassilev
authored andcommitted
Safely fallback when trying to differentiate functions with no parameter rather than crashing
Fix issue #1855
1 parent 06ad668 commit 18f7205

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

lib/Differentiator/ReverseModeForwPassVisitor.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,8 @@ ReverseModeForwPassVisitor::VisitReturnStmt(const clang::ReturnStmt* RS) {
300300
return m_Sema.BuildReturnStmt(validLoc, returnDiff.getExpr()).get();
301301
llvm::SmallVector<Expr*, 2> returnArgs = {returnDiff.getExpr(),
302302
returnDiff.getExpr_dx()};
303+
if (!returnArgs[1])
304+
return {nullptr, nullptr};
303305
Expr* returnInitList =
304306
m_Sema.ActOnInitList(validLoc, returnArgs, validLoc).get();
305307
Stmt* newRS = m_Sema.BuildReturnStmt(validLoc, returnInitList).get();

test/Regressions/issue-1855.cpp

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
// RUN: %cladclang -fsyntax-only -std=c++17 -I%S/../../include %s
1+
// RUN: %cladclang -fsyntax-only -Xclang -verify -std=c++17 -I%S/../../include %s
22

33
#include "clad/Differentiator/Differentiator.h"
44

5-
int* global_ptr;
5+
int* global_ptr; // expected-warning {{gradient uses a global variable}}
66

77
void use(int*) {}
88

@@ -14,3 +14,30 @@ double fn(double x) {
1414
void test() {
1515
auto grad_fn = clad::gradient(fn);
1616
}
17+
18+
typedef enum { a } b;
19+
typedef enum { c, d } e;
20+
e f;
21+
22+
int *g() {
23+
switch (f) {
24+
case c: break;
25+
case d: break;
26+
}
27+
} // expected-warning {{non-void function does not return a value}}
28+
void h(b, e, char[], char[], int, bool, char, char *, va_list) { g(); }
29+
30+
char i, o, j; // expected-warning 3 {{gradient uses a global variable}}
31+
int k; // expected-warning {{gradient uses a global variable}}
32+
33+
void l(float) {
34+
va_list arg;
35+
h(a, d, &i, &o, k, 0, '\0', &j, arg);
36+
}
37+
38+
float m; // expected-warning {{gradient uses a global variable}}
39+
40+
void n() {
41+
l(m);
42+
clad::gradient(n); // expected-error {{attempted to differentiate function with no parameters}}
43+
}

0 commit comments

Comments
 (0)