#![forbid(unsafe_code)]
use std::sync::Arc;
use vyre_foundation::ir::{validate, Node, Program};
use vyre_primitives::graph::program_graph::ProgramGraphShape;
use vyre_self_substrate::optimizer::dce_program::{
build_dce_bfs_program, build_persistent_bfs_program,
};
fn shape() -> ProgramGraphShape {
ProgramGraphShape::new(64, 256)
}
fn dce_program() -> Program {
build_dce_bfs_program(shape(), 8)
}
fn sticky_program() -> Program {
build_persistent_bfs_program(shape(), 8, u32::MAX)
}
const PERSISTENT_LOOP_VAR: &str = "iter";
fn loop_body(program: &Program) -> &[Node] {
fn find<'a>(nodes: &'a [Node]) -> Option<&'a [Node]> {
for node in nodes {
let found = match node {
Node::Loop { var, body, .. } if var.as_str() == PERSISTENT_LOOP_VAR => {
return Some(body.as_slice())
}
Node::Loop { body, .. } => find(body),
Node::If {
then, otherwise, ..
} => find(then).or_else(|| find(otherwise)),
Node::Block(body) => find(body),
Node::Region { body, .. } => find(body),
_ => None,
};
if found.is_some() {
return found;
}
}
None
}
find(program.entry()).unwrap_or_else(|| {
panic!("no persistent loop named `{PERSISTENT_LOOP_VAR}` in the program entry")
})
}
fn edit_loop_body(program: &mut Program, edit: impl FnOnce(&mut Vec<Node>)) {
fn walk(nodes: &mut [Node], edit: &mut Option<Box<dyn FnOnce(&mut Vec<Node>) + '_>>) -> bool {
for node in nodes.iter_mut() {
let done = match node {
Node::Loop { var, body, .. } if var.as_str() == PERSISTENT_LOOP_VAR => {
let apply = edit.take().expect("the edit runs exactly once");
apply(body);
true
}
Node::Loop { body, .. } => walk(body, edit),
Node::If {
then, otherwise, ..
} => walk(then, edit) || walk(otherwise, edit),
Node::Block(body) => walk(body, edit),
Node::Region { body, .. } => {
let owned: &mut Vec<Node> = Arc::make_mut(body);
walk(owned, edit)
}
_ => false,
};
if done {
return true;
}
}
false
}
let mut slot: Option<Box<dyn FnOnce(&mut Vec<Node>) + '_>> = Some(Box::new(edit));
assert!(
walk(program.entry_mut(), &mut slot),
"expected to edit the body of the persistent loop"
);
}
fn barriers_at_any_depth(nodes: &[Node]) -> usize {
nodes
.iter()
.map(|node| match node {
Node::Barrier { .. } => 1,
Node::If {
then, otherwise, ..
} => barriers_at_any_depth(then) + barriers_at_any_depth(otherwise),
Node::Loop { body, .. } => barriers_at_any_depth(body),
Node::Block(body) => barriers_at_any_depth(body),
Node::Region { body, .. } => barriers_at_any_depth(body),
_ => 0,
})
.sum()
}
fn top_level_barriers(nodes: &[Node]) -> usize {
nodes
.iter()
.filter(|node| matches!(node, Node::Barrier { .. }))
.count()
}
fn node_name(node: &Node) -> &'static str {
match node {
Node::Barrier { .. } => "Barrier",
Node::Return => "Return",
Node::If { .. } => "If",
Node::Loop { .. } => "Loop",
Node::Store { .. } => "Store",
Node::Let { .. } => "Let",
Node::Block(_) => "Block",
_ => "other",
}
}
fn returns_at_any_depth(nodes: &[Node]) -> usize {
nodes
.iter()
.map(|node| match node {
Node::Return => 1,
Node::If {
then, otherwise, ..
} => returns_at_any_depth(then) + returns_at_any_depth(otherwise),
Node::Loop { body, .. } => returns_at_any_depth(body),
Node::Block(body) => returns_at_any_depth(body),
Node::Region { body, .. } => returns_at_any_depth(body),
_ => 0,
})
.sum()
}
fn exit_index(body: &[Node]) -> usize {
let found: Vec<usize> = body
.iter()
.enumerate()
.filter(|(_, node)| returns_at_any_depth(std::slice::from_ref(*node)) > 0)
.map(|(index, _)| index)
.collect();
assert_eq!(
found.len(),
1,
"expected exactly one top-level node to carry the early exit"
);
found[0]
}
fn last_top_level_barrier(body: &[Node]) -> usize {
body.iter()
.enumerate()
.filter(|(_, node)| matches!(node, Node::Barrier { .. }))
.map(|(index, _)| index)
.next_back()
.expect("the iteration body must contain at least one barrier")
}
fn messages(program: &Program) -> Vec<String> {
validate(program)
.iter()
.map(|error| error.message().to_string())
.collect()
}
fn v055_count(program: &Program) -> usize {
messages(program)
.iter()
.filter(|message| message.contains("V055"))
.count()
}
#[test]
fn dce_program_validates_with_no_errors() {
let program = dce_program();
assert_eq!(
messages(&program),
Vec::<String>::new(),
"the DCE fixpoint program must validate clean"
);
}
#[test]
fn sticky_persistent_program_validates_with_no_errors() {
let program = sticky_program();
assert_eq!(
messages(&program),
Vec::<String>::new(),
"the sticky persistent-BFS program must validate clean"
);
}
#[test]
fn iteration_body_ends_with_a_barrier_in_both_variants() {
for (label, program) in [("dce", dce_program()), ("sticky", sticky_program())] {
let body = loop_body(&program);
let last = body.last().expect("the iteration body is not empty");
assert!(
matches!(last, Node::Barrier { .. }),
"{label}: the iteration body must END with a barrier, found {}",
node_name(last)
);
}
}
#[test]
fn the_early_exit_precedes_the_last_barrier() {
for (label, program) in [("dce", dce_program()), ("sticky", sticky_program())] {
let body = loop_body(&program);
let exit = exit_index(body);
let barrier = last_top_level_barrier(body);
assert!(
exit < barrier,
"{label}: the exit at index {exit} must come BEFORE the body's last \
barrier at index {barrier}"
);
assert_eq!(
barrier,
body.len() - 1,
"{label}: the last barrier must be the final node of the body"
);
}
}
#[test]
fn no_barrier_sits_inside_a_conditional_in_the_iteration_body() {
for (label, program) in [("dce", dce_program()), ("sticky", sticky_program())] {
let body = loop_body(&program);
assert_eq!(
barriers_at_any_depth(body),
top_level_barriers(body),
"{label}: every barrier in the iteration body must be unconditional \
at body level; a nested one means some lanes can skip it"
);
}
}
#[test]
fn the_iteration_body_holds_exactly_three_barriers() {
for (label, program) in [("dce", dce_program()), ("sticky", sticky_program())] {
let body = loop_body(&program);
assert_eq!(
top_level_barriers(body),
3,
"{label}: expected exactly three unconditional barriers"
);
}
}
#[test]
fn the_early_exit_is_retained_and_stays_conditional() {
for (label, program) in [("dce", dce_program()), ("sticky", sticky_program())] {
let body = loop_body(&program);
assert_eq!(
returns_at_any_depth(body),
1,
"{label}: the body must keep exactly one early exit"
);
assert_eq!(
body.iter()
.filter(|node| matches!(node, Node::Return))
.count(),
0,
"{label}: the exit must be nested under the convergence condition, \
never a top-level unconditional return"
);
}
}
#[test]
fn edge_iteration_budgets_still_validate() {
for max_iters in [0_u32, 1, 2, 1024] {
let program = build_dce_bfs_program(shape(), max_iters);
assert_eq!(
messages(&program),
Vec::<String>::new(),
"max_iters {max_iters} must validate clean"
);
let body = loop_body(&program);
assert!(
matches!(body.last(), Some(Node::Barrier { .. })),
"max_iters {max_iters} must still end its body with a barrier"
);
}
}
#[test]
fn assorted_graph_shapes_still_validate() {
for (nodes, edges) in [(1_u32, 0_u32), (2, 1), (64, 256), (4096, 16384)] {
let program = build_dce_bfs_program(ProgramGraphShape::new(nodes, edges), 8);
assert_eq!(
messages(&program),
Vec::<String>::new(),
"shape ({nodes}, {edges}) must validate clean"
);
}
}
#[test]
fn removing_the_trailing_barrier_is_still_refused() {
let mut program = dce_program();
assert_eq!(v055_count(&program), 0, "the built program starts clean");
edit_loop_body(&mut program, |body| {
let last = body.pop().expect("body is not empty");
assert!(
matches!(last, Node::Barrier { .. }),
"expected to remove the trailing barrier"
);
});
assert_eq!(
v055_count(&program),
1,
"with its trailing barrier gone the program must be refused; messages \
were {:?}",
messages(&program)
);
}
#[test]
fn a_barrier_moved_inside_the_convergence_gate_is_still_refused() {
let mut program = dce_program();
edit_loop_body(&mut program, |body| {
let barrier = body.pop().expect("body is not empty");
assert!(matches!(barrier, Node::Barrier { .. }));
let exit = body.pop().expect("body still holds the exit");
match exit {
Node::If {
cond,
mut then,
otherwise,
} => {
then.insert(0, barrier);
body.push(Node::If {
cond,
then,
otherwise,
});
}
other => panic!("expected the exit to be an If, found {}", node_name(&other)),
}
});
assert_eq!(
v055_count(&program),
1,
"a barrier under the convergence condition must not satisfy the \
back-edge rule; messages were {:?}",
messages(&program)
);
}
#[test]
fn moving_the_exit_after_the_last_barrier_is_still_refused() {
let mut program = dce_program();
let clean_barriers = top_level_barriers(loop_body(&program));
edit_loop_body(&mut program, |body| {
let barrier = body.pop().expect("body is not empty");
let exit = body.pop().expect("body still holds the exit");
body.push(barrier);
body.push(exit);
});
assert_eq!(
top_level_barriers(loop_body(&program)),
clean_barriers,
"the reordering must not change the barrier count"
);
assert_eq!(
v055_count(&program),
1,
"an exit after the last barrier must be refused however the body is \
otherwise shaped; messages were {:?}",
messages(&program)
);
}
#[test]
fn even_a_uniform_exit_after_the_barrier_is_refused_today() {
let mut program = dce_program();
edit_loop_body(&mut program, |body| body.push(Node::Return));
assert_eq!(
v055_count(&program),
1,
"V055 is conservative by design: it refuses any exit after the last \
barrier, including this uniform one; messages were {:?}",
messages(&program)
);
}