Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,35 @@ struct PendingSegments {

impl PendingSegments {
fn build(eu: &ExecutionUnit<RegionedAbsoluteAddr>) -> Self {
Self::build_with_working_inputs(eu, false)
}

fn build_with_working_inputs(eu: &ExecutionUnit<RegionedAbsoluteAddr>, inputs: bool) -> Self {
let mut endpoints: HashMap<AbsoluteAddr, Vec<usize>> = HashMap::default();
for block in eu.blocks.values() {
for instruction in &block.instructions {
match instruction {
SIRInstruction::Load(_, addr, offset, bits)
if inputs && addr.region == WORKING_REGION =>
{
let (start, end) = instruction_range(&eu.register_map, offset, *bits);
endpoints
.entry(addr.absolute_addr())
.or_default()
.extend([start, end]);
}
SIRInstruction::Commit(src, dst, offset, bits, _)
if inputs
&& src.region == STABLE_REGION
&& dst.region == WORKING_REGION
&& src.absolute_addr() == dst.absolute_addr() =>
{
let (start, end) = instruction_range(&eu.register_map, offset, *bits);
endpoints
.entry(dst.absolute_addr())
.or_default()
.extend([start, end]);
}
SIRInstruction::Store(addr, offset, bits, _, _, _)
if addr.region == WORKING_REGION
|| addr.region == SPARSE_WORKING_REGION =>
Expand Down Expand Up @@ -348,6 +373,90 @@ fn update_segments(bits: &mut [u64], range: std::ops::Range<usize>, set: bool) {
}
}

/// A partial event can read pending values produced by another task. Such
/// values cannot be redirected to STABLE or have their publication removed.
/// Track possibly uninitialized access fragments, rather than bits of the
/// declared object, so large arrays with sparse accesses remain sparse.
pub(crate) fn uninitialized_working_observations(
eu: &ExecutionUnit<RegionedAbsoluteAddr>,
) -> DirectStableStoreHazards {
use std::collections::VecDeque;
let segments = PendingSegments::build_with_working_inputs(eu, true);
let mut hazards = DirectStableStoreHazards::default();
if segments.count == 0 {
return hazards;
}
let words = segments.count.div_ceil(64);
let mut incoming = HashMap::default();
incoming.insert(eu.entry_block_id, vec![u64::MAX; words]);
let mut queue = VecDeque::from([eu.entry_block_id]);
while let Some(id) = queue.pop_front() {
let block = &eu.blocks[&id];
let mut undefined = incoming[&id].clone();
for instruction in &block.instructions {
let observed = match instruction {
SIRInstruction::Load(_, address, offset, width)
if address.region == WORKING_REGION =>
{
Some((*address, offset, *width))
}
SIRInstruction::Commit(source, _, offset, width, _)
if source.region == WORKING_REGION =>
{
Some((*source, offset, *width))
}
_ => None,
};
if let Some((address, offset, width)) = observed {
let (start, end) = instruction_range(&eu.register_map, offset, width);
segments.record_observation(
&mut hazards,
&undefined,
address.absolute_addr(),
start,
end,
);
}
let defined = match instruction {
SIRInstruction::Store(address, offset, width, ..)
if address.region == WORKING_REGION =>
{
Some((*address, offset, *width))
}
SIRInstruction::Commit(source, destination, offset, width, _)
if source.region == STABLE_REGION
&& destination.region == WORKING_REGION
&& source.absolute_addr() == destination.absolute_addr() =>
{
Some((*destination, offset, *width))
}
_ => None,
};
if let Some((address, offset, width)) = defined
&& let Some(start) = offset.constant_bit_offset()
&& let Some(end) = start.checked_add(width)
&& let Some(range) = segments.segment_range(address.absolute_addr(), start, end)
{
update_segments(&mut undefined, range, false);
}
}
for successor in crate::ir::cfg::terminator_successors(&block.terminator) {
let is_new = !incoming.contains_key(&successor);
let entry = incoming.entry(successor).or_insert_with(|| vec![0; words]);
let mut changed = is_new;
for (destination, source) in entry.iter_mut().zip(&undefined) {
let merged = *destination | *source;
changed |= merged != *destination;
*destination = merged;
}
if changed {
queue.push_back(successor);
}
}
}
hazards
}

/// Bit ranges for which replacing a WORKING/SPARSE write with an immediate
/// STABLE write could change an observation in this complete event CFG.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ pub fn eliminate_working_round_trip(
eu: &mut ExecutionUnit<RegionedAbsoluteAddr>,
_eu_boundary_blocks: &[BlockId],
) {
eliminate_working_round_trip_impl(eu, false);
}

/// Optimize one partial event task. Pending values can have producers outside
/// this function, so publication requires proof of a local definition on every
/// path. Sparse publication can also consume dirty entries from other tasks.
pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit<RegionedAbsoluteAddr>) {
eliminate_working_round_trip_impl(eu, true);
}

fn eliminate_working_round_trip_impl(eu: &mut ExecutionUnit<RegionedAbsoluteAddr>, partial: bool) {
use crate::HashMap;

// Phase 1: Scan — collect info about each WORKING variable
Expand Down Expand Up @@ -140,9 +151,16 @@ pub fn eliminate_working_round_trip(
.collect();

let unsafe_after_store = super::commit_ops::direct_stable_store_hazards(eu);
let uninitialized = (partial && !eligible.is_empty())
.then(|| super::commit_ops::uninitialized_working_observations(eu));
let eligible: crate::HashSet<AbsoluteAddr> = eligible
.into_iter()
.filter(|addr| !unsafe_after_store.contains_addr(*addr))
.filter(|addr| {
!unsafe_after_store.contains_addr(*addr)
&& !uninitialized
.as_ref()
.is_some_and(|undefined| undefined.contains_addr(*addr))
})
.collect();

// Sparse state has no per-EU seed: every producer writes the same pending
Expand All @@ -151,7 +169,8 @@ pub fn eliminate_working_round_trip(
let sparse_eligible: crate::HashSet<AbsoluteAddr> = sparse_vars
.iter()
.filter(|(addr, info)| {
info.has_store
!partial
&& info.has_store
&& info.stable_addr.is_some()
&& !info.invalid_apply
&& !unsafe_after_store.contains_addr(**addr)
Expand Down Expand Up @@ -627,4 +646,122 @@ mod tests {
SIRInstruction::Commit(..)
));
}
#[test]
fn partial_event_keeps_publication_of_another_producers_fragment() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(24), 8),
SIRInstruction::Store(
addr(WORKING_REGION),
SIROffset::Static(24),
8,
RegisterId(1),
Vec::new(),
Vec::new(),
),
working_apply(SIROffset::Static(16), 8),
working_apply(SIROffset::Static(24), 8),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}

#[test]
fn partial_event_requires_a_definition_on_every_branch() {
for both_paths in [false, true] {
let store = || {
SIRInstruction::Store(
addr(WORKING_REGION),
SIROffset::Static(0),
8,
RegisterId(1),
Vec::new(),
Vec::new(),
)
};
let mut unit = eu(vec![
block(
0,
vec![],
SIRTerminator::Branch {
cond: RegisterId(3),
true_block: (BlockId(1), vec![]),
false_block: (BlockId(2), vec![]),
},
),
block(1, vec![store()], SIRTerminator::Jump(BlockId(3), vec![])),
block(
2,
if both_paths { vec![store()] } else { vec![] },
SIRTerminator::Jump(BlockId(3), vec![]),
),
block(
3,
vec![working_apply(SIROffset::Static(0), 8)],
SIRTerminator::Return,
),
]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
if both_paths {
assert!(unit.blocks[&BlockId(3)].instructions.is_empty());
assert!(
matches!(unit.blocks[&BlockId(1)].instructions[0],SIRInstruction::Store(address,..) if address.region==STABLE_REGION)
);
} else {
assert_eq!(unit, before);
}
}
}

#[test]
fn partial_event_keeps_unseeded_dynamic_pending_values() {
let mut unit = eu(vec![block(
0,
vec![
indexed_working_store(),
working_apply(SIROffset::Static(0), 64),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}

#[test]
fn partial_event_can_redirect_a_locally_seeded_dynamic_update() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(0), 64),
indexed_working_store(),
working_apply(SIROffset::Static(0), 64),
],
SIRTerminator::Return,
)]);
eliminate_partial_working_round_trip(&mut unit);
assert!(
matches!(unit.blocks[&BlockId(0)].instructions.as_slice(),[SIRInstruction::Store(address,SIROffset::Element {..},..)] if address.region==STABLE_REGION)
);
}
#[test]
fn partial_event_keeps_reads_of_another_producers_pending_fragment() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(0), 8),
SIRInstruction::Load(RegisterId(2), addr(WORKING_REGION), SIROffset::Static(8), 8),
working_apply(SIROffset::Static(0), 8),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}
}
56 changes: 56 additions & 0 deletions crates/celox-test-suite/src/sv/cases/indexed_select.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -1958,3 +1958,59 @@
(assert_eq l0 0) (assert_eq l1 0x40) (assert_eq l2 0)
(run_until 1)
(assert_eq s0 0) (assert_eq s1 0x42) (assert_eq s2 0))

