Skip to content

Commit 4780e38

Browse files
consider in const folding that variables may be overwritten in loop bodies
1 parent 5e9dc8d commit 4780e38

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

src/optimisation/const_folding.rs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ pub struct ConstFoldState {
5454
pub vars: BTreeMap<Box<str>, ConstFoldItem>,
5555
}
5656

57+
impl ConstFoldState {
58+
fn merge(&mut self, other: Self) {
59+
for (var, _) in other.vars {
60+
self.vars.insert(
61+
var,
62+
ConstFoldItem::Unknown {
63+
possible_types: IrType::none(), // this is ok because the unknown value is never actually used
64+
opcodes: Rc::from([]),
65+
},
66+
);
67+
}
68+
}
69+
}
70+
5771
fn const_fold_step<S>(step: S, state: &mut ConstFoldState) -> HQResult<()>
5872
where
5973
S: Deref<Target = RefCell<Step>>,
@@ -89,12 +103,18 @@ where
89103
{
90104
let body_mut = Rc::new(Rc::unwrap_or_clone(body));
91105
let condition_mut = Rc::new(Rc::unwrap_or_clone(condition));
92-
const_fold_step(Rc::clone(&body_mut), &mut ConstFoldState::default())?;
93-
const_fold_step(Rc::clone(&condition_mut), &mut ConstFoldState::default())?;
106+
let mut body_state = ConstFoldState::default();
107+
const_fold_step(Rc::clone(&body_mut), &mut body_state)?;
108+
state.merge(body_state);
109+
let mut condition_state = ConstFoldState::default();
110+
const_fold_step(Rc::clone(&condition_mut), &mut condition_state)?;
111+
state.merge(condition_state);
94112
let first_condition_mut = first_condition
95113
.map(|first_cond_step| -> HQResult<_> {
96114
let first_cond_mut = Rc::new(Rc::unwrap_or_clone(first_cond_step));
97-
const_fold_step(Rc::clone(&first_cond_mut), &mut ConstFoldState::default())?;
115+
let mut cond_state = ConstFoldState::default();
116+
const_fold_step(Rc::clone(&first_cond_mut), &mut cond_state)?;
117+
state.merge(cond_state);
98118

99119
Ok(first_cond_mut)
100120
})

0 commit comments

Comments
 (0)