diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs index bfd4f3b2822..94fdee5616b 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs @@ -234,10 +234,35 @@ struct PendingSegments { impl PendingSegments { fn build(eu: &ExecutionUnit) -> Self { + Self::build_with_working_inputs(eu, false) + } + + fn build_with_working_inputs(eu: &ExecutionUnit, inputs: bool) -> Self { let mut endpoints: HashMap> = 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 => @@ -348,6 +373,90 @@ fn update_segments(bits: &mut [u64], range: std::ops::Range, 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, +) -> 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. /// diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs index 2d1c5932ce1..066d74dd102 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs @@ -17,6 +17,17 @@ pub fn eliminate_working_round_trip( eu: &mut ExecutionUnit, _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) { + eliminate_working_round_trip_impl(eu, true); +} + +fn eliminate_working_round_trip_impl(eu: &mut ExecutionUnit, partial: bool) { use crate::HashMap; // Phase 1: Scan — collect info about each WORKING variable @@ -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 = 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 @@ -151,7 +169,8 @@ pub fn eliminate_working_round_trip( let sparse_eligible: crate::HashSet = 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) @@ -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); + } } diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 3be0427242b..36ba67285b4 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -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;n0) begin : pipe + logic [7:0] r[N+2:3]; + for(genvar n=0;n 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)))) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 28811acbea5..b452f9474b6 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -821,11 +821,24 @@ pub(crate) struct NativeCodegenTrace { pub state_layout: String, } +/// Optimization context of a merged native function. Diagnostic labels do +/// not describe whether pending values can be produced outside this function. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum NativeMergeKind { + /// A complete sequential group of execution units. + Complete, + /// Combinational settling followed by an FF event in the same function. + FusedCombAndFf, + /// One task of a partitioned kernel; other tasks may define pending state. + Partial, +} + fn prepare_merged_sir( units: &[&crate::ir::ExecutionUnit], layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, diagnostics: &crate::optimizer::SirDiagnostics, cancel: Option<&CompileCancel>, @@ -900,7 +913,7 @@ fn prepare_merged_sir( } } report_phase("comb_state_dse"); - if label == "eval_comb_apply_ff" + if merge_kind == NativeMergeKind::FusedCombAndFf && crate::optimizer::sir::promote_fused_comb_static_slots(&mut sir_eu).map_err( |source| { codegen_err(CodegenError::Optimization { @@ -914,10 +927,17 @@ fn prepare_merged_sir( verify(&sir_eu, "after final fused comb StateSSA promotion")?; } report_phase("comb_state_ssa"); - crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_working_round_trip( - &mut sir_eu, - &boundaries, - ); + match merge_kind { + NativeMergeKind::Partial => { + crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_partial_working_round_trip(&mut sir_eu); + } + NativeMergeKind::Complete | NativeMergeKind::FusedCombAndFf => { + crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_working_round_trip( + &mut sir_eu, + &boundaries, + ); + } + } verify(&sir_eu, "after x86 direct working rewrite")?; if cancelled(cancel) { return Err(cancelled_error()); @@ -937,7 +957,7 @@ fn prepare_merged_sir( &mut sir_eu, layout, four_state, - label == "eval_comb_apply_ff", + merge_kind == NativeMergeKind::FusedCombAndFf, diagnostics, || cancelled(cancel), ) @@ -972,6 +992,7 @@ fn compile_units( layout, four_state, label, + NativeMergeKind::Complete, None, x86_options, capture_trace, @@ -985,6 +1006,7 @@ pub(super) fn compile_unit_refs( layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, x86_options: &crate::backend::X86BackendOptions, capture_trace: bool, @@ -996,6 +1018,7 @@ pub(super) fn compile_unit_refs( layout, four_state, label, + merge_kind, first_ff_unit, x86_options, capture_trace, @@ -1014,6 +1037,7 @@ pub(super) fn compile_unit_refs_inspected( layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, x86_options: &crate::backend::X86BackendOptions, capture_trace: bool, @@ -1103,6 +1127,7 @@ pub(super) fn compile_unit_refs_inspected( layout, four_state, label, + merge_kind, first_ff_unit, diagnostics, cancel, @@ -1288,6 +1313,7 @@ pub(super) fn native_function_at( struct NativeCompileTask<'a> { units: Vec<&'a crate::ir::ExecutionUnit>, label: &'static str, + merge_kind: NativeMergeKind, first_ff_unit: Option, bindings: Vec, } @@ -1343,7 +1369,9 @@ fn collect_comb_apply_compile_tasks<'a>( }; let binding = format!("{LABEL} trigger={}", sir.get_path(addr)); let index = if let Some(index) = tasks.iter().position(|task| { - task.label == LABEL && task.first_ff_unit == first_ff_unit && task.units == unit_refs + task.merge_kind == NativeMergeKind::FusedCombAndFf + && task.first_ff_unit == first_ff_unit + && task.units == unit_refs }) { tasks[index].bindings.push(binding); index @@ -1352,6 +1380,7 @@ fn collect_comb_apply_compile_tasks<'a>( tasks.push(NativeCompileTask { units: unit_refs, label: LABEL, + merge_kind: NativeMergeKind::FusedCombAndFf, first_ff_unit, bindings: vec![binding], }); @@ -1382,6 +1411,7 @@ fn collect_ff_compile_tasks_from<'a>( tasks.push(NativeCompileTask { units: unit_refs, label, + merge_kind: NativeMergeKind::Complete, first_ff_unit: None, bindings: vec![binding], }); @@ -2037,6 +2067,7 @@ fn compile_program( layout, options.four_state, task.label, + task.merge_kind, task.first_ff_unit, &options.x86_options, capture_trace, @@ -2087,6 +2118,7 @@ fn compile_program( layout, four_state, task.label, + task.merge_kind, task.first_ff_unit, x86_options, capture_trace, @@ -2146,6 +2178,7 @@ fn compile_program( layout, options.four_state, &format!("eval_comb_unit[{index}]"), + NativeMergeKind::Complete, None, &options.x86_options, false, @@ -2168,6 +2201,7 @@ fn compile_program( layout, options.four_state, &format!("process[{index}]"), + NativeMergeKind::Complete, None, &options.x86_options, false, diff --git a/crates/celox/src/backend/native/lanes.rs b/crates/celox/src/backend/native/lanes.rs index f5df76649e0..ac2882c4f48 100644 --- a/crates/celox/src/backend/native/lanes.rs +++ b/crates/celox/src/backend/native/lanes.rs @@ -13,8 +13,8 @@ use celox_sir_opt::parallel::Footprint; use serde::{Deserialize, Serialize}; use super::backend::{ - CompiledNativeFunction, NativeCodeEntry, NativeCodeSymbol, NativeSimFunc, append_native_code, - codegen_message, compile_unit_refs_inspected, native_function_at, + CompiledNativeFunction, NativeCodeEntry, NativeCodeSymbol, NativeMergeKind, NativeSimFunc, + append_native_code, codegen_message, compile_unit_refs_inspected, native_function_at, }; use super::jit_mem; use crate::backend::compile_cancel::CompileCancel; @@ -242,6 +242,7 @@ pub(super) fn compile_lane_kernels( layout, options.four_state, "lane_task", + NativeMergeKind::Partial, None, &lane_options, false, diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index dad4f88d17a..f1816a8b4ab 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -369,3 +369,9 @@ fn continuous_part_selects_partly_outside_drive_the_bits_inside() { assert_eq!(sim.get(q), 0xc1u8.into()); assert_eq!(sim.get(r), 0x5au8.into()); } + +sv_backends! { + fn generated_pipeline_with_explicit_generate_branches(sim) { + @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; + } +}