From 304f4ac3d531b073a168a2025ceb55a7f353c5bc Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:41:43 +0900 Subject: [PATCH 1/3] feat(sv)!: support $stop and $exit $stop in a process kernel suspends the simulation (IEEE 1800-2023 20.2): the process returns with the new Stop status, the scheduler settles combinational logic, saves the round in progress and returns with is_stopped() set. The next step continues that round after the $stop, so edges made before it still trigger their domains. Checkpoints and state files are refused while suspended. Outside a kernel, $stop is reported as RuntimeEvent::Stop, as $finish is reported as Finish. Batch hosts end the run at it. $exit is ignored: Celox has no program blocks, and 24.7 ignores a call from outside one. BREAKING CHANGE: RuntimeEvent, RuntimeEventKind, ProcessStatus, Halt and CheckpointError gain a Stop/Stopped variant. Change-Id: Ia7467b814439b7542423436ce48b87e1a2d0597f --- crates/celox-design/src/lib.rs | 8 + crates/celox-frontend-core/src/process.rs | 6 + .../src/symbolic/assembly.rs | 10 +- crates/celox-frontend-sv/src/lowering/comb.rs | 17 +- crates/celox-frontend-sv/src/lowering/ff.rs | 23 ++- .../src/lowering/procedural.rs | 15 +- .../src/lowering/logic_tree/effect.rs | 17 +- crates/celox-napi/src/lib.rs | 16 +- crates/celox-runtime/src/derived_tick.rs | 6 +- crates/celox-runtime/src/simulation/mod.rs | 33 +++- .../celox-runtime/src/simulation/persist.rs | 4 + .../celox-runtime/src/simulation/process.rs | 45 ++++- crates/celox-runtime/src/simulation/round.rs | 32 ++- crates/celox-runtime/src/simulation/time.rs | 23 ++- crates/celox-runtime/src/timing.rs | 3 + .../celox-sv-analyzer/src/system_functions.rs | 12 +- crates/celox-vpi/src/lib.rs | 4 +- crates/celox/examples/sv_tests.rs | 6 +- .../celox/src/backend/native/runtime_image.rs | 3 +- crates/celox/src/simulation.rs | 29 ++- crates/celox/src/simulator.rs | 23 ++- crates/celox/src/simulator/checkpoint.rs | 7 + crates/celox/src/testbench.rs | 3 +- .../systemverilog/system_functions.rs | 185 ++++++++++++++++-- docs/guide/systemverilog.md | 17 +- docs/ja/guide/systemverilog.md | 13 +- packages/celox/src/napi-helpers.ts | 3 + packages/celox/src/simulation.ts | 10 + packages/celox/src/types.ts | 2 + 29 files changed, 502 insertions(+), 73 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 21bb5cc0f63..2982ce71c1d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -67,6 +67,8 @@ pub enum RuntimeEventKind { AssertFatal, /// `$finish` executed by the design (IEEE 1800-2023 20.2). Finish, + /// `$stop` executed by the design (IEEE 1800-2023 20.2). + Stop, } /// How a runtime event site sizes its formatted arguments. @@ -244,6 +246,10 @@ pub enum ProcessStatus { /// The process returned so the runtime can charge its time-slot budget. /// It resumes at once. Yield, + /// The process suspended the simulation (`$stop`, IEEE 1800-2023 20.2). + /// It resumes at the point stored in [`ProcessSlots::resume`] when the + /// simulation continues. + Stop, } impl ProcessStatus { @@ -259,6 +265,7 @@ impl ProcessStatus { Self::Pending => 6, Self::Nba => 7, Self::Yield => 8, + Self::Stop => 9, } } @@ -272,6 +279,7 @@ impl ProcessStatus { 6 => Some(Self::Pending), 7 => Some(Self::Nba), 8 => Some(Self::Yield), + 9 => Some(Self::Stop), _ => None, } } diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 8b7b42e9480..dde70afe4f0 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -156,6 +156,12 @@ impl ProcessKernelBuilder { self.suspend(ProcessStatus::Yield) } + /// Suspend the simulation (`$stop`), and continue at a new resume point + /// when it continues. + pub fn stop(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Stop) + } + /// Suspend at wait site `site` of this process. The open block /// afterwards is the site's resume point: the caller lowers the wait's /// condition there and ends it with [`Self::wake_if`]. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 2c7e800be86..a4742149e02 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2976,7 +2976,10 @@ fn build_comb_observer_capture_paths( }; let emit_on_true = matches!( sites[observer.site_id as usize].kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ); let fatal_error_code = matches!( sites[observer.site_id as usize].kind, @@ -3029,7 +3032,10 @@ fn build_comb_observer_capture_paths( let member = &observers[member_idx]; let member_emit_on_true = matches!( sites[member.site_id as usize].kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ); let member_fatal_error_code = matches!( sites[member.site_id as usize].kind, diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index bb8fdea1ce8..a6a2b8cfbe7 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1916,6 +1916,12 @@ impl<'p, 'a> Comb<'p, 'a> { self.readmem(&mut store, frames, *format, args)?; Ok(store) } + // IEEE 1800-2023 24.7: `$exit` outside a program block is + // ignored. + sv::ir::Stmt::SystemTask { + task: sv::ir::SystemTask::Exit, + .. + } => Ok(store), sv::ir::Stmt::SystemTask { task, .. } if self.initial => Err(unsupported(format!( "system task `{task}` inside an initial block" ))), @@ -3152,7 +3158,7 @@ impl<'p, 'a> Comb<'p, 'a> { } let event_kind = match &kind { SystemTaskKind::Print(kind, _) => *kind, - SystemTaskKind::Finish => RuntimeEventKind::Finish, + SystemTaskKind::Control(kind) => *kind, SystemTaskKind::Message => RuntimeEventKind::AssertContinue, SystemTaskKind::Fatal => RuntimeEventKind::AssertFatal, SystemTaskKind::Assertion(kind) => *kind, @@ -3169,8 +3175,8 @@ impl<'p, 'a> Comb<'p, 'a> { }) } else { match (&kind, condition) { - (SystemTaskKind::Print(..) | SystemTaskKind::Finish, None) => None, - (SystemTaskKind::Print(..) | SystemTaskKind::Finish, Some((node, sources))) => { + (SystemTaskKind::Print(..) | SystemTaskKind::Control(_), None) => None, + (SystemTaskKind::Print(..) | SystemTaskKind::Control(_), Some((node, sources))) => { observed.extend(sources); Some(node) } @@ -3199,7 +3205,10 @@ impl<'p, 'a> Comb<'p, 'a> { effects.push(SLTForEffect::Event { site_id, guard, - emit_on_true: matches!(kind, SystemTaskKind::Print(..) | SystemTaskKind::Finish), + emit_on_true: matches!( + kind, + SystemTaskKind::Print(..) | SystemTaskKind::Control(_) + ), args: captured.clone(), fatal_error_code: kind.is_fatal().then_some(i64::from(site_id)), }); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 90d3adfda0d..1e727f1ea7d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1974,13 +1974,26 @@ impl<'p, 'a> Ff<'p, 'a> { } return Ok(true); } + // IEEE 1800-2023 24.7: `$exit` outside a program block is ignored. + if task == sv::ir::SystemTask::Exit { + return Ok(true); + } let kind = system_task_kind(task).ok_or_else(|| unsupported(format!("system task `{task}`")))?; // A process ends the simulation itself; the rest of its body does not - // run. - if matches!(kind, SystemTaskKind::Finish) && self.kernel.is_some() { - self.with_kernel(ProcessKernelBuilder::finish); - return Ok(false); + // run. A stop suspends the process with the simulation, which then + // continues after the call. + match kind { + SystemTaskKind::Control(RuntimeEventKind::Finish) if self.kernel.is_some() => { + self.with_kernel(ProcessKernelBuilder::finish); + return Ok(false); + } + SystemTaskKind::Control(RuntimeEventKind::Stop) if self.kernel.is_some() => { + self.with_kernel(ProcessKernelBuilder::stop) + .map_err(|error| unsupported(error.to_string()))?; + return Ok(true); + } + _ => {} } let assertion = if matches!(kind, SystemTaskKind::Assertion(_)) { let Some(sv::ir::SystemTaskArg::Expr(condition)) = args.first() else { @@ -2042,7 +2055,7 @@ impl<'p, 'a> Ff<'p, 'a> { }; let event_kind = match &kind { SystemTaskKind::Print(kind, _) => *kind, - SystemTaskKind::Finish => RuntimeEventKind::Finish, + SystemTaskKind::Control(kind) => *kind, SystemTaskKind::Message => RuntimeEventKind::AssertContinue, SystemTaskKind::Fatal => RuntimeEventKind::AssertFatal, SystemTaskKind::Assertion(kind) => *kind, diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 9f5131bc10a..b87fd7840c6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -790,8 +790,8 @@ pub(super) enum SystemTaskKind { /// `$display` and `$write`, with the radix of their `b`, `o` and `h` /// variants (`d` otherwise). Print(RuntimeEventKind, char), - /// `$finish`. - Finish, + /// `$finish` and `$stop`, with their event kind. + Control(RuntimeEventKind), /// `$error`, `$warning`, `$info`: a message, then execution continues. Message, /// `$fatal`: a message, then the simulation ends with an error. @@ -811,8 +811,8 @@ impl SystemTaskKind { } /// How a task reports, for the tasks that report: `$readmemh`/`$readmemb` -/// load memory instead, and the analyzer rewrites `$printtimescale` into a -/// `$display`. +/// load memory instead, the analyzer rewrites `$printtimescale` into a +/// `$display`, and `$exit` outside a program block does nothing. pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option { use sv::ir::SystemTask; Some(match task { @@ -820,12 +820,13 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()), - SystemTask::Finish => SystemTaskKind::Finish, + SystemTask::Finish => SystemTaskKind::Control(RuntimeEventKind::Finish), + SystemTask::Stop => SystemTaskKind::Control(RuntimeEventKind::Stop), SystemTask::Severity(_) => SystemTaskKind::Message, SystemTask::Fatal => SystemTaskKind::Fatal, SystemTask::Assert => SystemTaskKind::Assertion(RuntimeEventKind::AssertFatal), SystemTask::AssertContinue => SystemTaskKind::Assertion(RuntimeEventKind::AssertContinue), - SystemTask::Readmem(_) | SystemTask::Printtimescale => return None, + SystemTask::Readmem(_) | SystemTask::Printtimescale | SystemTask::Exit => return None, }) } @@ -863,7 +864,7 @@ pub(super) fn system_task_template( &args[1..] } SystemTaskKind::Assertion(_) => &args[1..], - SystemTaskKind::Finish => &[][..], + SystemTaskKind::Control(_) => &[][..], _ => args, }; let (mut template, values) = match args.first() { diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 24eaf85c9b0..07c99954f25 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -208,7 +208,10 @@ fn collect_system_function_effect( observed_inputs.extend(collector.active_guard_sources.iter().copied()); let guard = match (kind, collector.active_guard, explicit_guard) { ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop, active, None, ) => active, @@ -227,11 +230,14 @@ fn collect_system_function_effect( Some(active) } ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop, _, Some(_), ) => { - unreachable!("display/write/finish has no explicit guard") + unreachable!("display/write/finish/stop has no explicit guard") } } .map(|node| -> Result { @@ -249,7 +255,10 @@ fn collect_system_function_effect( guard, emit_on_true: matches!( kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ), args: observer_args.clone(), fatal_error_code: matches!(kind, RuntimeEventKind::AssertFatal) diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index e2d8ccccfc3..a07a0fcd5b0 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -957,8 +957,9 @@ impl HandleBackend { ) .map_or_else( |halt| match halt { - // A bare backend reports no `$finish`; settle next time. - celox::Halt::Finish => Ok(false), + // A bare backend reports no `$finish` or `$stop`; settle + // next time. + celox::Halt::Finish | celox::Halt::Stop => Ok(false), celox::Halt::Error(error) => Err(error), }, |outcome| { @@ -2097,6 +2098,17 @@ impl NativeSimulationHandle { Ok(sim.is_finished()) } + /// Returns whether the last step or run returned early because a process + /// of the design executed `$stop`. The next step continues it. + #[napi] + pub fn is_stopped(&self) -> Result { + let sim = self + .sim + .as_ref() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + Ok(sim.is_stopped()) + } + /// Evaluate combinational logic. #[napi] pub fn eval_comb(&mut self) -> Result<()> { diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 0de446ccf89..902b8ccaf08 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -496,9 +496,9 @@ impl DerivedTickPlan { } }; match result { - // An RTL `$finish` ends only a timed simulation, which does not - // tick; a tick leaves it to the host. - Ok(_) | Err(Halt::Finish) => Ok(()), + // An RTL `$finish` or `$stop` ends or suspends only a timed + // simulation, which does not tick; a tick leaves it to the host. + Ok(_) | Err(Halt::Finish | Halt::Stop) => Ok(()), Err(Halt::Error(error)) => Err(error), } } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 9638d412749..1e9708c0f61 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -27,7 +27,7 @@ use crate::{ SimulatorErrorCode, backend::SimBackend, schedule::ResolvedSchedule, - scheduler::Scheduler, + scheduler::{Scheduler, SimEvent}, timing::{Halt, ProcessState}, }; @@ -73,6 +73,13 @@ impl std::fmt::Debug for EventInfo { } } +/// A round suspended by `$stop` in its process phase: the round and the +/// scheduled events it processes, whose periodic clocks re-arm at its end. +struct Suspended { + round: Box, + events: Vec>, +} + /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, @@ -86,6 +93,10 @@ pub struct SimulationState { host_pending: bool, /// A process requested the end of the simulation. finished: bool, + /// A process suspended the simulation (`$stop`) in the last step. + stopped: bool, + /// The round a `$stop` suspended, which the next step continues. + suspended: Option>, /// Buffers of the round in progress, kept between rounds. scratch: Option>, /// Rounds and process-phase passes one time slot may run, and kernel @@ -135,6 +146,8 @@ impl SimulationState { process_state, host_pending: false, finished: false, + stopped: false, + suspended: None, scratch: None, round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, @@ -164,6 +177,7 @@ impl SimulationState { where E: SimulationExecutor, { + self.stopped = false; match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { @@ -172,6 +186,8 @@ impl SimulationState { self.finish(executor); Ok(Some(self.scheduler.time)) } + // The time slot goes on when the simulation continues. + Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => Err(error), } } @@ -190,6 +206,20 @@ impl SimulationState { self.finished } + /// Whether the last step returned because a process suspended the + /// simulation with `$stop` (IEEE 1800-2023 20.2). The simulation is + /// suspended in the middle of a time slot, and the next step continues it + /// after the `$stop`. + pub fn is_stopped(&self) -> bool { + self.stopped + } + + /// 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() + } + /// Settle externally driven state against the previous edge baseline even /// when no clock/reset signal is explicitly scheduled at this timestamp. pub fn settle_at( @@ -211,6 +241,7 @@ impl SimulationState { self.finish(executor); Ok(Some(self.scheduler.time)) } + Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => Err(error), } } diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 667c327ee9e..3006c553a39 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -58,6 +58,8 @@ impl SimulationState { self.process_state.clone_from(&snapshot.process_state); self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; + self.stopped = false; + self.suspended = None; Ok(()) } } @@ -168,6 +170,8 @@ impl SimulationState { self.process_state = parts.process_state; self.host_pending = parts.host_pending; self.finished = parts.finished; + self.stopped = false; + self.suspended = None; } } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index dab60b77349..2fcc709482f 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -59,6 +59,13 @@ impl SimulationState { self.charge(*returns, Some(process))?; return Ok(true); } + // The process continues after the `$stop`, first, when the + // simulation does. + Some(ProcessStatus::Stop) => { + self.stopped = true; + self.process_state.ready.insert(process); + return Err(Halt::Stop); + } Some(ProcessStatus::Yield) => { *returns += 1; self.charge(*returns, Some(process))?; @@ -88,10 +95,14 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); while let Some(process) = self.process_state.ready.pop_first() { loop { - let again = self.run_process(executor, current_time, process, returns)?; + let again = self.run_process(executor, current_time, process, returns); // Each run is a separate update of the event signals, so a - // pulse across two runs is an edge. - self.record_transitions(executor.backend(), round); + // pulse across two runs is an edge. A stop keeps those of its + // run for the rest of the round. + if matches!(again, Ok(_) | Err(Halt::Stop)) { + self.record_transitions(executor.backend(), round); + } + let again = again?; // Before the next run, its edges must be seen. After the last // one, the check following the settle sees them: a settle // does not write what processes write. @@ -106,6 +117,18 @@ impl SimulationState { Ok(true) } + /// Mark the edges the processes of a pass caused and settle them. + fn settle_pass(&mut self, executor: &mut E, round: &mut Round) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let transitions = std::mem::take(&mut round.transitions); + self.mark_scheduled_edges(executor.backend_mut(), round, &transitions); + round.transitions = transitions; + round.transitions.clear(); + self.settle_marked(executor, round) + } + /// The process phase of a round: the active and inactive regions before /// any domain publishes (IEEE 1800-2023 4.5). Without ready processes, /// waits or counted signals this is one settle, the batch step's. @@ -127,14 +150,18 @@ impl SimulationState { // and see the state settled at the previous time. The event // signals they change are edges of this time, like scheduled // events. - let ran = self.run_ready(executor, current_time, round, &mut returns)?; + let ran = match self.run_ready(executor, current_time, round, &mut returns) { + // The host sees the state settled at the stop. + Err(Halt::Stop) => { + round.kernels_ran = true; + self.settle_pass(executor, round)?; + return Err(Halt::Stop); + } + ran => ran?, + }; round.kernels_ran |= ran; if first || ran { - let transitions = std::mem::take(&mut round.transitions); - self.mark_scheduled_edges(executor.backend_mut(), round, &transitions); - round.transitions = transitions; - round.transitions.clear(); - self.settle_marked(executor, round)?; + self.settle_pass(executor, round)?; first = false; } if entry { diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 87dc735b9d6..e30bb87f56e 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -6,7 +6,7 @@ use bit_set::BitSet; use super::host::SimulationExecutor; use super::nba::{restore_working_image, working_image}; -use super::{EventInfo, SimulationState, event_level}; +use super::{EventInfo, SimulationState, Suspended, event_level}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -354,7 +354,6 @@ impl SimulationState { self.observe_host_write(signal, &value); } - let num_events = executor.backend().num_events(); for (index, event) in events_to_process.iter().enumerate() { let signal = event.signal; let value = event.next_val; @@ -402,8 +401,35 @@ impl SimulationState { // The check after the batch already saw every signal. let entry = entry && events_to_process.is_empty(); - self.process_phase(executor, current_time, &mut round, entry)?; + self.continue_round(executor, current_time, round, events_to_process, entry) + } + /// The rest of a round from its process phase. A `$stop` there suspends + /// the round, and the next step continues it here. + pub(super) fn continue_round( + &mut self, + executor: &mut E, + current_time: u64, + mut round: Box, + events_to_process: Vec>, + entry: bool, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + match self.process_phase(executor, current_time, &mut round, entry) { + Ok(()) => {} + Err(Halt::Stop) => { + self.suspended = Some(Suspended { + round, + events: events_to_process, + }); + return Err(Halt::Stop); + } + Err(halt) => return Err(halt), + } + + let num_events = executor.backend().num_events(); let mut triggered_domains = BitSet::with_capacity(num_events); let mut discovered_in_this_step = BitSet::with_capacity(num_events); let mut comb_already_done = false; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 960660b5b0e..4245098f1cf 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -89,6 +89,19 @@ impl SimulationState { where E: SimulationExecutor, { + // A suspended time slot continues where the `$stop` left it. + if let Some(suspended) = self.suspended.take() { + let current_time = self.scheduler.time; + self.continue_round( + executor, + current_time, + suspended.round, + suspended.events, + false, + )?; + self.end_time(executor, current_time)?; + return Ok(Some(current_time)); + } let mut settled = None; loop { let Some(current_time) = self.next_event_time() else { @@ -100,7 +113,7 @@ impl SimulationState { // Host writes alone: settle them, then go on to the next time. let host_only = self.host_pending && self.next_work_time() != Some(current_time); self.run_time(executor, current_time)?; - if !host_only { + if !host_only || self.stopped { return Ok(Some(current_time)); } settled = Some(current_time); @@ -125,6 +138,14 @@ impl SimulationState { }; let ready = self.take_ready_processes(current_time); self.step_round(executor, current_time, events_to_process, ready, true)?; + self.end_time(executor, current_time) + } + + /// The rounds of time slot `current_time` after its first. + fn end_time(&mut self, executor: &mut E, current_time: u64) -> Result<(), Halt> + where + E: SimulationExecutor, + { // A process that waited for zero time, or that the round woke, // resumes in a later round of this time, after the previous round's // edges have been handled. diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 4318bd6211f..c0da3a86a8c 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -21,6 +21,9 @@ use crate::{SignalRef, SimulatorErrorCode, backend::SimBackend}; pub enum Halt { /// `$finish`: the simulation ends where it is (IEEE 1800-2023 20.2). Finish, + /// `$stop`: the simulation is suspended where it is (IEEE 1800-2023 + /// 20.2), and continues there with the next step. + Stop, Error(SimulatorErrorCode), } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 1eade455720..59269ec1ba2 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -167,6 +167,12 @@ impl fmt::Display for SystemFunction { pub enum SystemTask { /// `$finish` (20.2). Finish, + /// `$stop` (20.2). + Stop, + /// `$exit` (20.2, 24.7), which ends the initial procedures of the + /// program block that calls it. Celox has no program blocks, and a call + /// from outside one is ignored. + Exit, /// `$printtimescale` (20.4.1); the analyzer rewrites it into a /// [`SystemTask::Display`] of the message. Printtimescale, @@ -239,6 +245,8 @@ impl SystemTask { use Radix::{Binary, Decimal, Hexadecimal, Octal}; match self { Self::Finish => "$finish", + Self::Stop => "$stop", + Self::Exit => "$exit", Self::Printtimescale => "$printtimescale", Self::Fatal => "$fatal", Self::Severity(Severity::Error) => "$error", @@ -435,8 +443,8 @@ const fn function(function: SystemFunction, min_args: usize, max_args: Option callbacks::request_finish(), + // Like `vpiStop` in `vpi_control`, `$stop` ends a run that has + // no interactive mode. + RuntimeEvent::Finish | RuntimeEvent::Stop => callbacks::request_finish(), RuntimeEvent::Missed { count } => { let _ = writeln!( std::io::stderr().lock(), diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index 95eb29dc429..9681e8ce05e 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -202,7 +202,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { .unwrap_or_else(|_| message.escape_ascii().to_string()) )); } - celox::RuntimeEvent::Finish => {} + celox::RuntimeEvent::Finish | celox::RuntimeEvent::Stop => {} celox::RuntimeEvent::Missed { count } => { return Err(format!("{count} runtime events were lost")); } @@ -215,7 +215,9 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { while !sim.is_finished() { let step = sim.step().map_err(|error| error.to_string()); output(&mut sim)?; - if step?.is_none() { + // A batch run has no interactive mode to suspend into, so it ends at + // `$stop`, as `vvp -n` does. + if step?.is_none() || sim.is_stopped() { break; } } diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7dfdf72d48e..c22fc1f196b 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -452,7 +452,8 @@ impl NativeProgramInstance { RuntimeEvent::Display { .. } | RuntimeEvent::Write { .. } | RuntimeEvent::AssertContinue { .. } - | RuntimeEvent::Finish => None, + | RuntimeEvent::Finish + | RuntimeEvent::Stop => None, }) { return Err(celox_runtime::SimulatorErrorCode::Runtime { message, diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4a877e70f4d..88b008f47b3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -242,6 +242,9 @@ impl Simulation { /// Save the design state, simulation time, clocks and pending events. pub fn checkpoint(&self) -> Result, CheckpointError> { + if self.state.is_suspended() { + return Err(CheckpointError::Stopped); + } Ok(SimulationCheckpoint { simulator: self.simulator.checkpoint()?, schedule: self.state.snapshot(), @@ -252,6 +255,9 @@ impl Simulation { /// Save the value of every state object by path, together with the /// simulation time, clocks and pending events by name. pub fn save_state(&mut self) -> Result { + if self.state.is_suspended() { + return Err(CheckpointError::Stopped.into()); + } let mut file = self.simulator.save_state()?; // Settling for the file may have executed a `$finish`. self.sync_finish(); @@ -407,6 +413,9 @@ impl Simulation { /// Advance time and run until `end_time` (inclusive). /// Targets earlier than the current time leave time and state unchanged. + /// A process that executes `$stop` returns control early, after the time + /// slot of the stop, with [`Self::is_stopped`] set; calling this again + /// continues. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { if end_time < self.state.time() { // Time only moves forward. Moving the timestamp back while the @@ -419,6 +428,9 @@ impl Simulation { break; } self.step_until(end_time)?; + if self.state.is_stopped() { + return Ok(()); + } } if self.state.is_finished() { return Ok(()); @@ -430,7 +442,8 @@ impl Simulation { /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, - /// when another step would be needed to reach `end_time`. + /// when another step would be needed to reach `end_time`, including when + /// a step stopped at `$stop`. pub fn run_until_bounded( &mut self, end_time: u64, @@ -449,9 +462,12 @@ impl Simulation { } self.step_until(end_time)?; steps += 1; + if self.state.is_stopped() { + return Ok(false); + } } self.run_until(end_time)?; - Ok(true) + Ok(!self.state.is_stopped()) } /// Whether a process of the design requested the end of the simulation. @@ -461,6 +477,15 @@ impl Simulation { self.state.is_finished() } + /// Whether the last [`Self::step`] or [`Self::run_until`] returned early + /// because a process of the design executed `$stop` (IEEE 1800-2023 + /// 20.2). The simulation is suspended in the middle of that time; the + /// next step continues it after the `$stop`. Checkpoints and state files + /// cannot be taken while it is suspended. + pub fn is_stopped(&self) -> bool { + self.state.is_stopped() + } + /// Returns the current simulation time. pub fn time(&self) -> u64 { self.state.time() diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 67f4b713b58..bc6a9a32ec4 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -167,6 +167,9 @@ mod host { }, /// The design executed `$finish`. The host decides whether to stop. Finish, + /// The design executed `$stop` outside a process kernel. The host + /// decides whether to suspend. + Stop, Missed { count: u64, }, @@ -361,14 +364,18 @@ mod host { let Some(template) = site.template.as_deref() else { let default_spec = match site.kind { // Veryl prints arguments without a format string in hexadecimal. - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop if site.sizing == DisplaySizing::Veryl => { 'x' } - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish => { - 'd' - } + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop => 'd', RuntimeEventKind::AssertContinue | RuntimeEventKind::AssertFatal => { if args.is_empty() { return b"assertion failed".to_vec(); @@ -467,6 +474,7 @@ mod host { RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, RuntimeEventKind::Finish => RuntimeEvent::Finish, + RuntimeEventKind::Stop => RuntimeEvent::Stop, }) } } @@ -1518,9 +1526,10 @@ mod host { } } Ok(celox_runtime::EdgeOutcome::Settled) => self.dirty = false, - // An RTL `$finish` ends only a timed simulation; an edge, as a - // tick, leaves it to the host. What ran may not have settled. - Err(celox_runtime::Halt::Finish) => self.dirty = true, + // An RTL `$finish` or `$stop` ends or suspends only a timed + // simulation; an edge, as a tick, leaves it to the host. What + // ran may not have settled. + Err(celox_runtime::Halt::Finish | celox_runtime::Halt::Stop) => self.dirty = true, Err(celox_runtime::Halt::Error(error)) => return Err(error), } Ok(()) diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index e766ce119df..b9c681a0a46 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -132,6 +132,13 @@ pub enum CheckpointError { switch to a new VCD file first" )] VcdRewind { time: u64, last_dumped: u64 }, + /// A `$stop` suspended the simulation in the middle of a time slot, + /// whose progress a checkpoint does not capture. + #[error( + "the simulation is suspended at `$stop` in the middle of a time step; \ + continue it before taking a checkpoint" + )] + Stopped, } impl Simulator { diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 6ba13234cba..91e1a4c4daf 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1482,7 +1482,8 @@ fn drain_runtime_assertions( } RuntimeEvent::Display { message } => forward_display(&message, true), RuntimeEvent::Write { message } => forward_display(&message, false), - RuntimeEvent::Finish => finished = true, + // The testbench has no interactive mode to suspend into. + RuntimeEvent::Finish | RuntimeEvent::Stop => finished = true, } } DrainedAssertionEvents { diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 24e485fbba5..9db62d543e1 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1250,16 +1250,7 @@ fn readmem_diagnostics_identify_task_and_requested_range() { } #[test] -fn rejects_stop_and_deferred_cover_instead_of_discarding_their_semantics() { - for body in [ - "initial $stop;", - "always_comb begin $stop(0); y = 0; end", - "always_ff @(posedge clk) begin $stop; y <= 0; end", - "function automatic int f(); $stop; return 1; endfunction initial y = f();", - ] { - let source = format!("module Top(input logic clk, output logic y); {body} endmodule"); - assert!(build_error(&source).contains("system task `$stop`")); - } +fn rejects_deferred_cover_instead_of_discarding_its_semantics() { for timing in ["#0", "final"] { let source = format!("module Top(output logic y); initial cover {timing} (1) y = 1; endmodule"); @@ -1267,6 +1258,176 @@ fn rejects_stop_and_deferred_cover_instead_of_discarding_their_semantics() { } } +/// IEEE 1800-2023 20.2: `$stop` suspends the simulation, and continuing it +/// resumes after the call, including inside loops and functions. The other +/// processes of the round wait for the simulation to continue. +#[test] +fn stop_suspends_the_simulation_until_it_continues() { + let source = r#" + module Top(input int rounds, output int count, other, sum); + int acc; + function automatic int bump(input int x); + $stop; + return x + 1; + endfunction + initial begin + count = 1; + $stop; + count = 2; + acc = 10; + for (int i = 0; i < rounds; i++) begin + if (i != 1) $stop(0); + count = count + 1; + acc = acc + i; + end + count = bump(count); + $display("done %0d %0d", count, acc); + end + // Reading an input keeps this block a process instead of initial + // state. + initial other = rounds + 2; + assign sum = count + other; + endmodule + "#; + let mut sim = initial_simulation(source); + let rounds = sim.signal("rounds"); + sim.modify(|io| io.set(rounds, 3u8)).unwrap(); + let (count, other, sum) = (sim.signal("count"), sim.signal("other"), sim.signal("sum")); + for expected in [1u8, 2, 4, 5] { + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(sim.is_stopped()); + assert_eq!(sim.get(count), expected.into()); + assert_eq!(sim.get(other), 0u8.into()); + assert_eq!(sim.get(sum), expected.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // A suspended time step cannot be captured. + assert!(matches!( + sim.checkpoint(), + Err(celox::CheckpointError::Stopped) + )); + } + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(!sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!(sim.get(count), 6u8.into()); + assert_eq!(sim.get(other), 5u8.into()); + assert_eq!(sim.get(sum), 11u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"done 6 13".to_vec(), + }], + ); + assert_eq!(sim.step().unwrap(), None); + assert!(sim.checkpoint().is_ok()); + + // `run_until` returns at the stop, before reaching its target time, and + // continues when called again. + let mut sim = initial_simulation(source); + let rounds = sim.signal("rounds"); + sim.modify(|io| io.set(rounds, 3u8)).unwrap(); + for expected in [1u8, 2, 4, 5] { + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(count), expected.into()); + } + sim.run_until(10).unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(sim.time(), 10); + assert_eq!(sim.get(count), 6u8.into()); + assert_eq!(sim.get(other), 5u8.into()); +} + +/// The time step a `$stop` suspends continues where it stopped: an edge a +/// process made before the stop triggers its domain after the rest of the +/// process has run. +#[test] +fn stop_keeps_the_edges_of_its_time_step() { + let source = r#" + module Top(input int start, output logic clk, output int q); + always_ff @(posedge clk) q <= q + 1; + initial begin + clk = start[0]; + clk = 1; + $stop; + $display("q=%0d", q); + end + endmodule + "#; + let mut sim = initial_simulation(source); + let q = sim.signal("q"); + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(sim.is_stopped()); + assert_eq!(sim.get(q), 0u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(!sim.is_stopped()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"q=0".to_vec(), + }], + ); + assert_eq!(sim.get(q), 1u8.into()); +} + +/// Outside a process kernel, `$stop` is reported to the host like `$finish`. +#[test] +fn stop_in_a_clocked_or_combinational_process_is_an_event() { + let source = r#" + module Top(input logic clk, enabled, output logic y); + always_ff @(posedge clk) if (enabled) $stop; + always_comb begin + if (enabled) $stop(2); + y = enabled; + end + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("stop.sv"))], "Top") + .build_cranelift() + .unwrap(); + sim.drain_runtime_events(); + sim.tick(sim.event("clk")).unwrap(); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + let enabled = sim.signal("enabled"); + sim.modify(|io| io.set(enabled, 1u8)).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![celox::RuntimeEvent::Stop]); + sim.tick(sim.event("clk")).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![celox::RuntimeEvent::Stop]); +} + +/// IEEE 1800-2023 24.7: `$exit` outside a program block is ignored. +#[test] +fn exit_outside_a_program_block_is_ignored() { + let source = r#" + module Top(input logic clk, output int a, b); + initial begin + a = 1; + $exit; + a = 2; + $exit(); + a = 3; + end + always_ff @(posedge clk) begin + $exit; + b <= b + 1; + end + endmodule + "#; + let mut sim = initial_simulation(source); + sim.run_until(0).unwrap(); + assert!(!sim.is_finished()); + assert!(!sim.is_stopped()); + assert_eq!(sim.get(sim.signal("a")), 3u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + let error = + build_error("module Top(output logic y); initial $exit(1); assign y = 0; endmodule"); + assert!( + error.contains("$exit") && error.contains("expected 0 arguments"), + "{error}" + ); +} + #[test] fn rejects_unknown_system_functions_in_every_context() { let cases = [ @@ -1360,8 +1521,8 @@ fn reports_where_a_known_system_function_is_not_supported() { endmodule", ), ( - "system task `$stop`", - "module Top(output logic y); initial $stop; assign y = 0; endmodule", + "system task `$dumpvars`", + "module Top(output logic y); initial $dumpvars; assign y = 0; endmodule", ), ( "system task `$stacktrace`", diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 963940f0c26..a274a65d2a6 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -86,7 +86,7 @@ synthesis and is tested at the design level. | Parameters | integral parameters, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range` and `$random` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | -| System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | +| System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -304,8 +304,19 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / - **System functions called as statements**, such as `$countones(f(a));`, are checked and evaluated like the same call in an expression, and their value is discarded. `$bits` and `$size` do not evaluate their operand. -- **Simulation suspension** (`$stop`) is rejected explicitly. The host API does - not provide suspended-process continuation; `$finish` remains supported. +- **Simulation suspension.** `$stop` in an `initial` block suspends the + simulation (IEEE 1800-2023 20.2): `Simulation::step` and `run_until` return + at the time of the stop with `is_stopped()` set, the other processes of that + time wait, and the next call continues after the `$stop`, also inside loops + and functions. The suspended time step keeps the edges the process made + before the stop. A checkpoint or state file cannot be taken while the + simulation is suspended (`CheckpointError::Stopped`). In an `always` process, `$stop` is reported as + `RuntimeEvent::Stop`, as `$finish` is reported as `RuntimeEvent::Finish`. + Its diagnostic level argument prints nothing. Batch hosts without an + interactive mode, such as the VPI host, end the run at `$stop`. +- **`$exit`** ends the initial procedures of the program block that calls it + (24.7). Celox has no program blocks, and a call from anywhere else is + ignored, as 24.7 specifies. - **Immediate cover** executes its pass statement when the condition is true. Coverage counters and reports are not exposed. Deferred cover (`#0` / `final`) is rejected because its scheduling is not modeled. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 52d84f87476..0fd535c3463 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -72,7 +72,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | パラメータ | 整数のパラメータと、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | -| システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | +| システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -241,3 +241,14 @@ Icarus Verilog などそれを実装するシミュレータと同じ値を返 `$random(seed)` はシード変数を更新します。引数がなければプロセスごとのシードを 使い、その初期値は0です。そのため `$random` を呼ぶプロセスが1つだけの設計では、 設計全体で1つのシードを持つシミュレータと一致します。 + +`initial` ブロックの `$stop` はシミュレーションを一時停止します(IEEE 1800-2023 20.2)。 +`Simulation::step` と `run_until` は停止した時刻で戻り、`is_stopped()` が真になります。 +その時刻の他のプロセスは待機し、次の呼び出しでループや関数の中も含めて `$stop` の +直後から再開します。停止した時刻の処理は、停止前にプロセスが起こしたエッジも保ったまま +再開します。停止中はチェックポイントと状態ファイルを作れません(`CheckpointError::Stopped`)。 +`always` 系のプロセスでは、`$finish` が `RuntimeEvent::Finish` に +なるのと同様に `RuntimeEvent::Stop` として報告します。診断レベルの引数では何も +表示しません。VPI ホストのように対話モードを持たないバッチ実行では `$stop` で終了します。 +`$exit` は呼び出した program ブロックの initial 手続きを終了します(24.7)。 +Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視します。 diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 05a36935464..0dea70c46d1 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -52,6 +52,8 @@ export interface RawNapiSimulationHandle { nextEventTime(): number | null; /** Whether a process requested the end of the simulation. */ isFinished?(): boolean; + /** Whether the last step or run returned early at `$stop`. */ + isStopped?(): boolean; evalComb(): void; dump(timestamp: number): void; sharedMemory(): Uint8Array; @@ -912,6 +914,7 @@ export function wrapDirectSimulationHandle( : {}), ...(raw.clockPeriods ? { clockPeriods: () => raw.clockPeriods!() } : {}), ...(raw.isFinished ? { isFinished: () => raw.isFinished!() } : {}), + ...(raw.isStopped ? { isStopped: () => raw.isStopped!() } : {}), }; } diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index f575986cd10..454a9e31565 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -514,6 +514,16 @@ export class Simulation

> { return this._handle.isFinished?.() ?? false; } + /** + * Whether the last `step()` or `runUntil()` returned early because a + * process of the design executed `$stop`. The next call continues the + * simulation after the `$stop`. + */ + isStopped(): boolean { + this.ensureAlive(); + return this._handle.isStopped?.() ?? false; + } + /** * Step until `condition()` returns true. * diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index c5f3c9e58ad..0440dc99017 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -245,6 +245,8 @@ export interface NativeSimulationHandle { nextEventTime(): number | null; /** Whether a process requested the end of the simulation. */ isFinished?(): boolean; + /** Whether the last step or run returned early at `$stop`. */ + isStopped?(): boolean; evalComb(): void; dump(timestamp: number): void; dispose(): void; From aa048d54891241a3adac53d2ceecdadfb3828e7e Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:44:17 +0900 Subject: [PATCH 2/3] test(sv-tests): accept the $stop and $exit results --- conformance/sv-tests/expected.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index df1c18dab94..c24b1699178 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -345,9 +345,9 @@ chapter-20/20.15--dist_poisson.sv fail chapter-20/20.15--dist_t.sv fail chapter-20/20.15--dist_uniform.sv fail chapter-20/20.15--random.sv pass -chapter-20/20.2--exit.sv fail +chapter-20/20.2--exit.sv pass chapter-20/20.2--finish.sv pass -chapter-20/20.2--stop.sv fail +chapter-20/20.2--stop.sv pass chapter-20/20.3--realtime.sv fail chapter-20/20.3--stime.sv fail chapter-20/20.3--time.sv fail From b78b0f51986ffbd6fa8ce5012af45dde3a136251 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 07:34:41 +0900 Subject: [PATCH 3/3] feat(sv): support generate-block imports of types and subroutines that differ from the module's Closes #1206. A generate block that imports a type or subroutine under a name the module binds to another declaration was rejected, because types, constant functions and subroutine metadata were looked up module-wide by the plain name. This gives the generate scope its own view of those tables instead. - `Scope` and `Item` record the names the block's imports bind (`imports`, filled by `bind_import`). `BlockImports` keeps the ones an inner declaration has not hidden again, and derives from them: - the type aliases the block sees: a name the blocks declare or import hides the module's type of that name, and an imported `t` denotes `p::t`'s type; - the installed constant-function table, with `f` aliased to `p::f`, or hidden when the block's `f` is no constant function (a DPI-C import). Calls in the bodies of the functions it hides are renamed to the outer binding, so a module function still calls the `f` it was declared with. - The elaborator evaluates a block's declarations, conditions and nested blocks with that view, and resolves a generate condition's call to the qualified declaration ahead of a module function of the same name. - `Item::dimensions` carries the block's type aliases (casts, `$bits(t)`), next to the function, formal-name and shape aliases it already had. The signal, process, instance, function and subroutine collectors use the item's type aliases and install its constant functions. - The two "imports as another declaration than its module" rejections are removed. - `resolve_imports` also records a block import of the declaration the module sees when a block around it imports another declaration or declares the name, so the inner block no longer inherits the outer binding. This was already wrong for values since #1184. - As a result, a generate-local declaration such as `localparam T` now also hides a module typedef `T`, so `T n;` under it is rejected instead of taking the outer type (IEEE 1800-2023 23.9). Validation: - `cargo fmt --all -- --check` - `cargo clippy -p celox-sv-analyzer -p celox-frontend-sv -p celox --all-targets --features celox/systemverilog,celox/sv-dpi --no-deps` - `cargo test -p celox-sv-analyzer -p celox-frontend-sv` - `cargo test -p celox --features systemverilog,sv-dpi` (11465 passed, 0 failed) New regressions: `generate_block_imports_bind_their_own_subroutines`, `generate_block_imports_bind_their_own_types`, `nested_generate_block_imports_restore_the_module_binding` and `generate_block_declarations_hide_outer_types` in `sv_packages.rs`, and `generate_block_imports_bind_their_own_dpi_formals` and `generate_block_dpi_imports_hide_outer_constant_functions` in `sv_dpi.rs`. Every case also uses the name outside the block, so the block-local binding is taken rather than the module-wide alias for names only blocks use. Unrelated defects found while testing are filed as #1435, #1436, #1437, #1438 and #1461. Change-Id: Ic706ae8c0a61ae10d0a6e8afa53fc99b83d759d2 --- .../celox-sv-analyzer/src/ast/comb_process.rs | 1 + .../src/ast/const_functions.rs | 4 + .../celox-sv-analyzer/src/ast/declarations.rs | 3 +- .../celox-sv-analyzer/src/ast/ff_process.rs | 1 + crates/celox-sv-analyzer/src/ast/functions.rs | 6 +- crates/celox-sv-analyzer/src/ast/generate.rs | 161 ++++++- crates/celox-sv-analyzer/src/ast/imports.rs | 48 +- crates/celox-sv-analyzer/src/ast/instances.rs | 1 + .../celox-sv-analyzer/src/ast/procedural.rs | 10 +- .../celox-sv-analyzer/src/ast/validation.rs | 1 + crates/celox/tests/sv_dpi.rs | 57 +++ crates/celox/tests/sv_packages.rs | 413 +++++++++++++++++- 12 files changed, 648 insertions(+), 58 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 029cb3bd6a4..dd47a03bb69 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -38,6 +38,7 @@ pub(super) fn comb_processes_from_module_node( if !relevant { continue; } + let _constant_functions = item.enter(); let start = processes.len(); let (dimensions, literals) = views.get(item); comb_processes_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 71898334e11..d418d39f8ba 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -170,6 +170,10 @@ impl ConstantFunctions { .retain(|name, _| keep(name)); } + pub(super) fn contains(&self, name: &str) -> bool { + self.functions.contains_key(name) || self.errors.by_name.contains_key(name) + } + /// Make the function `target` callable as `name` too. pub(super) fn alias(&mut self, name: &str, target: &str) { if let Some(function) = self.functions.get(target).cloned() { diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index bacb218b1c7..3207f979d8f 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -430,11 +430,12 @@ pub(super) fn signals_from_module_node( } ScopeItem::Package(_) => continue, }; + let _constant_functions = item.enter(); let start = signals.len(); signals_from_module_or_generate_item( node, syntax_tree, - type_aliases, + &item.type_aliases(type_aliases), &item.env, None, &mut signals, diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 5c2fec12880..bfda9f3e1be 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -28,6 +28,7 @@ pub(super) fn ff_processes_from_module_node( ) { continue; } + let _constant_functions = item.enter(); let start = processes.len(); let (dimensions, literals) = views.get(item); ff_processes_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index aa8abe5b5b6..8911eb6a048 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -9,14 +9,16 @@ pub(super) fn functions_from_module_node( packed_dimensions: &PackedDimensions, ) -> Result, AnalyzerError> { let mut functions = HashMap::default(); - let type_aliases = + let module_type_aliases = type_aliases_from_module_node_with_env(node.clone(), syntax_tree, const_env)?; - let active = generate::items(node.clone(), syntax_tree, const_env, &type_aliases)?; + let active = generate::items(node.clone(), syntax_tree, const_env, &module_type_aliases)?; let mut views = generate::ScopeViews::new(packed_dimensions); for (item, child) in active .iter() .flat_map(|item| item.node.node().into_iter().map(move |child| (item, child))) { + let _constant_functions = item.enter(); + let type_aliases = item.type_aliases(&module_type_aliases); if let RefNode::TaskDeclaration(declaration) = child { let task_dimensions = views.dimensions(item); let const_env = &item.env; diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 1f451d23239..14e23e21a24 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -53,11 +53,111 @@ pub(super) struct Item<'a> { pub literals: SharedMap, parameter_dimensions: Arc, names: SharedMap, + imports: SharedMap, shadowed: Arc>, scope: String, } +/// The names the imports of the enclosing generate blocks bind to another +/// declaration than the module does (see `imports::resolve_imports`), unless +/// a declaration of an inner block hides them again. The module-wide tables +/// hold those declarations under their qualified names. +#[derive(Clone, Copy)] +struct BlockImports<'s> { + names: &'s HashMap, + imports: &'s HashMap, + /// The names the blocks declare or import. + shadowed: &'s HashSet, +} + +impl<'s> BlockImports<'s> { + fn bindings(self) -> impl Iterator { + self.imports + .iter() + .filter(move |(name, target)| self.names.get(*name) == Some(*target)) + } + + /// The type aliases visible here: a name the blocks declare or import + /// hides the module's type of that name, and an imported name denotes + /// the type of its declaration. + fn type_aliases<'m>( + self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + let mut visible = Cow::Borrowed(aliases); + let hidden: Vec<&String> = if aliases.len() <= self.shadowed.len() { + aliases + .keys() + .filter(|name| self.shadowed.contains(*name)) + .collect() + } else { + self.shadowed + .iter() + .filter(|name| aliases.contains_key(*name)) + .collect() + }; + for name in hidden { + visible.to_mut().remove(name); + } + for (name, target) in self.bindings() { + if let Some(r#type) = aliases.get(target) { + visible.to_mut().insert(name.clone(), r#type.clone()); + } + } + visible + } + + /// Make each imported name call the constant function of its + /// declaration, until the guard is dropped; a name that imports no + /// constant function calls none. Calls in the bodies of the functions it + /// hides keep their definition-site meaning. + fn install_constant_functions(self) -> Option { + let installed = const_functions::installed(); + let rebound: Vec<_> = self + .bindings() + .filter(|(name, target)| installed.contains(name) || installed.contains(target)) + .collect(); + if rebound.is_empty() { + return None; + } + let hidden: HashMap = rebound + .iter() + .filter(|(name, _)| installed.contains(name)) + .map(|(name, _)| ((*name).clone(), format!("{OUTER_BINDING}{name}"))) + .collect(); + let rename = scope::Renamer { names: &hidden }; + let mut visible = + installed.renamed(&mut |name| rename.name(name), &mut |stmt| rename.stmt(stmt)); + for (name, target) in rebound { + visible.alias(name, target); + } + Some(const_functions::install(visible)) + } +} + impl Item<'_> { + fn block_imports(&self) -> BlockImports<'_> { + BlockImports { + names: &self.names, + imports: &self.imports, + shadowed: &self.shadowed, + } + } + + /// The type aliases this item sees, given the module's. + pub fn type_aliases<'m>( + &self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + self.block_imports().type_aliases(aliases) + } + + /// Make the constant functions this item sees the installed ones, until + /// the guard is dropped. + pub fn enter(&self) -> Option { + self.block_imports().install_constant_functions() + } + pub fn common(&self) -> Option<&sv_parser::ModuleCommonItem> { match self.node { ScopeItem::Module(sv_parser::ModuleOrGenerateItem::ModuleItem(item)) => { @@ -140,6 +240,9 @@ impl Item<'_> { self.function_aliases(dimensions.function_return_types.clone()); } } + if let Cow::Owned(aliases) = self.type_aliases(&dimensions.type_aliases) { + local.type_aliases = aliases; + } let mut signedness = dimensions.expression_signedness.clone(); for name in self.shadowed.iter() { let protected = format!("{OUTER_BINDING}{name}"); @@ -340,12 +443,25 @@ struct Scope { parameters: Vec, parameter_dimensions: Arc, names: SharedMap, + imports: SharedMap, shadowed: Arc>, } +impl Scope { + fn block_imports(&self) -> BlockImports<'_> { + BlockImports { + names: &self.names, + imports: &self.imports, + shadowed: &self.shadowed, + } + } +} + struct Elaborator<'a, 'b> { tree: &'a SyntaxTree, - aliases: &'b HashMap, + module_aliases: &'b HashMap, + /// The type aliases of the scope being elaborated. + aliases: Cow<'b, HashMap>, remaining: usize, functions: HashMap, items: Vec>, @@ -397,7 +513,8 @@ fn items_with_literal_use<'a>( ) -> Result>, AnalyzerError> { let mut elaborator = Elaborator { tree, - aliases, + module_aliases: aliases, + aliases: Cow::Borrowed(aliases), remaining: MAX_GENERATE_LOOP_EXPANSION, functions: HashMap::default(), items: Vec::new(), @@ -541,7 +658,7 @@ impl<'a> Elaborator<'a, '_> { RefNode::ConstantExpression(expr), self.tree, &scope.env, - self.aliases, + &self.aliases, )? else { return Ok(None); @@ -565,6 +682,16 @@ impl<'a> Elaborator<'a, '_> { for arg in args { self.expand_constant_calls(arg, scope)?; } + // A block import binds the call to the qualified declaration, + // which the installed constant functions evaluate. + if let Callee::Subroutine(name) = callee + && let Some(target) = scope + .block_imports() + .bindings() + .find_map(|(imported, target)| (imported == name).then_some(target)) + { + *name = target.clone(); + } if let Callee::Subroutine(name) = callee && self.functions.contains_key(name) { @@ -908,6 +1035,7 @@ impl<'a> Elaborator<'a, '_> { literals: scope.literals.clone(), parameter_dimensions: scope.parameter_dimensions.clone(), names: scope.names.clone(), + imports: scope.imports.clone(), shadowed: scope.shadowed.clone(), scope: scope.path.clone(), }); @@ -1140,7 +1268,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, Some(&name), &mut signals, @@ -1200,7 +1328,7 @@ impl<'a> Elaborator<'a, '_> { &mut scope.parameters, true, &base, - self.aliases, + &self.aliases, &HashMap::default(), &mut environment, )?; @@ -1249,7 +1377,7 @@ impl<'a> Elaborator<'a, '_> { &mut scope.parameters, true, &scope.env, - self.aliases, + &self.aliases, &HashMap::default(), )?; let parameter = scope @@ -1327,6 +1455,22 @@ impl<'a> Elaborator<'a, '_> { bind_import(&mut scope, name, target); } } + // The declarations and nested blocks are elaborated with the types and + // constant functions those imports bind. + let _constant_functions = scope.block_imports().install_constant_functions(); + let aliases = scope.block_imports().type_aliases(self.module_aliases); + let outer = std::mem::replace(&mut self.aliases, aliases); + let elaborated = self.block_contents(children, scope, index); + self.aliases = outer; + elaborated + } + + fn block_contents( + &mut self, + children: Vec<&'a sv_parser::GenerateItem>, + mut scope: Scope, + index: Option<(&str, i128)>, + ) -> Result<(), AnalyzerError> { // Bind all declarations before lowering expressions, including forward references. let mut declared = HashSet::default(); if let Some((genvar, value)) = index { @@ -1352,7 +1496,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, None, &mut signals, @@ -1404,7 +1548,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_module_or_generate_item( item, self.tree, - self.aliases, + &self.aliases, &scope.env, None, &mut signals, @@ -1450,6 +1594,7 @@ fn bind_import(scope: &mut Scope, name: &str, target: &str) { let imported = scope::imported(); Arc::make_mut(&mut scope.shadowed).insert(name.to_string()); scope.names.insert(name.to_string(), target.to_string()); + scope.imports.insert(name.to_string(), target.to_string()); // The constant value and type markers of the item, under the name. let names = |key: &str| -> Option { if key == target { diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index ce221725316..57b8a8a69ae 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -1271,9 +1271,9 @@ pub(super) fn resolve_imports( } // A name the generate blocks import is a name of the whole module when // nothing else gives it a meaning; otherwise each block that imports - // another declaration names it there. + // another declaration than the one visible around it names it there. let mut generate_imports: HashMap> = HashMap::default(); - for (name, uses) in scoped { + for (name, mut uses) in scoped { let outside = bindings .iter() .find(|binding| binding.name == name) @@ -1296,34 +1296,30 @@ pub(super) fn resolve_imports( }); continue; } - for (block, target) in uses { - if outside.as_ref() == Some(&target) { + uses.sort_unstable(); + uses.dedup(); + // A block around `block` that imports another declaration, or + // declares the name, hides the module's binding there. + let encloses = + |scope: &GenerateScope, block: usize| scope.start < block && scope.contains(block); + let hidden = |block: usize, target: &String| { + uses.iter().any(|(outer, other)| { + other != target + && all_scopes + .iter() + .any(|scope| scope.start == *outer && encloses(scope, block)) + }) || all_scopes + .iter() + .any(|scope| scope.declared.contains(&name) && encloses(scope, block)) + }; + for (block, target) in &uses { + if outside.as_ref() == Some(target) && !hidden(*block, target) { continue; } - // Types, and the formal names and shapes of subroutines, are - // looked up module-wide. - if symbols.type_aliases.contains_key(&target) { - return Err(AnalyzerError::Unsupported(format!( - "type `{name}` that a generate block imports as another declaration than \ - its module" - ))); - } - if symbols.subroutine_params.contains_key(&target) - || symbols.functions.contains_key(&target) - || symbols - .dpi_imports - .iter() - .any(|import| import.name() == target.as_str()) - { - return Err(AnalyzerError::Unsupported(format!( - "subroutine `{name}` that a generate block imports as another declaration \ - than its module" - ))); - } generate_imports - .entry(block) + .entry(*block) .or_default() - .insert(name.clone(), target); + .insert(name.clone(), target.clone()); } } symbols.generate_imports = generate_imports; diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 143c9a56b82..aa2d08409df 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -20,6 +20,7 @@ pub(super) fn instances_from_module_node( if !matches!(node, sv_parser::ModuleOrGenerateItem::Module(_)) { continue; } + let _constant_functions = item.enter(); let start = instances.len(); let dimensions = views.dimensions(item); instances_from_module_or_generate_item( diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 5961e9ffe82..c51fd75dc29 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1673,12 +1673,13 @@ pub(super) fn subroutine_argument_names( let Some(syntax) = syntax else { continue; }; + let _constant_functions = item.enter(); let params = subroutine_param_declarations( syntax.ports, syntax.items, tree, &item.env, - type_aliases, + &item.type_aliases(type_aliases), )?; let qualified = item.name(&syntax.name); let param_shapes: Vec = params @@ -1754,9 +1755,9 @@ pub(super) fn subroutines_with_symbolic_parameters( mut rejected: Option<&mut HashMap>, symbolic_parameters: &HashSet, ) -> Result, AnalyzerError> { - let type_aliases = packed_dimensions.type_aliases.clone(); + let module_type_aliases = &packed_dimensions.type_aliases; let mut subroutines = Vec::new(); - let active = generate::subroutine_items(node, tree, const_env, &type_aliases)?; + let active = generate::subroutine_items(node, tree, const_env, module_type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for item in &active { if item.is_parameter_declaration() { @@ -1796,6 +1797,8 @@ pub(super) fn subroutines_with_symbolic_parameters( ) }; + let _constant_functions = item.enter(); + let type_aliases = item.type_aliases(module_type_aliases); let name = syntax.name.clone(); let lowered = (|| -> Result { let params = subroutine_param_declarations( @@ -2000,6 +2003,7 @@ pub(super) fn initial_processes_from_module_node( if item.is_parameter_declaration() { continue; } + let _constant_functions = item.enter(); let mut assignments = Vec::new(); match item.node.declaration() { Some(sv_parser::PackageOrGenerateItemDeclaration::DataDeclaration(data)) => { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 7111b507008..10bdcdf8c7e 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -789,6 +789,7 @@ fn reject_silently_ignored_constructs_with_dimensions( let active = generate::items(node, syntax_tree, const_env, type_aliases)?; let mut views = generate::ScopeViews::new(indexed_dimensions); for item in &active { + let _constant_functions = item.enter(); let dimensions = views.dimensions(item); reject_silently_ignored_constructs_with_dimensions( item.node.node(), diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index ee6af3f67ef..f8c5bb8baf4 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -178,6 +178,35 @@ dpi_backends! { } } + // A generate block can import another declaration than its module + // (#1206): named arguments bind to the formals of the block's import. + fn generate_block_imports_bind_their_own_dpi_formals(sim) { + @build unsafe { + builder(r#" + package p; + import "DPI-C" digits = function int f(input int first, input int second); + endpackage + package q; + import "DPI-C" digits = function int f(input int second, input int first); + endpackage + module Top(input logic clk, input int a, b, output int block_result, module_result); + import q::*; + if (1) begin : g + import p::*; + always_ff @(posedge clk) block_result <= f(.first(a), .second(b)); + end + always_ff @(posedge clk) module_result <= f(.first(a), .second(b)); + endmodule + "#).dpi_function("digits", dpi_digits as *const ()) + }; + let clk = sim.event("clk"); + let (a, b) = (sim.signal("a"), sim.signal("b")); + sim.modify(|io| { io.set(a, 3u32); io.set(b, 4u32); }).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(sim.signal("block_result")), BigUint::from(34u32)); + assert_eq!(sim.get(sim.signal("module_result")), BigUint::from(43u32)); + } + fn int_function_in_nonblocking_assignment(sim) { @build unsafe { builder(r#" @@ -580,6 +609,34 @@ fn imports_of_one_c_name_must_share_a_prototype() { ); } +/// A generate block that imports a DPI-C function hides a constant function of +/// the same name from the module, so a constant expression of the block +/// cannot call either (#1206). +#[test] +fn generate_block_dpi_imports_hide_outer_constant_functions() { + for outer in [ + "function automatic int f(int a); return 99; endfunction", + "import q::*;", + ] { + let source = format!( + r#"package p; import "DPI-C" function int f(input int a); endpackage + package q; function automatic int f(int a); return 99; endfunction endpackage + module Top(output int y); + {outer} + int a; + if (1) begin : g + import p::*; + localparam int Y = f(1); + assign a = Y; + end + assign y = a + f(0); + endmodule"# + ); + let error = build_error(&source); + assert!(error.contains("user constant function call"), "{error}"); + } +} + fn build_error(source: &str) -> String { match Simulator::from_sv_sources(vec![(source, Path::new("dpi.sv"))], "Top").build_cranelift() { Ok(_) => panic!("design unexpectedly compiled:\n{source}"), diff --git a/crates/celox/tests/sv_packages.rs b/crates/celox/tests/sv_packages.rs index 967d52e0574..4a0093a21ba 100644 --- a/crates/celox/tests/sv_packages.rs +++ b/crates/celox/tests/sv_packages.rs @@ -983,24 +983,6 @@ fn generate_block_imports_are_scoped_to_their_block() { ), 59 ); - // A subroutine the block imports as another one than its module is not - // supported: calls look up formal names and shapes module-wide. - let detail = Simulator::from_sv_sources( - vec![( - "package p; function automatic int f(int a); return a + 1; endfunction endpackage - package q; function automatic int f(int b); return b + 2; endfunction endpackage - module Top(output logic [7:0] y); import q::*; logic [7:0] a; - if (1) begin : g import p::*; assign a = f(4); end - assign y = a + f(0); - endmodule", - std::path::Path::new("packages.sv"), - )], - "Top", - ) - .build() - .expect_err("a block-local subroutine binding is unsupported") - .to_string(); - assert!(detail.contains("subroutine `f`"), "{detail}"); // A loop's genvar hides a wildcard import of its body. assert_eq!( output( @@ -1204,3 +1186,398 @@ fn generate_scopes_declare_loop_body_names_and_keep_inner_imports() { 3 ); } + +/// A generate block can import a type or subroutine that is another +/// declaration than the one its module sees under that name (#1206). +#[test] +fn generate_block_imports_bind_their_own_subroutines() { + // `f` takes its formals in another order in each package. + let functions = "package p; function automatic int f(int a, int b = 0); return a * 10 + b; endfunction + endpackage + package q; function automatic int f(int b, int a = 0); return b * 3 + a; endfunction + endpackage"; + let cases = [ + // Positional and named arguments, against the block's formals. + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f(4); end + assign y = a + f(1);", + 43, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f(.b(2), .a(1)); end + assign y = a + f(.a(1), .b(2));", + 19, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; always_comb a = f(.a(2)); end + assign y = a + f(0);", + 20, + ), + // Constant calls in declarations, selects, loop bounds and generate + // conditions of the block, and in the blocks inside it. + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = f(.b(2), .a(1)); assign a = Y; end + assign y = a + f(1);", + 15, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; logic [f(1)-1:0] v; assign a = $bits(v); end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; int n = f(1); assign a = n; end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [15:0] w; logic [7:0] a; assign w = 16'h0780; + if (1) begin : g import p::*; assign a = w[f(1) - 3 +: 4]; end + assign y = a + f(0);", + 15, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + always_comb begin a = 0; for (int i = 0; i < f(1); i++) a = a + 1; end + end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + function automatic int k(logic [f(1)-1:0] v); return $bits(v); endfunction + assign a = k(0); + end + assign y = a + f(0);", + 10, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + if (f(1) == 10) begin : h assign a = 1; end else begin : h assign a = 2; end + end + assign y = a + f(0);", + 1, + ), + ( + "import q::*; logic [7:0] a; + if (1) begin : g import p::*; + if (1) begin : h localparam int Y = f(1); assign a = Y + f(2); end + end + assign y = a + f(0);", + 30, + ), + ( + "import q::*; logic [7:0] a [2]; + for (genvar i = 0; i < 2; i++) begin : g import p::*; assign a[i] = f(i); end + assign y = a[0] + a[1] + f(0);", + 10, + ), + // The block's import comes before a function of the module. + ( + "function automatic int f(int a); return 99; endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = f(1); assign a = Y; end + assign y = a + f(0);", + 109, + ), + ( + "function automatic int f(int a); return 99; endfunction logic [7:0] a; + if (1) begin : g import p::*; + if (f(1) == 10) begin : h assign a = 1; end else begin : h assign a = 2; end + end + assign y = a + f(0);", + 100, + ), + // A function of the module still calls the declaration it sees. + ( + "import q::*; function automatic int k(int v); return f(v); endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = k(1); assign a = Y + k(2); end + assign y = a;", + 9, + ), + ( + "function automatic int f(int a); return 99; endfunction + function automatic int k(int v); return f(v); endfunction logic [7:0] a; + if (1) begin : g import p::*; localparam int Y = k(1); assign a = Y + f(1); end + assign y = a;", + 109, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{functions} + module Top(output logic [7:0] y); {body} endmodule" + )), + expected, + "{body}" + ); + } + // Assignment-pattern arguments take the shape of the block's formal. + assert_eq!( + output( + "package p; function automatic int f(int v[2]); return v[0] * 10 + v[1]; endfunction + endpackage + package q; function automatic int f(int v[3]); return v[0] + v[1] + v[2]; endfunction + endpackage + module Top(output logic [7:0] y); import q::*; logic [7:0] a; + if (1) begin : g import p::*; assign a = f('{1, 2}); end + assign y = a + f('{1, 1, 1}); + endmodule" + ), + 15 + ); + assert_eq!( + output( + "package p; task automatic t(output int o, input int a); o = a + 1; endtask endpackage + package q; task automatic t(input int a, output int o); o = a + 2; endtask endpackage + module Top(output logic [7:0] y); import q::*; int a, b; + if (1) begin : g import p::*; always_comb t(a, 4); end + always_comb t(4, b); + assign y = a * 10 + b; + endmodule" + ), + 56 + ); +} + +/// A generate block can import a type that is another declaration than the +/// one its module sees under that name (#1206). +#[test] +fn generate_block_imports_bind_their_own_types() { + let types = "package p; typedef logic [3:0] t; endpackage + package q; typedef logic [7:0] t; endpackage"; + // The module's `m` is a `q::t`. + let cases = [ + ( + "if (1) begin : g import p::*; t n; assign n = '1; assign a = n; end", + 15, + ), + ( + "if (1) begin : g import p::*; t n; initial n = 8'hff; assign a = n; end", + 15, + ), + ( + "if (1) begin : g import p::*; t n = 8'hff; assign a = $bits(n); end", + 4, + ), + ( + "if (1) begin : g import p::*; t n = 8'hff; assign a = n; end", + 15, + ), + // Casts and type queries. + ( + "if (1) begin : g import p::*; assign a = t'(8'hff) + $bits(t); end", + 19, + ), + // Declarations and generate conditions of the block. + ( + "if (1) begin : g import p::*; localparam t Z = '1; localparam int W = $bits(t); + assign a = Z + W; end", + 19, + ), + ( + "if (1) begin : g import p::*; t n; localparam int W = $bits(n); assign a = W; end", + 4, + ), + ( + "if (1) begin : g import p::*; logic [$bits(t)-1:0] v; assign a = $bits(v); end", + 4, + ), + ( + "if (1) begin : g import p::*; + if ($bits(t) == 4) begin : h assign a = 1; end else begin : h assign a = 2; end + end", + 1, + ), + ( + "if (1) begin : g import p::*; t n; + if ($bits(n) == 4) begin : h assign a = 1; end else begin : h assign a = 2; end + end", + 1, + ), + // Subroutines of the block. + ( + "if (1) begin : g import p::*; + function automatic t inc(t v); return v + 1; endfunction + assign a = inc(8'h1f); + end", + 0, + ), + ( + "if (1) begin : g import p::*; + function automatic int w(t v [2]); return v[0] + v[1] + $bits(v); endfunction + assign a = w('{8'hff, 8'h01}); + end", + 24, + ), + ( + "if (1) begin : g import p::*; + task automatic k(output t o); o = 8'hff; endtask + always_comb k(a); + end", + 15, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{types} + module Top(output logic [7:0] y); import q::*; logic [7:0] a; t m; + assign m = 8'hf0; {body} assign y = a + m - 8'hf0; + endmodule" + )), + expected, + "{body}" + ); + } + assert_eq!( + output( + "package p; typedef struct packed { logic [3:0] x; logic [3:0] z; } t; endpackage + package q; typedef struct packed { logic [7:0] x; } t; endpackage + module Top(output logic [7:0] y); import q::*; logic [7:0] a; t m; + if (1) begin : g import p::*; t n; assign n = t'{x: 4'h1, z: 4'h2}; assign a = n; + end + assign m = t'{x: 8'h30}; assign y = a + m.x; + endmodule" + ), + 0x42 + ); + // A block import of a value hides the module's type of that name. + let values = "package p; localparam int T = 3; endpackage + package q; typedef logic [7:0] T; endpackage"; + assert_eq!( + output(&format!( + "{values} + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; + if (1) begin : g import p::*; assign a = T; end + assign m = 8'h10; assign y = a + m; + endmodule" + )), + 0x13 + ); + let result = Simulator::from_sv_sources( + vec![( + format!( + "{values} + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; + if (1) begin : g import p::*; T n; assign n = 8'hff; assign a = n; end + assign m = 0; assign y = a + m; + endmodule" + ) + .as_str(), + std::path::Path::new("packages.sv"), + )], + "Top", + ) + .build(); + assert!(result.is_err(), "`T` is a parameter in block `g`"); +} + +/// A declaration of a generate block hides a type of that name around it, +/// whether the module declares or imports the type (IEEE 1800-2023 23.9). +#[test] +fn generate_block_declarations_hide_outer_types() { + let cases = [ + "package p; typedef logic [3:0] T; endpackage + package q; typedef logic [7:0] T; endpackage + module Top(output logic [7:0] y); import q::*; T m; logic [7:0] a; assign m = 0; + if (1) begin : g import p::*; T o; + if (1) begin : h localparam int T = 2; + if (1) begin : i T n; assign n = '1; assign a = n; end + end + end + assign y = a + m; + endmodule", + "module Top(output logic [7:0] y); typedef logic [7:0] T; logic [7:0] a; + if (1) begin : h localparam int T = 2; + if (1) begin : i T n; assign n = '1; assign a = n; end + end + assign y = a; + endmodule", + "module Top(output logic [7:0] y); typedef logic [7:0] T; logic [7:0] a; + if (1) begin : h logic T; T n; assign n = '1; assign a = n; end + assign y = a; + endmodule", + ]; + for source in cases { + let result = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("packages.sv"))], "Top") + .build(); + assert!(result.is_err(), "`T` is not a type in the block:\n{source}"); + } +} + +/// An inner block that imports the declaration its module sees still hides +/// the binding of a block around it, by import or by declaration. +#[test] +fn nested_generate_block_imports_restore_the_module_binding() { + let packages = "package p; localparam int X = 3; typedef logic [3:0] t; + function automatic int f(int a); return a + 1; endfunction endpackage + package q; localparam int X = 5; typedef logic [7:0] t; + function automatic int f(int a); return a + 2; endfunction endpackage"; + let cases = [ + ( + "logic [7:0] a, c; + if (1) begin : g import p::*; assign c = X; + if (1) begin : h import q::*; assign a = X; end + end + assign y = a * 10 + c + X;", + 58, + ), + ( + "logic [7:0] a; t m; assign m = 0; + if (1) begin : g import p::*; t o; + if (1) begin : h import q::*; t n; assign n = '1; assign a = n; end + end + assign y = a + m;", + 255, + ), + ( + "logic [7:0] a, c; + if (1) begin : g import p::*; assign c = f(0); + if (1) begin : h import q::*; localparam int Y = f(0); assign a = Y + f(10); end + end + assign y = a + c * 10 + f(0);", + 26, + ), + // The binding alternates down a chain of blocks. + ( + "logic [7:0] a, b, c; + if (1) begin : g import p::*; assign c = X; + if (1) begin : h import q::*; + if (1) begin : i import p::*; assign b = X; end + assign a = X; + end + end + assign y = a * 10 + b + X + c * 0;", + 58, + ), + ( + "logic [7:0] a; + if (1) begin : g localparam int X = 9; + if (1) begin : h import q::X; assign a = X; end + end + assign y = a + X;", + 10, + ), + ]; + for (body, expected) in cases { + assert_eq!( + output(&format!( + "{packages} + module Top(output logic [7:0] y); import q::*; {body} endmodule" + )), + expected, + "{body}" + ); + } +}