From 7c6f1e57a9b57a856f6cef8a9bfddf262c334833 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 07:10:42 +0900 Subject: [PATCH] feat(sv)!: execute final procedures at simulation termination SystemVerilog final procedures were rejected, so testbenches could not inspect their last state or report results at termination. Preserve them as terminal process kernels and run them once on $finish, $fatal, or explicit Simulation::finish(). The batch CLI and sv-tests driver finish on quiescence; bounded host runs remain resumable. Program finals also run after implicit termination. Keep final execution sequential and at zero simulation time. Resume $stop inside final at its cursor, stop immediately at $finish inside final, preserve the initiating fatal error, and prevent queued HDL events or deferred assertions from executing after termination. Validate function-statement restrictions, including omitted argument defaults. Route fatal errors from explicit waveform dumps and end-of-run waveform evaluation through the same terminal phase. Finalize immediate fatal errors raised by lazy runtime-event draining before collecting reports. Settle and execute final procedures before capturing saved state, and reject saving if final execution stops. Keep differential scheduling synchronized on these host-triggered termination paths. Document the lifecycle and restrictions. Validation: - 18 final API tests cover two/four-state Interpreter, Cranelift, WASM, Native and Tiered execution, differential scheduling, checkpoints and native-image roundtrip. - CI follow-up: default-feature library 150, enabled-feature library 229, VCD 36, reference-adapter 7, the unsupported-construct regression and JS boundary 9 tests pass. Formatting and Clippy pass. Fatal errors terminate execution while preserving the original diagnostic and waveform; tests no longer require recovery from $fatal. - P2 regression coverage: all four added tests fail before the fix and pass after it. Related library, checkpoint, observer, runtime API, state-file, deferred-assertion and VCD tests pass (1,281 tests; 34 existing ignores). Rebuilt the debug NAPI addon; 28 JS checkpoint/runtime-event/timing tests, formatting and Clippy pass. - Direct portable fixtures: Icarus 13.0 passes all three; Verilator 5.052 passes state/hierarchy but continues after $finish inside final, contrary to 9.2.3. Keep immediate-termination expectations. These fixtures use owning-crate API tests because the shared timed emitter has its own final checker with unspecified relative ordering. - Focused sv-tests rerun: 70 additional passing cases per mode out of 108 previously blocked by final; update exactly 140 measured expectations. Full release-driver conformance remains in CI as requested. BREAKING CHANGE: ProcessSlots and ProcessRefs use ProcessKind instead of is_initializer; fatal errors have a distinct Fatal variant; SimulationState::finish is fallible; native image format advances to version 39. Change-Id: I75200be6ce640d73a84562a25ff48cdae2237106 --- conformance/sv-tests/expected.tsv | 280 +++++----- crates/celox-design/src/lib.rs | 19 +- crates/celox-frontend-core/src/sdk.rs | 2 +- .../src/symbolic/assembly.rs | 2 +- crates/celox-frontend-sv/src/lowering.rs | 24 +- crates/celox-runtime/src/error.rs | 23 +- crates/celox-runtime/src/schedule.rs | 6 +- .../celox-runtime/src/simulation/compiled.rs | 4 + crates/celox-runtime/src/simulation/mod.rs | 71 +-- .../celox-runtime/src/simulation/persist.rs | 21 +- .../celox-runtime/src/simulation/process.rs | 7 +- .../celox-runtime/src/simulation/terminal.rs | 99 ++++ crates/celox-runtime/src/simulation/time.rs | 5 +- crates/celox-runtime/src/timing.rs | 4 +- crates/celox-sv-analyzer/src/ast.rs | 24 +- .../src/ast/array_parameters.rs | 3 +- .../celox-sv-analyzer/src/ast/comb_process.rs | 5 +- .../src/ast/const_functions.rs | 88 +-- .../celox-sv-analyzer/src/ast/ff_process.rs | 5 +- .../celox-sv-analyzer/src/ast/procedural.rs | 36 +- .../src/ast/procedural/final_procedures.rs | 182 ++++++ .../src/ast/procedural/timed_tasks.rs | 9 +- crates/celox-sv-analyzer/src/ast/scope.rs | 18 +- .../celox-sv-analyzer/src/ast/validation.rs | 42 +- crates/celox-sv-analyzer/src/ir.rs | 30 +- crates/celox-sv-analyzer/src/parsed.rs | 2 +- .../src/source_tree/tests/process_roots.rs | 31 +- .../celox-sv-analyzer/src/system_functions.rs | 2 + crates/celox-sv-analyzer/src/tests.rs | 210 +++++++ crates/celox-vpi/src/bin/celox.rs | 29 +- crates/celox/examples/sv_tests.rs | 25 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 4 +- crates/celox/src/simulation.rs | 103 +++- crates/celox/src/simulation/differential.rs | 22 + .../src/simulation/runtime_core_tests.rs | 2 +- crates/celox/src/simulator.rs | 67 ++- crates/celox/src/simulator/builder.rs | 2 +- crates/celox/src/simulator/state_file.rs | 9 +- crates/celox/tests/comb_observer.rs | 14 +- crates/celox/tests/fixtures/final/finish.sv | 19 + .../celox/tests/fixtures/final/hierarchy.sv | 15 + crates/celox/tests/fixtures/final/state.sv | 16 + .../tests/frontends/systemverilog/final.rs | 521 ++++++++++++++++++ .../systemverilog/review_regressions.rs | 8 - crates/celox/tests/runtime_api.rs | 4 +- crates/celox/tests/shared_jit_cache.rs | 19 + crates/celox/tests/sv_vcd.rs | 26 +- crates/celox/tests/systemverilog.rs | 2 + crates/celox/tests/test_utils/veryl_sim.rs | 2 +- crates/celox/tests/veryl_reference_adapter.rs | 2 +- docs/guide/systemverilog-reference.md | 28 +- docs/guide/systemverilog.md | 5 +- 53 files changed, 1835 insertions(+), 365 deletions(-) create mode 100644 crates/celox-runtime/src/simulation/terminal.rs create mode 100644 crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs create mode 100644 crates/celox/tests/fixtures/final/finish.sv create mode 100644 crates/celox/tests/fixtures/final/hierarchy.sv create mode 100644 crates/celox/tests/fixtures/final/state.sv create mode 100644 crates/celox/tests/frontends/systemverilog/final.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index a6186810a34..404b148ae0e 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -777,18 +777,18 @@ chapter-21/21.2--write-boh.sv 2state pass chapter-21/21.2--write-boh.sv 4state pass chapter-21/21.2--write.sv 2state pass chapter-21/21.2--write.sv 4state pass -chapter-21/21.3--fdisplay-boh.sv 2state fail -chapter-21/21.3--fdisplay-boh.sv 4state fail -chapter-21/21.3--fdisplay.sv 2state fail -chapter-21/21.3--fdisplay.sv 4state fail +chapter-21/21.3--fdisplay-boh.sv 2state pass +chapter-21/21.3--fdisplay-boh.sv 4state pass +chapter-21/21.3--fdisplay.sv 2state pass +chapter-21/21.3--fdisplay.sv 4state pass chapter-21/21.3--feof.sv 2state pass chapter-21/21.3--feof.sv 4state pass chapter-21/21.3--ferror.sv 2state fail chapter-21/21.3--ferror.sv 4state fail chapter-21/21.3--fflush.sv 2state pass chapter-21/21.3--fflush.sv 4state pass -chapter-21/21.3--fgetc.sv 2state fail -chapter-21/21.3--fgetc.sv 4state fail +chapter-21/21.3--fgetc.sv 2state pass +chapter-21/21.3--fgetc.sv 4state pass chapter-21/21.3--fgets.sv 2state fail chapter-21/21.3--fgets.sv 4state fail chapter-21/21.3--file.sv 2state pass @@ -797,16 +797,16 @@ chapter-21/21.3--fmonitor.sv 2state fail chapter-21/21.3--fmonitor.sv 4state fail chapter-21/21.3--fpos.sv 2state pass chapter-21/21.3--fpos.sv 4state pass -chapter-21/21.3--fread.sv 2state fail -chapter-21/21.3--fread.sv 4state fail -chapter-21/21.3--fscanf.sv 2state fail -chapter-21/21.3--fscanf.sv 4state fail +chapter-21/21.3--fread.sv 2state pass +chapter-21/21.3--fread.sv 4state pass +chapter-21/21.3--fscanf.sv 2state pass +chapter-21/21.3--fscanf.sv 4state pass chapter-21/21.3--fstrobe.sv 2state fail chapter-21/21.3--fstrobe.sv 4state fail -chapter-21/21.3--fwrite-boh.sv 2state fail -chapter-21/21.3--fwrite-boh.sv 4state fail -chapter-21/21.3--fwrite.sv 2state fail -chapter-21/21.3--fwrite.sv 4state fail +chapter-21/21.3--fwrite-boh.sv 2state pass +chapter-21/21.3--fwrite-boh.sv 4state pass +chapter-21/21.3--fwrite.sv 2state pass +chapter-21/21.3--fwrite.sv 4state pass chapter-21/21.3--sscanf.sv 2state pass chapter-21/21.3--sscanf.sv 4state pass chapter-21/21.3--ungetc.sv 2state fail @@ -1579,8 +1579,8 @@ chapter-9/9.2.2.3--always_latch.sv 2state fail chapter-9/9.2.2.3--always_latch.sv 4state fail chapter-9/9.2.2.4--always_ff.sv 2state pass chapter-9/9.2.2.4--always_ff.sv 4state pass -chapter-9/9.2.3--final.sv 2state fail -chapter-9/9.2.3--final.sv 4state fail +chapter-9/9.2.3--final.sv 2state pass +chapter-9/9.2.3--final.sv 4state pass chapter-9/9.3.1--sequential_block.sv 2state pass chapter-9/9.3.1--sequential_block.sv 4state pass chapter-9/9.3.2--parallel_block_join.sv 2state fail @@ -1735,46 +1735,46 @@ generated/assignment_op/11.4.1--plus_assignment.sv 2state pass generated/assignment_op/11.4.1--plus_assignment.sv 4state pass generated/assignment_op/11.4.1--xor_assignment.sv 2state pass generated/assignment_op/11.4.1--xor_assignment.sv 4state pass -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state fail +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 2state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shr.sv 2state pass @@ -2467,22 +2467,22 @@ generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2s generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state fail +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state pass generated/nets/6.6.1--net_tri.sv 2state pass generated/nets/6.6.1--net_tri.sv 4state pass generated/nets/6.6.1--net_wire.sv 2state pass @@ -2507,42 +2507,42 @@ generated/nets/6.6.6--net_supply0.sv 2state fail generated/nets/6.6.6--net_supply0.sv 4state fail generated/nets/6.6.6--net_supply1.sv 2state fail generated/nets/6.6.6--net_supply1.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 4state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 4state pass -generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_exp_operator_sim.sv 2state pass @@ -2555,22 +2555,22 @@ generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 4state pass -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_gt_operator_sim.sv 2state pass @@ -2579,14 +2579,14 @@ generated/operators_sim/11.4.4--simple_le_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_le_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 4state pass -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_eq_xz_operator_sim.sv 2state pass @@ -2595,18 +2595,18 @@ generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 4state pass -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 2state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 4state pass generated/operators_sim/11.4.8--simple_bit_or_operator_sim.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7294c286a4e..42bf3b118f7 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -616,6 +616,17 @@ impl std::fmt::Display for ProcessOrigin { } } +/// When a procedural kernel is invoked by the runtime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ProcessKind { + /// Static declarations run before ordinary HDL procedures. + Initializer, + #[default] + Regular, + /// A final procedure runs only when simulation ends (IEEE 1800-2023 9.2.3). + Final, +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -625,9 +636,9 @@ impl std::fmt::Display for ProcessOrigin { /// checkpoints capture a suspended process. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { - /// A static declaration initializer, executed before all HDL procedures. - pub is_initializer: bool, - /// This kernel originated from an edge procedure and must execute in Simulation. + /// The phase in which the runtime invokes this kernel. + pub kind: ProcessKind, + /// This kernel requires Simulation's process scheduler rather than Simulator. pub requires_timed_simulation: bool, /// Every delay the kernel suspends for is a constant of at least one /// time unit. @@ -646,7 +657,7 @@ pub struct ProcessSlots { impl ProcessSlots { pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { - is_initializer: self.is_initializer, + kind: self.kind, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, program: self.program.map(&mut map), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f955fda9e87..c5c89c1135f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1729,7 +1729,7 @@ fn lower_processes( for (index, process) in artifact.processes().iter().enumerate() { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; let slots = ProcessSlots { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, requires_timed_simulation: false, const_delays: false, program: None, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 1b720f15176..e01059c7e68 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1940,7 +1940,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let declaration_startup = processes .iter() - .any(|process| process.slots.is_initializer) + .any(|process| process.slots.kind == celox_design::ProcessKind::Initializer) .then(|| { let targets: BTreeSet<_> = folded_initials.iter().map(|init| init.address).collect(); let mut reset = targets diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b5b0d177f4c..11a49c86e24 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1348,7 +1348,7 @@ fn kernel_window_writes( for process in module .initial_processes() .iter() - .filter(|process| !process.is_initializer()) + .filter(|process| !process.is_initializer() && !process.is_final()) { let body = process.body(); let first = if process.repeats() { @@ -4978,6 +4978,7 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig let construct = match process.site() { Some(site) => site.construct, None if process.is_initializer() => "declaration initializer", + None if process.is_final() => "final", None if process.repeats() => "always", None => "initial", }; @@ -4988,9 +4989,9 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig } } -/// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1, -/// 10.5): the initial state they define, and the processes that run the -/// others from time zero. +/// Lower declaration initializers and procedural kernels. Final procedures +/// retain kernels but execute only at simulation termination (9.2.3); they +/// must never contribute folded initial state. /// /// A block whose writes have constant values defines initial state, with /// the hidden variables used while executing it discarded. Declaration @@ -5062,7 +5063,10 @@ fn lower_initial_processes( // initial state. A program's `initial` procedure runs in the reactive // region set (IEEE 1800-2023 24.3.1), after the design's processes of // time zero, so it is not folded either. - if process.repeats() || (module.is_program() && !process.is_initializer()) { + if process.is_final() + || process.repeats() + || (module.is_program() && !process.is_initializer()) + { runtime.push((process, random_seed)); continue; } @@ -5138,8 +5142,8 @@ fn lower_initial_processes( id }; ProcessSlots { - is_initializer: process.is_initializer(), - requires_timed_simulation: process.is_scheduled_edge(), + kind: process.kind(), + requires_timed_simulation: process.is_scheduled_edge() || process.is_final(), const_delays: false, program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), @@ -5155,10 +5159,10 @@ fn lower_initial_processes( let program = slots .iter() .zip(&runtime) - .find(|(_, (process, _))| !process.is_initializer()) + .find(|(_, (process, _))| !process.is_initializer() && !process.is_final()) .map(|(slots, _)| slots.status); for (slots, (process, _)) in slots.iter_mut().zip(&runtime) { - if !process.is_initializer() { + if !process.is_initializer() && !process.is_final() { slots.program = program; } } @@ -10725,7 +10729,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|process| !process.is_initializer) + .filter(|process| process.kind != celox_design::ProcessKind::Initializer) .count() } diff --git a/crates/celox-runtime/src/error.rs b/crates/celox-runtime/src/error.rs index 33603a87ee6..5cb9f3f2f03 100644 --- a/crates/celox-runtime/src/error.rs +++ b/crates/celox-runtime/src/error.rs @@ -5,6 +5,11 @@ pub enum SimulatorErrorCode { DetectedTrueLoopAt { signals: Vec, }, + /// `$fatal` also implicitly requests simulation termination. + Fatal { + message: String, + signals: Vec, + }, Runtime { message: String, signals: Vec, @@ -36,6 +41,16 @@ impl PartialEq for SimulatorErrorCode { signals: sb, }, ) => a == b && sa == sb, + ( + Self::Fatal { + message: a, + signals: sa, + }, + Self::Fatal { + message: b, + signals: sb, + }, + ) => a == b && sa == sb, (Self::NotAnEvent(a), Self::NotAnEvent(b)) => a == b, _ => false, } @@ -54,8 +69,12 @@ impl std::fmt::Display for SimulatorErrorCode { Self::DetectedTrueLoopAt { signals } => { write!(f, "Detected True Loop: {}", signals.join(", ")) } - Self::Runtime { message, signals } if signals.is_empty() => write!(f, "{message}"), - Self::Runtime { message, signals } => { + Self::Fatal { message, signals } | Self::Runtime { message, signals } + if signals.is_empty() => + { + write!(f, "{message}") + } + Self::Fatal { message, signals } | Self::Runtime { message, signals } => { write!(f, "{}: {}", message, signals.join(", ")) } Self::InternalError => write!(f, "Internal Error"), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 064c9049bad..99e07af4d2a 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -198,7 +198,7 @@ impl ResolvedSchedule { .processes .iter() .map(|process| ProcessRefs { - is_initializer: process.slots.is_initializer, + kind: process.slots.kind, program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, @@ -312,7 +312,9 @@ impl ResolvedSchedule { program_processes: processes .iter() .enumerate() - .filter(|(_, process)| process.program.is_some()) + .filter(|(_, process)| { + process.kind == celox_design::ProcessKind::Regular && process.program.is_some() + }) .map(|(index, _)| index) .collect(), processes, diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 7173050bca6..852dd20dd2e 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -161,6 +161,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } let _ = self.finish_timed_boundary(executor, self.scheduler.time); let _ = executor.flush_output(); Err(error) diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index dded48af181..a0e68d89208 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -10,6 +10,7 @@ mod persist; mod process; mod round; mod stats; +mod terminal; mod time; mod wait; @@ -146,6 +147,8 @@ pub struct SimulationState { host_pending: bool, /// A process requested the end of the simulation. finished: bool, + /// Next final procedure while terminal execution is suspended by `$stop`. + finalizing: Option, /// A process suspended the simulation (`$stop`) in the last step. stopped: bool, /// The round a `$stop` suspended, which the next step continues. @@ -193,7 +196,9 @@ impl SimulationState { .processes .iter() .enumerate() - .filter_map(|(index, process)| process.is_initializer.then_some(index)) + .filter_map(|(index, process)| { + (process.kind == celox_design::ProcessKind::Initializer).then_some(index) + }) .collect(); let declarations_pending = !declaration_processes.is_empty(); let mut state = Self { @@ -202,6 +207,7 @@ impl SimulationState { last_clock_unknown: BitSet::new(), four_state: backend.layout().four_state, process_wakeups: (0..model.processes.len()) + .filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final) .map(|process| Reverse((0, process))) .collect(), model, @@ -210,6 +216,7 @@ impl SimulationState { declarations_pending, host_pending: false, finished: false, + finalizing: None, stopped: false, suspended: None, scratch: None, @@ -253,6 +260,13 @@ impl SimulationState { E: SimulationExecutor, { self.stopped = false; + if self.finalizing.is_some() { + if self.scheduler.time > limit { + return Ok(None); + } + self.finalize_terminal(executor)?; + return Ok(Some(self.scheduler.time)); + } match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { @@ -262,6 +276,10 @@ impl SimulationState { // The time slot goes on when the simulation continues. Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -312,7 +330,10 @@ impl SimulationState { // A process the scheduler does not run waits: the slot stays in // the reference loop. Test that first, as designs with such // processes fail it at every step. - let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels { + let compiled = if self.finalizing.is_none() + && compiles + && self.process_state.waiters.len() <= waiting_kernels + { self.compiled_limit(executor, end, observer.one_slot()) } else { None @@ -405,9 +426,14 @@ impl SimulationState { { match executor.try_finish_timed_step(time) { Ok(()) => Ok(()), - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } Err(Halt::Finish) => { - self.finish_checked(executor)?; + self.finalize_terminal(executor)?; Ok(()) } Err(Halt::Stop) => { @@ -417,34 +443,6 @@ impl SimulationState { } } - fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - executor.try_freeze() - } - - /// Once $finish is consumed, output errors must not make execution resumable. - pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - let output = self.finish_timed_boundary(executor, self.scheduler.time); - let frozen = executor.try_freeze(); - output.and(frozen) - } - - /// End the simulation where it is. - pub fn finish(&mut self, executor: &mut E) - where - E: SimulationExecutor, - { - self.finished = true; - executor.freeze(); - } - /// Whether a process requested the end of the simulation. pub fn is_finished(&self) -> bool { self.finished @@ -461,7 +459,8 @@ impl SimulationState { /// Whether the simulation is suspended in the middle of a time slot, so /// that its scheduling state cannot be captured. pub fn is_suspended(&self) -> bool { - self.suspended.is_some() || (self.stopped && self.declarations_pending) + self.suspended.is_some() + || (self.stopped && (self.declarations_pending || self.finalizing.is_some())) } /// Settle externally driven state against the previous edge baseline even @@ -486,6 +485,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -556,7 +559,7 @@ impl SimulationState { return None; } // Host writes are work of the current time. - if self.host_pending { + if self.host_pending || self.finalizing.is_some() { return Some(self.scheduler.time); } self.next_work_time() diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index aa0a94ff8e9..d652d9f9e82 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -26,6 +26,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } @@ -63,6 +64,7 @@ impl SimulationState { self.declarations_pending = snapshot.declarations_pending; self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; + self.finalizing = snapshot.finalizing; self.stopped = false; self.suspended = None; Ok(()) @@ -190,17 +192,14 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.process_state = parts.process_state; - self.declarations_pending = self - .process_wakeups - .iter() - .any(|Reverse((_, index))| self.model.processes[*index].is_initializer) - || self - .process_state - .ready - .iter() - .any(|&index| self.model.processes[index].is_initializer); + self.declarations_pending = self.process_wakeups.iter().any(|Reverse((_, index))| { + self.model.processes[*index].kind == celox_design::ProcessKind::Initializer + }) || self.process_state.ready.iter().any(|&index| { + self.model.processes[index].kind == celox_design::ProcessKind::Initializer + }); self.host_pending = parts.host_pending; self.finished = parts.finished; + self.finalizing = None; self.stopped = false; self.suspended = None; } @@ -218,6 +217,7 @@ pub struct SimulationSnapshot { declarations_pending: bool, host_pending: bool, finished: bool, + finalizing: Option, } impl Clone for SimulationSnapshot { @@ -233,6 +233,7 @@ impl Clone for SimulationSnapshot { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } } @@ -300,6 +301,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, stopped: self.stopped, suspended: self.suspended.is_some(), } @@ -329,6 +331,7 @@ pub struct ScheduleKey { pub declarations_pending: bool, pub host_pending: bool, pub finished: bool, + pub finalizing: Option, pub stopped: bool, pub suspended: bool, } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index bc74b2729d8..e8a7324dabd 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -29,7 +29,12 @@ impl SimulationState { self.stopped = true; Ok(()) } - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } } } diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs new file mode 100644 index 00000000000..8d2553e935d --- /dev/null +++ b/crates/celox-runtime/src/simulation/terminal.rs @@ -0,0 +1,99 @@ +//! Terminal procedures run sequentially, without scheduling another HDL event. + +use celox_design::{HostRequestKind, ProcessKind, ProcessStatus}; + +use super::{SimulationExecutor, SimulationState}; +use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; + +impl SimulationState { + /// Finish once, running final procedures before flushing output and freezing. + /// A `$stop` in a final procedure suspends this phase; the next step resumes it. + pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + if self.finished { + return Ok(()); + } + self.stopped = false; + if self.finalizing.is_none() { + // An explicit host finish may replace a stopped ordinary round. + self.suspended = None; + self.host_pending = false; + self.finalizing = Some(0); + } + let result = self.run_final_procedures(executor); + if matches!(result, Err(Halt::Stop)) { + self.stopped = true; + return Ok(()); + } + // A failed final procedure or output flush cannot make termination resumable. + self.finished = true; + self.finalizing = None; + let output = self.finish_timed_boundary(executor, self.scheduler.time); + let frozen = executor.try_freeze(); + match result { + Ok(()) | Err(Halt::Finish) => output.and(frozen), + Err(Halt::Error(error)) => Err(error), + Err(Halt::Stop) => unreachable!(), + } + } + + /// Explicitly end simulation at its current time. Merely exhausting currently + /// scheduled work does not end an externally driven simulation. + pub fn finish(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finalize_terminal(executor) + } + + fn run_final_procedures(&mut self, executor: &mut E) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let mut returns = 0; + while let Some(index) = self + .finalizing + .filter(|&index| index < self.model.processes.len()) + { + let process = &self.model.processes[index]; + if process.kind != ProcessKind::Final { + self.finalizing = Some(index + 1); + continue; + } + executor.run_process(index)?; + returns += 1; + self.charge(returns, Some(index))?; + let status: u8 = executor.backend().get_as(process.status); + match ProcessStatus::from_code(status) { + Some(ProcessStatus::Done) => self.finalizing = Some(index + 1), + Some(ProcessStatus::Finish) => return Err(Halt::Finish), + Some(ProcessStatus::Stop) => return Err(Halt::Stop), + Some(ProcessStatus::HostRequest) => { + let encoded: u64 = executor.backend().get_as(process.delay); + let (kind, site) = HostRequestKind::decode(encoded) + .ok_or(SimulatorErrorCode::InternalError)?; + let request = process + .host_requests + .iter() + .filter(|request| request.kind == kind) + .nth(site as usize) + .ok_or(SimulatorErrorCode::InternalError)?; + executor.host_request(request, self.scheduler.time)?; + } + // Yield is an implementation boundary, not an HDL timing control. + // NBA events created by a final never run after termination (9.2.3). + Some(ProcessStatus::Yield | ProcessStatus::Nba) => {} + _ => { + return Err(SimulatorErrorCode::Runtime { + message: "final procedure cannot suspend for HDL timing".into(), + signals: Vec::new(), + } + .into()); + } + } + } + Ok(()) + } +} diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index e25822ae243..89f621c1e8d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -299,7 +299,10 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() { + if self.finalizing.is_some() + || !self.process_state.ready.is_empty() + || !self.process_state.reactive.is_empty() + { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 9edb4ed0927..20cdc112493 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -153,7 +153,7 @@ pub struct NbaSiteRefs { /// Control slots and sites of one process kernel. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { - pub is_initializer: bool, + pub kind: celox_design::ProcessKind, /// The status slot naming the program instance of a program kernel /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive /// region set. @@ -175,7 +175,7 @@ impl ProcessRefs { /// A process without wait or nonblocking sites. pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, program: None, resume: status, starts_with_event_wait: false, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index cb6cbe72434..9472313a755 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1331,7 +1331,7 @@ impl Module { // Declaration initializers run before the other initial blocks. let first_block = initial_processes .iter() - .position(|process| !process.initializer) + .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); initial_processes.insert( first_block, @@ -1340,7 +1340,8 @@ impl Module { site: None, condition: None, body: static_initializers, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }, @@ -1379,6 +1380,7 @@ impl Module { } for process in &mut initial_processes { process.body = body(std::mem::take(&mut process.body)); + process.validation_body = body(std::mem::take(&mut process.validation_body)); } for subroutine in &mut subroutines { *subroutine = rename.subroutine(subroutine.clone()); @@ -2535,14 +2537,16 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, site: Option, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, + /// Folded-away statements retained only for final-procedure legality checks. + validation_body: Vec, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -2562,6 +2566,16 @@ impl InitialProcess { self.condition.as_ref() } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -2569,7 +2583,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 6dfd67cbc94..8429bf932e9 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -220,7 +220,8 @@ impl ArrayParameter { rhs: value, nonblocking: false, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: true, repeats: false, }) diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index d958288a35a..4bc6aaf825e 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -295,7 +295,10 @@ fn comb_process_from_procedure( parameter_literals: &HashMap, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } let Some(body) = always_comb_body(procedure, syntax_tree.declarations())? else { diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 49f89a48c9e..f8b18fc9f97 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -613,10 +613,10 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap HashMap { + Expressions(&'a [Option]), + Constants(&'a [ConstExpr]), +} + +impl CallArguments<'_> { + pub(in crate::ast) fn is_present(self, index: usize) -> bool { + match self { + Self::Expressions(args) => args.get(index).is_some_and(Option::is_some), + Self::Constants(args) => index < args.len(), + } + } +} + /// Calls in an expression, including the index expressions represented by /// ConstExpr. Those indices can contain runtime calls in procedural code. -fn visit_expr_callees<'a>(expr: &'a Expr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_expr_calls<'a>( + expr: &'a Expr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { Expr::Ident(_) | Expr::Literal(_) => {} Expr::Call { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Expressions(args)); for arg in args.iter().flatten() { - visit_expr_callees(arg, f); + visit_expr_calls(arg, f); } } Expr::Select { expr, msb, lsb, .. } => { - visit_expr_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_expr_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_callees(expr, f), + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_calls(expr, f), Expr::Concat(parts) => { for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::RepeatConcat { count, parts } => { - visit_const_callees(count, f); + visit_const_calls(count, f); for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::Binary { left, right, .. } => { - visit_expr_callees(left, f); - visit_expr_callees(right, f); + visit_expr_calls(left, f); + visit_expr_calls(right, f); } Expr::Mux { condition, then_expr, else_expr, } => { - visit_expr_callees(condition, f); - visit_expr_callees(then_expr, f); - visit_expr_callees(else_expr, f); + visit_expr_calls(condition, f); + visit_expr_calls(then_expr, f); + visit_expr_calls(else_expr, f); } Expr::Inside { expr, items } => { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); for item in items { for expr in item.exprs() { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); } } } } } -fn visit_const_callees<'a>(expr: &'a ConstExpr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_const_calls<'a>( + expr: &'a ConstExpr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} ConstExpr::Function { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Constants(args)); for arg in args { - visit_const_callees(arg, f); + visit_const_calls(arg, f); } } ConstExpr::Select { expr, bit } => { - visit_const_callees(expr, f); - visit_const_callees(bit, f); + visit_const_calls(expr, f); + visit_const_calls(bit, f); } ConstExpr::SelectRange { expr, msb, lsb, .. } => { - visit_const_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_const_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { - visit_const_callees(expr, f) + visit_const_calls(expr, f) } ConstExpr::Binary { left, right, .. } => { - visit_const_callees(left, f); - visit_const_callees(right, f); + visit_const_calls(left, f); + visit_const_calls(right, f); } ConstExpr::Mux { condition, then_expr, else_expr, } => { - visit_const_callees(condition, f); - visit_const_callees(then_expr, f); - visit_const_callees(else_expr, f); + visit_const_calls(condition, f); + visit_const_calls(then_expr, f); + visit_const_calls(else_expr, f); } } } diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index c4b8cb131dd..610a7de1bbf 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -60,7 +60,10 @@ fn ff_process_from_procedure( packed_dimensions: &PackedDimensions, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 8adc8f68e14..4d97adbc841 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -9,6 +9,7 @@ use super::*; mod assertions; mod control; +mod final_procedures; mod foreach; mod randomization; pub(super) mod timed_tasks; @@ -1001,6 +1002,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { fn allow_timing(&self, construct: &'static str) -> Result<(), AnalyzerError> { match self.body { system_functions::Body::Initial => Ok(()), + system_functions::Body::Final => Err(AnalyzerError::TimingControlOutsideProcess { + construct, + context: "a final procedure", + }), system_functions::Body::Always => Err(AnalyzerError::TimingControlOutsideProcess { construct, context: "an always_comb or always_ff body", @@ -3021,7 +3026,8 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }); @@ -3033,10 +3039,13 @@ pub(super) fn initial_processes_from_scope( }; let construct = match procedure.kind { celox_sv_syntax::ProcedureKind::Initial => "initial", + celox_sv_syntax::ProcedureKind::Final => "final", _ => "always", }; let repeats = match procedure.kind { - celox_sv_syntax::ProcedureKind::Initial => false, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final => { + false + } celox_sv_syntax::ProcedureKind::Always if validation::always_kind(procedure, tree.declarations())? == validation::AlwaysKind::Process @@ -3047,15 +3056,23 @@ pub(super) fn initial_processes_from_scope( _ => continue, }; let (item_dimensions, literals) = views.get(item); - // A process statement runs in the body kind of an `initial` block: - // it may suspend and call any task. + let is_final = procedure.kind == celox_sv_syntax::ProcedureKind::Final; let mut builder = BodyBuilder::new( tree, item_dimensions, state, - system_functions::Body::Initial, + if is_final { + system_functions::Body::Final + } else { + system_functions::Body::Initial + }, ); let body = builder.native_body(&[procedure.body], &procedure.authored_statements)?; + let mut validation_body = if is_final { + std::mem::take(&mut builder.sensitivity_body) + } else { + Vec::new() + }; let mut body = if repeats { vec![Stmt::Loop { kind: LoopKind::Forever, @@ -3067,7 +3084,7 @@ pub(super) fn initial_processes_from_scope( } else { body }; - for stmt in &mut body { + for stmt in body.iter_mut().chain(&mut validation_body) { substitute_stmt_constants(&tree.state, stmt, &item.env, literals); qualify_stmt(item, stmt); substitute_stmt_constants(&tree.state, stmt, const_env, parameter_literals); @@ -3081,7 +3098,12 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: false, + kind: if is_final { + celox_design::ProcessKind::Final + } else { + celox_design::ProcessKind::Regular + }, + validation_body, synthetic: false, repeats, }); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs new file mode 100644 index 00000000000..64466d163fe --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs @@ -0,0 +1,182 @@ +//! Function-statement restrictions across calls from final procedures (9.2.3). +use super::*; +use const_functions::CallArguments; + +pub(super) fn validate(subroutines: &[&Subroutine], processes: &[InitialProcess]) -> Converted<()> { + if !processes.iter().any(InitialProcess::is_final) { + return Ok(()); + } + let definitions = subroutines + .iter() + .map(|subroutine| (subroutine.name.as_str(), *subroutine)) + .collect(); + let mut forbidden = HashSet::default(); + let mut calls = Vec::new(); + let mut schedules = HashSet::default(); + let mut runtime_calls = Vec::new(); + for subroutine in subroutines { + let (invalid, _, callees) = effects( + subroutine.body.iter().chain(&subroutine.sensitivity_body), + &definitions, + ); + // Functions cannot enable even an untimed task (13.4 b). + if subroutine.is_task || invalid { + forbidden.insert(subroutine.name.clone()); + } + calls.push((&subroutine.name, callees)); + // Unlike the function-statement restrictions, 13.4.4 concerns an + // executed event scheduling operation. A folded-away NBA is harmless. + let (_, nba, callees) = effects(subroutine.body.iter(), &definitions); + if nba { + schedules.insert(subroutine.name.clone()); + } + runtime_calls.push((&subroutine.name, callees)); + } + loop { + let previous = (forbidden.len(), schedules.len()); + for (name, callees) in &calls { + if callees.iter().any(|callee| forbidden.contains(callee)) { + forbidden.insert((*name).clone()); + } + } + for (name, callees) in &runtime_calls { + if callees.iter().any(|callee| schedules.contains(callee)) { + schedules.insert((*name).clone()); + } + } + if previous == (forbidden.len(), schedules.len()) { + break; + } + } + for process in processes.iter().filter(|process| process.is_final()) { + let (invalid, _, callees) = effects( + process.body.iter().chain(&process.validation_body), + &definitions, + ); + if invalid { + return Err(unsupported("timing control in a final procedure")); + } + if let Some(callee) = callees + .iter() + .filter(|callee| forbidden.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` in a final procedure does not obey function-statement restrictions" + ))); + } + let (_, _, callees) = effects(process.body.iter(), &definitions); + if let Some(callee) = callees + .iter() + .filter(|callee| schedules.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` from a final procedure schedules an event after the function returns; IEEE 1800-2023 13.4.4 requires an initial/always process" + ))); + } + } + Ok(()) +} + +/// Include discarded branches, expression calls and lvalue selectors: legality +/// is a property of the authored procedure, not just the path executed now. +fn effects<'a>( + body: impl Iterator, + definitions: &HashMap<&str, &Subroutine>, +) -> (bool, bool, HashSet) { + let mut invalid = false; + let mut nba = false; + let mut calls = Calls { + definitions, + names: HashSet::default(), + defaults: Vec::new(), + expanded: HashSet::default(), + }; + for statement in body { + statement.walk(&mut |statement| { + invalid |= matches!( + statement, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) + ); + nba |= matches!( + statement, + Stmt::Assign { + nonblocking: true, + .. + } | Stmt::AssignConcat { + nonblocking: true, + .. + } + ); + if let Stmt::Call { name, args, .. } = statement { + calls.record(name, CallArguments::Expressions(args)); + } + let mut call = |callee: &Callee, args| { + if let Callee::Subroutine(name) = callee { + calls.record(name, args); + } + }; + for expr in lifetimes::stmt_exprs(statement) { + const_functions::visit_expr_calls(expr, &mut call); + } + let targets = match statement { + Stmt::Assign { lhs, .. } => std::slice::from_ref(lhs), + Stmt::AssignConcat { parts, .. } => parts.as_slice(), + _ => &[], + }; + for target in targets { + if let LValue::Select { + msb, + lsb, + array_slice_width, + .. + } = target + { + for index in [Some(msb), Some(lsb), array_slice_width.as_ref()] + .into_iter() + .flatten() + { + const_functions::visit_const_calls(index, &mut call); + } + } + } + }); + } + calls.expand_defaults(); + (invalid, nba, calls.names) +} + +struct Calls<'map, 'definition> { + definitions: &'map HashMap<&'definition str, &'definition Subroutine>, + names: HashSet, + defaults: Vec<&'definition Expr>, + expanded: HashSet<(String, usize)>, +} + +impl Calls<'_, '_> { + fn record(&mut self, name: &str, args: CallArguments<'_>) { + self.names.insert(name.to_owned()); + let Some(&subroutine) = self.definitions.get(name) else { + return; + }; + for (index, parameter) in subroutine.params.iter().enumerate() { + if !args.is_present(index) + && let Some(default) = ¶meter.default + && self.expanded.insert((name.to_owned(), index)) + { + self.defaults.push(default); + } + } + } + + fn expand_defaults(&mut self) { + while let Some(default) = self.defaults.pop() { + const_functions::visit_expr_calls(default, &mut |callee, args| { + if let Callee::Subroutine(name) = callee { + self.record(name, args); + } + }); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 76e37f3c563..06f9181f7e6 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -8,6 +8,7 @@ pub(in crate::ast) fn classify<'a>( processes: &mut Vec, ) -> Result<(), AnalyzerError> { let subroutines: Vec<_> = subroutines.collect(); + super::final_procedures::validate(&subroutines, processes)?; let mut timed = HashSet::default(); loop { let previous = timed.len(); @@ -132,7 +133,8 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); @@ -172,14 +174,15 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); } *ff = retained; if processes.len() != initial_count { - processes.sort_by_key(|process| (!process.initializer, process.creation_order)); + processes.sort_by_key(|process| (!process.is_initializer(), process.creation_order)); } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 2c1bd94a779..3e324055c7d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -355,7 +355,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -596,7 +602,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -609,7 +621,7 @@ impl ScopeSymbols { /// Whether `process` assigns the signal `name`. pub(super) fn initializes(process: &InitialProcess, name: &str) -> bool { - process.body.iter().any(|stmt| stmt_initializes(stmt, name)) + !process.is_final() && process.body.iter().any(|stmt| stmt_initializes(stmt, name)) } fn stmt_initializes(stmt: &Stmt, name: &str) -> bool { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 669af79e830..3d981ce9419 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -126,7 +126,7 @@ fn validate_procedure( use celox_sv_syntax::{EventControl, ProcedureKind, StatementKind, TimingControlKind}; let kind = match procedure.kind { ProcedureKind::Initial => return Ok(()), - ProcedureKind::Final => return Err(unsupported("final construct")), + ProcedureKind::Final => return validate_final(procedure.body, native), _ => always_kind(procedure, native)?, }; let mut pending = vec![procedure.body]; @@ -166,6 +166,46 @@ fn validate_procedure( Ok(()) } +/// Final restrictions are syntactic, so even branches later folded away +/// must obey the function-statement rules (IEEE 1800-2023 9.2.3, 13.4). +fn validate_final( + root: celox_sv_syntax::StatementId, + native: &celox_sv_syntax::Declarations, +) -> Converted<()> { + use celox_sv_syntax::StatementKind; + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + let statement = native.statement(id); + let forbidden = match &statement.kind { + StatementKind::Assignment { + timing: Some(_), .. + } + | StatementKind::Assignment { + event_control: Some(_), + .. + } + | StatementKind::Timing { .. } => Some("timing control"), + StatementKind::Wait { .. } + | StatementKind::WaitFork + | StatementKind::WaitOrder { .. } => Some("wait statement"), + StatementKind::Parallel { join, .. } if join != "join_none" => Some("fork-join block"), + // 13.4.4 permits join_none in functions. Its child statements + // obey task rules, so leave the whole construct to the existing + // unsupported parallel-process binder rather than rejecting it. + StatementKind::Parallel { .. } => continue, + StatementKind::Assertion { keyword, .. } if keyword == "expect" => { + Some("expect statement") + } + _ => None, + }; + if let Some(construct) = forbidden { + return Err(unsupported(format!("{construct} in a final procedure"))); + } + pending.extend(statement.kind.children()); + } + Ok(()) +} + /// Root module inspection skips control branches. The subsequent active-item /// inspection visits an opaque checker's complete captured syntax, matching the /// existing validation contract without implementing checker elaboration. diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 32df6c7df93..f094e067c62 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -125,14 +125,14 @@ impl Module { step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, synthetic: false, repeats: true, }); } self.ff_processes = retained; self.initial_processes - .sort_by_key(|process| (!process.initializer, process.creation_order)); + .sort_by_key(|process| (!process.is_initializer(), process.creation_order)); self } @@ -1146,7 +1146,7 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, @@ -1154,7 +1154,7 @@ pub struct InitialProcess { scheduled_edge: bool, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -1176,19 +1176,33 @@ impl InitialProcess { self.site.as_ref() } - pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { + pub(crate) fn new( + condition: Option, + body: Vec, + kind: celox_design::ProcessKind, + ) -> Self { Self { creation_order: 0, site: None, scheduled_edge: false, condition, body, - initializer, + kind, synthetic: false, repeats: false, } } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -1197,7 +1211,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers, which /// run before every `initial` and `always` procedure. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and @@ -1602,7 +1616,7 @@ impl From for InitialProcess { .cloned() .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), - process.is_initializer(), + process.kind(), ); result.creation_order = process.creation_order(); result.site = process.site().cloned(); diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 143a76ffce4..6fff884e774 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -1339,7 +1339,7 @@ mod declaration_tests { &ModuleInterfaces::default(), &packages ) - .is_err() + .is_ok() ); let ir = source .analyze_module_declarations("Top", &overrides, &packages) diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs index 401b8012f3c..be3717fa014 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs @@ -204,7 +204,7 @@ fn native_process_restrictions_apply_only_to_active_generate_items() { #[test] fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -229,7 +229,7 @@ fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { #[test] fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -248,26 +248,17 @@ fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { #[test] fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contract() { for (body, rejected) in [ - ("checker C;final begin end endchecker", true), - ("checker C;if(0)final begin end endchecker", true), + ("checker C;final #1; endchecker", true), + ("checker C;if(0)final #1; endchecker", true), + ("if(0)begin:g checker C;final #1; endchecker end", false), + ("if(1)begin:g checker C;final #1; endchecker end", true), + ("module N;checker C;final #1; endchecker endmodule", true), ( - "if(0)begin:g checker C;final begin end endchecker end", + "module N;checker C;if(0)final #1; endchecker endmodule", false, ), ( - "if(1)begin:g checker C;final begin end endchecker end", - true, - ), - ( - "module N;checker C;final begin end endchecker endmodule", - true, - ), - ( - "module N;checker C;if(0)final begin end endchecker endmodule", - false, - ), - ( - "module N;checker C;if(1)final begin end endchecker endmodule", + "module N;checker C;if(1)final #1; endchecker endmodule", false, ), ] { @@ -281,7 +272,9 @@ fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contr if rejected { let error = result.unwrap_err(); assert!( - error.to_string().contains("final construct"), + error + .to_string() + .contains("timing control in a final procedure"), "{body}: {error}" ); } else { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 6b3b0ef51fb..f6e85cb53f9 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -1465,6 +1465,8 @@ pub enum Body { /// `always`, `always_comb`, or `always_ff`. Always, Initial, + /// A final procedure, restricted to function statements (9.2.3). + Final, /// A function or task. Subroutine, } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c9385650f3d..10ebdfcfbd0 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -7031,3 +7031,213 @@ fn preserves_legal_enum_declaration_initializers() { .unwrap_or_else(|error| panic!("{source}: {error}")); } } + +#[test] +fn final_procedures_preserve_phase_and_active_generate_order() { + let ir = analyze_source( + r#"module Top; + int value = 3; + function int read_value(); return value; endfunction + initial value = 5; + final begin value = read_value(); $display("final %d", value); end + if (0) begin: inactive final #1; end + for (genvar i = 0; i < 2; i++) begin: active + final $display("generated %d", i); + end + endmodule"#, + Path::new("final_procedures.sv"), + ) + .unwrap(); + assert!(ir.modules()[0].comb_processes().is_empty()); + assert!(ir.modules()[0].ff_processes().is_empty()); + let processes = ir.modules()[0].initial_processes(); + assert_eq!( + processes + .iter() + .filter(|process| process.is_initializer()) + .count(), + 1 + ); + assert_eq!( + processes + .iter() + .filter(|process| process.is_final()) + .count(), + 3 + ); + let finals: Vec<_> = processes + .iter() + .filter(|process| process.is_final()) + .collect(); + assert!( + finals + .windows(2) + .all(|pair| pair[0].creation_order() < pair[1].creation_order()) + ); + assert!( + finals.iter().all(|process| !process.repeats() + && !process.is_initializer() + && !process.is_synthetic()) + ); + assert!( + finals + .iter() + .all(|process| process.kind() == celox_design::ProcessKind::Final) + ); +} + +#[test] +fn final_procedures_reject_timing_before_folding() { + for statement in [ + "#1 value = 1;", + "@(value) value = 1;", + "wait(value) value = 1;", + "wait fork;", + "fork value = 1; join", + "value = #1 2;", + ] { + for body in [ + statement.to_string(), + format!("if (0) begin {statement} end"), + ] { + let source = format!("module Top; int value; final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final.sv")).unwrap_err(); + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } +} + +#[test] +fn final_procedures_reject_task_and_nba_through_function_calls() { + for declarations in [ + "task work(); endtask", + "task work(); #1; endtask", + "task t(); endtask function void work(); t(); endfunction", + "function void work(); value <= 1; endfunction", + "function void bad(); value <= 1; endfunction function void work(); bad(); endfunction", + ] { + for body in ["work();", "if (0) work();"] { + if declarations.contains("<=") && body.starts_with("if (0)") { + continue; + } + let source = + format!("module Top; int value; {declarations} final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final_call.sv")).unwrap_err(); + if declarations.contains("<=") { + assert!(error.to_string().contains("13.4.4"), "{source}: {error}"); + } + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } + let source = "module Top; int value; function int bad(); value <= 1; return value; endfunction final value = bad(); endmodule"; + let error = analyze_source(source, Path::new("illegal_final_expression.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); + let source = "package p; task work(); endtask endpackage module Top; import p::*; final work(); endmodule"; + let error = analyze_source(source, Path::new("illegal_imported_final_call.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); +} + +#[test] +fn final_procedures_preserve_legal_functions_and_finish() { + for body in [ + "value = compute();", + "report();", + "$finish;", + "$stop;", + "$fatal;", + "$fclose(value);", + "$sscanf(\"1\", \"%d\", value);", + "begin int local_value; local_value = value; $display(local_value); end", + ] { + let source = format!( + "module Top; int value; function int compute(); return value + 1; endfunction function void report(); $display(value); endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("legal_final.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + assert_eq!( + ir.modules()[0] + .initial_processes() + .iter() + .filter(|process| process.is_final()) + .count(), + 1 + ); + } +} + +#[test] +fn final_procedures_allow_direct_nba_and_unexecuted_scheduling_calls() { + for body in ["value <= 1;", "if (0) schedule();", "no_schedule();"] { + let source = format!( + "module Top; int value; function void schedule(); value <= 1; endfunction function void no_schedule(); if (0) value <= 1; endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("final_nba.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + let process = ir.modules()[0] + .initial_processes() + .iter() + .find(|process| process.is_final()) + .unwrap(); + if body == "value <= 1;" { + assert!(matches!( + process.body(), + [ir::Stmt::Assign { + nonblocking: true, + .. + }] + )); + } + } +} + +#[test] +fn final_join_none_is_unsupported_rather_than_a_function_statement_violation() { + let error = analyze_source( + "module Top; final fork #1; join_none endmodule", + Path::new("final_join_none.sv"), + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Unsupported SystemVerilog construct: fork-join block" + ); +} + +#[test] +fn final_procedures_only_follow_defaults_for_omitted_arguments() { + let declarations = r#" + int value; + function int schedule(); value <= 1; return 0; endfunction + function int take(input int a = schedule(), input int b = 0); return a + b; endfunction + function int nested(input int a = take()); return a; endfunction + function void explicit_wrapper(); value = take(0); endfunction + function void omitted_wrapper(); value = take(); endfunction + "#; + for (body, rejected) in [ + ("value = take();", true), + ("value = take(, 1);", true), + ("value = take(.b(1));", true), + ("value = nested();", true), + ("omitted_wrapper();", true), + ("value = take(0);", false), + ("value = take(.a(0));", false), + ("value = nested(0);", false), + ("explicit_wrapper();", false), + ("if (0) value = take();", false), + ] { + let source = format!("module Top; {declarations} final {body} endmodule"); + let result = analyze_source(&source, Path::new("final_default_arguments.sv")); + if rejected { + let error = result.unwrap_err(); + assert!(error.to_string().contains("13.4.4"), "{body}: {error}"); + } else { + result.unwrap_or_else(|error| panic!("{body}: {error}")); + } + } +} diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index a996e6eb580..c68196a6dda 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -288,6 +288,9 @@ fn simulate_sv( saves.after_step(&mut simulation)?; steps += 1; } + let finished = simulation.finish(); + drain_sv_output(&mut simulation, output, &mut failed)?; + finished.map_err(|error| error.to_string())?; saves.finish(&mut simulation)?; if failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); @@ -1164,8 +1167,7 @@ mod tests { #[cfg(feature = "systemverilog")] #[test] fn sv_scheduler_limit_fails_and_preserves_scheduled_output() { - let source = - "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); endmodule"; + let source = "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); final $display(\"finalized\"); endmodule"; let mut simulation = celox::Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") .build() @@ -1174,7 +1176,28 @@ mod tests { let mut output = Vec::new(); let error = simulate_sv(simulation, 3, StateSaves::default(), &mut output).unwrap_err(); assert!(error.contains("exceeded --max-steps 3")); - assert!(String::from_utf8(output).unwrap().contains("tick")); + let output = String::from_utf8(output).unwrap(); + assert!(output.contains("tick")); + assert!(!output.contains("finalized")); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn sv_batch_runs_final_output_on_quiescence_and_finish() { + for ending in ["", "$finish;"] { + let source = format!( + "module Top; int value; initial begin value=42; {ending} end final $display(\"final=%0d\", value); endmodule" + ); + let simulation = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("top.sv"))], + "Top", + ) + .build() + .unwrap(); + let mut output = Vec::new(); + simulate_sv(simulation, 10, StateSaves::default(), &mut output).unwrap(); + assert_eq!(String::from_utf8(output).unwrap(), "final=42\n"); + } } /// Only `$error` and `$fatal` fail a run; every report is printed with diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index b87450b0b2f..f0726b032cd 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -237,6 +237,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { use std::io::Write as _; let mut stdout = std::io::stdout().lock(); let mut output = |sim: &mut celox::Simulation| -> Result<(), String> { + let mut fatal = None; for event in sim.drain_runtime_events() { match event { celox::RuntimeEvent::Report(celox::Report { @@ -246,7 +247,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { }) => { stdout.write_all(&message).unwrap(); stdout.write_all(b"\n").unwrap(); - return Err(format!( + fatal = Some(format!( "$fatal: {}", std::str::from_utf8(&message) .map(str::to_owned) @@ -265,7 +266,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { } } } - Ok(()) + fatal.map_or(Ok(()), Err) }; let initial = sim.eval_comb().map_err(|error| error.to_string()); output(&mut sim)?; @@ -279,6 +280,13 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { break; } } + if !sim.is_stopped() { + // Quiescence ends this batch run, but is not itself terminal for the + // reusable Simulation API (a host can still supply new inputs). + let finished = sim.finish().map_err(|error| error.to_string()); + output(&mut sim)?; + finished?; + } Ok(()) } @@ -421,6 +429,19 @@ mod tests { ); } + #[test] + fn simulation_runs_final_on_quiescence_but_elaboration_does_not() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture( + dir.path(), + "final.sv", + "module Top; initial #2; final $fatal(1, \"from final\"); endmodule", + ); + run(&fixture_options(vec![path.clone()], Mode::Elaboration)).unwrap(); + let error = run(&fixture_options(vec![path], Mode::Simulation)).unwrap_err(); + assert!(error.contains("from final"), "{error}"); + } + #[test] fn simulation_variants_use_separate_arguments_and_fresh_state() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 984c26ba14a..ae25f64d4a2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 38; +const CONTAINER_VERSION: u16 = 39; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 05002091ffb..f3dcfc3baa6 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -425,8 +425,10 @@ impl Plan { for (index, slots) in schema.processes.iter().enumerate() { let process = &model.processes[index]; let unit = &sir.processes[index]; - let reason = if slots.is_initializer { + let reason = if slots.kind == celox_design::ProcessKind::Initializer { Some("a declaration initializer") + } else if slots.kind == celox_design::ProcessKind::Final { + Some("a final procedure") } else if slots.program.is_some() { Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 967e6da71b4..56bd3dfcdaa 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -158,9 +158,7 @@ impl UnitExecutor for Simulator { } fn run_process(&mut self, index: usize) -> Result<(), Halt> { - self.backend - .run_process(index) - .map_err(|e| self.decorate_runtime_error(e))?; + self.run_process_checked(index)?; self.runtime_finish() } @@ -474,9 +472,22 @@ impl Simulation { if self.state.is_suspended() { return Err(CheckpointError::Stopped.into()); } - let mut file = self.simulator.save_state()?; + if let Err(error) = self.simulator.prepare_save_state() { + if let StateError::Runtime(error) = &error { + self.finalize_fatal(error); + } + return Err(error); + } // Settling for the file may have executed a `$finish`. self.sync_finish_checked().map_err(StateError::Runtime)?; + // A final procedure can write state or suspend with `$stop`. + if self.state.is_suspended() { + return Err(CheckpointError::Stopped.into()); + } + let mut file = self + .simulator + .state_schema() + .capture(&self.simulator.backend)?; let parts = self.state.export_schedule(&self.simulator.backend); let mut record = self.simulator.name_schedule(parts); record.processes.host_writes = self.simulator.name_host_writes(); @@ -537,11 +548,19 @@ impl Simulation { /// step, during a direct settle, read or dump, ends the simulation too. fn sync_finish_checked(&mut self) -> Result<(), RuntimeErrorCode> { if !self.state.is_finished() && self.simulator.take_runtime_finish() { - self.state.finalize_terminal(&mut self.simulator)?; + self.finish()?; } Ok(()) } + /// A fatal report implicitly calls `$finish`; retain the original diagnostic + /// even if a final procedure or output flush fails during termination. + fn finalize_fatal(&mut self, error: &RuntimeErrorCode) { + if matches!(error, RuntimeErrorCode::Fatal { .. }) { + let _ = self.finish(); + } + } + /// Publish diagnostic state without replacing a primary evaluation error /// or freezing a simulation whose caller may recover. fn flush_error_output(&mut self) { @@ -556,13 +575,17 @@ impl Simulation { /// Captures the current state of all signals and writes them to the VCD file. pub fn dump(&mut self, timestamp: u64) { - self.simulator.dump(timestamp); - self.sync_finish(); + if let Err(error) = self.try_dump(timestamp) { + panic!("VCD dump at {timestamp} failed: {error}"); + } } /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { let result = self.simulator.try_dump(timestamp); + if let Err(crate::simulator::DumpError::Runtime(error)) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if matches!(&result, Err(crate::simulator::DumpError::Runtime(_))) { self.flush_error_output(); @@ -615,6 +638,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); result?; finished?; @@ -716,6 +742,7 @@ impl Simulation { Ok(()) }; if let Err(error) = result.and_then(|()| self.simulator.mature_deferred_assertions()) { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -801,6 +828,9 @@ impl Simulation { /// that wake no process, at the current time, and watch its reports. A /// watched run does this before it moves to a later time. fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(()); + } // The run leaves the time or ends at it: the slot is over, and the // deferred actions waiting from any settle at that time mature // before the reports are watched. @@ -811,6 +841,7 @@ impl Simulation { } if self.simulator.dirty { if let Err(error) = self.simulator.eval_comb_checked() { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -821,6 +852,9 @@ impl Simulation { } else { Ok(()) }; + if let Err(error) = &matured { + self.finalize_fatal(error); + } self.watch_reports(); if let Err(error) = matured { self.flush_error_output(); @@ -906,7 +940,8 @@ impl Simulation { return Ok(()); } if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { - if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + if let crate::simulator::DumpError::Runtime(runtime_error) = &error { + self.finalize_fatal(runtime_error); self.flush_error_output(); } return Err(vcd_dump_runtime_error(error)); @@ -984,9 +1019,28 @@ impl Simulation { Ok(!self.state.is_stopped()) } - /// Whether a process of the design requested the end of the simulation. - /// Once it has, [`Self::step`] returns `None` and [`Self::run_until`] - /// stops at the time of the request. + /// End simulation at its current time, running final procedures once. + /// Idle steps and bounded runs remain resumable until this is requested. + /// If a final procedure executes `$stop`, a later step resumes finalization. + pub fn finish(&mut self) -> Result<(), RuntimeErrorCode> { + use celox_runtime::StepObserver; + let Some(mut shadow) = self.shadow.take() else { + return self.state.finish(&mut self.simulator); + }; + let mut check = differential::ShadowCheck::new(&mut shadow, self.mode()); + check.before_step(&self.state, &mut self.simulator); + let result = self.state.finish(&mut self.simulator); + let comparison = check.after_finish(&self.state, &mut self.simulator, &result); + self.checked_steps += check.checked; + self.shadow = Some(shadow); + comparison?; + result + } + + /// Whether simulation has terminated and its final procedures have completed. + /// Termination can be requested by the design or by [`Self::finish`]. + /// Once complete, [`Self::step`] returns `None` and [`Self::run_until`] + /// stops at the termination time. pub fn is_finished(&self) -> bool { self.state.is_finished() } @@ -1014,18 +1068,32 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + // Keep termination visible to the timed owner before collecting reports. + // The untimed drain intentionally turns immediate fatals into reports. + if self.simulator.dirty { + let settled = self.simulator.eval_comb_checked(); + self.simulator.dirty = false; + match settled.and_then(|()| self.sync_finish_checked()) { + Err(error @ RuntimeErrorCode::Fatal { .. }) => self.finalize_fatal(&error), + result => result.unwrap(), + } + } // A slot with nothing more due is over, also before the first step: // the initial settle of combinational logic belongs to time zero. // A fatal action is drained as a fatal report. - if self.simulator.deferred_assertions + if !self.state.is_finished() + && self.simulator.deferred_assertions && self.state.next_event_time() != Some(self.state.time()) { - // Lazily settled logic runs in the slot too. - self.simulator.settle_for_runtime_event_drain(); - let _ = self.simulator.mature_deferred_assertions(); + if let Err(error) = self.simulator.mature_deferred_assertions() { + self.finalize_fatal(&error); + } } let mut events = std::mem::take(&mut self.reports.events); - events.extend(self.simulator.drain_runtime_events()); + events.extend( + self.simulator + .drain_settled_runtime_events_with_context(crate::RuntimeFormatContext::default()), + ); events } @@ -1037,6 +1105,9 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { let result = self.simulator.eval_comb(); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if result.is_err() { self.flush_error_output(); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ceb3ba86f99..76f162baa87 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -69,6 +69,28 @@ impl<'a, B: SimBackend> ShadowCheck<'a, B> { } } +impl ShadowCheck<'_, B> { + pub(super) fn after_finish( + &mut self, + state: &SimulationState, + primary: &mut Simulator, + result: &Result<(), RuntimeErrorCode>, + ) -> Result<(), RuntimeErrorCode> { + let shadow = &mut *self.shadow; + let reference = shadow.state.finish(&mut shadow.simulator); + self.checked += 1; + let result = result.clone().map(|()| Some(state.time())); + let reference = reference.map(|()| Some(shadow.state.time())); + match difference(state, primary, shadow, &result, &reference) { + None => Ok(()), + Some(message) => Err(RuntimeErrorCode::Runtime { + message: format!("finalization diverged from the reference: {message}"), + signals: Vec::new(), + }), + } + } +} + impl StepObserver> for ShadowCheck<'_, B> { fn one_slot(&self) -> bool { self.one_slot diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 2b497812fd2..53d13ef05df 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -796,7 +796,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|slots| !slots.is_initializer) + .filter(|slots| slots.kind != celox_design::ProcessKind::Initializer) .map(|slots| slots.const_delays) .collect(); // `initial clk = 1'b0` folds into an initial value. A real delay diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 6e1d6ae5327..b34212fdae3 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -952,7 +952,7 @@ mod host { match err { RuntimeErrorCode::DetectedTrueLoopCode(code) => { if self.comb_fatal_site(code).is_some() { - return RuntimeErrorCode::Runtime { + return RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)" .to_string(), signals: Vec::new(), @@ -1470,7 +1470,9 @@ mod host { /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. pub(crate) fn mature_deferred_assertions(&mut self) -> Result<(), RuntimeErrorCode> { - if !self.deferred_assertions { + // Terminal output draining must not execute actions left in the + // Observed/Postponed queues after final procedures (9.2.3). + if self.frozen || !self.deferred_assertions { return Ok(()); } self.stash_runtime_events(); @@ -1493,7 +1495,7 @@ mod host { }) else { return Ok(()); }; - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message: message_diagnostic(&report.message), signals: Vec::new(), }) @@ -1584,6 +1586,9 @@ mod host { } fn runtime_event_write_seq(&self) -> u64 { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return 0; + } if let Some(buffer) = self.backend.runtime_event_buffer() { buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire) } else { @@ -1822,7 +1827,7 @@ mod host { return Err(error); } if fatal_status { - return Err(RuntimeErrorCode::Runtime { + return Err(RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)".to_string(), signals: Vec::new(), }); @@ -1835,7 +1840,9 @@ mod host { ) -> (Result<(), RuntimeErrorCode>, Vec) { // Event-drain writes use this entry directly instead of the // checked facade. Leave observers and runtime events untouched. - if self.declaration_phase { + // A boundary observer may have marked the state dirty immediately + // before freezing; draining output must not activate HDL afterwards. + if self.frozen || self.declaration_phase { return (Ok(()), Vec::new()); } if self.program.runtime_schema.runtime_event_sites.is_empty() { @@ -1931,7 +1938,7 @@ mod host { if !site.kind.is_fatal() || site.deferred.is_some() { return None; } - Some(RuntimeErrorCode::Runtime { + Some(RuntimeErrorCode::Fatal { message: message_diagnostic(&render_runtime_event_message( site, args, @@ -1942,40 +1949,62 @@ mod host { }) } + /// Keep a fatal report distinct from ordinary runtime faults before its + /// backend status is decorated into a diagnostic. + fn checked_kernel_result( + &self, + result: Result<(), RuntimeErrorCode>, + start: u64, + ) -> Result<(), RuntimeErrorCode> { + result.map_err(|error| { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return self.decorate_runtime_error(error); + } + self.fatal_comb_capture_error(&self.peek_backend_runtime_events_from(start)) + .unwrap_or_else(|| self.decorate_runtime_error(error)) + }) + } + + pub(crate) fn run_process_checked(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + let start = self.runtime_event_write_seq(); + let result = self.backend.run_process(index); + self.checked_kernel_result(result, start) + } + pub(crate) fn eval_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_comb_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_comb_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_comb_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_only_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_only_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_only_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.apply_ff_at(event); + self.checked_kernel_result(result, start) } /// One clock period of an event's signal: its active edge, then its @@ -3535,7 +3564,7 @@ mod host { assert!(sim.fatal_comb_capture_error(&events).is_none()); assert!(sim.check_comb_backend_result(result.clone()).is_ok()); assert!(matches!(sim.decorate_runtime_error(result.unwrap_err()), - RuntimeErrorCode::Runtime { message, .. } if message.contains("overwritten"))); + RuntimeErrorCode::Fatal { message, .. } if message.contains("overwritten"))); let drained = sim.drain_runtime_events(); assert!(matches!( drained.first(), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 75e1a4f61a5..d052dadf20c 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -4061,7 +4061,7 @@ mod host { .runtime_schema .processes .iter() - .any(|slots| slots.is_initializer) + .any(|slots| slots.kind == celox_design::ProcessKind::Initializer) { sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..1cdab79f2a7 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -303,6 +303,13 @@ impl Simulator { /// Combinational values are settled first, so the file shows the values /// a read would return. pub fn save_state(&mut self) -> Result { + self.prepare_save_state()?; + self.state_schema().capture(&self.backend) + } + + /// Validate support and settle before a timed owner synchronizes termination. + /// Capture must follow that synchronization, since final procedures can write state. + pub(crate) fn prepare_save_state(&mut self) -> Result<(), StateError> { self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); @@ -311,7 +318,7 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - self.state_schema().capture(&self.backend) + Ok(()) } /// Load the state saved in `file`, matching objects by path. diff --git a/crates/celox/tests/comb_observer.rs b/crates/celox/tests/comb_observer.rs index ae525ef7dbf..47f1ca24605 100644 --- a/crates/celox/tests/comb_observer.rs +++ b/crates/celox/tests/comb_observer.rs @@ -783,7 +783,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fail".to_string(), signals: Vec::new(), }, @@ -806,7 +806,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal".to_string(), signals: Vec::new(), }, @@ -831,7 +831,7 @@ module Top ( let err = sim.modify(|io| io.set(trigger, 1u8)).unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fatal after modify".to_string(), signals: Vec::new(), }, @@ -853,7 +853,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "user says for-loop step does not advance the loop variable".to_string(), signals: Vec::new(), }, @@ -899,7 +899,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "a must be set".to_string(), signals: Vec::new(), }, @@ -1205,7 +1205,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "fatal y".to_string(), signals: Vec::new(), }, @@ -1718,7 +1718,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "x1 became 1".to_string(), signals: Vec::new(), }, diff --git a/crates/celox/tests/fixtures/final/finish.sv b/crates/celox/tests/fixtures/final/finish.sv new file mode 100644 index 00000000000..cfb9816211f --- /dev/null +++ b/crates/celox/tests/fixtures/final/finish.sv @@ -0,0 +1,19 @@ +`timescale 1ns/1ns +// Whichever final runs first must terminate the current and remaining finals. +module Top(output int calls, after_finish); + initial begin calls = 0; after_finish = 0; #1; $finish; end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 1; + $display("unreachable first"); + end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 2; + $display("unreachable second"); + end +endmodule diff --git a/crates/celox/tests/fixtures/final/hierarchy.sv b/crates/celox/tests/fixtures/final/hierarchy.sv new file mode 100644 index 00000000000..32b84b938ff --- /dev/null +++ b/crates/celox/tests/fixtures/final/hierarchy.sv @@ -0,0 +1,15 @@ +`timescale 1ns/1ns +// The order of final procedures is unspecified. Each emits a distinct +// label so an external check can compare the labels without ordering them. +module Child(output bit done); + final begin done = 1; $display("child"); end +endmodule +module Top(output bit first, second, child_done, output bit [1:0] generated); + Child child(child_done); + initial begin #1; $finish; end + final begin first = 1; $display("top first"); end + final begin second = 1; $display("top second"); end + for (genvar i = 0; i < 2; i++) begin : g + final begin generated[i] = 1; $display("generate %0d", i); end + end +endmodule diff --git a/crates/celox/tests/fixtures/final/state.sv b/crates/celox/tests/fixtures/final/state.sv new file mode 100644 index 00000000000..ae4e6549072 --- /dev/null +++ b/crates/celox/tests/fixtures/final/state.sv @@ -0,0 +1,16 @@ +`timescale 1ns/1ns +// IEEE 1800-2023 9.2.3: final observes the last state and runs once. +module Top(output int value, calls); + initial begin + value = 3; calls = 0; + $display("initial calls=%0d", calls); + #2 value = 7; + $finish; + end + final begin + calls = calls + 1; + value = value + 10; + if (value != 17 || calls != 1) $fatal(1, "bad final state"); + $display("final value=%0d calls=%0d", value, calls); + end +endmodule diff --git a/crates/celox/tests/frontends/systemverilog/final.rs b/crates/celox/tests/frontends/systemverilog/final.rs new file mode 100644 index 00000000000..f904597200c --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/final.rs @@ -0,0 +1,521 @@ +use celox::{RuntimeEvent, SimBackend, Simulation}; +use std::path::Path; + +// The shared timed-suite emitter uses its own final checker and therefore +// rejects final procedures whose order relative to that checker is unspecified. +// These portable fixtures are also suitable for direct external execution; +// API checks here inspect state only after finalization has completed. +// Every source uses 1ns/1ns so API ticks and HDL delay units coincide. +const STATE: &str = include_str!("../../fixtures/final/state.sv"); +const HIERARCHY: &str = include_str!("../../fixtures/final/hierarchy.sv"); +const FINISH: &str = include_str!("../../fixtures/final/finish.sv"); + +#[test] +fn final_procedures_require_the_simulation_api() { + let source = "module Top(input logic done); final assert (done); endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("final.sv"))], "Top") + .build_interpreter() + .unwrap_err(); + assert!( + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" + ); +} + +fn displays(events: Vec) -> Vec> { + events + .into_iter() + .filter_map(|event| match event { + RuntimeEvent::Display { message } => Some(message), + _ => None, + }) + .collect() +} + +fn check_final_state(mut sim: Simulation) { + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![ + b"initial calls=0".to_vec(), + b"final value=17 calls=1".to_vec(), + ] + ); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert!(displays(sim.drain_runtime_events()).is_empty()); +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn final_procedures_survive_native_image_roundtrip() { + let image = Simulation::from_sv_sources(vec![(STATE, Path::new("final_state.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + check_final_state( + Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); +} + +macro_rules! check_backends { + ($source:expr, $check:ident) => { + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![($source, Path::new("final.sv"))], "Top") + .four_state(four_state) + }; + $check(build().build_interpreter().unwrap()); + $check(build().build_cranelift().unwrap()); + $check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + $check(build().build_native().unwrap()); + $check(build().build_tiered().unwrap()); + $check( + build() + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(), + ); + } + } + }; +} + +#[test] +fn final_nonblocking_updates_do_not_run_after_termination() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, observed); + initial begin value=3; #1; $finish; end + final begin value <= 99; observed = value; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + assert_eq!(sim.get(sim.signal("observed")), 3u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn explicit_finish_runs_final_with_last_state() { + check_backends!(STATE, check_final_state); +} + +#[test] +fn final_procedures_run_in_modules_and_generate_blocks() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + for name in ["first", "second"] { + assert_eq!(sim.get(sim.signal(name)), 1u8.into(), "{name}"); + } + // Output variable ports connect through implicit continuous + // assignments (4.9.6, 23.2.2.3). Finalization does not run another + // scheduled settle (9.2.3), so inspect the child's own final write. + let child_done = sim.child_signal(&[("child", 0)], "done"); + assert_eq!(sim.get(child_done), 1u8.into()); + assert_eq!(sim.get(sim.signal("generated")), 3u8.into()); + let mut labels = displays(sim.drain_runtime_events()); + labels.sort(); + assert_eq!( + labels, + [ + "child", + "generate 0", + "generate 1", + "top first", + "top second" + ] + .map(|text| text.as_bytes().to_vec()) + ); + } + check_backends!(HIERARCHY, check); +} + +#[test] +fn finish_in_final_stops_remaining_execution() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("after_finish")), 0u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final calls=1".to_vec()] + ); + } + check_backends!(FINISH, check); +} + +#[test] +fn host_finish_is_explicit_and_runs_final_only_once() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #2 value = 7; end + final begin calls = calls + 1; value = value + 10; $display("final"); end + endmodule"#; + fn check(mut sim: Simulation) { + let value = sim.signal("value"); + let calls = sim.signal("calls"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(value), 3u8.into()); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(value), 7u8.into()); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 0u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(value), 17u8.into()); + assert_eq!(sim.get(calls), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 1u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn stop_in_final_resumes_at_the_cursor_without_running_scheduled_events() { + let source = r#"`timescale 1ns/1ns + module Top(output int calls, other_calls, late_event); + initial begin calls = 0; other_calls = 0; late_event = 0; #10 late_event = 1; end + final begin calls = calls + 1; $stop; calls = calls + 1; end + final other_calls = other_calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.finish().unwrap(); + assert!(sim.is_stopped()); + assert!(sim.checkpoint().is_err()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + // The other final may precede or follow the suspended one. After + // resumption both must be complete, with no restart of either body. + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + let finished = sim.checkpoint().unwrap(); + sim.restore(&finished).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + sim.run_until(100).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn stop_suspends_without_running_final() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #1 $stop; value = 7; $finish; end + final begin calls = calls + 1; value = value + 10; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 0u8.into()); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn fatal_runs_final_and_preserves_the_original_error() { + // IEEE 1800-2023 20.10: $fatal implicitly calls $finish. + let source = r#"`timescale 1ns/1ns + module Top(output int calls); + initial begin calls = 0; #1 $fatal(1, "initial fatal"); end + final begin calls = calls + 1; $display("final after fatal"); end + endmodule"#; + fn check(mut sim: Simulation) { + let error = sim.run_until(2).unwrap_err(); + assert!(error.to_string().contains("initial fatal"), "{error}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + let events = sim.drain_runtime_events(); + assert!(events.iter().any(|event| matches!(event, + RuntimeEvent::Report(report) + if report.severity == celox::Severity::Fatal && report.message == b"initial fatal" + )), "{events:?}"); + assert!( + events.iter().any(|event| matches!(event, + RuntimeEvent::Display { message } if message == b"final after fatal" + )), + "{events:?}" + ); + } + check_backends!(source, check); +} + +#[test] +fn final_order_is_sequential_and_repeatable() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin #1; $finish; end + final begin $write("A"); $display("a"); end + final begin $write("B"); $display("b"); end + final begin $write("C"); $display("c"); end + endmodule"#; + fn transcript(mut sim: Simulation) -> Vec { + sim.run_until(2).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| { + matches!( + event, + RuntimeEvent::Write { .. } | RuntimeEvent::Display { .. } + ) + }) + .collect() + } + // Order is implementation-defined; require complete procedure pairs and + // stability between fresh instances, not a particular source order. + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![(source, Path::new("final_order.sv"))], "Top") + .four_state(four_state) + }; + let first = transcript(build().build_interpreter().unwrap()); + assert_eq!(first, transcript(build().build_interpreter().unwrap())); + assert_eq!(first.len(), 6); + let mut labels = Vec::new(); + for pair in first.as_chunks::<2>().0 { + let [ + RuntimeEvent::Write { message: upper }, + RuntimeEvent::Display { message: lower }, + ] = pair + else { + panic!("interleaved final procedures: {first:?}"); + }; + assert_eq!(upper.len(), 1); + assert_eq!(lower, &upper.to_ascii_lowercase()); + labels.push(upper[0]); + } + labels.sort_unstable(); + assert_eq!(labels, b"ABC"); + } +} + +#[test] +fn watched_idle_deferred_fatal_runs_final_and_preserves_the_error() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb assert final (!fail) else $fatal(1, "deferred fatal"); + final calls = calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.set_fail_on(Some(celox::Severity::Error)); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + // No timed process is scheduled: run_until must finalize a fatal + // deferred report matured while settling watched host writes. + let error = sim.run_until(1).unwrap_err(); + assert!(error.to_string().contains("deferred fatal"), "{error}"); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_after_final() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final $display("final"); + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + assert_eq!(sim.step().unwrap(), None); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_while_final_is_stopped() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final begin $display("before"); $stop; $display("after"); end + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"before".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"after".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn event_drain_finalizes_immediate_fatal_before_deferred_actions() { + for deferred in [ + "", + "always_comb assert final (!fail) else $display(\"deferred\");", + ] { + let source = format!( + r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "drain fatal"); + {deferred} + final begin calls += 1; $display("final"); end + endmodule"# + ); + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.drain_runtime_events(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + let events = sim.drain_runtime_events(); + assert!(sim.is_finished(), "{events:?}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + events + .iter() + .filter(|event| matches!(event, + RuntimeEvent::Report(report) if report.severity == celox::Severity::Fatal + && report.message == b"drain fatal" + )) + .count(), + 1, + "{events:?}" + ); + assert_eq!(displays(events), vec![b"final".to_vec()]); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source.as_str(), check); + } +} + +#[test] +fn saved_state_contains_final_updates_after_lazy_finish() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result, calls); + initial begin result = 7; calls = 0; end + always_comb if (go) $finish; + final begin result = 42; calls += 1; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let before = sim.save_state().unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let finished = sim.save_state().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + sim.load_state(&before).unwrap(); + assert!(!sim.is_finished()); + sim.load_state(&finished).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_rejects_a_stop_reached_inside_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result); + initial result = 0; + always_comb if (go) $finish; + final begin result = 7; $stop; result = 42; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + assert!(matches!( + sim.save_state(), + Err(celox::StateError::Checkpoint( + celox::CheckpointError::Stopped + )) + )); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 7u8.into()); + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + let finished = sim.save_state().unwrap(); + sim.load_state(&finished).unwrap(); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_preserves_fatal_and_runs_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "save fatal"); + final calls += 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + assert!(matches!(sim.save_state(), + Err(celox::StateError::Runtime(celox::RuntimeErrorCode::Fatal { message, .. })) + if message == "save fatal" + )); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index e34c6124f7a..9000b8ab688 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5486,14 +5486,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "final construct", - r#" - module Top(input logic done); - final assert (done); - endmodule - "#, - ), ( "non-ANSI port expressions", r#" diff --git a/crates/celox/tests/runtime_api.rs b/crates/celox/tests/runtime_api.rs index d88637e469c..4e34e8420a9 100644 --- a/crates/celox/tests/runtime_api.rs +++ b/crates/celox/tests/runtime_api.rs @@ -13,7 +13,7 @@ all_backends! { @build Simulator::builder(r#" module Top { always_comb { $assert(1'd0, "site zero"); } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site zero")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site zero")); assert_eq!(bare(sim.drain_runtime_events()), vec![RuntimeEvent::Report(Report::new(Severity::Fatal, b"site zero".to_vec()))]); assert!(bare(sim.drain_runtime_events()).is_empty()); } @@ -30,7 +30,7 @@ module Top { } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site two")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site two")); assert_eq!(bare(sim.drain_runtime_events()), vec![ RuntimeEvent::Display { message: b"first".to_vec() }, RuntimeEvent::Display { message: b"second".to_vec() }, diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 43766a4dabe..1bf274b058a 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -678,6 +678,25 @@ fn native_program_image_rejects_v19_before_loading_float_helper_abi() { )); } +/// Version 39 replaces the initializer flag with a process phase. +#[test] +fn native_program_image_rejects_v38_before_decoding_process_kinds() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&38u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(38)) + )); +} + /// Version 38 adds host operand value kinds to the runtime metadata. #[test] fn native_program_image_rejects_v37_before_decoding_host_operand_value_kinds() { diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs index c642322ee11..bef605a10ed 100644 --- a/crates/celox/tests/sv_vcd.rs +++ b/crates/celox/tests/sv_vcd.rs @@ -681,8 +681,8 @@ fn scoped_parameter_dump_does_not_select_imported_state() { } #[test] -fn direct_fatal_errors_publish_waveform_without_freezing_recovery() { - for action in ["eval_comb", "try_dump"] { +fn direct_fatal_errors_publish_waveform_and_terminate() { + for action in ["eval_comb", "try_dump", "dump"] { check_direct_fatal_waveform(action); } } @@ -701,9 +701,10 @@ fn check_direct_fatal_waveform(action: &str) { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("direct-fatal.vcd"); let source = format!( - r#"module Top(input logic fail_now, output logic value); - initial begin $dumpfile("{}"); $dumpvars(0,Top.value); end + r#"module Top(input logic fail_now, output logic value, output int final_calls); + initial begin final_calls=0; $dumpfile("{}"); $dumpvars(0,Top.value); end always_comb begin value=fail_now; if(fail_now) $fatal(1,"direct primary"); end + final final_calls += 1; endmodule"#, path.display() ); @@ -716,6 +717,13 @@ fn check_direct_fatal_waveform(action: &str) { let error = match action { "eval_comb" => format!("{:?}", simulation.eval_comb().unwrap_err()), "try_dump" => format!("{:?}", simulation.try_dump(0).unwrap_err()), + "dump" => { + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + simulation.dump(0); + })) + .unwrap_err(); + *panic.downcast::().unwrap() + } "run_until" => format!("{:?}", simulation.run_until(1).unwrap_err()), "run_until_bounded" => format!("{:?}", simulation.run_until_bounded(1, 10).unwrap_err()), _ => unreachable!(), @@ -723,11 +731,17 @@ fn check_direct_fatal_waveform(action: &str) { assert!(error.contains("direct primary"), "{action}: {error}"); let text = std::fs::read_to_string(path).unwrap(); assert!(text.contains("1!"), "{action}: {text}"); + // $fatal implicitly calls $finish (20.10), including when lazy + // combinational evaluation was triggered by a waveform API. + assert!(simulation.is_finished(), "{action}"); + let final_calls = simulation.signal("final_calls"); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); simulation.modify(|io| io.set(fail, 0u8)).unwrap(); simulation.eval_comb().unwrap(); let value = simulation.signal("value"); - assert_eq!(simulation.get(value), 0u8.into()); - assert!(!simulation.is_finished()); + assert_eq!(simulation.get(value), 1u8.into(), "{action}"); + simulation.finish().unwrap(); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); } #[test] diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index e33f385b835..541cfe4ae39 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -113,6 +113,8 @@ mod edges; mod file_core; #[path = "frontends/systemverilog/file_io.rs"] mod file_io; +#[path = "frontends/systemverilog/final.rs"] +mod final_procedures; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchical_references.rs"] diff --git a/crates/celox/tests/test_utils/veryl_sim.rs b/crates/celox/tests/test_utils/veryl_sim.rs index e19773cfad0..ed3eb9010ea 100644 --- a/crates/celox/tests/test_utils/veryl_sim.rs +++ b/crates/celox/tests/test_utils/veryl_sim.rs @@ -148,7 +148,7 @@ fn take_runtime_error() -> Result<(), RuntimeErrorCode> { if is_non_progressing_loop_diagnostic(&message) { Err(RuntimeErrorCode::DetectedTrueLoop) } else { - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message, signals: Vec::new(), }) diff --git a/crates/celox/tests/veryl_reference_adapter.rs b/crates/celox/tests/veryl_reference_adapter.rs index 2955afbbce7..af26db3177d 100644 --- a/crates/celox/tests/veryl_reference_adapter.rs +++ b/crates/celox/tests/veryl_reference_adapter.rs @@ -87,7 +87,7 @@ fn empty_modify_still_reports_initial_fatal_diagnostics() { let mut sim = build_veryl_adapter(&[(code, Path::new("test.veryl"))], "Top", false); assert_eq!( sim.modify(|_| {}).unwrap_err(), - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal from empty modify".to_string(), signals: Vec::new(), }, diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ced3e927699..a3972e2dd6c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -188,7 +188,7 @@ it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). - Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. -- Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), +- Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), @@ -594,6 +594,28 @@ simulation is suspended (`CheckpointError::Stopped`). In an `always` process, `$ Its diagnostic level argument prints nothing. Batch hosts without an interactive mode, such as the VPI host, end the run at `$stop`. +### Final procedures {#final-procedures} + +`final` procedures require `Simulation`. They run once, sequentially at the +termination time, on `$finish`, `$fatal` or an explicit `Simulation::finish()` +call (IEEE 1800-2023 9.2.3, 20.10). Their relative order is deterministic but +unspecified. The CLI and sv-tests batch driver finish when scheduled work runs +out. An idle `step()` or the end of `run_until()` does not terminate the reusable +Rust simulation; a host can supply more inputs or call `finish()`. + +Ordinary `$stop` does not run final procedures. A `$stop` inside a final +procedure suspends finalization, and a later step or `finish()` resumes it. +`$finish` inside a final procedure immediately ends that procedure and skips +all remaining finals. The original `$fatal` error is preserved when it starts +termination. + +No scheduled HDL events run after final procedures. In particular, a +nonblocking assignment made directly in a final procedure never applies its +queued update. Timing controls and calls to user tasks are rejected, including +through functions. Calls to functions that schedule events after returning +require an initial/always process context and are rejected from final +procedures (13.4.4). `fork` / `join_none` remains unsupported. + ### Programs {#programs} A `program` (IEEE 1800-2023 Clause 24) is declared and instantiated like a @@ -621,8 +643,8 @@ so a program that resumes after `#0` reads their new values, whereas 4.5 evaluates them only once the reactive region set is empty; programs nested in modules and anonymous programs are rejected; a program that no module instantiates is not an implicit top level next to the design's top -module; `final` procedures and clocking blocks are unsupported in programs as -everywhere. +module; clocking blocks are unsupported. Program `final` procedures run during +termination, including the implicit `$finish` after the last initial procedure. ### `$exit` diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 952eb064d73..f148c3826f0 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -55,12 +55,12 @@ compilation unit; choose the top by its SystemVerilog module name. | What your test needs | API | | --- | --- | | Set inputs, evaluate logic and advance clock events from Rust | `Simulator::from_sv_sources` | -| Advance simulation time and run `initial` and `always` processes with timing controls | `Simulation::from_sv_sources` | +| Advance simulation time, run timed processes and execute `final` procedures | `Simulation::from_sv_sources` | | Include both Veryl and SystemVerilog sources | `Simulator::from_mixed_sources` | `Simulator::tick` drives the rising edge of the selected event. `Simulation` tracks time and runs scheduled edges. Constant initialization applies to both. -`initial` blocks that read design state or call system tasks, processes with +`final` procedures, `initial` blocks that read design state or call system tasks, processes with timing controls and `always` blocks whose sensitivity list is neither `@*` nor [the variables they read](./systemverilog-reference#timing-controls) run as processes and need `Simulation`. A `Simulator` runs no process, so building @@ -85,6 +85,7 @@ The main supported areas are: | Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | | Simulation helpers | Immediate and deferred immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | +| Termination | `final` procedures on `$finish`, `$fatal` or explicit `Simulation::finish()`; see [termination semantics](./systemverilog-reference#final-procedures) | Each area has restrictions. Use the [detailed support list](./systemverilog-reference#what-is-supported) to check