Closed
Description
Works:
$ clang-repl
clang-repl> int a = 42;
clang-repl> int i = 0;
clang-repl> for (; i<42; i+=1) a-=1;
clang-repl> %quit
Fails:
$ clang-repl
clang-repl> int a = 42;
clang-repl> for(int i=0; i<42; i+=1) a-=1;
clang-repl: llvm-project/clang/lib/CodeGen/CGDecl.cpp:161: void clang::CodeGen::CodeGenFunction::EmitDecl(const Decl &): Assertion `VD.isLocalVarDecl() && "Should not see file-scope variables inside a function!"' failed.
Aborted (core dumped)
Other side-effects include incorrect behavior for definitions inside if
conditions:
$ clang-repl -Xcc -Xclang,-ast-dump
clang-repl> int *a=nullptr;
TranslationUnitDecl 0x5555d8962468 prev 0x5555d893e690 <<invalid sloc>> <invalid sloc>
`-VarDecl 0x5555d8962518 <input_line_1:1:1, col:8> col:6 a 'int *' cinit
`-ImplicitCastExpr 0x5555d8962590 <col:8> 'int *' <NullToPointer>
`-CXXNullPtrLiteralExpr 0x5555d8962580 <col:8> 'std::nullptr_t'
clang-repl> if (auto *b=a) *b += 1;
TranslationUnitDecl 0x5555d8962608 prev 0x5555d8962468 <<invalid sloc>> <invalid sloc>
|-VarDecl 0x5555d89626c0 <input_line_2:1:5, col:13> col:11 used b 'int *' cinit
| `-ImplicitCastExpr 0x5555d8986b10 <col:13> 'int *' <LValueToRValue>
| `-DeclRefExpr 0x5555d8962728 <col:13> 'int *' lvalue Var 0x5555d8962518 'a' 'int *'
`-TopLevelStmtDecl 0x5555d8986cb0 <col:1, col:22> col:1
`-IfStmt 0x5555d8986c70 <col:1, col:22> has_var
|-DeclStmt 0x5555d8986c98 <col:5, col:13>
| `-VarDecl 0x5555d89626c0 <col:5, col:13> col:11 used b 'int *' cinit
| `-ImplicitCastExpr 0x5555d8986b10 <col:13> 'int *' <LValueToRValue>
| `-DeclRefExpr 0x5555d8962728 <col:13> 'int *' lvalue Var 0x5555d8962518 'a' 'int *'
|-ImplicitCastExpr 0x5555d8986bb8 <col:11> 'bool' <PointerToBoolean>
| `-ImplicitCastExpr 0x5555d8986ba0 <col:11> 'int *' <LValueToRValue>
| `-DeclRefExpr 0x5555d8986b80 <col:11> 'int *' lvalue Var 0x5555d89626c0 'b' 'int *'
`-CompoundAssignOperator 0x5555d8986c40 <col:16, col:22> 'int' lvalue '+=' ComputeLHSTy='int' ComputeResultTy='int'
|-UnaryOperator 0x5555d8986c08 <col:16, col:17> 'int' lvalue prefix '*' cannot overflow
| `-ImplicitCastExpr 0x5555d8986bf0 <col:17> 'int *' <LValueToRValue>
| `-DeclRefExpr 0x5555d8986bd0 <col:17> 'int *' lvalue Var 0x5555d89626c0 'b' 'int *'
`-IntegerLiteral 0x5555d8986c20 <col:22> 'int' 1
clang-repl> if (auto *b=a) *b += 1;
In file included from <<< inputs >>>:1:
input_line_3:1:11: error: redefinition of 'b'
1 | if (auto *b=a) *b += 1;
| ^
<<< inputs >>>:1:1: note: '' included multiple times, additional include site here
<<< inputs >>>:1:1: note: '' included multiple times, additional include site here
error: Parsing failed.
clang-repl> %quit
I guess the VarDecl 0x5555d89626c0
for b
should be emitted inside the TopLevelStmtDecl 0x5555d8986cb0
or even inside IfStmt 0x5555d8986c70
.