Skip to content

Commit 043fea7

Browse files
Vedant2005goyalvgvassilev
authored andcommitted
Corrected the wrong scope of the variables declared inside the Lambda function
Fixes vgvassilev#1701
1 parent 2368e28 commit 043fea7

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

lib/Differentiator/ReverseModeVisitor.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1823,9 +1823,11 @@ Expr* ReverseModeVisitor::getStdInitListSizeExpr(const Expr* E) {
18231823
getCurrentScope(), DS));
18241824

18251825
m_DerivativeFnScope = getCurrentScope();
1826+
Stmts OuterGlobals;
1827+
std::swap(m_Globals, OuterGlobals);
1828+
18261829
beginBlock();
18271830

1828-
// FIXME: Fix m_Globals being emmitted to the outer function.
18291831
StmtDiff BodyDiff = Visit(LE->getCallOperator()->getBody());
18301832
for (auto* S : cast<CompoundStmt>(BodyDiff.getStmt())->body())
18311833
addToCurrentBlock(S);
@@ -1834,6 +1836,19 @@ Expr* ReverseModeVisitor::getStdInitListSizeExpr(const Expr* E) {
18341836

18351837
CompoundStmt* DerivedBody = endBlock();
18361838

1839+
if (!m_Globals.empty()) {
1840+
llvm::SmallVector<Stmt*, 32> NewBodyStmts;
1841+
NewBodyStmts.append(m_Globals.begin(), m_Globals.end());
1842+
NewBodyStmts.append(DerivedBody->body().begin(),
1843+
DerivedBody->body().end());
1844+
1845+
DerivedBody = CompoundStmt::Create(
1846+
m_Sema.getASTContext(), NewBodyStmts, FPOptionsOverride(),
1847+
DerivedBody->getLBracLoc(), DerivedBody->getRBracLoc());
1848+
}
1849+
m_Globals.clear();
1850+
std::swap(m_Globals, OuterGlobals);
1851+
18371852
Expr* lambda =
18381853
m_Sema
18391854
.ActOnLambdaExpr(

test/Regressions/issue-1701.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// RUN: %cladclang -std=c++17 -I%S/../../include %s -o %t
2+
// RUN: %t | %filecheck_exec %s
3+
// UNSUPPORTED: clang-10, clang-11, clang-12, clang-13, clang-14, clang-15, clang-16
4+
#include <cstdio>
5+
#include "clad/Differentiator/Differentiator.h"
6+
7+
void f2(double i, double j){
8+
auto _f = [] () {
9+
{
10+
double a = 1;
11+
}
12+
};
13+
}
14+
int main(){
15+
auto diff=clad::gradient(f2);
16+
double di=0,dj=0;
17+
double i=7,j=7;
18+
diff.execute(i,j,&di,&dj);
19+
20+
printf("Execution successful\n");
21+
// CHECK-EXEC: Execution successful
22+
return 0;
23+
}

0 commit comments

Comments
 (0)