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"] {