Skip to content

Commit 041c01f

Browse files
authored
Hoist const variables from goto_block (#182)
1 parent 8009afc commit 041c01f

4 files changed

Lines changed: 11 additions & 4 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,8 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
474474
auto *method_or_null =
475475
curr_function_ ? clang::dyn_cast<clang::CXXMethodDecl>(curr_function_)
476476
: nullptr;
477-
if (!qual_type.isConstQualified() && !qual_type->isReferenceType() &&
477+
if ((hoisted_decls_.contains(decl) || !qual_type.isConstQualified()) &&
478+
!qual_type->isReferenceType() &&
478479
((method_or_null == nullptr) || !method_or_null->isVirtual()) &&
479480
!IsGlobalVar(decl)) {
480481
StrCat(keyword_mut_);

tests/unit/goto_cleanup.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ static int early(int n) {
77
goto out;
88
}
99
ret = 100;
10+
const int intentionally_const_var = 22;
1011
out:
11-
return ret;
12+
return ret + intentionally_const_var - intentionally_const_var;
1213
}
1314

1415
static int from_loop(int n) {

tests/unit/out/refcount/goto_cleanup.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::rc::{Rc, Weak};
99
pub fn early_0(n: i32) -> i32 {
1010
let n: Value<i32> = Rc::new(RefCell::new(n));
1111
let ret: Value<i32> = <Value<i32>>::default();
12+
let intentionally_const_var: Value<i32> = <Value<i32>>::default();
1213
goto_block!({
1314
'__entry: {
1415
*ret.borrow_mut() = 0;
@@ -17,9 +18,11 @@ pub fn early_0(n: i32) -> i32 {
1718
goto!('out);
1819
}
1920
(*ret.borrow_mut()) = 100;
21+
*intentionally_const_var.borrow_mut() = 22;
2022
}
2123
'out: {
22-
return (*ret.borrow());
24+
return (((*ret.borrow()) + (*intentionally_const_var.borrow()))
25+
- (*intentionally_const_var.borrow()));
2326
}
2427
});
2528
panic!("ub: non-void function does not return a value")

tests/unit/out/unsafe/goto_cleanup.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::os::fd::{AsFd, FromRawFd, IntoRawFd};
88
use std::rc::Rc;
99
pub unsafe fn early_0(mut n: i32) -> i32 {
1010
let mut ret: i32 = 0_i32;
11+
let mut intentionally_const_var: i32 = 0_i32;
1112
goto_block!({
1213
'__entry: {
1314
ret = 0;
@@ -16,9 +17,10 @@ pub unsafe fn early_0(mut n: i32) -> i32 {
1617
goto!('out);
1718
}
1819
ret = 100;
20+
intentionally_const_var = 22;
1921
}
2022
'out: {
21-
return ret;
23+
return (((ret) + (intentionally_const_var)) - (intentionally_const_var));
2224
}
2325
});
2426
panic!("ub: non-void function does not return a value")

0 commit comments

Comments
 (0)