From 3880dfb74baf567e08ffa832a125d3377bee7eed Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 14:58:41 +0900 Subject: [PATCH 1/5] perf(sv): skip the always_comb alternative nothing can watch In a design with a wait, every always_comb that may store a variable twice was also lowered as an imperative unit, which assembly drops unless a wait or flip-flop domain counts one of its targets. A module now collects what may name its variables: wait terms, triggers, event copies, package variables, instance connections, ports of an instantiated module, and whatever a same-width write and read of a combinational process connects to them. The second lowering runs only for a process whose targets meet that set. Designs with a nonblocking switch or with foreign modules lower every alternative as before. Closes #1754 Change-Id: I6ca8cdf3e1561a784cd9ac5536b8d42b3618b9a3 --- crates/celox-frontend-sv/src/lowering.rs | 203 ++++++++++++++++++ .../src/lowering/procedural.rs | 28 +++ 2 files changed, 231 insertions(+) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 605b02f32bb..f7e7390e94b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1817,6 +1817,7 @@ fn prepare_external_hierarchy_collecting( &lowered_modules, four_state, allow_inferred_latches, + true, warnings, )?; modules.insert( @@ -2331,6 +2332,7 @@ fn schedule_sources_collecting( &lowered_modules, four_state, allow_inferred_latches, + false, warnings, )?; module_names.insert(module_id, key.name.clone()); @@ -3554,6 +3556,7 @@ pub(crate) fn attach_instance_glue( lowered_modules: &HashMap, four_state: bool, allow_inferred_latches: bool, + foreign: bool, warnings: &mut Vec, ) -> Result<(), ParserError> { let mut signal_names = lowered.signal_names.clone(); @@ -3683,6 +3686,67 @@ pub(crate) fn attach_instance_glue( let waits = lowered_modules .values() .any(|module| !module.sim_module.wait_sites.is_empty()); + // An `always_comb` alternative is kept only if a wait or a flip-flop + // domain counts one of its targets. Within the module, they name its + // wait terms, its triggers and whole-variable copies of them; beyond + // it, ports, instance connections and package variables. Every counter + // a design declares also keeps nonblocking writes queued, so a design + // with a nonblocking switch lowers every alternative, and so does a + // module of a design with foreign modules, which this module does not see. + let watch_seeds = (waits + && !foreign + && !lowered_modules + .values() + .any(|module| !module.sim_module.nba_switches.is_empty())) + .then(|| { + let mut seeds: HashSet = module + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|&(signal, _)| signal)) + .collect(); + let triggers = module + .eval_only_ff_blocks + .keys() + .chain(module.apply_ff_blocks.keys()) + .chain(module.eval_apply_ff_blocks.keys()) + .chain(module.split_commit_ff_blocks.keys()) + .chain(module.parallel_ff_parts.keys()); + for trigger in triggers { + seeds.insert(trigger.clock); + seeds.extend(trigger.resets.iter().copied()); + } + for &(copy, signal) in &lowered.event_copies { + seeds.extend([copy, signal]); + } + seeds.extend(lowered.package_variables.iter().map(|(id, _, _)| *id)); + let instantiated = lowered_modules.values().any(|other| { + other + .instances + .iter() + .any(|instance| &LoweredSvModuleKey::instance_key(instance) == current_key) + }); + if instantiated { + seeds.extend( + parent_variables + .iter() + .filter(|(_, variable)| variable.kind.is_port()) + .map(|(id, _)| *id), + ); + } + let mut names = HashSet::default(); + for (_, _, _, connections) in &resolved_instances { + for actual in connections.iter().filter_map(|c| c.actual_expr.as_ref()) { + procedural::expr_idents(actual, &mut names); + } + } + seeds.extend( + names + .iter() + .filter_map(|name| signal_names.get(name).copied()), + ); + seeds.extend(port_assignments.iter().map(|(target, _)| *target)); + seeds + }); let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) = lower_comb_processes( &lowered.source, @@ -3697,6 +3761,7 @@ pub(crate) fn attach_instance_glue( &mut module.extern_functions, warnings, waits, + watch_seeds.as_ref(), ) .map_err(|error| match error { sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { @@ -4264,6 +4329,7 @@ fn lower_comb_processes( extern_functions: &mut Vec, warnings: &mut Vec, waits: bool, + watch_seeds: Option<&HashSet>, ) -> Result< ( Vec>, @@ -4292,6 +4358,8 @@ fn lower_comb_processes( pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); let random_seeds = process_random_seeds(module); + let watchable = + watch_seeds.map(|seeds| watchable_variables(&pm, module, port_assignments, seeds)); for (index, process) in module.comb_processes().iter().enumerate() { if let Some(condition) = process.condition() { let condition = @@ -4352,6 +4420,15 @@ fn lower_comb_processes( targets.sort_unstable(); targets.dedup(); comb_blocks.extend(paths); + if let Some(watchable) = &watchable + && targets + .iter() + .map(|target| target.id) + .chain(pm.written_variables(process.body())) + .all(|id| !watchable.contains(&id)) + { + continue; + } if let Some((paths, alternative)) = lower_comb_alternative( &mut pm, process, @@ -4490,6 +4567,65 @@ fn lower_comb_processes( Ok((comb_blocks, arena, created, observers, sites, alternatives)) } +/// `seeds` and the variables a whole-variable copy of a combinational +/// process or a port assignment may connect to them, in either direction. +/// Any variable a process writes may copy any variable of the same width +/// the process writes or reads. +fn watchable_variables( + pm: &procedural::ProcModule<'_>, + module: &sv::ir::Module, + port_assignments: &[(SourceVarId, Vec)], + seeds: &HashSet, +) -> HashSet { + let mut groups: HashMap<(usize, usize), Vec> = HashMap::default(); + let mut group = |index: usize, writes: HashSet, reads: Vec| { + let widths: HashSet = writes.iter().map(|&id| pm.var(id).width).collect(); + for id in writes.into_iter().chain(reads) { + let width = pm.var(id).width; + if widths.contains(&width) { + groups.entry((index, width)).or_default().push(id); + } + } + }; + let processes = module.comb_processes(); + for (index, process) in processes.iter().enumerate() { + let mut reads = pm.implicit_reads(process.body(), true); + reads.extend(pm.implicit_reads(process.sensitivity_body(), true)); + group( + index, + pm.written_variables(process.body()), + reads.iter().map(|read| read.id).collect(), + ); + } + for (index, (target, body)) in port_assignments.iter().enumerate() { + let mut writes = pm.written_variables(body); + writes.insert(*target); + group( + processes.len() + index, + writes, + pm.implicit_reads(body, true) + .iter() + .map(|read| read.id) + .collect(), + ); + } + let mut watchable = seeds.clone(); + let mut groups: Vec<_> = groups.into_values().collect(); + loop { + let before = groups.len(); + groups.retain(|group| { + if !group.iter().any(|id| watchable.contains(id)) { + return true; + } + watchable.extend(group.iter().copied()); + false + }); + if groups.len() == before { + return watchable; + } + } +} + /// The imperative unit of an `always_comb` process lowered symbolically to /// `targets`, and its [`CombAlternative`], if the unit may store a variable /// of the design twice in one execution. Otherwise nothing of the attempt @@ -9164,6 +9300,73 @@ mod tests { .count() } + /// The `always_comb` alternatives the modules of `source` lowered. + fn comb_alternatives(source: &str) -> usize { + let mut trace = FrontendTrace::default(); + schedule_sources( + &[(source, Path::new("top.sv"))], + "Top", + &[], + &[], + &[], + false, + &celox_frontend_core::ParallelScheduleOptions::default(), + &FrontendTraceOptions { + sim_modules: true, + ..Default::default() + }, + Some(&mut trace), + &mut Vec::new(), + ) + .unwrap_or_else(|error| panic!("{error}")); + trace + .sim_modules + .expect("traced modules") + .values() + .map(|module| module.comb_alternatives.len()) + .sum() + } + + /// An `always_comb` that stores a variable twice gets its imperative + /// alternative only where a wait or a flip-flop domain may watch it. + #[test] + fn comb_alternatives_only_for_watchable_targets() { + let multi_store = "always_comb begin w = 0; if (s[0]) w = 1; end"; + for (case, body, alternatives) in [ + ("unwatched", "initial forever @(s) ;", 0), + ("waited", "initial forever @(w) ;", 1), + ( + "aliased clock", + "bit c; assign c = w; bit q; always_ff @(posedge c) q <= ~q; + initial forever @(s) ;", + 1, + ), + ( + "nonblocking switch", + "bit [7:0] t; initial forever @(s) t <= s;", + 1, + ), + ] { + let source = format!( + "module Top(input bit [7:0] s); + bit w; + {multi_store} + {body} + endmodule" + ); + assert_eq!(comb_alternatives(&source), alternatives, "{case}"); + } + let child_port = "module Child(input bit [7:0] s, output bit w); + always_comb begin w = 0; if (s[0]) w = 1; end + endmodule + module Top(input bit [7:0] s); + bit w; + Child child(.s(s), .w(w)); + initial forever @(w) ; + endmodule"; + assert_eq!(comb_alternatives(child_port), 1, "child output port"); + } + /// Only the `always @(list)` processes of a combinational loop stay /// processes; one `initial` block drives each design. #[test] diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..51298818d29 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -319,6 +319,34 @@ impl<'a> ProcModule<'a> { false } + /// The variables `body` may write, directly or in the bodies of its + /// callees. Names a callee declares itself may resolve to a variable of + /// the module too, so the set may be larger than the writes. + pub fn written_variables(&self, body: &[sv::ir::Stmt]) -> HashSet { + let mut names = HashSet::default(); + let mut calls = Vec::new(); + written_names(body, &mut names); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + let mut visited = HashSet::default(); + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + if let Some(subroutine) = self.subroutine(&name) { + default_calls(subroutine, &args, &mut calls); + if visited.insert(name) { + written_names(&subroutine.body, &mut names); + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + } + } + } + names.iter().filter_map(|name| self.id(name)).collect() + } + /// Whether `always @(items) body` is `always @* body`: no item has an edge /// or a select, the items name exactly the variables the implicit event /// expression of `body` has (IEEE 1800-2023 9.4.2.2), and the body neither From 9a10bbafb8469f7d613e91663aedb0572f7b6d8b Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 17:48:39 +0900 Subject: [PATCH 2/5] perf(sv): join every read of a combinational process to the watch set A process that writes a watchable variable or reads one makes all the variables it writes and reads watchable, at any width and through any expression, not only same-width pairs. Unit tests keep the alternative for waits through a part-select, a concatenation and an arithmetic expression, and check that a hierarchical reference is rejected. Change-Id: Ib61347656ea07409622b103f02eeb213d3405364 --- crates/celox-frontend-sv/src/lowering.rs | 119 +++++++++++++---------- 1 file changed, 70 insertions(+), 49 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index f7e7390e94b..d957daf9c34 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4567,50 +4567,38 @@ fn lower_comb_processes( Ok((comb_blocks, arena, created, observers, sites, alternatives)) } -/// `seeds` and the variables a whole-variable copy of a combinational -/// process or a port assignment may connect to them, in either direction. -/// Any variable a process writes may copy any variable of the same width -/// the process writes or reads. +/// `seeds` and every variable a combinational process or a port assignment +/// connects to them, in either direction. Clock-domain unification aliases +/// only whole-variable copies, but any variable a process writes and any it +/// writes or reads join one group, at any width and through any expression. fn watchable_variables( pm: &procedural::ProcModule<'_>, module: &sv::ir::Module, port_assignments: &[(SourceVarId, Vec)], seeds: &HashSet, ) -> HashSet { - let mut groups: HashMap<(usize, usize), Vec> = HashMap::default(); - let mut group = |index: usize, writes: HashSet, reads: Vec| { - let widths: HashSet = writes.iter().map(|&id| pm.var(id).width).collect(); - for id in writes.into_iter().chain(reads) { - let width = pm.var(id).width; - if widths.contains(&width) { - groups.entry((index, width)).or_default().push(id); - } + let mut groups: Vec> = Vec::new(); + let mut group = |writes: HashSet, reads: HashSet>| { + if !writes.is_empty() { + groups.push( + writes + .into_iter() + .chain(reads.iter().map(|read| read.id)) + .collect(), + ); } }; - let processes = module.comb_processes(); - for (index, process) in processes.iter().enumerate() { + for process in module.comb_processes() { let mut reads = pm.implicit_reads(process.body(), true); reads.extend(pm.implicit_reads(process.sensitivity_body(), true)); - group( - index, - pm.written_variables(process.body()), - reads.iter().map(|read| read.id).collect(), - ); + group(pm.written_variables(process.body()), reads); } - for (index, (target, body)) in port_assignments.iter().enumerate() { + for (target, body) in port_assignments { let mut writes = pm.written_variables(body); writes.insert(*target); - group( - processes.len() + index, - writes, - pm.implicit_reads(body, true) - .iter() - .map(|read| read.id) - .collect(), - ); + group(writes, pm.implicit_reads(body, true)); } let mut watchable = seeds.clone(); - let mut groups: Vec<_> = groups.into_values().collect(); loop { let before = groups.len(); groups.retain(|group| { @@ -9302,6 +9290,10 @@ mod tests { /// The `always_comb` alternatives the modules of `source` lowered. fn comb_alternatives(source: &str) -> usize { + try_comb_alternatives(source).unwrap_or_else(|error| panic!("{error}")) + } + + fn try_comb_alternatives(source: &str) -> Result { let mut trace = FrontendTrace::default(); schedule_sources( &[(source, Path::new("top.sv"))], @@ -9317,54 +9309,83 @@ mod tests { }, Some(&mut trace), &mut Vec::new(), - ) - .unwrap_or_else(|error| panic!("{error}")); - trace + )?; + Ok(trace .sim_modules .expect("traced modules") .values() .map(|module| module.comb_alternatives.len()) - .sum() + .sum()) } /// An `always_comb` that stores a variable twice gets its imperative - /// alternative only where a wait or a flip-flop domain may watch it. + /// alternative only where a wait or a flip-flop domain may watch it, + /// directly or through any expression of combinational logic or a port. #[test] fn comb_alternatives_only_for_watchable_targets() { - let multi_store = "always_comb begin w = 0; if (s[0]) w = 1; end"; + let multi_store = "always_comb begin y = 0; if (s[0]) y = s; end"; for (case, body, alternatives) in [ - ("unwatched", "initial forever @(s) ;", 0), - ("waited", "initial forever @(w) ;", 1), + ("unwatched", "bit u; initial forever @(u) ;", 0), + ("source waited", "initial forever @(s) ;", 1), + ("waited", "initial forever @(y) ;", 1), + ( + "part-select", + "bit [3:0] w; assign w = y[3:0]; initial forever @(w) ;", + 1, + ), + ( + "concatenation", + "bit [15:0] w; assign w = {y, s}; initial forever @(w) ;", + 1, + ), + ( + "arithmetic", + "bit [8:0] w; assign w = y + 9'd1; initial forever @(w) ;", + 1, + ), ( "aliased clock", - "bit c; assign c = w; bit q; always_ff @(posedge c) q <= ~q; - initial forever @(s) ;", + "bit c; assign c = y[0]; bit q; always_ff @(posedge c) q <= ~q; + bit u; initial forever @(u) ;", 1, ), ( "nonblocking switch", - "bit [7:0] t; initial forever @(s) t <= s;", + "bit [7:0] t; bit u; initial forever @(u) t <= u;", 1, ), ] { let source = format!( "module Top(input bit [7:0] s); - bit w; + bit [7:0] y; {multi_store} {body} endmodule" ); assert_eq!(comb_alternatives(&source), alternatives, "{case}"); } - let child_port = "module Child(input bit [7:0] s, output bit w); - always_comb begin w = 0; if (s[0]) w = 1; end - endmodule - module Top(input bit [7:0] s); - bit w; - Child child(.s(s), .w(w)); - initial forever @(w) ; + let child = "module Child(input bit [7:0] s, output bit [7:0] y); + always_comb begin y = 0; if (s[0]) y = s; end + endmodule"; + let port = "module Top(input bit [7:0] s); + bit [7:0] y; + Child child(.s(s), .y(y)); + initial forever @(y) ; + endmodule"; + assert_eq!( + comb_alternatives(&format!("{child}\n{port}")), + 1, + "child output port" + ); + // Only ports reach the variables of another module: a hierarchical + // reference is rejected, so no wait names them otherwise. + let hierarchical = "module Top(input bit [7:0] s); + Child child(.s(s), .y()); + initial forever @(child.y) ; endmodule"; - assert_eq!(comb_alternatives(child_port), 1, "child output port"); + let error = try_comb_alternatives(&format!("{child}\n{hierarchical}")) + .expect_err("a hierarchical reference is rejected"); + assert!(error.to_string().contains("child.y"), "{error}"); } /// Only the `always @(list)` processes of a combinational loop stay From e76981dd4bd7338354c0d7754652e277c3d5f6f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 17:48:39 +0900 Subject: [PATCH 3/5] test(sv): wait on a part-select of a rewritten always_comb variable Change-Id: I9f2a272e29a62dcb551993e8ca60979cb137fb92 --- .../src/sv/cases/timing.vtest | 28 +++++++++++++++++++ .../verification/sv/icarus/timing.json | 11 ++++++++ .../verification/sv/verilator/timing.json | 11 ++++++++ .../tests/frontends/systemverilog/timing.rs | 1 + 4 files changed, 51 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 6700235ed25..c7706353c05 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1987,6 +1987,34 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (run_to_finish) (expect_output "y=0111 w=11 n=3\n")) +; A wait on a part-select of a variable an always_comb rewrites through 0. +; The continuous assignment updates w when y changes (IEEE 1800-2023 10.3); +; a simulator may interleave it with the process (4.7), but Celox, like +; Icarus and Verilator, evaluates it after the process: one event per +; settled change of y[3:0]. +(case intermediate_combinational_writes_reach_part_select_waiters_settled + (source "part_select.sv" #" + module Top; + logic [7:0] y, a = 8'h15; + logic [3:0] w; + logic c = 0; + int n; + always_comb begin y = 8'h0; if (c) y = a; end + assign w = y[3:0]; + initial #1 forever begin @(w); n++; end + initial begin + #2 c = 1; + #1 a = 8'h16; + #1 a = 8'h26; + #1 $display("y=%h w=%h n=%0d", y, w, n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=26 w=6 n=2\n")) + ; The counted variable is an output port that the parent connects to a ; concatenation. (case intermediate_combinational_writes_reach_concatenated_ports diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index ebe8418ed61..7cbdf02153d 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -607,6 +607,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_reach_part_select_waiters_settled", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 35f824e434c..2ac3e87028c 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -644,6 +644,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_reach_part_select_waiters_settled", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index b3916379346..9171836bda6 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -160,6 +160,7 @@ timed_cases! { fn parallel_flip_flop_parts_keep_pulses = "timing::parallel_flip_flop_parts_keep_pulses"; fn staged_nonblocking_writes_follow_later_blocking_writes = "timing::staged_nonblocking_writes_follow_later_blocking_writes"; fn intermediate_combinational_writes_replace_split_definitions = "timing::intermediate_combinational_writes_replace_split_definitions"; + fn intermediate_combinational_writes_reach_part_select_waiters_settled = "timing::intermediate_combinational_writes_reach_part_select_waiters_settled"; fn intermediate_combinational_writes_reach_concatenated_ports = "timing::intermediate_combinational_writes_reach_concatenated_ports"; fn blocking_write_waiters_run_before_nonblocking_updates = "timing::blocking_write_waiters_run_before_nonblocking_updates"; fn blocking_write_waiters_rearm_before_nonblocking_updates = "timing::blocking_write_waiters_rearm_before_nonblocking_updates"; From dbeeb17fde2496f3dd20e8e83d52d5e700b40b6f Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 00:41:17 +0900 Subject: [PATCH 4/5] perf(sv): count written call arguments in the watch set written_variables now maps every output and inout formal of a user call, and every argument a system function writes, to the names of its actual argument, for calls in statements and expressions and through the bodies of callees. A process that writes only through such an argument, like `always @* if ($random(w) && y[0]) ...` or a function that writes its output only through a nested system call, keeps its group, so a wait on the argument keeps the alternative of what it reads. Change-Id: I6bd823800910fabb75486fb969f84cbe6647f941 --- crates/celox-frontend-sv/src/lowering.rs | 68 ++++++++++++++----- .../src/lowering/procedural.rs | 30 ++++++-- 2 files changed, 75 insertions(+), 23 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d957daf9c34..bebd4d59635 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -9288,12 +9288,13 @@ mod tests { .count() } - /// The `always_comb` alternatives the modules of `source` lowered. - fn comb_alternatives(source: &str) -> usize { + /// The targets of the `always_comb` alternatives the modules of `source` + /// lowered, by name. + fn comb_alternatives(source: &str) -> BTreeSet { try_comb_alternatives(source).unwrap_or_else(|error| panic!("{error}")) } - fn try_comb_alternatives(source: &str) -> Result { + fn try_comb_alternatives(source: &str) -> Result, FrontendError> { let mut trace = FrontendTrace::default(); schedule_sources( &[(source, Path::new("top.sv"))], @@ -9314,8 +9315,15 @@ mod tests { .sim_modules .expect("traced modules") .values() - .map(|module| module.comb_alternatives.len()) - .sum()) + .flat_map(|module| { + module.comb_alternatives.iter().flat_map(|alternative| { + alternative + .targets + .iter() + .map(|target| module.variables[&target.id].path.join(".")) + }) + }) + .collect()) } /// An `always_comb` that stores a variable twice gets its imperative @@ -9324,35 +9332,60 @@ mod tests { #[test] fn comb_alternatives_only_for_watchable_targets() { let multi_store = "always_comb begin y = 0; if (s[0]) y = s; end"; - for (case, body, alternatives) in [ - ("unwatched", "bit u; initial forever @(u) ;", 0), - ("source waited", "initial forever @(s) ;", 1), - ("waited", "initial forever @(y) ;", 1), + for (case, body, keeps) in [ + ("unwatched", "bit u; initial forever @(u) ;", false), + ("source waited", "initial forever @(s) ;", true), + ("waited", "initial forever @(y) ;", true), ( "part-select", "bit [3:0] w; assign w = y[3:0]; initial forever @(w) ;", - 1, + true, ), ( "concatenation", "bit [15:0] w; assign w = {y, s}; initial forever @(w) ;", - 1, + true, ), ( "arithmetic", "bit [8:0] w; assign w = y + 9'd1; initial forever @(w) ;", - 1, + true, ), ( "aliased clock", "bit c; assign c = y[0]; bit q; always_ff @(posedge c) q <= ~q; bit u; initial forever @(u) ;", - 1, + true, + ), + ( + "output argument of an expression call", + "function automatic bit copy(input bit v, output bit o); + o = v; return 1; + endfunction + bit w; always_comb if (copy(y[0], w)) begin end + bit q; always_ff @(posedge w) q <= ~q; + bit t; initial forever @(t) ;", + true, + ), + ( + "output argument of a nested call", + "function automatic bit draw(output int o); + return $random(o) == 0; + endfunction + int w; always @* if (draw(w) && y[0]) begin end + initial forever @(w) ;", + true, + ), + ( + "argument a system function writes", + "int w; always @* if ($random(w) == 0 && y[0]) begin end + initial forever @(w) ;", + true, ), ( "nonblocking switch", "bit [7:0] t; bit u; initial forever @(u) t <= u;", - 1, + true, ), ] { let source = format!( @@ -9362,7 +9395,7 @@ mod tests { {body} endmodule" ); - assert_eq!(comb_alternatives(&source), alternatives, "{case}"); + assert_eq!(comb_alternatives(&source).contains("y"), keeps, "{case}"); } let child = "module Child(input bit [7:0] s, output bit [7:0] y); always_comb begin y = 0; if (s[0]) y = s; end @@ -9372,9 +9405,8 @@ mod tests { Child child(.s(s), .y(y)); initial forever @(y) ; endmodule"; - assert_eq!( - comb_alternatives(&format!("{child}\n{port}")), - 1, + assert!( + comb_alternatives(&format!("{child}\n{port}")).contains("y"), "child output port" ); // Only ports reach the variables of another module: a hierarchical diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 51298818d29..4e7b8dda7a7 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -319,9 +319,11 @@ impl<'a> ProcModule<'a> { false } - /// The variables `body` may write, directly or in the bodies of its - /// callees. Names a callee declares itself may resolve to a variable of - /// the module too, so the set may be larger than the writes. + /// The variables `body` may write, directly, through the output and + /// inout arguments of the calls of statements and expressions, or in the + /// bodies of its callees. Every name of a written argument counts, and + /// names a callee declares itself may resolve to a variable of the module + /// too, so the set may be larger than the writes. pub fn written_variables(&self, body: &[sv::ir::Stmt]) -> HashSet { let mut names = HashSet::default(); let mut calls = Vec::new(); @@ -331,10 +333,28 @@ impl<'a> ProcModule<'a> { } let mut visited = HashSet::default(); while let Some((callee, args)) = calls.pop() { - let sv::ir::Callee::Subroutine(name) = callee else { - continue; + let name = match callee { + sv::ir::Callee::System(function) => { + for (position, arg) in args.iter().enumerate() { + if function.writes_argument(position) + && let Some(arg) = arg + { + expr_idents(arg, &mut names); + } + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + _ => continue, }; if let Some(subroutine) = self.subroutine(&name) { + for (param, arg) in subroutine.params.iter().zip(&args) { + if param.direction.is_written() + && let Some(arg) = arg + { + expr_idents(arg, &mut names); + } + } default_calls(subroutine, &args, &mut calls); if visited.insert(name) { written_names(&subroutine.body, &mut names); From 050ece5ca612a484989f15fa553e0ef12632d61b Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 01:16:12 +0900 Subject: [PATCH 5/5] test(sv): keep the passing part-select case out of the retained reports Change-Id: Ibfaeb92d38d799b99267b34c2bb5e72e9f55565b --- .../verification/sv/icarus/timing.json | 11 ----------- .../verification/sv/verilator/timing.json | 11 ----------- 2 files changed, 22 deletions(-) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 7cbdf02153d..ebe8418ed61 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -607,17 +607,6 @@ "tag_reasons": {}, "tags": [] }, - { - "category": "Sequential", - "detail": "", - "expectation": "Simulation", - "name": "timing::intermediate_combinational_writes_reach_part_select_waiters_settled", - "phase": "execute", - "status": "passed", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] - }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 2ac3e87028c..35f824e434c 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -644,17 +644,6 @@ "tag_reasons": {}, "tags": [] }, - { - "category": "Sequential", - "detail": "", - "expectation": "Simulation", - "name": "timing::intermediate_combinational_writes_reach_part_select_waiters_settled", - "phase": "execute", - "status": "passed", - "stronger_than_sv": false, - "tag_reasons": {}, - "tags": [] - }, { "category": "Sequential", "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.",