From f52c00e577c9205bd2332b2bf0bf8d5b50a85b1b Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 18:56:33 +0900 Subject: [PATCH 1/4] perf(native): deduplicate compile tasks by unit classes instead of deep comparison The native backend found an existing task for each trigger by comparing its unit list with every task so far, unit by unit and block by block. An unfused comb-apply task starts with all of `eval_comb`, so each comparison walked the whole combinational program: O(triggers^2 x program size). On C906 the backend sat in compile_program for 19+ minutes, mostly in memcmp and HashMap::eq. Each distinct execution unit is now hashed once and assigned a class of structurally equal units, and tasks are looked up by their list of classes. Two unit lists have the same classes exactly when they compare equal, and tasks are visited in the same order, so the tasks, their order and their bindings are the same as before and the generated code does not change. Closes #1982 Change-Id: I03837ef8fa9804562d781436411449be6cb1c9b8 --- crates/celox/src/backend/native/backend.rs | 198 ++++++++++++++++++--- 1 file changed, 170 insertions(+), 28 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b452f9474b6..bb0b9c8ea91 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -1320,42 +1320,101 @@ struct NativeCompileTask<'a> { type NativeTaskBindings = HashMap<(&'static str, AbsoluteAddr), usize>; +type NativeUnit = crate::ir::ExecutionUnit; + +/// Classes of structurally equal execution units. Each distinct unit is +/// hashed once and compared only against the units of its hash, so tasks +/// whose unit lists share whole programs, such as every unfused comb-apply +/// task starting with all of `eval_comb`, are told apart by their class +/// lists instead of by comparing the programs again for each trigger. +#[derive(Default)] +struct NativeUnitClasses<'a> { + by_unit: HashMap<*const NativeUnit, usize>, + by_hash: HashMap>, + count: usize, +} + +impl<'a> NativeUnitClasses<'a> { + fn class(&mut self, unit: &'a NativeUnit) -> usize { + if let Some(class) = self.by_unit.get(&std::ptr::from_ref(unit)) { + return *class; + } + let bucket = self.by_hash.entry(native_unit_hash(unit)).or_default(); + let class = match bucket.iter().find(|(other, _)| *other == unit) { + Some((_, class)) => *class, + None => { + let class = self.count; + self.count += 1; + bucket.push((unit, class)); + class + } + }; + self.by_unit.insert(std::ptr::from_ref(unit), class); + class + } + + fn classes(&mut self, units: &[&'a NativeUnit]) -> Vec { + units.iter().map(|unit| self.class(unit)).collect() + } +} + +/// A hash of `unit` that equal units share, independent of the iteration +/// order of its maps. +fn native_unit_hash(unit: &NativeUnit) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = fxhash::FxHasher::default(); + unit.entry_block_id.hash(&mut hasher); + let mut blocks = unit.blocks.iter().collect::>(); + blocks.sort_unstable_by_key(|(id, _)| **id); + for (id, block) in blocks { + id.hash(&mut hasher); + block.id.hash(&mut hasher); + block.params.hash(&mut hasher); + block.instructions.hash(&mut hasher); + block.terminator.hash(&mut hasher); + } + let mut registers = unit.register_map.iter().collect::>(); + registers.sort_unstable_by_key(|(id, _)| **id); + registers.hash(&mut hasher); + hasher.finish() +} + fn collect_ff_compile_tasks( sir: &LaidOutProgram, ) -> (Vec>, NativeTaskBindings) { let mut tasks = Vec::new(); let mut task_bindings = HashMap::default(); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_apply_ffs, - "eval_apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_only_ffs, - "eval_only_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.apply_ffs, - "apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_comb_apply_compile_tasks(sir, &mut tasks, &mut task_bindings); + let mut classes = NativeUnitClasses::default(); + // Edge tasks of every label share one index: a task is reused for any + // edge trigger with equal units. + let mut ff_tasks = HashMap::default(); + for (ff_map, label) in [ + (&sir.sir.eval_apply_ffs, "eval_apply_ff"), + (&sir.sir.eval_only_ffs, "eval_only_ff"), + (&sir.sir.apply_ffs, "apply_ff"), + ] { + collect_ff_compile_tasks_from( + sir, + ff_map, + label, + &mut classes, + &mut ff_tasks, + &mut tasks, + &mut task_bindings, + ); + } + collect_comb_apply_compile_tasks(sir, &mut classes, &mut tasks, &mut task_bindings); (tasks, task_bindings) } fn collect_comb_apply_compile_tasks<'a>( sir: &'a LaidOutProgram, + classes: &mut NativeUnitClasses<'a>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { const LABEL: &str = "eval_comb_apply_ff"; + let mut comb_tasks = HashMap::<(Option, Vec), usize>::default(); for (addr, ff_units) in &sir.sir.eval_apply_ffs { let fused_units = sir.sir.eval_comb_apply_ffs.get(addr); let (unit_refs, first_ff_unit) = if let Some(fused_units) = fused_units { @@ -1368,11 +1427,8 @@ fn collect_comb_apply_compile_tasks<'a>( (unit_refs, first_ff_unit) }; let binding = format!("{LABEL} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| { - task.merge_kind == NativeMergeKind::FusedCombAndFf - && task.first_ff_unit == first_ff_unit - && task.units == unit_refs - }) { + let key = (first_ff_unit, classes.classes(&unit_refs)); + let index = if let Some(&index) = comb_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1384,6 +1440,7 @@ fn collect_comb_apply_compile_tasks<'a>( first_ff_unit, bindings: vec![binding], }); + comb_tasks.insert(key, index); index }; task_bindings.insert((LABEL, *addr), index); @@ -1397,13 +1454,16 @@ fn collect_ff_compile_tasks_from<'a>( Vec>, >, label: &'static str, + classes: &mut NativeUnitClasses<'a>, + ff_tasks: &mut HashMap, usize>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { for (addr, units) in ff_map { let unit_refs = units.iter().collect::>(); let binding = format!("{label} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| task.units == unit_refs) { + let key = classes.classes(&unit_refs); + let index = if let Some(&index) = ff_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1415,6 +1475,7 @@ fn collect_ff_compile_tasks_from<'a>( first_ff_unit: None, bindings: vec![binding], }); + ff_tasks.insert(key, index); index }; task_bindings.insert((label, *addr), index); @@ -3515,3 +3576,84 @@ impl super::super::SimBackend for NativeBackend { celox_runtime::backend::triggered_bits_from_bytes(&self.mem_bytes()[offset..offset + size]) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir::{ + BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, + }; + + /// A unit of `blocks` blocks loading `value`, with its maps filled in + /// forward or reverse order. + fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit { + let mut ids = (0..blocks).collect::>(); + if reverse { + ids.reverse(); + } + NativeUnit { + entry_block_id: BlockId(0), + blocks: ids + .iter() + .map(|&id| { + let terminator = if id + 1 < blocks { + SIRTerminator::Jump(BlockId(id + 1), vec![]) + } else { + SIRTerminator::Return + }; + let block = BasicBlock { + id: BlockId(id), + params: vec![], + instructions: vec![SIRInstruction::Imm( + RegisterId(id), + SIRValue::new(value), + )], + terminator, + }; + (BlockId(id), block) + }) + .collect(), + register_map: ids + .iter() + .map(|&id| (RegisterId(id), RegisterType::Logic { width })) + .collect(), + } + } + + #[test] + fn unit_classes_match_deep_comparison() { + let mut pool = Vec::new(); + for blocks in 1..4 { + for value in 0..2 { + for width in [1, 8] { + for reverse in [false, true] { + pool.push(unit(blocks, value, width, reverse)); + } + } + } + } + let units = pool.iter().collect::>(); + // Lists of up to two units, repeating the same references as the + // shared prefix of comb-apply tasks does. + let lists = std::iter::once(Vec::new()) + .chain(units.iter().map(|unit| vec![*unit])) + .chain( + units + .iter() + .flat_map(|a| units.iter().map(move |b| vec![*a, *b])), + ) + .collect::>(); + let mut classes = NativeUnitClasses::default(); + let keys = lists + .iter() + .map(|list| classes.classes(list)) + .collect::>(); + for (a, key_a) in lists.iter().zip(&keys) { + for (b, key_b) in lists.iter().zip(&keys) { + assert_eq!(a == b, key_a == key_b, "{a:?} {b:?}"); + } + } + // The pool has equal units with differently ordered maps. + assert!(classes.count < pool.len()); + } +} From 1ea32b4f8e75ba330706709d7427dc7be2b97a62 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:53:32 +0900 Subject: [PATCH 2/4] perf(runtime): share the interpreter's combinational program across clocks Closes #2004 Change-Id: I25c5836030d05db672adcb2159c9aa2fdb9e7890 --- crates/celox/src/backend/interp.rs | 265 +++++++++++++++++++++++------ 1 file changed, 211 insertions(+), 54 deletions(-) diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 1101a082e15..4a5b61d7673 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1089,6 +1089,69 @@ fn collect_trigger_addrs( addrs } +/// The trigger-bearing addresses of a schedule group: the union of two +/// sorted lists, so a clock's group shares the combinational list instead of +/// holding a copy of it. +#[derive(Clone, Copy, Default)] +struct TriggerAddrs<'a> { + first: &'a [(AbsoluteAddr, u32)], + second: &'a [(AbsoluteAddr, u32)], +} + +impl<'a> TriggerAddrs<'a> { + fn len(&self) -> usize { + self.first.len() + self.second.len() + } + + /// The addresses of both lists in order, each once. + fn iter(self) -> impl Iterator + 'a { + let (mut first, mut second) = ( + self.first.iter().copied().peekable(), + self.second.iter().copied().peekable(), + ); + std::iter::from_fn(move || match (first.peek(), second.peek()) { + (Some(a), Some(b)) if a < b => first.next(), + (Some(a), Some(b)) if b < a => second.next(), + (Some(_), Some(_)) => { + second.next(); + first.next() + } + (Some(_), None) => first.next(), + (None, _) => second.next(), + }) + } +} + +/// The trigger-bearing addresses of one clock's FF units, from every group +/// it is scheduled in. +#[derive(Default)] +struct ClockTriggerAddrs { + /// Whether the clock's groups also snapshot the combinational units' + /// addresses: an eval/apply clock may run them in a combined tick. + with_comb: bool, + ff: Vec<(AbsoluteAddr, u32)>, +} + +/// The trigger-bearing addresses snapshot at the entry of a group of +/// `clock`. +fn clock_trigger_addrs<'a>( + event_trigger_addrs: &'a HashMap, + comb_trigger_addrs: &'a [(AbsoluteAddr, u32)], + clock: AbsoluteAddr, +) -> TriggerAddrs<'a> { + let Some(addrs) = event_trigger_addrs.get(&clock) else { + return TriggerAddrs::default(); + }; + TriggerAddrs { + first: if addrs.with_comb { + comb_trigger_addrs + } else { + &[] + }, + second: &addrs.ff, + } +} + /// One scheduled SIR unit with register metadata prepared once at backend /// construction. Keeping register storage with the unit removes per-tick /// HashMap walks and slot clearing from the interpreter dispatch path. @@ -1117,15 +1180,15 @@ fn prepare_units( /// Execute every unit in `units` against the split backend storage. #[allow(clippy::too_many_arguments)] -fn run_units( +fn run_units<'u>( memory: &mut [u64], layout: &MemoryLayout, extern_functions: &ExternFunctionTable, four_state: bool, comb_capture_enabled: &mut [u8], heap: &mut celox_heap::Heap, - units: &mut [PreparedUnit], - trigger_addrs: &[(AbsoluteAddr, u32)], + units: impl IntoIterator, + trigger_addrs: TriggerAddrs<'_>, trigger_snapshots: &mut Vec<((AbsoluteAddr, u32), u64)>, emit_triggers: bool, ) -> Result<(), SimulatorErrorCode> { @@ -1136,7 +1199,7 @@ fn run_units( trigger_snapshots.clear(); if emit_triggers { trigger_snapshots.reserve(trigger_addrs.len()); - for &(absolute, region) in trigger_addrs { + for (absolute, region) in trigger_addrs.iter() { let addr = RegionedAbsoluteAddrBase::from_absolute_addr(region, absolute); let machine = Machine { memory: &mut *memory, @@ -1224,14 +1287,15 @@ pub struct InterpBackend { id_to_addr: Vec, id_to_event: Vec, four_state_inits: Vec<(usize, usize)>, - /// Units for the fused comb+FF tick of each event, mirroring the - /// compiled `comb_apply_func`: fused schedules when present, otherwise - /// comb units followed by the clock's FF units. - comb_apply_units: HashMap>, + /// Units for the fused comb+FF tick of an eval/apply clock with a fused + /// schedule, mirroring the compiled `comb_apply_func`. The other + /// eval/apply clocks run `eval_comb_units` followed by their + /// `eval_apply_units` in one group, without a copy of either. + fused_comb_apply_units: HashMap>, /// Trigger-bearing addresses per schedule group, precomputed so a group /// invocation only performs snapshot reads. comb_trigger_addrs: Vec<(AbsoluteAddr, u32)>, - event_trigger_addrs: HashMap>, + event_trigger_addrs: HashMap, /// Reused group-entry trigger snapshots; sorted by address and region. trigger_snapshots: Vec<((AbsoluteAddr, u32), u64)>, /// The extern functions the units call. @@ -1359,17 +1423,15 @@ impl InterpBackend { // program; executing independently scheduled comb and FF units can // observe a different pre-edge snapshot around reset and NBA regions, // exactly as with the compiled backends. - let mut comb_apply_units: HashMap> = HashMap::default(); - for (clock, ff_units) in &laid_out.sir.eval_apply_ffs { - let units = if let Some(fused) = laid_out.sir.eval_comb_apply_ffs.get(clock) { - prepare_units(fused, four_state) - } else { - let mut combined = prepare_units(&laid_out.sir.eval_comb, four_state); - combined.extend(prepare_units(ff_units, four_state)); - combined - }; - comb_apply_units.insert(*clock, units); - } + let fused_comb_apply_units: HashMap> = laid_out + .sir + .eval_apply_ffs + .keys() + .filter_map(|clock| { + let fused = laid_out.sir.eval_comb_apply_ffs.get(clock)?; + Some((*clock, prepare_units(fused, four_state))) + }) + .collect(); let eval_comb_units = prepare_units(&laid_out.sir.eval_comb, four_state); let eval_apply_units = laid_out .sir @@ -1393,29 +1455,23 @@ impl InterpBackend { // Only eval/apply clocks receive combined ticks; eval-only and // apply-only groups fall back to the default two-phase evaluation. let comb_trigger_addrs = collect_trigger_addrs(&laid_out.sir.eval_comb); - let mut event_trigger_addrs: HashMap> = - HashMap::default(); - for (clock, ff_units) in &laid_out.sir.eval_apply_ffs { - let mut addrs = comb_trigger_addrs.clone(); - addrs.extend(collect_trigger_addrs(ff_units)); - addrs.sort_unstable(); - addrs.dedup(); - event_trigger_addrs.insert(*clock, addrs); + let mut event_trigger_addrs: HashMap = HashMap::default(); + for clock in laid_out.sir.eval_apply_ffs.keys() { + event_trigger_addrs.entry(*clock).or_default().with_comb = true; } // Split scheduling can register the same canonical clock under both // maps; merge the address sets so neither phase loses snapshots. for (clock, units) in laid_out .sir - .eval_only_ffs + .eval_apply_ffs .iter() + .chain(&laid_out.sir.eval_only_ffs) .chain(&laid_out.sir.apply_ffs) { let entry = event_trigger_addrs.entry(*clock).or_default(); - let mut addrs = collect_trigger_addrs(units); - addrs.extend(entry.iter().copied()); - addrs.sort_unstable(); - addrs.dedup(); - *entry = addrs; + entry.ff.extend(collect_trigger_addrs(units)); + entry.ff.sort_unstable(); + entry.ff.dedup(); } let mut backend = Self { @@ -1436,7 +1492,7 @@ impl InterpBackend { id_to_addr, id_to_event, four_state_inits, - comb_apply_units, + fused_comb_apply_units, comb_trigger_addrs, event_trigger_addrs, trigger_snapshots: Vec::new(), @@ -1536,7 +1592,10 @@ impl SimBackend for InterpBackend { &mut self.comb_capture_enabled, &mut self.heap, &mut self.eval_comb_units, - &self.comb_trigger_addrs, + TriggerAddrs { + first: &self.comb_trigger_addrs, + second: &[], + }, &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1553,20 +1612,32 @@ impl SimBackend for InterpBackend { self.eval_apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) } fn eval_comb_apply_ff_at(&mut self, event: InterpEventRef) -> Result<(), SimulatorErrorCode> { - let Some(units) = self.comb_apply_units.get_mut(&event.addr()) else { - // Events outside the eval/apply map keep the default ordering. - self.eval_comb()?; - return self.eval_apply_ff_at(event); - }; + let trigger_addrs = clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ); + let (first, second): (&mut [PreparedUnit], &mut [PreparedUnit]) = + if let Some(fused) = self.fused_comb_apply_units.get_mut(&event.addr()) { + (fused, &mut []) + } else if let Some(ff_units) = self.eval_apply_units.get_mut(&event.addr()) { + (&mut self.eval_comb_units, ff_units) + } else { + // Events outside the eval/apply map keep the default ordering. + self.eval_comb()?; + return self.eval_apply_ff_at(event); + }; run_units( self.memory.as_mut_slice(), &self.layout, @@ -1574,8 +1645,8 @@ impl SimBackend for InterpBackend { self.four_state, &mut self.comb_capture_enabled, &mut self.heap, - units, - &self.event_trigger_addrs[&event.addr()], + first.iter_mut().chain(second), + trigger_addrs, &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1592,9 +1663,11 @@ impl SimBackend for InterpBackend { self.eval_only_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1611,9 +1684,11 @@ impl SimBackend for InterpBackend { self.apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1633,8 +1708,8 @@ impl SimBackend for InterpBackend { self.four_state, &mut self.comb_capture_enabled, &mut self.heap, - std::slice::from_mut(unit), - &[], + std::iter::once(unit), + TriggerAddrs::default(), &mut self.trigger_snapshots, false, ) @@ -2078,4 +2153,86 @@ mod tests { } } } + + #[test] + fn trigger_addrs_iterate_the_union_in_order() { + let addr = |id: u32| AbsoluteAddr { + instance_id: celox_design::InstanceId(0), + var_id: celox_design::StateObjectId(id), + }; + let lists: [&[u32]; 5] = [&[], &[1], &[1, 4, 9], &[2, 4, 7, 9, 11], &[0, 3, 11]]; + for first in lists { + for second in lists { + for region in [0, 1] { + let entries = |ids: &[u32]| -> Vec<(AbsoluteAddr, u32)> { + ids.iter().map(|&id| (addr(id), region)).collect() + }; + let (first, second) = (entries(first), entries(second)); + let mut expected: Vec<_> = first.iter().chain(&second).copied().collect(); + expected.sort_unstable(); + expected.dedup(); + let addrs = TriggerAddrs { + first: &first, + second: &second, + }; + assert_eq!(addrs.iter().collect::>(), expected); + } + } + } + } + + /// Clocks sharing one combinational program each run it before their + /// flip-flops in a combined tick, as the compiled backends do. + #[test] + fn combined_ticks_of_several_clocks_match_the_compiled_backend() { + const CODE: &str = r#" +module Top ( + clk_a: input 'a clock, + clk_b: input 'b clock, + clk_c: input 'c clock, + din: input 'a logic<8>, + qa: output 'a logic<8>, + qb: output 'b logic<8>, + qc: output 'c logic<8>, +) { + var x: 'a logic<8>; + assign x = din ^ qa; + always_ff (clk_a) { + qa = x + 1; + } + unsafe (cdc) { + always_ff (clk_b) { + qb = qa + x; + } + always_ff (clk_c) { + qc = qb ^ x; + } + } +} +"#; + fn run(mut sim: crate::Simulator) -> Vec { + let clocks = [sim.event("clk_a"), sim.event("clk_b"), sim.event("clk_c")]; + let din = sim.signal("din"); + let outputs = [sim.signal("qa"), sim.signal("qb"), sim.signal("qc")]; + let mut seen = Vec::new(); + for step in 0..60u64 { + let value = (step * 37 + 11) as u8; + sim.modify(|io| io.set(din, value)).unwrap(); + sim.tick_deferred_comb(clocks[(step * 7 % 3) as usize]) + .unwrap(); + if step % 4 == 0 { + sim.tick_deferred_comb(clocks[((step + 1) % 3) as usize]) + .unwrap(); + } + for output in outputs { + seen.push(sim.get(output)); + } + } + seen + } + let builder = || crate::Simulator::builder(CODE, "Top"); + let interpreted = builder().build_interpreter().unwrap(); + assert_eq!(interpreted.backend.eval_apply_units.len(), 3); + assert_eq!(run(interpreted), run(builder().build_cranelift().unwrap())); + } } From f8985cfe5d0d9376f6da1908b6b91afd82140ba8 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:22:49 +0900 Subject: [PATCH 3/4] perf(sv): instrument each unit once for all probes Closes #1991 Change-Id: Ied3fc477003f360c2ea17b71e19b6fd1a4559abb --- .../src/symbolic/assembly.rs | 256 ++++++++++-------- crates/celox-frontend-core/src/watch.rs | 226 +++++++++++++++- 2 files changed, 374 insertions(+), 108 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f53a2af7176..c42896d21be 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -936,85 +936,126 @@ pub fn schedule_symbolic_rtl_reporting_loops( // working state is seeded with the stable value first, so a store // compares with the value its update replaces. let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); - for (source, counter) in probes { - let width = source.access.msb - source.access.lsb + 1; - let four_state = four_state && variables[&source.id].1; - let offset = match unpacked_element_widths.get(&source.id) { - Some(&element_width) - if width > element_width - && source.access.lsb.is_multiple_of(element_width) - && width.is_multiple_of(element_width) => - { - celox_sir::SIROffset::PackedElements { - bit_offset: source.access.lsb, - element_width, + // Each unit is instrumented once for all probes. Probe `p` is pass + // `2p` over the stable state and pass `2p + 1` over a flip-flop + // evaluation's working state, the order of instrumenting probe by + // probe. + let probe_codes: Vec<_> = probes + .iter() + .map(|&(source, counter)| { + let width = source.access.msb - source.access.lsb + 1; + let four_state = four_state && variables[&source.id].1; + let offset = match unpacked_element_widths.get(&source.id) { + Some(&element_width) + if width > element_width + && source.access.lsb.is_multiple_of(element_width) + && width.is_multiple_of(element_width) => + { + celox_sir::SIROffset::PackedElements { + bit_offset: source.access.lsb, + element_width, + } } - } - _ => celox_sir::SIROffset::Static(source.access.lsb), - }; - let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == STABLE_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: stable(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for process in &mut processes { - crate::watch::instrument_unit(&mut process.kernel, code); + _ => celox_sir::SIROffset::Static(source.access.lsb), + }; + (counter, width, four_state, offset) + }) + .collect(); + let mut probes_of: HashMap> = HashMap::default(); + for (index, (source, _)) in probes.iter().enumerate() { + probes_of.entry(source.id).or_default().push(index); + } + // The first probe of `signal` whose `pass` is `after` or later. + let first_probe = |signal: AbsoluteAddr, pass: fn(usize) -> usize, after: usize| { + let indices = probes_of.get(&signal)?; + indices + .get(indices.partition_point(|&index| pass(index) < after)) + .copied() + }; + fn probe_code( + probe: &(AbsoluteAddr, usize, bool, celox_sir::SIROffset), + signal: A, + counter: A, + ) -> crate::watch::WatchCode { + let &(_, width, four_state, ref offset) = probe; + crate::watch::WatchCode { + signal, + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, counter)], } - for units in eval_apply_ffs - .values_mut() - .chain(eval_only_ffs.values_mut()) - .chain(apply_ffs.values_mut()) + } + let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); + let working = |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let stable_code = |instruction: &SIRInstruction, after: usize| { + let address = crate::watch::write_destination(instruction)?; + if address.region != STABLE_REGION { + return None; + } + let index = first_probe(address.absolute_addr(), |index| 2 * index, after)?; + Some(( + 2 * index, + probe_code( + &probe_codes[index], + stable(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )) + }; + // A flip-flop evaluation's stores to a signal of `ff_multi_stored`; + // the commits that seed its working state are not writes of the + // process. + let evaluation_code = |instruction: &SIRInstruction, after: usize| { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && ff_multi_stored.contains(&address.absolute_addr()) + && let Some(index) = + first_probe(address.absolute_addr(), |index| 2 * index + 1, after) { - for unit in units { - crate::watch::instrument_unit(unit, code); - } + return Some(( + 2 * index + 1, + probe_code( + &probe_codes[index], + working(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )); } - for parts in parallel_ff_units.values_mut() { - for (_, part) in parts { - crate::watch::instrument_unit(&mut part.evaluate, code); - crate::watch::instrument_unit(&mut part.apply, code); - } + stable_code(instruction, after) + }; + for process in &mut processes { + crate::watch::instrument_writes_in_passes(&mut process.kernel, stable_code); + } + for units in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, evaluation_code); } - if ff_multi_stored.contains(&source.id) { - let working = - |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: working(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for_each_ff_evaluation( - &mut eval_apply_ffs, - &mut eval_only_ffs, - &mut parallel_ff_units, - |unit| instrument_stores(unit, code), - ); + } + for units in apply_ffs.values_mut() { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, stable_code); } - for path in &mut comb_blocks { - if let LogicPathTarget::Process { unit, .. } = &mut path.target { - crate::watch::instrument_unit(unit, |address| { - (*address == source.id).then(|| crate::watch::WatchCode { - signal: source.id, - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, counter)], - }) - }); - } + } + for parts in parallel_ff_units.values_mut() { + for (_, part) in parts { + crate::watch::instrument_writes_in_passes(&mut part.evaluate, evaluation_code); + crate::watch::instrument_writes_in_passes(&mut part.apply, stable_code); + } + } + for path in &mut comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let &address = crate::watch::write_destination(instruction)?; + let index = first_probe(address, |index| index, after)?; + Some(( + index, + probe_code(&probe_codes[index], address, probe_codes[index].0), + )) + }); } } let ff_units = eval_apply_ffs @@ -1052,31 +1093,45 @@ pub fn schedule_symbolic_rtl_reporting_loops( .iter() .map(|slots| slots.signal) .collect(); - for (signal, slots) in &counted { - if !ff_multi_stored.contains(signal) || pending.contains(signal) { - continue; - } - let (width, is_4state) = variables[signal]; - let regioned = RegionedAbsoluteAddr::from_absolute_addr; - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( - || crate::watch::WatchCode { - signal: regioned(WORKING_REGION, *signal), - offset: celox_sir::SIROffset::Static(0), - width, - four_state: four_state && is_4state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) - .collect(), - }, - ) - }; + // One pass per signal, in signal order; each pass watches only its + // own signal. + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let multi_stored: HashMap)> = counted + .iter() + .filter(|(signal, _)| ff_multi_stored.contains(signal) && !pending.contains(signal)) + .enumerate() + .map(|(pass, (&signal, slots))| { + let (width, is_4state) = variables[&signal]; + let code = crate::watch::WatchCode { + signal: regioned(WORKING_REGION, signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }; + (signal, (pass, code)) + }) + .collect(); + if !multi_stored.is_empty() { for_each_ff_evaluation( &mut eval_apply_ffs, &mut eval_only_ffs, &mut parallel_ff_units, - |unit| instrument_stores(unit, code), + |unit| { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let SIRInstruction::Store(address, ..) = instruction else { + return None; + }; + if address.region != WORKING_REGION { + return None; + } + let (pass, code) = multi_stored.get(&address.absolute_addr())?; + (*pass >= after).then(|| (*pass, code.clone())) + }) + }, ); } counted @@ -4012,19 +4067,6 @@ fn ff_multi_stored( .collect() } -/// [`crate::watch::instrument_unit`] for the stores alone: the commits that -/// seed a flip-flop evaluation's working state are not writes of the -/// process. -fn instrument_stores( - unit: &mut ExecutionUnit, - watch_for: impl Fn(&RegionedAbsoluteAddr) -> Option>, -) { - crate::watch::instrument_writes(unit, |instruction| match instruction { - SIRInstruction::Store(address, ..) => watch_for(address), - _ => None, - }); -} - /// Run `f` on every flip-flop evaluation. fn for_each_ff_evaluation( eval_apply_ffs: &mut FfUnits, diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 40a2bdbbc5c..b29ce3188b5 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -641,6 +641,113 @@ pub fn instrument_writes( } } +/// The result of [`instrument_writes`] once per pass, in pass order, in one +/// walk over `unit`. `watch_for(instruction, after)` gives the first pass +/// from `after` on that watches `instruction`, and its code. +/// +/// A later pass also sees the code an earlier one added, and wraps the write +/// inside it, so a write watched by several passes is surrounded by their +/// code from the first pass outward in. The new registers are numbered as +/// the passes one after another would number them. +pub fn instrument_writes_in_passes( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&SIRInstruction, usize) -> Option<(usize, WatchCode)>, +) { + let ExecutionUnit { + blocks, + register_map, + .. + } = unit; + let first_new = register_map.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let mut next_register = first_new; + // The pass, block and first register of every piece of code added, in + // the order the walk adds them. + let mut added: Vec<(usize, usize, usize)> = Vec::new(); + let mut instrumented = Vec::new(); + for (order, block) in blocks.values_mut().enumerate() { + if !block + .instructions + .iter() + .any(|instruction| watch_for(instruction, 0).is_some()) + { + continue; + } + let mut instructions = Vec::with_capacity(block.instructions.len()); + let mut work: Vec<(SIRInstruction, usize)> = Vec::new(); + for instruction in std::mem::take(&mut block.instructions) { + work.push((instruction, 0)); + while let Some((instruction, after)) = work.pop() { + let Some((pass, watch)) = watch_for(&instruction, after) else { + instructions.push(instruction); + continue; + }; + let value_type = match &instruction { + SIRInstruction::Store(_, _, _, value, ..) => register_map.get(value).cloned(), + _ => None, + }; + let mut b = SIRBuilder::new_with(next_register); + emit_watched(&mut b, &watch, instruction, value_type.as_ref()); + b.seal_block(SIRTerminator::Return); + let (mut emitted, registers, next) = b.drain(); + added.push((pass, order, next_register)); + next_register = next; + register_map.extend(registers); + let emitted = emitted + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions; + work.extend(emitted.into_iter().rev().map(|emitted| (emitted, pass + 1))); + } + } + block.instructions = instructions; + instrumented.push(block.id); + } + if added.is_empty() { + return; + } + + // Renumber the new registers pass by pass, then block by block in the + // order a pass visits them; within a block the walk already added each + // pass's code in order. + let mut ends: Vec = added.iter().skip(1).map(|&(.., first)| first).collect(); + ends.push(next_register); + let mut pieces: Vec<(usize, usize, usize, usize)> = added + .iter() + .zip(ends) + .map(|(&(pass, order, first), end)| (pass, order, first, end)) + .collect(); + pieces.sort_by_key(|&(pass, order, ..)| (pass, order)); + let mut renumbered = vec![0; next_register - first_new]; + let mut next = first_new; + for (.., first, end) in pieces { + for register in first..end { + renumbered[register - first_new] = next; + next += 1; + } + } + let renumber = |register: &mut RegisterId| { + if register.0 >= first_new { + register.0 = renumbered[register.0 - first_new]; + } + }; + for id in instrumented { + let block = blocks.get_mut(&id).expect("an instrumented block"); + for instruction in &mut block.instructions { + if let Some(register) = instruction.defined_register_mut() { + renumber(register); + } + instruction.for_each_use_mut(renumber); + } + } + let new_registers: Vec<_> = (first_new..next_register) + .filter_map(|id| register_map.remove_entry(&RegisterId(id))) + .collect(); + register_map.extend(new_registers.into_iter().map(|(mut id, ty)| { + renumber(&mut id); + (id, ty) + })); +} + /// Objects that hold back the occurrences of one flip-flop evaluation's /// writes to a signal until the commit that publishes them. /// @@ -1281,7 +1388,10 @@ pub fn declare_pending_slots( mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; - use super::{multi_store_candidates, multi_write_candidates, successors, write_destination}; + use super::{ + WatchCode, instrument_writes, instrument_writes_in_passes, multi_store_candidates, + multi_write_candidates, successors, write_destination, + }; /// Store a constant to `address` at the open block. fn store(b: &mut SIRBuilder, address: u32) { @@ -1556,4 +1666,118 @@ mod tests { let found = multi_store_candidates(&unit, |address| Some(*address)); assert_eq!(found, (0..10000).step_by(2).collect::>()); } + + /// One pass of the equivalence test: the writes it watches and the + /// code it adds. + struct Pass { + address: u32, + stores_only: bool, + code: WatchCode, + } + + impl Pass { + fn watches(&self, instruction: &SIRInstruction) -> bool { + match instruction { + SIRInstruction::Store(address, ..) => *address == self.address, + _ => !self.stores_only && write_destination(instruction) == Some(&self.address), + } + } + } + + /// A random unit of a few blocks writing a few addresses, and random + /// passes over the same addresses; a pass's counters may be written + /// by another pass's code. + fn random_instrumentation(seed: u64) -> (celox_sir::ExecutionUnit, Vec) { + use celox_design::CounterKind; + let state = std::cell::Cell::new(seed); + let next = |bound: u64| { + state.set( + state + .get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + (state.get() >> 33) % bound + }; + let addresses = 1 + next(6) as u32; + let widths = [1, 4, 8]; + let mut b = SIRBuilder::new(); + let blocks = 1 + next(4); + for block in 0..blocks { + for _ in 0..next(6) { + let width = widths[next(3) as usize]; + let value = if next(2) == 0 { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Imm(value, SIRValue::new(next(256) as u8))); + let address = next(addresses as u64) as u32; + b.emit(match next(3) { + 0 => SIRInstruction::Commit( + address, + address, + SIROffset::Static(0), + width, + Vec::new(), + ), + _ => SIRInstruction::Store( + address, + SIROffset::Static(next(2) as usize * 2), + width, + value, + Vec::new(), + Vec::new(), + ), + }); + } + if block + 1 < blocks { + let following = b.new_block(); + b.seal_block(SIRTerminator::Jump(following, Vec::new())); + b.switch_to_block(following); + } + } + let value = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(0u8))); + let unit = b.flush_eu().unwrap(); + let passes = (0..1 + next(8)) + .map(|_| Pass { + address: next(addresses as u64) as u32, + stores_only: next(2) == 0, + code: WatchCode { + signal: next(addresses as u64) as u32, + width: widths[next(3) as usize], + offset: SIROffset::Static(next(2) as usize * 2), + four_state: next(2) == 0, + counters: CounterKind::ALL + .into_iter() + .filter(|_| next(2) == 0) + .map(|kind| (kind, next(addresses as u64 + 2) as u32)) + .collect(), + }, + }) + .collect(); + (unit, passes) + } + + #[test] + fn instrumenting_in_passes_matches_one_pass_after_another() { + for seed in 0..3000 { + let (unit, passes) = random_instrumentation(seed); + let mut one_by_one = unit.clone(); + for pass in &passes { + instrument_writes(&mut one_by_one, |instruction| { + pass.watches(instruction).then(|| pass.code.clone()) + }); + } + let mut at_once = unit; + instrument_writes_in_passes(&mut at_once, |instruction, after| { + let found = passes[after.min(passes.len())..] + .iter() + .position(|pass| pass.watches(instruction))?; + Some((after + found, passes[after + found].code.clone())) + }); + assert_eq!(at_once, one_by_one, "seed {seed}"); + } + } } From 10dc5a2c4cee23d796d7f84404043cc60fb54144 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 21:28:08 +0900 Subject: [PATCH 4/4] perf(sv)!: run initial loops without a static trip count as a process An `initial` block is first folded into initial state by symbolic execution, and runs as a process only when that fails. A loop whose trip count the folding could not determine beforehand was unrolled one iteration at a time until `MAX_UNROLLED_ITERATIONS` (10000) failed the fold, so the block cost up to 10000 iterations of its body before running as the process it becomes anyway. The C906 testbench loads its program with two such loops (`for (j = 0; i < 32'h4000; i = j/4)` with 64 hierarchical memory writes per iteration), about 450 s each. While folding an `initial` block, a loop now proceeds only when its trip count is known before it runs; otherwise the fold fails at once and the block runs as a process: - `repeat` loops, and canonical `for` loops whose body does not write the loop variable (their trip count was already checked by `loop_needs_fold`); - `while` and `do`-`while` loops shaped like one (`counted_while_loop`): the condition compares a variable with a bound, the last statement steps that variable as a canonical `for` step would, and no other statement writes the variable or the bound. They start from the variable's current value and keep folding when their trip count fits the unroll limit. Other loops, such as a condition on a variable that another one derives, `forever`, or a `while` whose counter is stepped elsewhere, are not folded. The check costs one pass over the body, not iterations of it. The SystemVerilog reference lists the loops that fold. BREAKING CHANGE: an `initial` block with such a loop is no longer folded even when it would finish within the unroll limit. It runs as a process, which a `Simulator` rejects ("`initial` ... is a process, which Simulator does not run"); build a `Simulation` instead. Closes #1992. - Shared cases `procedural::initial_loops_without_a_static_trip_count_run_as_a_process` (the testbench's load-loop shape with hierarchical memory writes, plus `while` and `do`-`while`, matching Icarus and Verilator) and `procedural::initial_while_loops_define_the_state` (a counted `while` loop still defines the state a `Simulator` sees). - A reduction of the C906 memory load (the C906 `f_spsram_524288x128` and `ram` modules with the testbench's wipe and load loops) now takes 3.3 s instead of 223 s, with identical output; the load loop alone (`memC2.v`) takes 1.9 s instead of not finishing in 300 s. Change-Id: I596c31f5ce2d71957b3e39e8c7afa7ac159dccee --- crates/celox-frontend-sv/src/lowering/comb.rs | 34 ++++++++++- .../src/lowering/procedural.rs | 30 ++++++++++ .../src/sv/cases/procedural.vtest | 59 +++++++++++++++++++ .../frontends/systemverilog/procedural.rs | 9 +++ docs/guide/systemverilog-reference.md | 2 +- docs/ja/guide/systemverilog-reference.md | 2 +- 6 files changed, 132 insertions(+), 4 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 27fabd04104..a7a1d8c72ba 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2678,8 +2678,38 @@ impl<'p, 'a> Comb<'p, 'a> { continue_flag, }); - if let sv::ir::LoopKind::For = kind - && let Some(canonical) = canonical_for_loop(init, condition, step) + let canonical = match kind { + sv::ir::LoopKind::For => canonical_for_loop(init, condition, step), + _ => None, + }; + // An `initial` block runs as a process when it cannot be folded into + // initial state, so a loop whose trip count is not known before it + // runs goes there instead of being unrolled until the limit. + if self.initial { + let counted = match kind { + sv::ir::LoopKind::Repeat(_) => true, + sv::ir::LoopKind::For => canonical.as_ref().is_some_and(|canonical| { + let mut written = HashSet::default(); + written_names(body, &mut written); + !written.contains(&canonical.var) + }), + sv::ir::LoopKind::While | sv::ir::LoopKind::DoWhile => { + match counted_while_loop(condition, body) { + Some((counted, rest)) => { + !self.loop_needs_fold(&store, frames, &counted, rest)? + } + None => false, + } + } + sv::ir::LoopKind::Forever => false, + }; + if !counted { + return Err(unsupported( + "initial block loop without a static trip count", + )); + } + } + if let Some(canonical) = canonical && self.loop_needs_fold(&store, frames, &canonical, body)? { self.folding += 1; diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index def194c3e1d..a1a1c6bddb8 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2320,6 +2320,36 @@ pub(super) fn canonical_for_loop( }) } +/// The counted loop a `while` or `do`-`while` loop is when its condition +/// compares a variable with a bound and its last statement steps that +/// variable, as the step of a [`canonical_for_loop`] would; the loop starts +/// from the variable's current value. Also returns the statements before +/// the step, which must not write the variable or the bound. +pub(super) fn counted_while_loop<'s>( + condition: Option<&sv::ir::Expr>, + body: &'s [sv::ir::Stmt], +) -> Option<(CanonicalLoop, &'s [sv::ir::Stmt])> { + let (step, rest) = body.split_last()?; + let sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var), + .. + } = step + else { + return None; + }; + let init = [sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var.clone()), + rhs: sv::ir::Expr::Ident(var.clone()), + nonblocking: false, + }]; + let canonical = canonical_for_loop(&init, condition, std::slice::from_ref(step))?; + let mut written = HashSet::default(); + written_names(rest, &mut written); + let mut bound = HashSet::default(); + expr_idents(&canonical.end, &mut bound); + (!written.contains(&canonical.var) && written.is_disjoint(&bound)).then_some((canonical, rest)) +} + /// The identifiers an expression reads. pub(super) fn expr_idents(expr: &sv::ir::Expr, names: &mut HashSet) { fn const_idents(expr: &sv::ir::ConstExpr, names: &mut HashSet) { diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 867a5ff44e3..576be5cc0ee 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -280,6 +280,65 @@ (assert_eq y (+ (* i 3) 1)) (assert_eq z 0x5a))) +; An initial block whose loops have no static trip count (a condition on +; another variable than the one the step assigns, `while`, `do`-`while`) runs +; as a process instead of being unrolled into initial state (#1992). +(case initial_loops_without_a_static_trip_count_run_as_a_process + (source "initial_loops.sv" #" + module Ram; + logic [7:0] mem [16]; + endmodule + module Top; + Ram r0(), r1(); + logic [31:0] src [32]; + logic [7:0] w [8]; + integer i, j, n; + initial begin + for (n = 0; n < 32; n = n + 1) src[n] = 32'h01010101 * n; + i = 0; + for (j = 0; i < 16; i = j / 2) begin + r0.mem[i] = src[j][15:8]; + j = j + 1; + r1.mem[i] = src[j][31:24]; + j = j + 1; + end + n = 0; + while (n < 8) begin + w[n] = 8'(n * 5); + n = n + 1; + end + do n = n - 3; while (n > 0); + #1 $display("%0d %0d %h %h %h %h %h %0d", i, j, r0.mem[0], r0.mem[15], + r1.mem[0], r1.mem[15], w[7], n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "16 32 00 1e 01 1f 23 -1\n")) + +; The state such an initial block writes is visible like folded initial state. +(case initial_while_loops_define_the_state + (source "initial_while.sv" #" + module Top(input logic [1:0] index, output logic [7:0] y); + logic [7:0] mem [4]; + int n; + initial begin + n = 0; + while (n < 4) begin + mem[n] = 8'(n * 3 + 1); + n++; + end + end + assign y = mem[index]; + endmodule + "#) + (top Top) + (for i (range 0 4) + (modify (set index i)) + (assert_eq y (+ (* i 3) 1)))) + (case loop_initializer_widens_by_its_own_signedness (source "loop_start.sv" #" module Top(input logic [7:0] value, output logic [7:0] count, output logic [7:0] registered, diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 11835e6e428..b05942b9658 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -253,3 +253,12 @@ sv_backends! { @case "procedural::static_function_wide_packed_storage_keeps_all_bits"; } } + +sv_backends! { + fn initial_loops_without_a_static_trip_count_run_as_a_process(sim) { + @case "procedural::initial_loops_without_a_static_trip_count_run_as_a_process"; + } + fn initial_while_loops_define_the_state(sim) { + @case "procedural::initial_while_loops_define_the_state"; + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 04c403a1f49..ebf7590fcf2 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -42,7 +42,7 @@ synthesis and is tested at the design level. | Continuous logic | `assign`, `wire w = expr;` | | Combinational processes | `always_comb`, `always @*`, blocking `always_latch`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | -| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | +| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if`, `$readmemh` / `$readmemb`, and loops whose trip count is known before they run (`repeat`, and `for`, `while` or `do`-`while` loops that step one variable by a constant up to a fixed bound), defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 5de49f53e7f..ef745e2e4bf 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -40,7 +40,7 @@ outline: [2, 3] | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロッキング代入の `always_latch`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | -| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | +| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if`、`$readmemh` / `$readmemb`、実行前に反復回数が分かるループ(`repeat` と、1 つの変数を定数ずつ固定の境界まで進める `for` / `while` / `do`-`while`)を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 |