(case generated_pipeline_with_explicit_generate_branches
; Separate FF producers may share one array. Removing a task's staging
; must preserve publication of elements computed by other tasks (10.4.2).
(source "generated_pipeline.sv" #"
module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[3:N+2];
for(genvar n=0;n<N;n++) begin : stage
if (n==0) begin
always_ff @(posedge clk) if(rst) r[n+3]<='0; else r[n+3]<=d;
end else begin
always_ff @(posedge clk) if(rst) r[n+3]<='0; else r[n+3]<=r[n+2];
end
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Desc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[N+2:3];
for(genvar n=0;n<N;n++) begin : stage
if (n==0) begin
always_ff @(posedge clk) if(rst) r[n+3]<='0; else r[n+3]<=d;
end else begin
always_ff @(posedge clk) if(rst) r[n+3]<='0; else r[n+3]<=r[n+2];
end
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Top(input logic clk, rst, input logic [7:0] d,
output logic [7:0] a1,a2,a4,b1,b2,b4);
Asc #(.N(1)) u1(clk,rst,d,a1);
Asc #(.N(2)) u2(clk,rst,d,a2);
Asc #(.N(4)) u4(clk,rst,d,a4);
Desc #(.N(1)) v1(clk,rst,d,b1);
Desc #(.N(2)) v2(clk,rst,d,b2);
Desc #(.N(4)) v4(clk,rst,d,b4);
endmodule
"#)
(top Top)
(modify (set rst 1))
(tick clk)
(modify (set rst 0))
(for cycle (range 1 8)
(modify (set d (* cycle 17)))
(tick clk)
(assert_eq a1 (* cycle 17))
(assert_eq b1 (* cycle 17))
(assert_eq a2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0))
(assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0))))
Loading
Loading