From 2c391c42ceddd78ce355589a816dffb9085890f2 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 05:19:04 +0900 Subject: [PATCH 1/2] fix(sv)!: settle two-state sensitivity-list processes at time zero, like Verilator `always @*` and `always @(list)` wait for a change before their first run (IEEE 1800-2023 9.2.2.2, 9.4.2). In four-state mode their outputs start as X, so the wait rarely shows. In two-state mode the outputs start as a real 0 that drives logic. In rtlmeter's C906, `axi_slave128` computes `mem_cen` / `mem_wen` in `always @(cur_state or wdata_s0[127:0] or wvalid_s0 or wready or wstrb_s0[15:0])`. Until an input changed, the 0s read as a write enable: at cycle 2 every SRAM bank wrote 0 over the reset vector the testbench had loaded, and the CPU never started. Verilator 5.052 (two-state) evaluates these blocks once at time zero, after the initial blocks. Two-state mode now does the same; four-state mode keeps the LRM behavior: - `always @*`, and a list that names exactly the reads of its statement (which the frontend already lowers as `always @*`), run on their first activation like `always_comb`: no startup snapshot, and ordered after the initial blocks (`Ff::lower_comb_process`). - Any other level-sensitive `always @(list) statement` lowers as `#0; forever begin statement; @(list); end`. It runs once at time zero after the time-zero statements of the initial blocks, then waits. This covers C906's list, whose full-width part-selects do not count as naming the variables, and incomplete or over-complete lists. Treating a full-width part-select in a list as naming the variable would have turned C906's blocks into combinational processes. That cost about 10% more instructions before the testbench starts, so those blocks stay processes. With this change, C906 (interpreter, two-state) runs 2-3% more instructions up to "Init Program", spread over the frontend. BREAKING CHANGE: in two-state mode, `always @*` and sensitivity-list processes run once at time zero, so their outputs and `$display`s appear at time zero. Use four-state mode for the LRM's wait. Closes #2021. Closes #2026. - Shared cases `always_comb::two_state_sensitivity_lists_run_at_time_zero` (C906's write-enable block and an `always @*`) and `always_comb::two_state_other_sensitivity_lists_run_at_time_zero` (an over-complete and an incomplete list) match Verilator. They carry the new oracle tag `two_state_time_zero_settle`, since SV has the processes wait. Icarus simulates them in four-state SV and prints X, which the new reviewed exclusion `sv_icarus_two_state_time_zero_settle` records, with standalone probes in `verification/repros/sv_two_state_time_zero_settle.json`. - Cases and tests whose subject is the LRM wait or the startup guard now run in four-state mode: the latch `always @*` startup and change-return cases, `timing::explicit_list_of_every_read_waits_for_a_change`, `timing::list_with_an_extra_signal_wakes_on_it`, `program::program_nonblocking_updates_follow_design_updates`, and the startup-guard tests of `sv_declaration_startup`. The `$urandom` sensitivity test expects `always @*` draws at time zero. Change-Id: I73580672abd3acfb040c78cfd4daae2f7df786e2 --- crates/celox-frontend-sv/src/lowering.rs | 35 +++++- crates/celox-frontend-sv/src/lowering/ff.rs | 12 +- crates/celox-test-suite/LIMITATIONS.md | 3 +- crates/celox-test-suite/README.md | 1 + crates/celox-test-suite/src/lib.rs | 5 + crates/celox-test-suite/src/script/ast.rs | 1 + .../src/sv/cases/always_comb.vtest | 63 ++++++++++ .../celox-test-suite/src/sv/cases/latch.vtest | 12 ++ .../src/sv/cases/program.vtest | 3 + .../src/sv/cases/timing.vtest | 9 +- .../repros/sv_two_state_time_zero_settle.json | 52 ++++++++ .../verification/sv/icarus/always_comb.json | 54 ++++++++ .../verification/sv/limitations.json | 18 +++ .../frontends/systemverilog/always_comb.rs | 12 ++ .../tests/frontends/systemverilog/latch.rs | 41 +++---- .../systemverilog/system_functions.rs | 13 +- crates/celox/tests/sv_declaration_startup.rs | 115 ++++++++---------- 17 files changed, 349 insertions(+), 100 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_two_state_time_zero_settle.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 04e2ab43bc7..fa54240afe6 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5092,11 +5092,36 @@ fn lower_initial_processes( .zip(slots) .enumerate() .map(|(index, ((process, random_seed), slots))| { - let kernel = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel( - process.body(), - slots, - index, - )?; + // `always @(list) statement` waits for a change (IEEE 1800-2023 + // 9.4.2). In two-state mode its outputs would then start as a + // real 0, so it runs once at time zero, after the time-zero + // statements of the initial blocks, before it waits, as + // Verilator settles it: `#0; forever begin statement; @(list); end`. + let settled; + let body = match process.level_sensitive().filter(|_| !four_state) { + Some((items, statements)) => { + let mut looped = statements.to_vec(); + looped.push(sv::ir::Stmt::WaitEvent(items.to_vec())); + settled = [ + sv::ir::Stmt::Delay { + amount: sv::ir::Expr::Literal("0".to_string()), + ticks_per_unit: 1, + ticks_per_precision: 1, + }, + sv::ir::Stmt::Loop { + kind: sv::ir::LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body: looped, + }, + ]; + &settled[..] + } + None => process.body(), + }; + let kernel = + ff::Ff::new(&mut pm, random_seed).lower_initial_kernel(body, slots, index)?; wait_sites.extend(kernel.wait_sites); nba_sites.extend(kernel.nba_sites); nba_switches.extend(kernel.nba_switches); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 7c9c153da7c..3dc8a09386f 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3950,6 +3950,11 @@ impl<'p, 'a> Ff<'p, 'a> { arena: &mut SLTNodeArena, ) -> Result>, sv::AnalyzerError> { let always_comb = kind != sv::ir::CombProcessKind::AlwaysStar; + // `always @*` and a sensitivity list wait for a change (IEEE + // 1800-2023 9.2.2.2). In two-state mode their outputs would then + // start as a real 0, so they run once at time zero, after the + // `initial` blocks, like `always_comb`, as Verilator settles them. + let runs_at_time_zero = always_comb || !self.m.four_state; self.direct = true; let mut reads = self.m.implicit_reads(body, always_comb); reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); @@ -4113,7 +4118,7 @@ impl<'p, 'a> Ff<'p, 'a> { counter_snapshots.push((counter, saved_counter)); } let run = self.b.alloc_bit(1, false); - if always_comb { + if runs_at_time_zero { let first = self.b.alloc_bit(1, false); self.b .emit(SIRInstruction::Unary(first, UnaryOp::LogicNot, init)); @@ -4227,7 +4232,7 @@ impl<'p, 'a> Ff<'p, 'a> { target: LogicPathTarget::Process { process: initialized, sensitivity_counters: sensitivity_counters.clone(), - startup: (!always_comb).then(|| celox_slt::CombStartup { + startup: (!runs_at_time_zero).then(|| celox_slt::CombStartup { initialized, counters: counter_snapshots.clone(), inputs: sources @@ -4239,7 +4244,8 @@ impl<'p, 'a> Ff<'p, 'a> { after_initials: matches!( kind, sv::ir::CombProcessKind::AlwaysComb | sv::ir::CombProcessKind::AlwaysLatch - ), + ) || (kind == sv::ir::CombProcessKind::AlwaysStar + && !self.m.four_state), target, unit: Box::new(unit.clone()), }, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index bc57d47a063..65deec8647c 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -465,7 +465,7 @@ including its positive check that changing the argument does wake the procedures The [standalone comparison](verification/repros/wildcard_task_sensitivity_verilator.json) records both executions. Only this Verilator case is excluded for this reason. -The SystemVerilog suite's exclusions are listed in [`verification/sv/limitations.json`](verification/sv/limitations.json), with the failures observed before them in [`verification/sv/limitations/`](verification/sv/limitations). A case is excluded for a tool only when the expected value follows IEEE 1800 and the tool either cannot run the design or disagrees with the standard; where the two tools disagree with each other, the entry says so. +The SystemVerilog suite's exclusions are listed in [`verification/sv/limitations.json`](verification/sv/limitations.json), with the failures observed before them in [`verification/sv/limitations/`](verification/sv/limitations). A case is excluded for a tool only when the expected value follows IEEE 1800 and the tool either cannot run the design or disagrees with the standard; where the two tools disagree with each other, the entry says so. A case tagged with an expectation stronger than SV (see the [tag table](README.md)) may also be excluded for a tool whose state model cannot produce it. The interface-array connection cases cover packed distribution, unpacked connections and array ports, and multidimensional instance arrays (IEEE @@ -541,6 +541,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | | `sv_verilator_constant_unknown_bits` | execute | verilator | 1 | Verilator 5.052 is two-state: unknown bits in constant system function arguments ($onehot(2'bx1)) are not kept unknown, so a generate condition differs from IEEE 1800-2023 20.9. Icarus agrees with the expected values. | +| `sv_icarus_two_state_time_zero_settle` | execute | icarus | 2 | Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a [standalone probe](verification/repros/sv_two_state_time_zero_settle.json) prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus. | | `sv_verilator_generate_case_unknown_label` | compile | verilator | 1 | Verilator 5.052 rejects an x or ? digit in a case-generate label ("no such thing as generate casez"). Icarus passes the case. | | `sv_verilator_self_determined_index` | execute | verilator | 1 | Verilator 5.052 does not wrap a self-determined index expression (2'd3 + 2'd1) to its width before selecting; IEEE 1800-2023 11.5.1 and 11.6.1 make the index 0. Icarus agrees with the expected value. | | `sv_verilator_short_circuit_calls` | execute | verilator | 1 | Verilator 5.052 runs a function call in the right operand of && in a select index when the left operand is false, so its output argument is written; IEEE 1800-2023 11.4.7 does not evaluate that operand. Icarus cannot compile the design (sv_icarus_function_outputs). | diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 8931a473d01..0cd2495c6b6 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -177,6 +177,7 @@ case still runs its original assertions by default. | `eager_assertion_messages` | Veryl `$assert` / `$assert_continue` message argument effects occur even on success; these calls have no standard SV counterpart | | `two_state_zero_division` | The suite's two-state model returns zero for division/remainder by zero, including four-state `logic` destinations in emitted SV (11.3.4, 11.4.3) | | `two_state_initialization` | An explicit check of zero-initialized storage even for emitted four-state `logic` (6.8, Table 6-7) | +| `two_state_time_zero_settle` | Two-state `always @*` and sensitivity-list processes run once at time zero, after the initial blocks, as Verilator settles them, whereas SV has them wait for a change (9.2.2.2, 9.4.2) | The initial review tags 21 cases; cases may carry multiple tags. Matching a word such as `source_order` in a case name is insufficient: the two output diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index 4ff79bb0570..b9c5aa4dfce 100644 --- a/crates/celox-test-suite/src/lib.rs +++ b/crates/celox-test-suite/src/lib.rs @@ -89,6 +89,7 @@ pub enum TestTag { EagerAssertionMessages, TwoStateZeroDivision, TwoStateInitialization, + TwoStateTimeZeroSettle, } impl TestTag { @@ -101,6 +102,7 @@ impl TestTag { Self::EagerAssertionMessages => "eager_assertion_messages", Self::TwoStateZeroDivision => "two_state_zero_division", Self::TwoStateInitialization => "two_state_initialization", + Self::TwoStateTimeZeroSettle => "two_state_time_zero_settle", } } @@ -125,6 +127,9 @@ impl TestTag { Self::TwoStateInitialization => { "Explicitly requires the suite's zero-initialized two-state storage even for emitted four-state logic; SV default initialization depends on the declared type (IEEE 1800-2023 6.8, Table 6-7)." } + Self::TwoStateTimeZeroSettle => { + "Requires two-state `always @*` and sensitivity-list processes to run once at time zero, after the initial blocks, as Verilator settles them; SV has them wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2)." + } } } } diff --git a/crates/celox-test-suite/src/script/ast.rs b/crates/celox-test-suite/src/script/ast.rs index 820ef77050c..ebb58447d42 100644 --- a/crates/celox-test-suite/src/script/ast.rs +++ b/crates/celox-test-suite/src/script/ast.rs @@ -384,6 +384,7 @@ fn tag(name: &str, pos: Pos) -> Result { "eager_assertion_messages" => TestTag::EagerAssertionMessages, "two_state_zero_division" => TestTag::TwoStateZeroDivision, "two_state_initialization" => TestTag::TwoStateInitialization, + "two_state_time_zero_settle" => TestTag::TwoStateTimeZeroSettle, _ => return error(pos, format!("unknown tag `{name}`")), }) } 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 fd365ba0700..1c65de34d59 100644 --- a/crates/celox-test-suite/src/sv/cases/always_comb.vtest +++ b/crates/celox-test-suite/src/sv/cases/always_comb.vtest @@ -105,3 +105,66 @@ (modify (set a 10)) (assert_eq y 15) (assert_eq z 5)) + +; In two-state mode, `always @*` and a sensitivity list run once at time +; zero, after the initial blocks, as Verilator settles them: C906's memory +; enable would otherwise start as a real 0, a write enable (#2021). IEEE +; 1800-2023 9.2.2.2 has them wait for a change, which four-state mode keeps. +(case two_state_sensitivity_lists_run_at_time_zero + (tags two_state_time_zero_settle) + (source "time_zero.sv" #" + module Top; + localparam logic [1:0] READ = 2'd1; + logic [1:0] cur_state; + logic wvalid, wready; + logic [15:0] wstrb; + logic cen; + logic [15:0] wen; + logic [3:0] st = 4'd2; + logic hit; + always @(cur_state or wvalid or wready or wstrb[15:0]) begin + if (cur_state == READ) begin + cen = 1'b0; + wen = 16'hffff; + end else if (wvalid && wready) begin + cen = 1'b0; + wen = ~wstrb; + end else begin + cen = 1'b1; + wen = 16'hffff; + end + end + always @* hit = (st == 4'd2); + initial begin + #1 $display("%b %h %b", cen, wen, hit); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "1 ffff 1\n")) + +; Two-state mode also runs a sensitivity list that does not name exactly the +; reads of its statement once at time zero, after the initial blocks, and then +; waits at it, as Verilator settles it (#2026): `y` lists a variable it does +; not read, and `z` reads `b` without listing it. +(case two_state_other_sensitivity_lists_run_at_time_zero + (tags two_state_time_zero_settle) + (source "time_zero_lists.sv" #" + module Top; + logic [3:0] a, b; + logic [3:0] y, z; + always @(a or b) y = a + 4'd1; + always @(a) z = a + b + 4'd2; + initial begin + b = 4'd5; + #1 $display("%0d %0d", y, z); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "1 7\n")) + diff --git a/crates/celox-test-suite/src/sv/cases/latch.vtest b/crates/celox-test-suite/src/sv/cases/latch.vtest index b57e6242195..19eb1cf2573 100644 --- a/crates/celox-test-suite/src/sv/cases/latch.vtest +++ b/crates/celox-test-suite/src/sv/cases/latch.vtest @@ -105,6 +105,8 @@ endmodule (top Top) (run_to_finish)) +; `always @*` waits for a change in four-state mode only; two-state mode runs +; it at time zero (#2021). (case classic_star_declaration_startup (source "declaration_startup.sv" #" module Top; @@ -120,6 +122,7 @@ module Top; endmodule "#) (top Top) + (four_state) (run_to_finish)) (case classic_star_initial_startup @@ -178,6 +181,8 @@ endmodule (top Top) (run_to_finish)) +; `always @*` waits for a change in four-state mode only; two-state mode runs +; it at time zero (#2021). (case same_activation_change_return (source "change_return.sv" #" module Top; @@ -201,8 +206,11 @@ module Top; endmodule "#) (top Top) + (four_state) (run_to_finish)) +; `always @*` waits for a change in four-state mode only; two-state mode runs +; it at time zero (#2021). (case hierarchy_same_activation_change_return (source "hierarchy_change_return.sv" #" module Latch(input wire a, output wire [7:0] q); @@ -224,6 +232,7 @@ module Top(output wire [7:0] q); endmodule "#) (top Top) + (four_state) (run_to_finish)) (case star_select_sensitivity @@ -245,6 +254,8 @@ endmodule (top Top) (run_to_finish)) +; `always @*` waits for a change in four-state mode only; two-state mode runs +; it at time zero (#2021). (case star_complete_declaration_startup (source "star_complete_declaration_startup.sv" #" module Top; @@ -260,6 +271,7 @@ module Top; endmodule "#) (top Top) + (four_state) (run_to_finish)) (case task_call_sensitivity diff --git a/crates/celox-test-suite/src/sv/cases/program.vtest b/crates/celox-test-suite/src/sv/cases/program.vtest index 033758f52d1..8a6bf5410dd 100644 --- a/crates/celox-test-suite/src/sv/cases/program.vtest +++ b/crates/celox-test-suite/src/sv/cases/program.vtest @@ -35,6 +35,8 @@ ; A program's nonblocking assignment updates in the Re-NBA region, after the ; design's NBA region; the design processes the update wakes run in the ; active region set that follows. +; Four-state, so that `always @(r)` waits for a change; two-state mode would +; also run it once at time zero (#2026). (case program_nonblocking_updates_follow_design_updates (source "program_renba.sv" #" module Top; @@ -58,6 +60,7 @@ endprogram "#) (top Top) + (four_state) (run_to_finish) (expect_output "design sees r=1 count=0\nprogram count=1 r=1\ndesign sees r=11 count=1\nprogram count=2 r=11\ndesign sees r=12 count=2\n")) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 04d74494fac..5249c27248d 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -171,8 +171,9 @@ (assert_eq y 9)) (case explicit_list_of_every_read_waits_for_a_change - ; Like `always @*`, the list waits before its first run: neither the - ; declaration initializers nor the write of `y` wake it (9.4.2). + ; In four-state mode, like `always @*`, the list waits before its first + ; run: neither the declaration initializers nor the write of `y` wake it + ; (9.4.2). Two-state mode runs it at time zero (#2021). (source "level_list.sv" #" module Top(output logic [7:0] y); logic [7:0] a = 8'd0; @@ -187,6 +188,7 @@ endmodule "#) (top Top) + (four_state) (run_until 1) (assert_eq y 1) (run_until 3) @@ -217,6 +219,8 @@ (run_to_finish) (assert_eq y 9)) +; In four-state mode the list waits for a change; two-state mode also runs +; it once at time zero (#2026). (case list_with_an_extra_signal_wakes_on_it (source "extra_signal.sv" #" module Top; @@ -232,6 +236,7 @@ endmodule "#) (top Top) + (four_state) (run_to_finish) (expect_output "sum=3\nsum=3\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_two_state_time_zero_settle.json b/crates/celox-test-suite/verification/repros/sv_two_state_time_zero_settle.json new file mode 100644 index 00000000000..bfe14ec8b71 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_two_state_time_zero_settle.json @@ -0,0 +1,52 @@ +{ + "standard": "IEEE 1800-2023 9.2.2.2 and 9.4.2", + "expected": "In four-state SV, `always @*` and a sensitivity-list process wait at their event control until an input changes, so an output whose inputs never change stays X. The suite case's two-state oracle follows Verilator, which runs these processes once at time zero after the initial blocks.", + "probes": [ + { + "name": "time_zero_settle", + "note": "The suite case always_comb::two_state_sensitivity_lists_run_at_time_zero.", + "source": "module Top;\n localparam logic [1:0] READ = 2'd1;\n logic [1:0] cur_state;\n logic wvalid, wready;\n logic [15:0] wstrb;\n logic cen;\n logic [15:0] wen;\n logic [3:0] st = 4'd2;\n logic hit;\n always @(cur_state or wvalid or wready or wstrb[15:0]) begin\n if (cur_state == READ) begin\n cen = 1'b0;\n wen = 16'hffff;\n end else if (wvalid && wready) begin\n cen = 1'b0;\n wen = ~wstrb;\n end else begin\n cen = 1'b1;\n wen = 16'hffff;\n end\n end\n always @* hit = (st == 4'd2);\n initial begin\n #1 $display(\"%b %h %b\", cen, wen, hit);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "1 ffff 1\n- /probe.sv:25: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 1ps; walltime 0.000 s; speed 36.075 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "x xxxx x\n/probe.sv:25: $finish called at 1 (1s)\n" + } + }, + { + "name": "other_lists", + "note": "The suite case always_comb::two_state_other_sensitivity_lists_run_at_time_zero: lists that do not name exactly the reads of their statement.", + "source": "module Top;\n logic [3:0] a, b;\n logic [3:0] y, z;\n always @(a or b) y = a + 4'd1;\n always @(a) z = a + b + 4'd2;\n initial begin\n b = 4'd5;\n #1 $display(\"%0d %0d\", y, z);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "1 7\n- /probe.sv:9: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 1ps; walltime 0.000 s; speed 37.509 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "x x\n/probe.sv:9: $finish called at 1 (1s)\n" + } + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/always_comb.json b/crates/celox-test-suite/verification/sv/icarus/always_comb.json index d1fc38dfad0..0128850f1b4 100644 --- a/crates/celox-test-suite/verification/sv/icarus/always_comb.json +++ b/crates/celox-test-suite/verification/sv/icarus/always_comb.json @@ -43,6 +43,60 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Combinational", + "detail": "Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a standalone probe prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_two_state", + "evidence": [ + "verification/repros/sv_two_state_time_zero_settle.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_two_state_time_zero_settle", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "phase": "execute", + "reason": "Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a standalone probe prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus.", + "upstream": [] + }, + "name": "always_comb::two_state_other_sensitivity_lists_run_at_time_zero", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": true, + "tag_reasons": { + "two_state_time_zero_settle": "Requires two-state `always @*` and sensitivity-list processes to run once at time zero, after the initial blocks, as Verilator settles them; SV has them wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2)." + }, + "tags": [ + "two_state_time_zero_settle" + ] + }, + { + "category": "Combinational", + "detail": "Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a standalone probe prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_two_state", + "evidence": [ + "verification/repros/sv_two_state_time_zero_settle.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_two_state_time_zero_settle", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "phase": "execute", + "reason": "Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a standalone probe prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus.", + "upstream": [] + }, + "name": "always_comb::two_state_sensitivity_lists_run_at_time_zero", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": true, + "tag_reasons": { + "two_state_time_zero_settle": "Requires two-state `always @*` and sensitivity-list processes to run once at time zero, after the initial blocks, as Verilator settles them; SV has them wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2)." + }, + "tags": [ + "two_state_time_zero_settle" + ] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 3f5e9c99ed6..1a3d03d220e 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -552,6 +552,24 @@ ] } }, + { + "id": "sv_icarus_two_state_time_zero_settle", + "category": "simulator_two_state", + "phase": "execute", + "observed_version": "Icarus 13.0 / Verilator 5.052", + "reason": "Icarus 13.0 simulates the emitted design in four-state SV, where `always @*` and a sensitivity-list process wait for a change (IEEE 1800-2023 9.2.2.2, 9.4.2), so an output whose inputs never change stays X. The case's two-state oracle follows Verilator 5.052, which runs these processes once at time zero after the initial blocks, as Celox's two-state mode does; a standalone probe prints `1 ffff 1` in Verilator and `x xxxx x` in Icarus.", + "upstream": [], + "evidence": [ + "verification/repros/sv_two_state_time_zero_settle.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "always_comb::two_state_sensitivity_lists_run_at_time_zero", + "always_comb::two_state_other_sensitivity_lists_run_at_time_zero" + ] + } + }, { "id": "sv_verilator_generate_case_unknown_label", "category": "simulator_compile_limitation", diff --git a/crates/celox/tests/frontends/systemverilog/always_comb.rs b/crates/celox/tests/frontends/systemverilog/always_comb.rs index 217da03437b..010bffac2c0 100644 --- a/crates/celox/tests/frontends/systemverilog/always_comb.rs +++ b/crates/celox/tests/frontends/systemverilog/always_comb.rs @@ -27,3 +27,15 @@ sv_backends! { @case "always_comb::explicit_list_of_every_read_settles_like_a_wildcard"; } } + +sv_backends! { + fn two_state_sensitivity_lists_run_at_time_zero(sim) { + @case "always_comb::two_state_sensitivity_lists_run_at_time_zero"; + } +} + +sv_backends! { + fn two_state_other_sensitivity_lists_run_at_time_zero(sim) { + @case "always_comb::two_state_other_sensitivity_lists_run_at_time_zero"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/latch.rs b/crates/celox/tests/frontends/systemverilog/latch.rs index cc5b7d756b5..54629006c10 100644 --- a/crates/celox/tests/frontends/systemverilog/latch.rs +++ b/crates/celox/tests/frontends/systemverilog/latch.rs @@ -228,35 +228,30 @@ fn latch_policy_preserves_compilation_diagnostic_overrides() { } #[test] -fn change_return_activation_in_both_state_modes_at_o0_and_o2() { +fn change_return_activation_at_o0_and_o2() { for name in [ "latch::same_activation_change_return", "latch::hierarchy_same_activation_change_return", ] { let case = celox_test_suite::sv::case(name).unwrap(); let design = case.design(); - for four_state in [false, true] { - for level in [celox::OptLevel::O0, celox::OptLevel::O2] { - let mut sim = celox::Simulation::from_sv_sources( - design - .sources - .iter() - .map(|source| (source.text.as_str(), source.path.as_path())) - .collect(), - "Top", - ) - .four_state(four_state) - .opt_level(level) - .build_interpreter() - .unwrap(); - sim.run_until(10_000).unwrap_or_else(|error| { - panic!("{name}, four_state={four_state}, {level:?}: {error}") - }); - assert!( - sim.is_finished(), - "{name}, four_state={four_state}, {level:?}" - ); - } + // The cases are four-state: two-state mode runs `always @*` at time zero. + for level in [celox::OptLevel::O0, celox::OptLevel::O2] { + let mut sim = celox::Simulation::from_sv_sources( + design + .sources + .iter() + .map(|source| (source.text.as_str(), source.path.as_path())) + .collect(), + "Top", + ) + .four_state(true) + .opt_level(level) + .build_interpreter() + .unwrap(); + sim.run_until(10_000) + .unwrap_or_else(|error| panic!("{name}, {level:?}: {error}")); + assert!(sim.is_finished(), "{name}, {level:?}"); } } } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index e56ff78d97a..597c2b2438f 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -280,21 +280,24 @@ sv_backends! { @build Simulator::from_sv_sources(vec![(source, Path::new("random_sensitivity.sv"))], "Top").four_state(false); let a = sim.signal("a"); let b = sim.signal("b"); + // Two-state mode runs `always @*` once at time zero, like always_comb. let first = sim.get(a); assert_ne!(first, 0u8.into()); - assert_eq!(sim.get(b), 0u8.into()); + let first_b = sim.get(b); + assert_ne!(first_b, 0u8.into()); let initial_draw = sim.get(sim.signal("initial_draw")); assert_ne!(initial_draw, 0u8.into()); - assert_eq!(sim.get(sim.signal("star_draw")), 0u8.into()); + let star_draw = sim.get(sim.signal("star_draw")); + assert_ne!(star_draw, 0u8.into()); let global_input = sim.signal("global_input"); sim.modify(|io| io.set(global_input, 1u8)).unwrap(); assert_ne!(sim.get(a), first); - assert_eq!(sim.get(b), 0u8.into()); + assert_eq!(sim.get(b), first_b); let trigger = sim.signal("trigger"); sim.modify(|io| io.set(trigger, 1u8)).unwrap(); - assert_ne!(sim.get(b), 0u8.into()); + assert_ne!(sim.get(b), first_b); assert_eq!(sim.get(sim.signal("initial_draw")), initial_draw); - assert_eq!(sim.get(sim.signal("star_draw")), 0u8.into()); + assert_eq!(sim.get(sim.signal("star_draw")), star_draw); } fn urandom_select_keeps_distinct_source_calls(sim) { diff --git a/crates/celox/tests/sv_declaration_startup.rs b/crates/celox/tests/sv_declaration_startup.rs index 6bb88b8f387..2a0558ac244 100644 --- a/crates/celox/tests/sv_declaration_startup.rs +++ b/crates/celox/tests/sv_declaration_startup.rs @@ -5,6 +5,9 @@ use std::path::Path; // IEEE 1800-2023 6.8 initializes static declarations before initial/always // procedures, including initializers that require runtime evaluation. +// `always @*` waits for a change only in four-state mode; in two-state mode it +// runs once at time zero (#2021), so the tests of its startup guard build +// four-state simulations. const RANDOM_DECLARATION: &str = r#" module Top; int a = $urandom | 1; @@ -247,17 +250,15 @@ macro_rules! declaration_backend { #[test] fn runtime_declaration_does_not_wake_wildcard() { - for four_state in [false, true] { - finishes( - Simulation::from_sv_sources( - vec![(RANDOM_DECLARATION, Path::new("runtime_declaration.sv"))], - "Top", - ) - .four_state(four_state) - .$build() - .unwrap(), - ); - } + finishes( + Simulation::from_sv_sources( + vec![(RANDOM_DECLARATION, Path::new("runtime_declaration.sv"))], + "Top", + ) + .four_state(true) + .$build() + .unwrap(), + ); } #[test] @@ -317,35 +318,31 @@ macro_rules! declaration_backend { #[test] fn host_request_declaration_finishes_before_wildcard_registration() { - for four_state in [false, true] { - finishes( - Simulation::from_sv_sources( - vec![(HOST_DECLARATION, Path::new("declaration_plusargs.sv"))], - "Top", - ) - .four_state(four_state) - .plusargs(["+on"]) - .$build() - .unwrap(), - ); - } + finishes( + Simulation::from_sv_sources( + vec![(HOST_DECLARATION, Path::new("declaration_plusargs.sv"))], + "Top", + ) + .four_state(true) + .plusargs(["+on"]) + .$build() + .unwrap(), + ); } #[test] fn host_reads_and_eval_do_not_activate_a_stopped_declaration() { - for four_state in [false, true] { - stopped_declaration_keeps_comb_inert( - Simulation::from_sv_sources( - vec![(STOPPED_DECLARATION, Path::new("declaration_stop.sv"))], - "Top", - ) - .four_state(four_state) - .live_signal(Vec::new(), vec!["a".into()]) - .live_signal(Vec::new(), vec!["q".into()]) - .$build() - .unwrap(), - ); - } + stopped_declaration_keeps_comb_inert( + Simulation::from_sv_sources( + vec![(STOPPED_DECLARATION, Path::new("declaration_stop.sv"))], + "Top", + ) + .four_state(true) + .live_signal(Vec::new(), vec!["a".into()]) + .live_signal(Vec::new(), vec!["q".into()]) + .$build() + .unwrap(), + ); } #[test] @@ -391,19 +388,17 @@ macro_rules! declaration_backend { #[test] fn checkpoint_restores_the_armed_startup_guard() { - for four_state in [false, true] { - restored_guard_remains_inert( - Simulation::from_sv_sources( - vec![(HOST_WRITES, Path::new("declaration_checkpoint.sv"))], - "Top", - ) - .four_state(four_state) - .live_signal(Vec::new(), vec!["a".into()]) - .live_signal(Vec::new(), vec!["q".into()]) - .$build() - .unwrap(), - ); - } + restored_guard_remains_inert( + Simulation::from_sv_sources( + vec![(HOST_WRITES, Path::new("declaration_checkpoint.sv"))], + "Top", + ) + .four_state(true) + .live_signal(Vec::new(), vec!["a".into()]) + .live_signal(Vec::new(), vec!["q".into()]) + .$build() + .unwrap(), + ); } } }; @@ -425,18 +420,16 @@ declaration_backend!(wasm, build_wasm); ))] fn native_runtime_declaration_startup_at_o0_and_o2() { for level in [celox::OptLevel::O0, celox::OptLevel::O2] { - for four_state in [false, true] { - finishes( - Simulation::from_sv_sources( - vec![(RANDOM_DECLARATION, Path::new("declaration_opt_level.sv"))], - "Top", - ) - .four_state(four_state) - .opt_level(level) - .build_native() - .unwrap(), - ); - } + finishes( + Simulation::from_sv_sources( + vec![(RANDOM_DECLARATION, Path::new("declaration_opt_level.sv"))], + "Top", + ) + .four_state(true) + .opt_level(level) + .build_native() + .unwrap(), + ); } } From 4082ff4f6fbf4aae86c57d21c35e2535b5283cd3 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 05:13:48 +0900 Subject: [PATCH 2/2] fix(sv): validate enum initializer declarations Reject sized enum literals whose width differs from the base, X/Z values without an explicit four-state base, and implicit successors of X/Z values as required by IEEE 1800-2023 6.19. Preserve masks across references to preceding members and allow expressions that resolve to known values. Defer typedef validation until enum constants and dependent aliases resolve. Keep inline declarations checked when their types are bound. Leave ranged member expansion to the existing unsupported path instead of guessing values. Update the three affected sv-tests cases in both state modes. Validation: all analyzer tests (811 passed, 3 existing ignored), 2 doctests, combined analyzer tests (814 passed, 3 ignored), all-target Clippy and fmt. Full release-driver sv-tests validation runs in CI as requested. Change-Id: I71ba3443f34b307ef6a424decec09ef01881948d --- conformance/sv-tests/expected.tsv | 12 +- .../celox-sv-analyzer/src/ast/parameters.rs | 19 ++- .../celox-sv-analyzer/src/ast/type_binding.rs | 2 +- .../src/ast/type_binding/binding.rs | 155 ++++++++++++++++++ crates/celox-sv-analyzer/src/tests.rs | 72 ++++++++ .../systemverilog/review_regressions.rs | 19 ++- 6 files changed, 264 insertions(+), 15 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b4e64f909ce..3560aabeea7 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1153,14 +1153,14 @@ chapter-6/6.18--typedef.sv 2state pass chapter-6/6.18--typedef.sv 4state pass chapter-6/6.19--enum_anon.sv 2state pass chapter-6/6.19--enum_anon.sv 4state pass -chapter-6/6.19--enum_value_inv.sv 2state fail -chapter-6/6.19--enum_value_inv.sv 4state fail +chapter-6/6.19--enum_value_inv.sv 2state pass +chapter-6/6.19--enum_value_inv.sv 4state pass chapter-6/6.19--enum_xx.sv 2state pass chapter-6/6.19--enum_xx.sv 4state pass -chapter-6/6.19--enum_xx_inv.sv 2state fail -chapter-6/6.19--enum_xx_inv.sv 4state fail -chapter-6/6.19--enum_xx_inv_order.sv 2state fail -chapter-6/6.19--enum_xx_inv_order.sv 4state fail +chapter-6/6.19--enum_xx_inv.sv 2state pass +chapter-6/6.19--enum_xx_inv.sv 4state pass +chapter-6/6.19--enum_xx_inv_order.sv 2state pass +chapter-6/6.19--enum_xx_inv_order.sv 4state pass chapter-6/6.19.1--enum_typedef.sv 2state pass chapter-6/6.19.1--enum_typedef.sv 4state pass chapter-6/6.19.2--enum_sequence.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index d27f1403a84..250465ada6c 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -1046,20 +1046,25 @@ pub(super) fn enum_member_constants_from_items( let DataTypeKind::Enum { base, items } = &native.data_type(id).kind else { unreachable!(); }; - let member_type = match base { + let member_base = match base { Some(id) => type_binding::enum_constant_base( *id, syntax_tree, &eval_env, &resolved_type_aliases, - )? - .and_then(|ty| expr_type_from_type(&syntax_tree.state, &ty, &eval_env)), - None => Some(ExprType { - width: 32, - signed: true, - }), + )?, + None => type_binding::builtin_type("int", None), } .ok_or_else(|| unsupported("enum base type"))?; + type_binding::binding::validate_enum_initializers( + id, + native, + syntax_tree, + &PackedDimensions::new(HashMap::default(), &eval_env, &resolved_type_aliases), + &member_base, + )?; + let member_type = expr_type_from_type(&syntax_tree.state, &member_base, &eval_env) + .ok_or_else(|| unsupported("enum base type"))?; let mut next_enum_value = 0i128; for new in items { let name = instances::normalize_identifier(&new.name.spelling); diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 419dad7b2bd..5d2ecd8d7ef 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -250,7 +250,7 @@ pub(super) fn alias_base_type( return Ok(None); } let context = PackedDimensions::new(HashMap::default(), env, aliases); - binding::bind_in(id, native, tree, &context) + binding::bind_alias_in(id, native, tree, &context) } /// Builtin integral identity/width without syntax or aggregate layout. diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 6d152b61b19..9f0fe4aa2be 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -15,6 +15,27 @@ pub(in crate::ast) fn bind_in( native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, context: &PackedDimensions, +) -> Converted> { + bind_in_with_validation(root, native, tree, context, true) +} + +/// Typedef discovery precedes enum constant resolution, so dependent aliases +/// may still have provisional widths. Validate them when collecting members. +pub(in crate::ast) fn bind_alias_in( + root: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, +) -> Converted> { + bind_in_with_validation(root, native, tree, context, false) +} + +fn bind_in_with_validation( + root: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + validate_enums: bool, ) -> Converted> { enum Job { Enter(TypeId), @@ -88,6 +109,9 @@ pub(in crate::ast) fn bind_in( } else { let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; + if validate_enums { + validate_enum_initializers(id, native, tree, context, &ty)?; + } ty.enum_values = enum_values(id, native, tree, context, &ty); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); @@ -182,6 +206,9 @@ pub(in crate::ast) fn bind_in( let Some(mut ty) = values.pop() else { return Err(unsupported("enum base type")); }; + if validate_enums { + validate_enum_initializers(id, native, tree, context, &ty)?; + } let mut outer = ranges; outer.extend(ty.packed_ranges); ty.packed_ranges = outer; @@ -317,6 +344,134 @@ pub(in crate::ast) fn expression_type( Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) } +/// IEEE 1800-2023 6.19 imposes declaration rules even when no enum member +/// is used. Keep these checks separate from best-effort randomization metadata. +pub(in crate::ast) fn validate_enum_initializers( + id: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + ty: &Type, +) -> Converted<()> { + let DataTypeKind::Enum { base, items } = &native.data_type(id).kind else { + return Ok(()); + }; + let Some(shape) = casts::expr_type_from_type(&tree.state, ty, &context.const_env) else { + return Ok(()); + }; + let mut env = context.const_env.clone(); + let mut unknown_literals = HashMap::default(); + let mut previous_unknown = false; + let mut next = Some(0i128); + for item in items { + let name = normalize_identifier(&item.name.spelling); + let Some(value) = item.value else { + if previous_unknown { + return Err(unsupported(format!( + "enum member `{name}` cannot implicitly increment an X/Z value" + ))); + } + if !item.dimensions.is_empty() { + next = None; + continue; + } + if let Some(value) = next { + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1); + } + continue; + }; + // Check authored syntax, not a folded expression: a parameter, cast, + // or arithmetic expression is not a sized literal constant. + let mut literal_id = value; + while let ExprKind::Group(inner) = native.expression(literal_id).kind { + literal_id = inner; + } + if let ExprKind::Literal(text) = &native.expression(literal_id).kind + && let Some((size, _)) = text.split_once('\'') + && !size.is_empty() + && let Ok(width) = size.replace('_', "").parse::() + && width != shape.width + { + return Err(unsupported(format!( + "enum member `{name}` sized literal width {width} differs from base width {}", + shape.width + ))); + } + // During signature discovery some constants are still unresolved. + // Leave their resolution to the ordinary constant-binding pass. + let expr = constant_binding::expression(value, native, tree, &env, &context.type_aliases) + .ok() + .flatten() + .and_then(|expr| { + expr_to_const( + &tree.state, + constants::substitute_expr_constants_with_parameter_literals( + &tree.state, + const_expr_to_expr(expr), + &env, + &unknown_literals, + ), + ) + }); + let expr = expr.map(|expr| match expr { + ConstExpr::Literal(text) => ConstExpr::Literal( + resize_unbased_fill_literal_for_cast(&text, shape.width, shape.signed) + .unwrap_or(text), + ), + expr => expr, + }); + let literal = expr.as_ref().and_then(|expr| { + typecheck::eval_const_integral_literal_with_lookup( + &expr.clone().into(), + &env, + &|name| { + dimensions::parameter_type_from_const_env(&env, name) + .map(|ty| (ty.width, ty.signed)) + }, + ) + }); + previous_unknown = literal + .as_ref() + .is_some_and(|value| value.mask != Default::default()); + if previous_unknown && (base.is_none() || ty.kind == TypeKind::Bit) { + return Err(unsupported(format!( + "enum member `{name}` X/Z value requires an explicit four-state base type" + ))); + } + if !item.dimensions.is_empty() { + next = None; + continue; + } + if previous_unknown { + // Preserve masks when a later enumerator refers to this member. + // Numeric constant environments cannot represent X/Z values. + unknown_literals.insert( + name.clone(), + Expr::Literal(resize_integral_literal_for_cast( + literal.unwrap(), + shape.width, + shape.signed, + )), + ); + env.remove(&name); + } + next = expr + .as_ref() + .and_then(|expr| eval_ast_const_expr(&tree.state, expr, &env)) + .map(|value| { + parameters::coerce_const_parameter_value(value, shape.width, shape.signed) + }); + if let Some(value) = next { + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1); + } + } + Ok(()) +} + /// Domain metadata is best-effort during signature discovery. Only a caller /// requesting randomization requires a resolved domain; unused types must not /// start reporting new errors merely because this metadata is collected. diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 5c6a2c29d8c..c9385650f3d 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6959,3 +6959,75 @@ fn class_visibility_checks_constructors() { } } } + +#[test] +fn rejects_invalid_enum_declaration_initializers() { + for (declaration, diagnostic) in [ + ( + "enum logic [2:0] { Global = 4'h2, Local = 4'h3 } value;", + "sized literal width 4 differs from base width 3", + ), + ( + "typedef enum logic [2:0] { A = 2'b01 } E;", + "sized literal width 2 differs from base width 3", + ), + ( + "enum bit [1:0] { a=0, b=2'bxx, c=1 } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "enum { a='z } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "typedef bit [1:0] B; enum B { a=2'b0z } value;", + "X/Z value requires an explicit four-state base type", + ), + ( + "enum integer { a=0, b={32{1'bx}}, c } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a='z, b } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a=2'bxx, b=a, c } value;", + "cannot implicitly increment an X/Z value", + ), + ( + "enum logic [1:0] { a='x, b=a | 2'b00, c } value;", + "cannot implicitly increment an X/Z value", + ), + ] { + let source = format!("module Top; {declaration} endmodule"); + let error = + analyze_source(&source, Path::new("invalid_enum_initializers.sv")).expect_err(&source); + assert!(error.to_string().contains(diagnostic), "{source}: {error}"); + } +} + +#[test] +fn preserves_legal_enum_declaration_initializers() { + for declaration in [ + "enum logic [2:0] { A=3'h2, B=3'h3 } value;", + "enum bit [3:0] { bronze='h3, silver, gold='h5 } value;", + "enum logic [3:0] { A='1 } value;", + "enum integer { a=0, b={32{1'bx}}, c=1, d } value;", + "enum logic [1:0] { a=2'bxx, b=2'bzz, c=0 } value;", + "enum bit [1:0] { a=(2'bxx & 2'b00), b } value;", + "enum logic [1:0] { a=2'bxx, b=2'b01, c } value;", + "enum logic [1:0] { a=2'bxx, b=a & 2'b00, c } value;", + "localparam P=4'h2; enum logic [2:0] { A=P, B=4'h1+1 } value;", + "enum logic [2:0] { A=3'(4'h2) } value;", + "enum logic [2:0] { A=3'h2 } value [2];", + "typedef enum int { W=3 } E; typedef logic [W'(2):0] B; enum B { A=3'b101 } value;", + "localparam W=3; enum logic [W-1:0] { A=3'b101 } value;", + "enum logic [2:0] { A=3'h2 } [1:0] value;", + "typedef enum logic signed [1:0] { A=2'b10, B } E;", + ] { + let source = format!("module Top; {declaration} endmodule"); + analyze_source(&source, Path::new("valid_enum_initializers.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 92ffc36ceb1..5ad82945518 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -4185,7 +4185,7 @@ fn rejects_enum_initializers_that_do_not_fit_the_base_type() { let error = cranelift_build_error( r#" module Top(output logic [1:0] y); - typedef enum logic [1:0] { A = 3'd4 } E; + typedef enum logic [1:0] { A = 4 } E; assign y = A; endmodule "#, @@ -4196,6 +4196,23 @@ fn rejects_enum_initializers_that_do_not_fit_the_base_type() { ); } +#[test] +fn rejects_enum_literals_with_mismatched_explicit_widths() { + let error = cranelift_build_error( + r#" + module Top(output logic [1:0] y); + typedef enum logic [1:0] { A = 3'd1 } E; + assign y = A; + endmodule + "#, + ); + // The value fits, but an explicitly sized literal must match the enum base. + assert!( + error.contains("enum member `A` sized literal width 3 differs from base width 2"), + "unexpected error: {error}" + ); +} + #[test] fn preserves_masked_parameter_guards_before_latch_detection() { let source = r#"