From c42418d23a9c3c4e92e856f2ef4c4370e8b3c3e3 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 06:59:26 +0900 Subject: [PATCH] perf(sv): simulate sensitivity lists that cover their reads like always @* rtlmeter's C906 simulated at about 88 cycles/s on the native backend (four-state). Most of the simulation phase went to `SimulationState::check_waits`: about 720 processes waited on level-sensitive lists, and every round compared the watched signals of all of them (about 3,000 small terms per round, 60 rounds per cycle). These processes are the core's generated combinational blocks, such as `always @(a or b[127:0] or c[14:12])`. Only an `always` whose list names exactly the variables of the implicit event expression was simulated like `always @*` (IEEE 1800-2023 9.4.2.2). A part-select in the list, whether of the whole variable or narrower, kept the block a process. A level-sensitive list now also simulates like `always @*` when it covers every bit its statement reads (longest static prefixes) and running the statement more often cannot be observed: - the statement calls no subroutine or system task and no system function that reads the simulation; - it reads no variable it writes, so a run whose inputs did not change writes the values it wrote last time; - it stores each variable at most once per run, so an extra run does not pulse a variable for its waiters (4.3, 9.4.2). A list that names whole variables through full-width part-selects is now exact as well. Blocks that store a variable twice, such as a default assignment followed by a `case`, stay processes in both state modes: Celox wakes waiters on intermediate values, so an extra run would be observable, including against Verilator in two-state mode. C906 hello (native, four-state, heliodor-dev): the simulation phase takes 10.6 s instead of 37.8 s, about 312 cycles/s instead of 88. `check_waits` falls from about half of the phase to under 5%. The comb processes cost frontend work; #2062 (one unit per process schedule, which this change builds on) recovers most of it. Closes #2079. - Shared cases `always_comb::covering_sensitivity_lists_settle_like_a_wildcard` and its four-state twin (the untimed harness builds a `Simulator`, which runs no processes) and `always_comb::multi_store_blocks_with_covering_lists_stay_processes` (an edge waiter counts no extra pulses), matching Icarus and Verilator. - The SystemVerilog reference describes the rule and its reason. Change-Id: I8fb99a7ef1dbc09969a27024f479ee5f795412e5 --- .../src/lowering/procedural.rs | 164 +++++++++++++++++- .../src/sv/cases/always_comb.vtest | 78 +++++++++ .../frontends/systemverilog/always_comb.rs | 12 ++ docs/guide/systemverilog-reference.md | 11 +- docs/ja/guide/systemverilog-reference.md | 4 + 5 files changed, 257 insertions(+), 12 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index a1a1c6bddb8..37095d43ae5 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -373,26 +373,116 @@ impl<'a> ProcModule<'a> { 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 - /// suspends nor makes a nonblocking assignment, directly or in a call. + /// Whether `always @(items) body` simulates like `always @* body`. The + /// body must neither suspend nor make a nonblocking assignment, directly + /// or in a call. Then either + /// - the items name exactly the variables the implicit event expression + /// of `body` has (IEEE 1800-2023 9.4.2.2), a part-select of a whole + /// variable naming it, or + /// - the items cover every bit `body` reads, and running `body` when + /// none of those bits changed is unobservable: it has no side effects, + /// reads no variable it writes, and stores each variable at most once + /// per run, so it writes the values it wrote last time without + /// pulsing a variable for the waiters on it (4.3, 9.4.2). pub fn is_implicit_event_list( &self, items: &[sv::ir::EventItem], body: &[sv::ir::Stmt], ) -> bool { - let mut listed = HashSet::default(); + if self.suspends_or_defers(body) { + return false; + } + let mut listed: HashSet> = HashSet::default(); + let mut exact = true; for item in items { - let sv::ir::Expr::Ident(name) = &item.expr else { - return false; + let (name, range) = match &item.expr { + sv::ir::Expr::Ident(name) => (name, None), + sv::ir::Expr::Select { + expr: base, + msb, + lsb, + .. + } => { + let sv::ir::Expr::Ident(name) = &**base else { + return false; + }; + let Some(range) = sv::typecheck::eval_const_expr_with_types( + msb, + self.constants, + self.parameter_types, + ) + .zip(sv::typecheck::eval_const_expr_with_types( + lsb, + self.constants, + self.parameter_types, + )) + .and_then(|(msb, lsb)| { + packed_expr_select_offsets(base, msb, lsb, self.variables, self.name_to_id) + }) else { + return false; + }; + (name, Some((range.0.min(range.1), range.0.max(range.1)))) + } + _ => return false, }; let Some(id) = self.id(name).filter(|id| !self.is_hidden(*id)) else { return false; }; - listed.insert(VarAtomBase::new(id, 0, self.var(id).width - 1)); + let width = self.var(id).width; + let (lsb, msb) = range.unwrap_or((0, width - 1)); + exact &= lsb == 0 && msb == width - 1; + listed.insert(VarAtomBase::new(id, lsb, msb)); + } + let reads = self.implicit_reads(body, false); + if exact && listed == reads { + return true; + } + if !self.is_pure(body) { + return false; } - !self.suspends_or_defers(body) && listed == self.implicit_reads(body, false) + let mut written = HashSet::default(); + written_names(body, &mut written); + let written: HashSet<_> = written + .iter() + .filter_map(|name| self.id(name)) + .filter(|id| !self.is_hidden(*id)) + .collect(); + if reads.iter().any(|read| written.contains(&read.id)) { + return false; + } + if stores_twice(body, &mut HashSet::default()) { + return false; + } + // Longest static prefixes: constant selects keep their bits. + self.implicit_reads(body, true).iter().all(|read| { + (read.access.lsb..=read.access.msb).all(|bit| { + listed.iter().any(|item| { + item.id == read.id && item.access.lsb <= bit && bit <= item.access.msb + }) + }) + }) + } + + /// Whether `body` has no effect but its writes: no system task, no + /// subroutine call, no system function that reads the simulation. + fn is_pure(&self, body: &[sv::ir::Stmt]) -> bool { + let mut pure = true; + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| { + pure &= !matches!( + stmt, + sv::ir::Stmt::SystemTask { .. } + | sv::ir::Stmt::Eval(_) + | sv::ir::Stmt::Call { .. } + | sv::ir::Stmt::Return(_) + ); + stmt_calls(stmt, &mut calls); + }); + } + pure && calls.iter().all(|(callee, _)| { + matches!(callee, sv::ir::Callee::System(function) if !function.reads_simulation_state()) + }) } fn suspends_or_defers(&self, body: &[sv::ir::Stmt]) -> bool { @@ -2606,6 +2696,62 @@ pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&sv::ir::Callee } /// The names written by the assignments (and through call arguments) of a +/// Whether a run of `stmts` may store a variable twice, given the variables +/// `written` on some path before them. Locals are not variables of the +/// design, and a loop counts as storing twice. +fn stores_twice(stmts: &[sv::ir::Stmt], written: &mut HashSet) -> bool { + let mut locals = HashSet::default(); + stores_twice_in(stmts, written, &mut locals) +} + +fn stores_twice_in( + stmts: &[sv::ir::Stmt], + written: &mut HashSet, + locals: &mut HashSet, +) -> bool { + for stmt in stmts { + match stmt { + sv::ir::Stmt::Local { name, .. } => { + locals.insert(name.clone()); + } + sv::ir::Stmt::Assign { .. } | sv::ir::Stmt::AssignConcat { .. } => { + let mut names = HashSet::default(); + written_names(std::slice::from_ref(stmt), &mut names); + for name in names { + if !locals.contains(&name) && !written.insert(name) { + return true; + } + } + } + sv::ir::Stmt::If { + then_body, + else_body, + .. + } => { + let mut other = written.clone(); + if stores_twice_in(then_body, written, locals) + || stores_twice_in(else_body, &mut other, locals) + { + return true; + } + written.extend(other); + } + sv::ir::Stmt::Case { items, default, .. } => { + let before = written.clone(); + for body in items.iter().map(|item| &item.body).chain(default.iter()) { + let mut branch = before.clone(); + if stores_twice_in(body, &mut branch, locals) { + return true; + } + written.extend(branch); + } + } + _ => return true, + } + } + false +} + /// statement list. pub(super) fn written_names(stmts: &[sv::ir::Stmt], names: &mut HashSet) { for stmt in stmts { diff --git a/crates/celox-test-suite/src/sv/cases/always_comb.vtest b/crates/celox-test-suite/src/sv/cases/always_comb.vtest index 1c65de34d59..3acf7359e56 100644 --- a/crates/celox-test-suite/src/sv/cases/always_comb.vtest +++ b/crates/celox-test-suite/src/sv/cases/always_comb.vtest @@ -168,3 +168,81 @@ (run_to_finish) (expect_output "1 7\n")) +; A sensitivity list that covers every bit its statement reads, through +; part-selects narrower than the variables, simulates like `always @*` when +; running the statement more often is unobservable: no side effects, no +; feedback, and each variable stored at most once per run (#2079). The +; untimed harness builds a `Simulator`, which runs no processes. +(case covering_sensitivity_lists_settle_like_a_wildcard + (source "covering_lists.sv" #" + module Top(input logic [7:0] x, input logic [3:0] s, + output logic [2:0] y, output logic [3:0] z); + always @(x[2:0]) y = x[2:0] + 3'd1; + always @(x[7:4] or s) begin + case (s) + 4'd0: z = x[7:4]; + default: z = ~x[7:4]; + endcase + end + endmodule + "#) + (top Top) + (modify (set x 0x15) (set s 0)) + (assert_eq y 6) (assert_eq z 1) + (modify (set x 0x35)) + (assert_eq y 6) (assert_eq z 3) + (modify (set x 0x36) (set s 1)) + (assert_eq y 7) (assert_eq z 0xc)) + +(case covering_sensitivity_lists_settle_like_a_wildcard_in_four_state + (source "covering_lists.sv" #" + module Top(input logic [7:0] x, input logic [3:0] s, + output logic [2:0] y, output logic [3:0] z); + always @(x[2:0]) y = x[2:0] + 3'd1; + always @(x[7:4] or s) begin + case (s) + 4'd0: z = x[7:4]; + default: z = ~x[7:4]; + endcase + end + endmodule + "#) + (top Top) + (four_state) + (modify (set x 0x15) (set s 0)) + (assert_eq y 6) (assert_eq z 1) + (modify (set x 0x35)) + (assert_eq y 6) (assert_eq z 3) + (modify (set x 0x36) (set s 1)) + (assert_eq y 7) (assert_eq z 0xc)) + +; A block with a covering list that stores a variable twice per run stays a +; process: run on a change of an unlisted bit, it would pulse `p` and wake +; the edge waiter (4.3, 9.4.2). +(case multi_store_blocks_with_covering_lists_stay_processes + (source "multi_store_list.sv" #" + module Top; + logic [7:0] x; + logic p; + int n; + always @(x[0]) begin + p = 1'b0; + if (x[0]) p = 1'b1; + end + initial n = 0; + always @(posedge p) n = n + 1; + initial begin + x = 8'h15; + #1 $display("%b %0d", p, n); + x = 8'h35; + #1 $display("%b %0d", p, n); + x = 8'h36; + #1 $display("%b %0d", p, n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "1 1\n1 1\n0 1\n")) + diff --git a/crates/celox/tests/frontends/systemverilog/always_comb.rs b/crates/celox/tests/frontends/systemverilog/always_comb.rs index 010bffac2c0..c1612100df7 100644 --- a/crates/celox/tests/frontends/systemverilog/always_comb.rs +++ b/crates/celox/tests/frontends/systemverilog/always_comb.rs @@ -39,3 +39,15 @@ sv_backends! { @case "always_comb::two_state_other_sensitivity_lists_run_at_time_zero"; } } + +sv_backends! { + fn covering_sensitivity_lists_settle_like_a_wildcard(sim) { + @case "always_comb::covering_sensitivity_lists_settle_like_a_wildcard"; + } + fn covering_sensitivity_lists_settle_like_a_wildcard_in_four_state(sim) { + @case "always_comb::covering_sensitivity_lists_settle_like_a_wildcard_in_four_state"; + } + fn multi_store_blocks_with_covering_lists_stay_processes(sim) { + @case "always_comb::multi_store_blocks_with_covering_lists_stay_processes"; + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ced3e927699..ebf89de8f3b 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -60,9 +60,14 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: An `always` whose sensitivity list names exactly the variables its statement reads, as `@*` would (IEEE 1800-2023 9.4.2.2), simulates like `always @*` in both `Simulator` and `Simulation`: `always @(a or b) y = a + b;` or -`always @(b, a) y = a + b;`. The statement must not contain a timing control -or a nonblocking assignment. Any other sensitivity list without edges runs as -a process: `always @(a) y = a + b;` leaves `y` unchanged when only `b` +`always @(b, a) y = a + b;`. So does a list that covers every bit the +statement reads through part-selects, such as `always @(x[2:0]) y = x[2:0] + 1;`, +when running the statement more often cannot be observed: it calls no +subroutine or system task, reads no variable it writes, and stores each +variable at most once per run, so an extra run writes the same values without +pulsing a variable for its waiters (IEEE 1800-2023 4.3, 9.4.2). The statement +must not contain a timing control or a nonblocking assignment. Any other +sensitivity list without edges runs as a process: `always @(a) y = a + b;` leaves `y` unchanged when only `b` changes. So does a list that, as `always @*`, would close a combinational loop with other logic. So does an edge-sensitive `always` that does not have the shape of a flip-flop: one with an edge of a select or diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 11956d111ea..ff7e7377ff9 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -58,6 +58,10 @@ outline: [2, 3] 文が読む変数をちょうど並べたセンシティビティリスト(`@*` が求めるもの、IEEE 1800-2023 9.4.2.2)を持つ `always` は、`always @(a or b) y = a + b;` や `always @(b, a) y = a + b;` のように、 `Simulator` でも `Simulation` でも `always @*` と同様にシミュレーションします。 +`always @(x[2:0]) y = x[2:0] + 1;` のように、文が読むすべてのビットを部分選択で覆うリストも、 +文を余分に実行しても観測できない場合は同様です。つまり、文がサブルーチンもシステムタスクも呼ばず、 +書き込む変数を読まず、各変数への格納が 1 回の実行につき高々 1 回である場合で、余分な実行は同じ値を書き、 +待機中のプロセスに対して変数をパルスさせません(IEEE 1800-2023 4.3、9.4.2)。 文にはタイミング制御とノンブロッキング代入を含められません。エッジを持たないそれ以外の センシティビティリストを持つ `always` はプロセスとして実行します。`always @(a) y = a + b;` は `b` だけが変化しても `y` を更新しません。`always @*` として扱うと他の論理と組み合わせループを作るリストも