From 31eedffe85e839b4f6c92ad70847cf6adb8d663c Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 15:26:34 +0900 Subject: [PATCH] perf(sv): publish only written elements of nonblocking array writes An edge process that writes an unpacked array by a nonblocking assignment at a run-time element seeded the whole array into its next state and committed all of it back on every edge. Each edge cost O(array size), and the generated code and compile time grew with the array (#1855). Such an array now uses the sparse next-state protocol that shared edge memories (and Veryl's dynamic writes) already use: element stores mark dirty 64-bit chunks, and the commit copies only those. Precondition, decided in `edge_only_memories()` (lowering.rs): - all local drivers of the array are edge processes of its module, and - the process writes it only by nonblocking constant-range or element writes, at least one at a run-time element (no blocking, whole-array or read-modify-write assignment). Every other array keeps the full next state. The function's doc comment is the hook for writers outside the module (hierarchical references, #1856). A write by another process between the evaluation and the NBA region (e.g. a `#0` resumption of an `initial`) is clobbered by the commit. This is pre-existing for every edge-process target, not only arrays, and is tracked and fixed separately in #1864. This change only narrows it: the sparse commit rewrites the dirty chunks, where the old one rewrote the whole array. Performance (100,000 cycles, `celox run --two-state --unlimited --backend cranelift`, release build, user time, `taskset -c 8-11`): | b3_mem_sweep | master | this | |---|---:|---:| | 2^10 | 0.12 s | 0.07 s | | 2^12 | 0.20 s | 0.07 s | | 2^14 | 0.64 s | 0.07 s | | 2^16 | 4.26 s | 0.09 s | | 2^22 (heliodor-dev) | 2-cycle startup alone 86.8 s user, 3.7 GB | full run 0.50 s, 125 MB | | 2^22 four-state (heliodor-dev) | - | full run 0.44 s | Startup of the 2-cycle variants (heliodor-dev): 2^16 0.88 s -> 0.01 s user; 2^22 110 s wall / 3.7 GB -> 0.36 s / 125 MB. Compile time and memory had the same cause. Unaffected workloads (callgrind, release): b2_vm_dispatch_bit.sv generates identical JIT code; whole-program 44.51 G -> 44.57 G instructions (+0.12%), all in compile-time functions this change does not touch, with identical call counts (e.g. `DriverScan::body` 56,773,692 calls in both). A Veryl 64K-word dynamic-index memory workload: identical JIT code, 188.40 M -> 188.80 M (+0.2%, about 4 host instructions per cycle in `testbench::clock_periods` and two runtime-event helpers this change does not touch). Both are code-layout differences of the LTO build. Validation: - `cargo test -p celox --features systemverilog --test systemverilog`: 4372 passed. - New shared case `procedural::nonblocking_runtime_element_writes_apply_in_order` (cranelift, native, wasm, parallel variants), passes on Verilator 5.052 and Icarus 13.0 (`verify-sv-verilator`, `verify-sv-icarus`). - New IR test `nonblocking_runtime_element_writes_use_sparse_next_state` (sparse for NBA element writes; full next state with a blocking or whole-array write). - A semantics stress design (multiple NBAs to one element, reads of old values, part-select merge, constant elements, X index) gives identical results to master on cranelift, interpreter, native O0 and wasm, two- and four-state; four-state matches xezim. - `cargo clippy -p celox-frontend-sv -p celox --features celox/systemverilog --tests`, `cargo fmt --check`. Closes #1855 Change-Id: I04824191d94b708b96866eab3e40f39eea515417 --- crates/celox-frontend-sv/src/lowering.rs | 62 +++++++++++++++++++ crates/celox-frontend-sv/src/lowering/ff.rs | 54 ++++++++++++++-- .../src/sv/cases/procedural.vtest | 47 ++++++++++++++ .../frontends/systemverilog/procedural.rs | 4 ++ .../systemverilog/review_regressions.rs | 56 +++++++++++++++++ 5 files changed, 219 insertions(+), 4 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c44bd3b34c1..765af0db277 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1052,6 +1052,66 @@ fn shared_edge_memories( memories } +/// The unpacked arrays that only edge-triggered processes of `module` drive. +/// A process that writes one of them only by nonblocking assignments, at +/// least one of them at a run-time element, publishes just the elements it +/// wrote (see `Ff::lower_process`) instead of seeding and committing the +/// whole array on every edge. +/// +/// This uses the drivers within `module`. The sparse commit copies back +/// only the 64-bit chunks the process wrote, so a write from another scope +/// that lands between the evaluation and the commit of the process can be +/// lost only within those chunks, where a whole-array commit loses it +/// everywhere. A writer outside `module` (a hierarchical reference) that +/// must not lose such writes has to be excluded here. +fn edge_only_memories( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, +) -> HashSet { + let first_ff = module.comb_processes().len(); + let end_ff = first_ff + module.ff_processes().len(); + // Only an array a nonblocking assignment of an edge process writes can + // qualify; the driver scan is for those. + let mut nonblocking = HashSet::default(); + for process in module.ff_processes() { + for stmt in process.body() { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { + lhs, + nonblocking: true, + .. + } => { + nonblocking.insert(lhs.name()); + } + sv::ir::Stmt::AssignConcat { + parts, + nonblocking: true, + .. + } => nonblocking.extend(parts.iter().map(sv::ir::LValue::name)), + _ => {} + }); + } + } + module + .signals() + .iter() + .filter(|s| { + !s.is_net() + && !s.r#type().unpacked_ranges().is_empty() + && nonblocking.contains(s.name()) + }) + .filter(|signal| { + let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); + !drivers.is_empty() + && drivers + .iter() + .all(|(id, _)| (first_ff..end_ff).contains(id)) + }) + .map(|signal| signal.name().to_string()) + .collect() +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, @@ -8429,6 +8489,7 @@ fn lower_ff_processes( } } + let edge_memories = edge_only_memories(module, pm.constants, pm.parameter_types); let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { let mut events = events @@ -8455,6 +8516,7 @@ fn lower_ff_processes( staged, } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) + .with_sparse_candidates(&edge_memories) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b77cd77394d..61296800342 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -39,6 +39,15 @@ struct FunctionBlocks { pub(super) struct Ff<'p, 'a> { pub m: &'p mut ProcModule<'a>, sparse_memories: HashSet, + /// Arrays only edge-triggered processes drive. One this process writes + /// only by nonblocking element writes, at least one at a run-time + /// element, joins `sparse_memories`. + sparse_candidates: HashSet, + /// Variables written at a run-time element of an unpacked array. + element_writes: HashSet, + /// Variables written other than at a constant range or one element of + /// an unpacked array, which a sparse publication does not support. + other_writes: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -108,6 +117,9 @@ impl<'p, 'a> Ff<'p, 'a> { Self { m, sparse_memories: HashSet::default(), + sparse_candidates: HashSet::default(), + element_writes: HashSet::default(), + other_writes: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -147,6 +159,11 @@ impl<'p, 'a> Ff<'p, 'a> { self } + pub fn with_sparse_candidates(mut self, names: &HashSet) -> Self { + self.sparse_candidates = names.iter().filter_map(|name| self.m.id(name)).collect(); + self + } + /// Where a write of `id`, and a read of a value the process wrote, go: /// the working region, or stable state in a process kernel. fn target(&self, id: SourceVarId) -> Addr { @@ -204,8 +221,8 @@ impl<'p, 'a> Ff<'p, 'a> { .flatten() .and_then(|write| write.window) .unwrap_or(BitAccess::new(0, variable.width - 1)); - let access = match lvalue { - sv::ir::LValue::Ident(_) => BitAccess::new(0, variable.width - 1), + let constant = match lvalue { + sv::ir::LValue::Ident(_) => None, sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( msb, self.m.constants, @@ -216,8 +233,20 @@ impl<'p, 'a> Ff<'p, 'a> { self.m.constants, self.m.parameter_types, )) - .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0) - .unwrap_or(whole), + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0), + }; + if constant.is_none() { + // `write` takes the same order: a constant range, then one + // run-time element, then a read-modify-write of the variable. + if element_write { + self.element_writes.insert(id); + } else { + self.other_writes.insert(id); + } + } + let access = match lvalue { + sv::ir::LValue::Ident(_) => BitAccess::new(0, variable.width - 1), + sv::ir::LValue::Select { .. } => constant.unwrap_or(whole), }; self.targets.push((id, access)); } @@ -3937,6 +3966,23 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + // Publish only the written elements of an array this process alone + // updates by nonblocking element writes, rather than seeding and + // committing all of it on every edge. The element stores keep + // statement order, so the last write to an element wins, and reads + // see stable state (IEEE 1800-2023 4.6, 10.4.2). + let sparse: Vec<_> = self + .sparse_candidates + .iter() + .copied() + .filter(|id| { + self.element_writes.contains(id) + && !self.working.contains(id) + && !self.other_writes.contains(id) + && !self.m.is_hidden(*id) + }) + .collect(); + self.sparse_memories.extend(sparse); if self .working .iter() diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index a0a35cf1779..30c65da968d 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -478,6 +478,53 @@ (assert_eq next 0) (assert_eq picked (? (< i 8) 0 (fourstate 1 1))))) +(case nonblocking_runtime_element_writes_apply_in_order + ; Nonblocking writes to run-time elements of one array apply after the + ; process in statement order: reads see the old values, the last write to + ; an element wins, also through different index expressions, and a later + ; part-select write merges into an earlier whole element write (IEEE + ; 1800-2023 10.4.2). Elements next to written ones keep their values. + (source "nba_runtime_elements.sv" #" + module Top(input logic clk, input logic we, input logic [3:0] a, b, + input logic [3:0] c, input logic [31:0] d, + input logic [3:0] ra, rb, + output logic [31:0] qa, qb, old); + logic [31:0] mem [16]; + initial for (int i = 0; i < 16; i++) mem[i] = i; + always_ff @(posedge clk) begin + old <= mem[a]; + if (we) begin + mem[a] <= d; + mem[b] <= mem[a] + 32'd1; + mem[a][7:0] <= 8'h5a; + end + mem[c] <= 32'hffff_ffff; + end + assign qa = mem[ra]; + assign qb = mem[rb]; + endmodule + "#) + (top Top) + (for (w x y z v r s ea eb eo) + (list (1 2 5 11 0x1000 2 5 0x105a 3 2) + (1 7 7 6 0x2000 7 6 0x5a 0xffffffff 7) + (0 2 0 11 0 3 4 3 4 0x105a) + (1 4 5 11 0xabcd0000 4 5 0xabcd005a 5 4) + (1 4 0 4 1 4 0 0xffffffff 0xabcd005b 0xabcd005a) + (0 0 0 11 0 2 11 0x105a 0xffffffff 0xabcd005b)) + (modify + (set we w) + (set a x) + (set b y) + (set c z) + (set d v) + (set ra r) + (set rb s)) + (tick clk) + (assert_eq qa ea) + (assert_eq qb eb) + (assert_eq old eo))) + (case declaration_initializers_define_the_initial_state (source "initializers.sv" #" module Top(input logic clk, input logic [1:0] index, diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 709c06a182f..dd47e78f796 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -93,6 +93,10 @@ sv_backends! { @case "procedural::runtime_bits_stay_within_their_element"; } + fn nonblocking_runtime_element_writes_apply_in_order(sim) { + @case "procedural::nonblocking_runtime_element_writes_apply_in_order"; + } + fn declaration_initializers_define_the_initial_state(sim) { @case "procedural::declaration_initializers_define_the_initial_state"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 286bcb3b487..0b5bcf1427b 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8760,6 +8760,62 @@ fn shared_ff_memories_keep_native_sparse_next_state() { } } +/// An array one edge process updates only by nonblocking element writes +/// publishes the written elements, not a seed and commit of the whole array +/// per edge (#1855). A blocking write keeps the whole-array next state. +#[test] +fn nonblocking_runtime_element_writes_use_sparse_next_state() { + use celox_design::{SPARSE_WORKING_REGION, WORKING_REGION}; + use celox_sir::SIRInstruction; + + for (body, sparse) in [ + ("mem[addr] <= data; mem[3][7:0] <= data[7:0];", true), + ("mem[addr] = data;", false), + ("mem[addr] <= data; mem <= '{default: 0};", false), + ] { + let source = format!( + r#"module Top(input bit clk, input bit [11:0] addr, input bit [31:0] data, + output wire [31:0] q); + bit [31:0] mem[4096]; + always_ff @(posedge clk) begin {body} end + assign q = mem[addr]; + endmodule"# + ); + let result = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("nba_ram.sv"))], "Top") + .trace_pre_optimized_sir() + .build_with_trace(); + let sim = result.res.unwrap(); + let memory = sim.program().get_addr(&[], &["mem"]).unwrap(); + let program = result.trace.pre_optimized_sir.unwrap(); + let mut regions = Vec::new(); + for instruction in program + .sir + .eval_apply_ffs + .values() + .flatten() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + { + match instruction { + SIRInstruction::Store(address, ..) if address.absolute_addr() == memory => { + regions.push(address.region); + } + SIRInstruction::Commit(source, destination, ..) + if source.absolute_addr() == memory + || destination.absolute_addr() == memory => + { + regions.push(source.region); + regions.push(destination.region); + } + _ => {} + } + } + assert_eq!(regions.contains(&SPARSE_WORKING_REGION), sparse, "{body}"); + assert_eq!(regions.contains(&WORKING_REGION), !sparse, "{body}"); + } +} + #[test] fn rejects_overlapping_continuous_concatenation_drivers() { for declaration in ["wire [7:0] q", "logic [7:0] q"] {