diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index f4729eccf3e..091ffbfa863 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2263,6 +2263,25 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(Expr::Ident(ret_name)) } + /// The value of `expr` now, in a temporary of its type. + fn keep_argument(&mut self, expr: &sv::ir::Expr) -> Result { + let signed = self.expr_signed(expr); + let float = floating::precision(expr, self.m.variables, self.m.name_to_id); + let handle = reads_string_variable(expr, self.m.variables, self.m.name_to_id); + let value = self.eval(expr, None)?; + let register = self.b.register(&value).clone(); + let width = register.width(); + let four_state = matches!(register, celox_sir::RegisterType::Logic { .. }); + let (temp, name) = self.m.temp("task_argument", width, signed, four_state); + let variable = self.m.variables.get_mut(&temp).unwrap(); + variable.float = float; + if handle { + variable.value_kind = celox_design::ValueKind::StrRef; + } + self.store(temp, SIROffset::Static(0), width, value); + Ok(sv::ir::Expr::Ident(name)) + } + fn plusargs( &mut self, function: sv::ir::SystemFunction, @@ -3216,6 +3235,32 @@ impl<'p, 'a> Ff<'p, 'a> { }; let (template, mut values) = system_task_template(self.m, &kind, args); prepare_time_operands(self.m, template.as_deref(), &mut values)?; + // Arguments are evaluated left to right. A later argument's call can + // change what an earlier one reads, or suspend the process (a host + // request) so that a value read before it would not survive the + // resume. So every argument before the last one with a call is + // evaluated whole into a temporary at its place; that one only has + // its calls run before its own reads, as any expression does. + let last_call = values.iter().rposition( + |value| matches!(value, sv::ir::SystemTaskArg::Expr(expr) if self.m.calls(expr)), + ); + if let Some(last_call) = last_call { + for (index, value) in values[..=last_call].iter_mut().enumerate() { + let sv::ir::SystemTaskArg::Expr(expr) = value else { + continue; + }; + let hoisted = if self.m.calls(expr) { + self.hoist(expr)? + } else { + expr.clone() + }; + *expr = if index == last_call || matches!(hoisted, sv::ir::Expr::Literal(_)) { + hoisted + } else { + self.keep_argument(&hoisted)? + }; + } + } let mut regs = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); @@ -3225,11 +3270,7 @@ impl<'p, 'a> Ff<'p, 'a> { for value in &values { match value { sv::ir::SystemTaskArg::Expr(expr) => { - let expr = if self.m.calls(expr) { - self.hoist(expr)? - } else { - expr.clone() - }; + let expr = expr.clone(); let signed = self.expr_signed(&expr); arg_is_handle.push(reads_string_variable( &expr, 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/crates/celox/tests/sv_plusargs.rs b/crates/celox/tests/sv_plusargs.rs index 1ec753fbd58..c7b90d39448 100644 --- a/crates/celox/tests/sv_plusargs.rs +++ b/crates/celox/tests/sv_plusargs.rs @@ -287,3 +287,79 @@ packed_string_literals_backend!(packed_string_literals_cranelift, build); #[cfg(target_arch = "x86_64")] packed_string_literals_backend!(packed_string_literals_native, build_native); packed_string_literals_backend!(packed_string_literals_wasm, build_wasm); + +/// A plusargs query among the arguments of a `$display` suspends the process +/// for the host; the arguments read before and after it keep their values. +const DISPLAYED: &str = r#" +module Top; + int i; + logic [7:0] v; + initial begin + i = 3; + v = 0; + $display("%0d %0d %0d %0d", i, $test$plusargs("verbose"), $value$plusargs("v=%d", v), v); + end +endmodule +"#; + +/// Arguments are evaluated left to right: a later argument's call does not +/// change what an earlier argument read (Icarus prints `3 1 5 7`). +const ORDERED: &str = r#" +module Top; + int i; + function automatic int f(); + return 0; + endfunction + function automatic int g(); + i = 7; + return 5; + endfunction + initial begin + i = 3; + $display("%0d %0d %0d %0d", i + f(), $test$plusargs("verbose"), g(), i); + end +endmodule +"#; + +macro_rules! display_plusargs { + ($name:ident, $backend:ident) => { + display_plusargs!($name, $backend, DISPLAYED, "3 1 1 7"); + }; + ($name:ident, $backend:ident, $source:expr, $expected:literal) => { + #[test] + fn $name() { + let mut sim = celox::Simulation::from_sv_sources( + vec![($source, Path::new("displayed.sv"))], + "Top", + ) + .plusargs(["+verbose", "+v=7"]) + .$backend() + .unwrap(); + sim.run_until(0).unwrap(); + let lines: Vec = sim + .drain_runtime_events() + .into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Display { message } => { + Some(String::from_utf8_lossy(&message).into_owned()) + } + _ => None, + }) + .collect(); + assert_eq!(lines, [$expected]); + } + }; +} +display_plusargs!(display_of_plusargs_interpreter, build_interpreter); +display_plusargs!(display_of_plusargs_compiled, build); +#[cfg(target_arch = "x86_64")] +display_plusargs!(display_of_plusargs_native, build_native); +display_plusargs!( + ordered_arguments_interpreter, + build_interpreter, + ORDERED, + "3 1 5 7" +); +display_plusargs!(ordered_arguments_compiled, build, ORDERED, "3 1 5 7"); +#[cfg(target_arch = "x86_64")] +display_plusargs!(ordered_arguments_native, build_native, ORDERED, "3 1 5 7"); 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 @*` として扱うと他の論理と組み合わせループを作るリストも