diff --git a/crates/celox-frontend-veryl/src/dynamic_for_check.rs b/crates/celox-frontend-veryl/src/dynamic_for_check.rs index f186e9b4a9d..ea95cacc476 100644 --- a/crates/celox-frontend-veryl/src/dynamic_for_check.rs +++ b/crates/celox-frontend-veryl/src/dynamic_for_check.rs @@ -513,7 +513,7 @@ fn collect_immediate_state_writes( } } } - propagate_comb_writes(&scheduled.sir.eval_comb, &mut writes); + propagate_comb_writes(scheduled, &mut writes); writes } @@ -640,7 +640,7 @@ fn collect_state_change_writes( // comb propagation and newly reached event domains. loop { let before = writes.clone(); - propagate_comb_writes(&scheduled.sir.eval_comb, &mut writes); + propagate_comb_writes(scheduled, &mut writes); for event in &scheduled.design.events.ordered_events { if writes .iter() @@ -726,16 +726,20 @@ fn push_unit_stable_writes( } } -fn propagate_comb_writes( - units: &[ExecutionUnit], - writes: &mut Vec, -) { +fn propagate_comb_writes(scheduled: &ScheduledRtl, writes: &mut Vec) { + // A partitioned settle's flags only say what to recompute: running a + // partition whose inputs did not change stores the values already there. + let settle_flags = scheduled + .runtime_schema + .settle_partitions + .as_ref() + .map(|settle| settle.flags); // A later unit may feed an earlier one when a conservative scheduler path // was retained. Iterate to a fixed point rather than relying on unit order. loop { let before = writes.clone(); - for unit in units { - propagate_comb_unit(unit, writes); + for unit in &scheduled.sir.eval_comb { + propagate_comb_unit(unit, settle_flags, writes); } if *writes == before { break; @@ -745,6 +749,7 @@ fn propagate_comb_writes( fn propagate_comb_unit( unit: &ExecutionUnit, + settle_flags: Option, writes: &mut Vec, ) { let mut registers: HashMap> = HashMap::default(); @@ -883,6 +888,8 @@ fn propagate_comb_unit( }; changed |= extend_register_taint(&mut registers, *dst, taint); } + SIRInstruction::Store(address, ..) + if Some(address.absolute_addr()) == settle_flags => {} SIRInstruction::Store(address, offset, width, source, ..) => { let address_tainted = offset .dynamic_registers() diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index 4f2f1390dd8..aff8b5c5892 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -3499,13 +3499,28 @@ const MAX_JOINT_FOLD_ROOTS: usize = 16; struct PlannedPartition { reads: Vec, writes: Vec, - /// The partitions whose flags it sets when it runs: those reading what - /// it writes, itself included when it reads the previous value of its - /// own writes. + /// The partitions whose flags it sets whenever it runs: the readers of + /// what it writes whose width is unknown. marks: Vec, + /// What it writes that other partitions read, itself included when it + /// reads the previous value of its own writes. It sets the readers' + /// flags only when it changes the value. + watched: Vec>, pinned: bool, } +/// A chunk of an object a partition writes, compared before and after the +/// partition runs. +struct WatchedChunk { + object: Addr, + offset: SIROffset, + width: usize, + readers: Vec, +} + +/// The widest chunk of a written object compared at once. +const MAX_WATCHED_WIDTH: usize = 4096; + /// The partitions of a settle, each a contiguous run of scheduled work. struct PartitionPlan { /// The first scheduled work of each partition. @@ -3626,6 +3641,7 @@ fn plan_settle_partitions, arena: &SLTNodeArena, var_widths: &HashMap, + unpacked_element_widths: &HashMap, partitioning: SettlePartitioning, ) -> Option<(PartitionPlan, Addr)> { let input = &prepared.input; @@ -3762,17 +3778,48 @@ fn plan_settle_partitions = readers + .get(addr) + .into_iter() + .flatten() + .copied() + .filter(|&reader| reader != partition || previous[partition].contains(addr)) + .collect(); + if targets.is_empty() { + continue; + } + let Some(&width) = var_widths.get(addr) else { + marks.extend(targets); + continue; + }; + // Compare an unpacked array in whole elements. + let element = unpacked_element_widths + .get(addr) + .copied() + .filter(|&element| element != 0 && width.is_multiple_of(element)) + .unwrap_or(1); + let step = (MAX_WATCHED_WIDTH / element).max(1) * element; + for lsb in (0..width).step_by(step) { + let chunk = (width - lsb).min(step); + watched.push(WatchedChunk { + object: *addr, + offset: static_access_offset( + addr, + BitAccess::new(lsb, lsb + chunk - 1), + unpacked_element_widths, + ), + width: chunk, + readers: targets.clone(), + }); } } PlannedPartition { reads: reads[partition].iter().copied().collect(), writes: writes[partition].iter().copied().collect(), marks: marks.into_iter().collect(), + watched, pinned: pinned[partition], } }) @@ -3841,6 +3888,8 @@ struct WorkLowering<'a, Addr: Clone + Eq + Hash> { in_partition: bool, /// Where a guarded partition continues when it is skipped. partition_merge: Option, + /// The open partition's watched chunks before it ran. + partition_old: Vec, } impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a, Addr> { @@ -3857,6 +3906,7 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a run_processes: HashSet::default(), in_partition: false, partition_merge: None, + partition_old: Vec::new(), } } @@ -3921,12 +3971,62 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a Vec::new(), Vec::new(), )); + self.partition_old.clear(); + for chunk in &partition.watched { + let old = self.builder.alloc_logic(chunk.width); + self.builder.emit(SIRInstruction::Load( + old, + chunk.object, + chunk.offset.clone(), + chunk.width, + )); + self.partition_old.push(old); + } } /// Close a partition: set the flags of the partitions reading what it - /// wrote, then join the path that skipped it. + /// changed, then join the path that skipped it. fn end_partition(&mut self, flags: Addr, partition: &PlannedPartition) { self.flush_pending_folds(); + if !partition.watched.is_empty() { + let one = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + let old = std::mem::take(&mut self.partition_old); + for (chunk, old) in partition.watched.iter().zip(old) { + let new = self.builder.alloc_logic(chunk.width); + self.builder.emit(SIRInstruction::Load( + new, + chunk.object, + chunk.offset.clone(), + chunk.width, + )); + // Both planes: an X turning into a known value is a change. + let changed = self.builder.alloc_bit(1, false); + self.builder + .emit(SIRInstruction::Binary(changed, old, BinaryOp::NeCase, new)); + for &reader in &chunk.readers { + let flag = self.builder.alloc_bit(8, false); + self.builder.emit(SIRInstruction::Load( + flag, + flags, + SIROffset::Static(reader * 8), + 8, + )); + let marked = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Mux(marked, changed, one, flag)); + self.builder.emit(SIRInstruction::Store( + flags, + SIROffset::Static(reader * 8), + 8, + marked, + Vec::new(), + Vec::new(), + )); + } + } + } if !partition.marks.is_empty() { let one = self.builder.alloc_bit(8, false); self.builder @@ -4435,7 +4535,13 @@ fn sort_impl( let plan = partitioning .filter(|_| ff.is_none()) .and_then(|partitioning| { - plan_settle_partitions(&prepared, arena, var_widths, partitioning) + plan_settle_partitions( + &prepared, + arena, + var_widths, + unpacked_element_widths, + partitioning, + ) }); for (index, work) in prepared.scheduled_work.iter().enumerate() { if let Some((plan, flags)) = &plan { @@ -5174,9 +5280,10 @@ mod tests { ); assert!(result.partitions.iter().all(|partition| !partition.pinned)); // Each partition loads its own flag and the untracked-writes flag - // after them; a partition sets its reader's. + // after them, and sets its reader's when it changed what it wrote. let mut loaded = Vec::new(); let mut stored = Vec::new(); + let mut compares = 0; for unit in &result.execution_units { for block in unit.blocks.values() { for instruction in &block.instructions { @@ -5187,6 +5294,7 @@ mod tests { SIRInstruction::Store(99, SIROffset::Static(byte), 8, ..) => { stored.push(*byte) } + SIRInstruction::Binary(_, _, BinaryOp::NeCase, _) => compares += 1, _ => {} } } @@ -5194,9 +5302,13 @@ mod tests { } loaded.sort_unstable(); stored.sort_unstable(); - assert_eq!(loaded, vec![0, 8, 16, 24, 24, 24]); + // Guards of 0, 8 and 16, the untracked byte for each, and the + // readers' flags of partitions 1 and 2 before a conditional mark. + assert_eq!(loaded, vec![0, 8, 8, 16, 16, 24, 24, 24]); // The clears of all three flags, and the marks of partitions 1 and 2. assert_eq!(stored, vec![0, 8, 8, 16, 16]); + // 11 and 12 are compared before their readers are marked. + assert_eq!(compares, 2); } #[test] diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs index 24a5bf6bde5..fbd78cac2f8 100644 --- a/crates/celox/src/settle.rs +++ b/crates/celox/src/settle.rs @@ -2,9 +2,9 @@ //! the flag layout, and the flag stores of the units outside the settle. //! //! A partition of the settle runs only when its flag is set. The settle's -//! own partitions set the flags of their readers; every other writer of -//! state the settle reads or writes sets them here, at each store or commit -//! to the state, and host writes set them through +//! own partitions set the flags of the readers of what they change; every +//! other writer of state the settle reads or writes sets them here, at each +//! store or commit that changes the state, and host writes set them through //! [`celox_state_layout::SettleLayout`]. use crate::ir::{ ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, RegisterType, SIRInstruction, @@ -188,6 +188,29 @@ impl<'a> Marker<'a> { } } + /// Whether an access covers more than one element of an element-strided + /// array whose elements are padded: a load of it would not gather the + /// elements on every backend, so the store cannot be compared. + fn spans_padded_elements( + &self, + address: &RegionedAbsoluteAddr, + offset: &SIROffset, + width: usize, + ) -> bool { + let Some(array) = self.layout.unpacked_arrays.get(&address.absolute_addr()) else { + return false; + }; + if array.element_stride * 8 == array.element_width { + return false; + } + match offset.constant_bit_offset() { + Some(start) => { + start / array.element_width != (start + width.max(1) - 1) / array.element_width + } + None => width > array.element_width, + } + } + fn instrument(&self, unit: &mut ExecutionUnit) { let mut next_register = unit .register_map @@ -195,44 +218,104 @@ impl<'a> Marker<'a> { .map(|register| register.0 + 1) .max() .unwrap_or(0); - for block in unit.blocks.values_mut() { + let mut alloc = |unit: &mut ExecutionUnit, ty: RegisterType| { + let register = RegisterId(next_register); + next_register += 1; + unit.register_map.insert(register, ty); + register + }; + let byte = RegisterType::Bit { + width: 8, + signed: false, + }; + let block_ids: Vec<_> = unit.blocks.keys().copied().collect(); + for block_id in block_ids { + let block = unit.blocks.get_mut(&block_id).expect("listed block"); + let old_instructions = std::mem::take(&mut block.instructions); let mut one = None; - let mut instructions = Vec::with_capacity(block.instructions.len()); - for instruction in std::mem::take(&mut block.instructions) { - let readers = match &instruction { - SIRInstruction::Store(address, ..) => self.readers(address), - SIRInstruction::Commit(_, address, ..) => self.readers(address), - _ => Vec::new(), + let mut instructions = Vec::with_capacity(old_instructions.len()); + for instruction in old_instructions { + let target = match &instruction { + SIRInstruction::Store(address, offset, width, ..) + | SIRInstruction::Commit(_, address, offset, width, _) => { + Some((*address, offset.clone(), *width)) + } + _ => None, }; - instructions.push(instruction); + let Some((address, offset, width)) = target else { + instructions.push(instruction); + continue; + }; + let readers = self.readers(&address); if readers.is_empty() { + instructions.push(instruction); continue; } let one = *one.get_or_insert_with(|| { - let register = RegisterId(next_register); - next_register += 1; - unit.register_map.insert( - register, - RegisterType::Bit { - width: 8, - signed: false, - }, - ); + let register = alloc(unit, byte.clone()); instructions.push(SIRInstruction::Imm(register, SIRValue::new(1u64))); register }); + if width > MAX_COMPARED_WIDTH + || self.spans_padded_elements(&address, &offset, width) + { + instructions.push(instruction); + for partition in readers { + instructions.push(SIRInstruction::Store( + self.flags, + SIROffset::Static(partition as usize * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + continue; + } + // Set the readers' flags only when the store changes the + // state, both planes compared. + let old = alloc(unit, RegisterType::Logic { width }); + instructions.push(SIRInstruction::Load(old, address, offset.clone(), width)); + instructions.push(instruction); + let new = alloc(unit, RegisterType::Logic { width }); + instructions.push(SIRInstruction::Load(new, address, offset, width)); + let changed = alloc( + unit, + RegisterType::Bit { + width: 1, + signed: false, + }, + ); + instructions.push(SIRInstruction::Binary( + changed, + old, + celox_sir::BinaryOp::NeCase, + new, + )); for partition in readers { + let flag = alloc(unit, byte.clone()); + let marked = alloc(unit, byte.clone()); + let offset = SIROffset::Static(partition as usize * 8); + instructions.push(SIRInstruction::Load(flag, self.flags, offset.clone(), 8)); + instructions.push(SIRInstruction::Mux(marked, changed, one, flag)); instructions.push(SIRInstruction::Store( self.flags, - SIROffset::Static(partition as usize * 8), + offset, 8, - one, + marked, Vec::new(), Vec::new(), )); } } - block.instructions = instructions; + unit.blocks + .get_mut(&block_id) + .expect("listed block") + .instructions = instructions; } } } + +/// The widest store compared before it marks the readers; wider ones mark +/// them on every store, like stores across padded array elements. +const MAX_COMPARED_WIDTH: usize = 4096; diff --git a/crates/celox/tests/settle_partitions.rs b/crates/celox/tests/settle_partitions.rs index 3e9fa3dba0f..4237e5286b3 100644 --- a/crates/celox/tests/settle_partitions.rs +++ b/crates/celox/tests/settle_partitions.rs @@ -173,7 +173,7 @@ fn loaded_state_reaches_partitions() { mod systemverilog { use std::path::Path; - use celox::{BigUint, SettlePartition, Simulation, SirPass}; + use celox::{BigUint, SettlePartition, Simulation, Simulator, SirPass}; /// A clock gated through a latch (Xilinx BUFGCE): the latch is a process /// of the settle, and the gated clock's edge runs another domain. @@ -290,6 +290,96 @@ endmodule assert_eq!(single[5][2], BigUint::from(3u8)); } + /// A padded unpacked array (13-bit elements, two bytes each in the + /// element-strided layout) whose element writes publish through one bulk + /// commit of the whole array: the commit must mark the reader of the last + /// element when only that element changes. + const PADDED: &str = r#" +module Top ( + input logic clk, + input logic we, + input logic [2:0] idx, + input logic [12:0] d, + input logic [2:0] ri, + output logic [12:0] q, + output logic [12:0] last +); + logic [12:0] m [8]; + always_ff @(posedge clk) if (we) m[idx] <= d; + assign q = m[ri]; + assign last = m[7]; +endmodule +"#; + + /// Whether `m` is element-strided, and the outputs after each tick. + macro_rules! padded_trace { + ($sim:expr) => {{ + let mut sim = $sim; + let strided = sim.signal("m").array_layout.is_some(); + let (clk, we, idx, d, ri) = ( + sim.event("clk"), + sim.signal("we"), + sim.signal("idx"), + sim.signal("d"), + sim.signal("ri"), + ); + let outputs = ["last", "q"].map(|name| sim.signal(name)); + let mut trace: Vec> = Vec::new(); + for step in 0..12u16 { + sim.modify(|io| { + io.set(we, 1u8); + // Mostly the last element, sometimes the first. + io.set(idx, if step % 3 == 2 { 0u8 } else { 7u8 }); + io.set(d, step.wrapping_mul(0x9e5) & 0x1fff); + io.set(ri, 0u8); + }) + .unwrap(); + sim.tick(clk).unwrap(); + trace.push(outputs.iter().map(|&signal| sim.get(signal)).collect()); + } + (strided, trace) + }}; + } + + fn padded(four_state: bool) -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::from_sv_sources(vec![(PADDED, Path::new("padded.sv"))], "Top") + .four_state(four_state) + } + + #[test] + fn element_writes_to_a_padded_array_match_single_pass() { + for four_state in [false, true] { + let (_, single) = padded_trace!( + padded(four_state) + .disable_pass(SirPass::PartitionedSettle) + .build_interpreter() + .unwrap() + ); + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + { + let (strided, trace) = padded_trace!( + padded(four_state) + .settle_partition(SettlePartition::Always) + .build_native() + .unwrap() + ); + assert!(strided, "native stores the array strided"); + assert_eq!(trace, single, "native, four_state={four_state}"); + } + let (strided, trace) = padded_trace!( + padded(four_state) + .settle_partition(SettlePartition::Always) + .build_tiered() + .unwrap() + ); + assert!(strided, "the tiered interpreter stores the array strided"); + assert_eq!(trace, single, "tiered, four_state={four_state}"); + } + } + #[test] fn copy_of_a_process_output_matches_single_pass() { matches_single_pass(COPY, &["r", "q"], 40);