From 883befed556beb5f4e042388950ceec6cb79756f Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 19:41:37 +0900 Subject: [PATCH 1/3] feat(runtime)!: run program kernels in the reactive region set A kernel of a program instance names the status slot of the instance's first kernel (ProcessSlots::program). Such kernels start, wake and resume in the Reactive region, a #0 resumes them in the Re-Inactive region, and their nonblocking updates take effect in the Re-NBA region (IEEE 1800-2023 4.4.2.6-4.4.2.8, 24.3.1). The reactive region set runs once the active region set is empty and returns to the active region set for the design activity it creates (4.5). ProcessStatus::Exit ends every kernel of the calling program instance (24.7), and the implicit $finish fires once every program kernel has ended (24.3). Program kernels run on the reference scheduler. Designs without programs schedule as before. BREAKING CHANGE: ProcessSlots gains `program`, ProcessStatus gains `Exit`, ProcessState and ScheduleKey gain the reactive, re-inactive and Re-NBA queues, and the native image container format is now 35. Change-Id: I6c899de1f0d5e8ca722733a53655ee80e3c988b8 --- crates/celox-design/src/lib.rs | 13 ++ crates/celox-frontend-core/src/process.rs | 7 + crates/celox-frontend-core/src/sdk.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-runtime/src/schedule.rs | 9 ++ crates/celox-runtime/src/simulation/mod.rs | 2 +- crates/celox-runtime/src/simulation/nba.rs | 144 +++++++++++++----- .../celox-runtime/src/simulation/persist.rs | 6 + .../celox-runtime/src/simulation/process.rs | 113 ++++++++++++-- crates/celox-runtime/src/simulation/round.rs | 13 +- crates/celox-runtime/src/simulation/time.rs | 42 ++++- crates/celox-runtime/src/simulation/wait.rs | 40 ++++- crates/celox-runtime/src/timing.rs | 14 ++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 2 + crates/celox/src/simulator/state_file.rs | 1 + 16 files changed, 347 insertions(+), 63 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5e45cf13916..bdedcd2e93b 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -291,6 +291,9 @@ pub enum ProcessStatus { /// A synchronous host operation. The delay slot holds its family and /// local site index; the same process resumes after the host responds. HostRequest, + /// A program kernel called `$exit` (IEEE 1800-2023 24.7): it and every + /// other kernel of its program instance ([`ProcessSlots::program`]) end. + Exit, } impl ProcessStatus { @@ -308,6 +311,7 @@ impl ProcessStatus { Self::Yield => 8, Self::Stop => 9, Self::HostRequest => 10, + Self::Exit => 11, } } @@ -323,6 +327,7 @@ impl ProcessStatus { 8 => Some(Self::Yield), 9 => Some(Self::Stop), 10 => Some(Self::HostRequest), + 11 => Some(Self::Exit), _ => None, } } @@ -465,6 +470,12 @@ pub struct ProcessSlots { /// Every delay the kernel suspends for is a constant of at least one /// time unit. pub const_delays: bool, + /// For an `initial` procedure of a program instance (IEEE 1800-2023 + /// 24.3), the status slot of that instance's first such kernel, which + /// every kernel of the instance names: the kernel runs in the reactive + /// region set (24.3.1), and `$exit` and the end of the instance's + /// kernels act on them together (24.7). `None` for design code. + pub program: Option, pub resume: A, pub status: A, pub delay: A, @@ -476,6 +487,7 @@ impl ProcessSlots { is_initializer: self.is_initializer, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, + program: self.program.map(&mut map), resume: map(self.resume), status: map(self.status), delay: map(self.delay), @@ -1791,6 +1803,7 @@ mod tests { ProcessStatus::from_code(10), Some(ProcessStatus::HostRequest) ); + assert_eq!(ProcessStatus::from_code(11), Some(ProcessStatus::Exit)); } #[test] diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 1931a26203b..b141ad8d532 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -368,6 +368,13 @@ impl ProcessKernelBuilder { self.end(ProcessStatus::Finish); } + /// End the kernel and the other kernels of its program instance + /// (`$exit`, IEEE 1800-2023 24.7). No block is open afterwards. + pub fn exit(&mut self) { + self.wait_site = None; + self.end(ProcessStatus::Exit); + } + /// Complete the kernel. If a block is still open, the process ends there. pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f74172ab2a4..18232d0b2a4 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1732,6 +1732,7 @@ fn lower_processes( is_initializer: false, requires_timed_simulation: false, const_delays: false, + program: None, resume: lowering .hidden .declare(name("resume"), PROCESS_RESUME_WIDTH, false), diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 4b662c6bf0d..1a9cccf8986 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4451,6 +4451,7 @@ fn lower_initial_processes( is_initializer: process.is_initializer(), requires_timed_simulation: process.is_scheduled_edge(), const_delays: false, + program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index b9a0e39311b..7585cab6a7e 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -21,6 +21,8 @@ pub struct ResolvedSchedule { pub(crate) signal_to_id: FxHashMap, pub(crate) signal_index_by_id: Vec, pub(crate) processes: Vec, + /// The kernels of program instances, in declaration order. + pub(crate) program_processes: Vec, /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, @@ -190,6 +192,7 @@ impl ResolvedSchedule { .iter() .map(|process| ProcessRefs { is_initializer: process.slots.is_initializer, + program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, status: resolve(&process.slots.status), @@ -299,6 +302,12 @@ impl ResolvedSchedule { event_info, signal_to_id, signal_index_by_id, + program_processes: processes + .iter() + .enumerate() + .filter(|(_, process)| process.program.is_some()) + .map(|(index, _)| index) + .collect(), processes, counted, counted_by_offset, diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 7523e231da0..515b4cfb26e 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -454,7 +454,7 @@ impl SimulationState { E: SimulationExecutor, { self.slot_passes = 0; - match self.step_round(executor, time, Vec::new(), Vec::new(), true) { + match self.step_round(executor, time, Vec::new(), Vec::new(), true, false) { Ok(()) => { self.finish_timed_boundary(executor, time)?; Ok(Some(time)) diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index f2395e208c7..00b493f1180 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -32,7 +32,14 @@ impl SimulationState { let Some((lsb, width)) = refs.range(backend) else { return Ok(()); }; - self.process_state.nba_queue.push(NbaUpdate { + // A program process's update waits for the Re-NBA region (IEEE + // 1800-2023 24.3.1). + let queue = if self.model.processes[process].program.is_some() { + &mut self.process_state.re_nba_queue + } else { + &mut self.process_state.nba_queue + }; + queue.push(NbaUpdate { target: refs.target, lsb, width, @@ -57,6 +64,7 @@ impl SimulationState { self.model .processes .iter() + .filter(|process| process.program.is_none()) .flat_map(|process| &process.nba_sites) .filter_map(|site| site.pending) .filter(|&pending| backend.get_as::(pending) != 0) @@ -76,45 +84,12 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); round.transitions.clear(); } - for update in &queued { - let new = NbaValue::Queued(&update.value); - self.publish_update(executor.backend_mut(), update, new); - if several { - self.record_transitions(executor.backend(), round); - } - } + self.publish_queued(executor, round, &queued, several); // Keep the queue's storage for the next time slot. queued.clear(); self.process_state.nba_queue = queued; if flagged > 0 { - for process in 0..self.model.processes.len() { - for site in 0..self.model.processes[process].nba_sites.len() { - let backend = executor.backend_mut(); - let Some(pending) = self.model.processes[process].nba_sites[site].pending - else { - continue; - }; - if backend.get_as::(pending) == 0 { - continue; - } - backend.set(pending, 0u8); - let site = &self.model.processes[process].nba_sites[site]; - let Some((lsb, width)) = site.range(backend) else { - continue; - }; - let (target, value) = (site.target, site.value); - let update = NbaUpdate { - target, - lsb, - width, - value: Value::default(), - }; - self.publish_update(backend, &update, NbaValue::Staged(value)); - if several { - self.record_transitions(executor.backend(), round); - } - } - } + self.publish_flagged(executor, round, false, several); } if several { let transitions = std::mem::take(&mut round.transitions); @@ -126,6 +101,103 @@ impl SimulationState { true } + /// Publish the nonblocking assignments of program processes (the Re-NBA + /// region, IEEE 1800-2023 4.4.2.8): the queued ones in issue order, then + /// the flagged ones. Like the writes of a process run, each is recorded + /// in `round.transitions` for the caller to settle. Returns whether any + /// was published. + pub(super) fn publish_re_nba(&mut self, executor: &mut E, round: &mut Round) -> bool + where + E: SimulationExecutor, + { + let any_flagged = self.model.has_pending_nba_sites && { + let backend = executor.backend(); + self.model + .program_processes + .iter() + .flat_map(|&process| &self.model.processes[process].nba_sites) + .filter_map(|site| site.pending) + .any(|pending| backend.get_as::(pending) != 0) + }; + if self.process_state.re_nba_queue.is_empty() && !any_flagged { + return false; + } + self.event_values(executor.backend(), &mut round.before); + let mut queued = std::mem::take(&mut self.process_state.re_nba_queue); + self.publish_queued(executor, round, &queued, true); + // Keep the queue's storage for the next time slot. + queued.clear(); + self.process_state.re_nba_queue = queued; + if any_flagged { + self.publish_flagged(executor, round, true, true); + } + true + } + + /// Publish `queued` in issue order, recording the transitions of each in + /// `round.transitions` if `record`. + fn publish_queued( + &mut self, + executor: &mut E, + round: &mut Round, + queued: &[NbaUpdate], + record: bool, + ) where + E: SimulationExecutor, + { + for update in queued { + let new = NbaValue::Queued(&update.value); + self.publish_update(executor.backend_mut(), update, new); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + + /// Publish the flagged nonblocking sites of the program processes if + /// `program`, otherwise of the design's, in declaration order, recording + /// the transitions of each in `round.transitions` if `record`. + fn publish_flagged( + &mut self, + executor: &mut E, + round: &mut Round, + program: bool, + record: bool, + ) where + E: SimulationExecutor, + { + for process in 0..self.model.processes.len() { + if self.model.processes[process].program.is_some() != program { + continue; + } + for site in 0..self.model.processes[process].nba_sites.len() { + let backend = executor.backend_mut(); + let Some(pending) = self.model.processes[process].nba_sites[site].pending else { + continue; + }; + if backend.get_as::(pending) == 0 { + continue; + } + backend.set(pending, 0u8); + let site = &self.model.processes[process].nba_sites[site]; + let Some((lsb, width)) = site.range(backend) else { + continue; + }; + let (target, value) = (site.target, site.value); + let update = NbaUpdate { + target, + lsb, + width, + value: Value::default(), + }; + self.publish_update(backend, &update, NbaValue::Staged(value)); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + } + /// Write `update`, whose value is `new`, into its target. An update /// inside a target of at most 64 bits with one state plane is merged as /// `u64`; any other as [`Value`]. diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index a5a5525fc53..aa0a94ff8e9 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -293,6 +293,9 @@ impl SimulationState { ready: state.ready.iter().copied().collect(), inactive: state.inactive.iter().copied().collect(), nba_queue: state.nba_queue.clone(), + reactive: state.reactive.iter().copied().collect(), + re_inactive: state.re_inactive.iter().copied().collect(), + re_nba_queue: state.re_nba_queue.clone(), domain_counters: state.domain_counters.clone(), declarations_pending: self.declarations_pending, host_pending: self.host_pending, @@ -319,6 +322,9 @@ pub struct ScheduleKey { pub ready: Vec, pub inactive: Vec, pub nba_queue: Vec, + pub reactive: Vec, + pub re_inactive: Vec, + pub re_nba_queue: Vec, pub domain_counters: Vec<[u32; 3]>, pub declarations_pending: bool, pub host_pending: bool, diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 3faece18b35..bc74b2729d8 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -1,12 +1,19 @@ //! The process phase of a round: running ready kernels and filing them //! where they resume. +use std::collections::BTreeSet; + use celox_design::{HostRequestKind, ProcessStatus}; use super::SimulationState; use super::host::SimulationExecutor; use super::round::Round; -use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; +use super::wait::wake_in_region; +use crate::{ + SimulatorErrorCode, + backend::SimBackend, + timing::{Halt, ProcessState}, +}; impl SimulationState { /// Execute static declaration initializers before any ordinary process, @@ -132,13 +139,25 @@ impl SimulationState { } Some(ProcessStatus::InactiveDelay) => { let delay = delay(); - if delay == 0 { - self.process_state.inactive.insert(process); - } else { + if delay != 0 { self.wake_after(current_time, delay, process)?; + } else if self.model.processes[process].program.is_some() { + // A program process resumes in the Re-Inactive + // region (IEEE 1800-2023 4.4.2.7). + self.process_state.re_inactive.insert(process); + } else { + self.process_state.inactive.insert(process); + } + } + Some(ProcessStatus::Done) => { + if self.model.processes[process].program.is_some() { + self.program_kernel_ended(executor.backend())?; } } - Some(ProcessStatus::Done) => {} + Some(ProcessStatus::Exit) => { + self.exit_program(executor.backend_mut(), process)?; + self.program_kernel_ended(executor.backend())?; + } Some(ProcessStatus::Finish) => return Err(Halt::Finish), Some(ProcessStatus::Wait | ProcessStatus::Pending) => { let site = delay() as usize; @@ -169,7 +188,10 @@ impl SimulationState { // simulation does. Some(ProcessStatus::Stop) => { self.stopped = true; - self.process_state.ready.insert(process); + let ProcessState { + ready, reactive, .. + } = &mut self.process_state; + wake_in_region(&self.model.processes, ready, reactive, process); return Err(Halt::Stop); } Some(ProcessStatus::Yield) => { @@ -195,17 +217,18 @@ impl SimulationState { where E: SimulationExecutor, { - if self.process_state.ready.is_empty() { + let reactive = round.reactive; + if self.region_ready(reactive).is_empty() { return Ok(false); } self.event_values(executor.backend(), &mut round.before); let mut resume_process = round.resume_process.take(); if let Some(process) = resume_process { - self.process_state.ready.remove(&process); + self.region_ready(reactive).remove(&process); } while let Some(process) = resume_process .take() - .or_else(|| self.process_state.ready.pop_first()) + .or_else(|| self.region_ready(reactive).pop_first()) { loop { let again = self.run_process(executor, current_time, process, returns); @@ -222,7 +245,7 @@ impl SimulationState { // 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. - if again || !self.process_state.ready.is_empty() { + if again || !self.region_ready(reactive).is_empty() { self.observe_driven(executor.backend()); } if !again { @@ -233,6 +256,55 @@ impl SimulationState { Ok(true) } + /// The processes ready in the Reactive region if `reactive`, otherwise in + /// the Active region. + #[inline] + fn region_ready(&mut self, reactive: bool) -> &mut BTreeSet { + if reactive { + &mut self.process_state.reactive + } else { + &mut self.process_state.ready + } + } + + /// `$exit` of program kernel `process` (IEEE 1800-2023 24.7): every + /// kernel of its program instance ends, as if it had run to its end. + fn exit_program(&mut self, backend: &mut B, process: usize) -> Result<(), Halt> { + let program = self.model.processes[process] + .program + .ok_or(SimulatorErrorCode::InternalError)?; + for &index in &self.model.program_processes { + let refs = &self.model.processes[index]; + if refs.program != Some(program) { + continue; + } + backend.set(refs.status, ProcessStatus::Done.code()); + let state = &mut self.process_state; + state.waiters.remove(index); + state.ready.remove(&index); + state.reactive.remove(&index); + state.re_inactive.remove(&index); + } + let model = &self.model; + self.process_wakeups + .retain(|std::cmp::Reverse((_, index))| { + model.processes[*index].program != Some(program) + }); + Ok(()) + } + + /// A program kernel ended. Once every program kernel has, the simulation + /// ends with an implicit `$finish` (IEEE 1800-2023 24.3). + fn program_kernel_ended(&self, backend: &B) -> Result<(), Halt> { + let done = ProcessStatus::Done.code(); + let all_done = self + .model + .program_processes + .iter() + .all(|&process| backend.get_as::(self.model.processes[process].status) == done); + if all_done { Err(Halt::Finish) } else { Ok(()) } + } + /// 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 @@ -290,6 +362,27 @@ impl SimulationState { } else { self.observe_driven(executor.backend()); } + if round.reactive { + // The Reactive region is empty: the Re-Inactive region's + // processes resume, and once both are empty the Re-NBA region + // publishes the program's nonblocking assignments. Design + // processes and domains wait for the active region set (IEEE + // 1800-2023 4.5, 24.3.1). + if !self.process_state.reactive.is_empty() { + continue; + } + if !self.process_state.re_inactive.is_empty() { + let inactive = std::mem::take(&mut self.process_state.re_inactive); + self.process_state.reactive.extend(inactive); + continue; + } + if self.publish_re_nba(executor, round) { + self.settle_pass(executor, round)?; + self.observe_driven(executor.backend()); + continue; + } + return Ok(()); + } if !self.process_state.ready.is_empty() { continue; } diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 813b446c1a2..c1738942c0f 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -18,6 +18,10 @@ use crate::{ /// Bookkeeping of one round of a time slot. #[derive(Default)] pub(super) struct Round { + /// The round's process phase is the reactive region set's: it runs + /// program processes, and the design activity they create follows it + /// (IEEE 1800-2023 4.5). + pub(super) reactive: bool, /// The stopped process resumes before any newly woken ready processes. pub(super) resume_process: Option, /// Event ids whose trigger survives the settling filter. @@ -89,7 +93,8 @@ impl Round { impl Round { /// Start a round, keeping the buffers of earlier ones. - fn reset(&mut self, track_stable_edges: bool) { + fn reset(&mut self, track_stable_edges: bool, reactive: bool) { + self.reactive = reactive; self.resume_process = None; self.scheduled_trigger_ids.make_empty(); self.track_stable_edges = track_stable_edges; @@ -422,7 +427,8 @@ impl SimulationState { /// trigger evaluate, zero-delay processes run in the inactive region, /// and only then are nonblocking assignments published. A round /// without ready processes and counted signals does exactly the batch - /// step. + /// step. In a `reactive` round the process phase is that of the reactive + /// region set, and the domains its processes trigger evaluate after it. pub(super) fn step_round( &mut self, executor: &mut E, @@ -430,6 +436,7 @@ impl SimulationState { events_to_process: Vec>, ready_processes: Vec, entry: bool, + reactive: bool, ) -> Result<(), Halt> where E: SimulationExecutor, @@ -474,7 +481,7 @@ impl SimulationState { } let mut round = self.scratch.take().unwrap_or_default(); - round.reset(events_to_process.is_empty()); + round.reset(events_to_process.is_empty(), reactive); round.begin_scan(self.model.domain_kinds.len()); self.process_state.ready.extend(ready_processes); executor.backend_mut().clear_triggered_bits(); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index f5e2bde7145..d516834414e 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -170,7 +170,14 @@ impl SimulationState { } ready.retain(|&process| !self.model.processes[process].starts_with_event_wait); } - self.step_round(executor, current_time, events_to_process, ready, true)?; + self.step_round( + executor, + current_time, + events_to_process, + ready, + true, + false, + )?; self.end_time(executor, current_time) } @@ -185,15 +192,32 @@ impl SimulationState { loop { let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.process_state.ready.is_empty() { - break; + // The active region set is empty: the reactive region set + // runs, and the design activity it creates runs in the active + // region set again (IEEE 1800-2023 4.5). + if !self.reactive_pending() { + break; + } + self.charge_pass()?; + self.step_round(executor, current_time, Vec::new(), Vec::new(), false, true)?; + continue; } self.charge_pass()?; - self.step_round(executor, current_time, Vec::new(), ready, false)?; + self.step_round(executor, current_time, Vec::new(), ready, false, false)?; } executor.try_finish_timed_step(current_time)?; Ok(()) } + /// Whether a region of the reactive region set holds work. + #[inline] + fn reactive_pending(&self) -> bool { + let state = &self.process_state; + !state.reactive.is_empty() + || !state.re_inactive.is_empty() + || !state.re_nba_queue.is_empty() + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. @@ -225,7 +249,9 @@ impl SimulationState { })) } - /// Remove the processes waiting for `time`, in declaration order. + /// Remove the processes waiting for `time`, in declaration order. Program + /// processes resume in the Reactive region (IEEE 1800-2023 24.3.1): they + /// join its queue, and only design processes are returned. fn take_ready_processes(&mut self, time: u64) -> Vec { let mut ready = Vec::new(); while let Some(&Reverse((wakeup, process))) = self.process_wakeups.peek() { @@ -233,7 +259,11 @@ impl SimulationState { break; } self.process_wakeups.pop(); - ready.push(process); + if self.model.processes[process].program.is_some() { + self.process_state.reactive.insert(process); + } else { + ready.push(process); + } } ready } @@ -259,7 +289,7 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() { + if !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/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index bfbd004c30d..d9f4c083796 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -1,5 +1,7 @@ //! Waiting processes: registering waits and testing them against writes. +use std::collections::BTreeSet; + use celox_design::CounterKind; use super::SimulationState; @@ -7,8 +9,8 @@ use crate::{ SignalRef, SimulatorErrorCode, backend::SimBackend, timing::{ - Halt, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, planes, - planes_equal, planes_occur, read, + Halt, ProcessRefs, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, + planes, planes_equal, planes_occur, read, }, }; @@ -148,7 +150,12 @@ impl SimulationState { fn check_waits(&mut self, backend: &B, only: Option, driven_only: bool) { let processes = &self.model.processes; let state = StateView::new(backend); - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(driven_only, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -210,7 +217,7 @@ impl SimulationState { }; } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); @@ -231,7 +238,12 @@ impl SimulationState { /// Show the waits one value the host wrote to `signal`. pub(super) fn observe_host_write(&mut self, signal: SignalRef, value: &Value) { let processes = &self.model.processes; - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(false, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -253,13 +265,29 @@ impl SimulationState { } } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); } } +/// Make the woken `process` ready: in the Reactive region if it is a program +/// process (IEEE 1800-2023 24.3.1), otherwise in the Active region. +#[inline] +pub(super) fn wake_in_region( + processes: &[ProcessRefs], + ready: &mut BTreeSet, + reactive: &mut BTreeSet, + process: usize, +) { + if processes[process].program.is_some() { + reactive.insert(process); + } else { + ready.insert(process); + } +} + /// What one term of a waiting process compares against. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Baseline { diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 113a88a9975..9edb4ed0927 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -154,6 +154,10 @@ pub struct NbaSiteRefs { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { pub is_initializer: bool, + /// The status slot naming the program instance of a program kernel + /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive + /// region set. + pub program: Option, pub resume: SignalRef, /// A converted edge procedure starts by registering its event control /// before scheduled time-zero inputs are applied. @@ -172,6 +176,7 @@ impl ProcessRefs { pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { is_initializer: false, + program: None, resume: status, starts_with_event_wait: false, status, @@ -333,6 +338,15 @@ pub struct ProcessState { pub inactive: std::collections::BTreeSet, /// Queued nonblocking assignments, in issue order. pub nba_queue: Vec, + /// Program processes ready to run in the Reactive region of the current + /// time (IEEE 1800-2023 4.4.2.6). + pub reactive: std::collections::BTreeSet, + /// Program processes that resume in the Re-Inactive region (`#0`, + /// 4.4.2.7). + pub re_inactive: std::collections::BTreeSet, + /// Nonblocking assignments of program processes for the Re-NBA region + /// (4.4.2.8), in issue order. + pub re_nba_queue: Vec, /// Counter values each counted domain last triggered on, by counted /// signal index and kind. pub domain_counters: Vec<[u32; 3]>, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c95b249cc8..7278978181c 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 = 34; +const CONTAINER_VERSION: u16 = 35; 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 6287e96a9ee..02e7bb18b06 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -355,6 +355,8 @@ impl Plan { let unit = &sir.processes[index]; let reason = if slots.is_initializer { Some("a declaration initializer") + } else if slots.program.is_some() { + Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { Some("an edge procedure") } else if !process.host_requests.is_empty() { diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 2fc6b63fb8e..803b46afdaa 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -829,6 +829,7 @@ impl Simulator { inactive, nba_queue, domain_counters, + ..ProcessState::default() }, )) } From f22d0d670675539e00795c9ceba3452e27e1c8f0 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:37:40 +0900 Subject: [PATCH 2/3] feat(sim): build a timed Simulation from a native image Simulation's builder gets compile_native, which returns a NativeCompilation whose image carries the process kernels and the compiled scheduler, and build_native_from_image, which starts a timed simulation of such an image without code generation. A differential simulation loads a second copy of the image for its reference-loop shadow. Simulation::advance_to runs the slots before a time and stops there, so a host can act at the start of that slot. NativeProgramInstance now fails to attach an image with process kernels, as every Simulator loader already does. Part of #1730 Change-Id: I94db5d6a6ee51fd7059303f78a0c7b8cadd9312c --- .../celox/src/backend/native/runtime_image.rs | 10 + crates/celox/src/simulation.rs | 22 ++ crates/celox/src/simulator/builder.rs | 238 ++++++++++++++++-- .../tests/frontends/systemverilog/suite.rs | 12 + .../tests/frontends/systemverilog/timing.rs | 10 +- crates/celox/tests/native_simulation_image.rs | 196 +++++++++++++++ 6 files changed, 462 insertions(+), 26 deletions(-) create mode 100644 crates/celox/tests/native_simulation_image.rs diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index ff7cbbfbb6e..4320699814e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -59,7 +59,17 @@ impl NativeProgramInstance { /// /// The image's machine code must come from a trusted source. Image /// validation is structural and does not authenticate executable code. + /// + /// An image with process kernels, which only a timed + /// [`crate::Simulation`] runs, fails to attach. pub unsafe fn from_image(image: NativeProgramImage) -> Result { + let schema = image.runtime_schema(); + if !schema.processes.is_empty() { + let origin = schema.process_origins.first().cloned().unwrap_or_default(); + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fa8d71e731d..e1f60ae082d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -608,6 +608,28 @@ impl Simulation { Ok(()) } + /// Run every time slot before `time`, then move to `time` without + /// running its slot: the next [`Self::step`] or [`Self::run_until`] + /// runs it, together with the host writes made in between. A target not + /// after the current time changes nothing. Like [`Self::run_until`], it + /// returns early, before `time`, at a `$stop` or `$finish`. + pub fn advance_to(&mut self, time: u64) -> Result<(), RuntimeErrorCode> { + let Some(last) = time.checked_sub(1).filter(|&last| last >= self.time()) else { + return Ok(()); + }; + self.run_until(last)?; + if self.time() != last || self.is_finished() || self.is_stopped() { + return Ok(()); + } + self.state.advance_time(&mut self.simulator.backend, time); + if let Some(shadow) = &mut self.shadow { + shadow + .state + .advance_time(&mut shadow.simulator.backend, time); + } + Ok(()) + } + /// 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`, including when diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 7f8b600c462..2335c89efa3 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1710,20 +1710,24 @@ mod host { /// /// Keeping compilation separate from initialization lets compiler-only /// clients stop after native code generation without applying initial - /// values or executing the first combinational settle. + /// values or executing the first combinational settle. `Target` is what + /// [`Self::initialize`] builds: a [`Simulator`], or a timed + /// [`crate::Simulation`] whose image carries the process kernels and the + /// compiled scheduler. #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", target_arch = "aarch64" ))] #[must_use] - pub struct NativeCompilation { + pub struct NativeCompilation { image: crate::backend::native::NativeProgramImage, program: LaidOutProgram, warnings: Vec, options: SimulatorOptions, vcd_path: Option, injected_components: crate::InjectedComponents, + _target: std::marker::PhantomData, } /// `Simulator` runs no process kernel, so a design with one would @@ -1851,7 +1855,7 @@ mod host { feature = "arm64-codegen", target_arch = "aarch64" ))] - impl NativeCompilation { + impl NativeCompilation { /// Warnings emitted while compiling this artifact. pub fn warnings(&self) -> &[CompilationWarning] { &self.warnings @@ -1885,7 +1889,14 @@ mod host { ) -> Result<(), crate::backend::native::NativeImageContainerError> { self.image.write_container(output_path) } + } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { /// Load the image into executable memory and initialize runtime state. pub fn initialize( self, @@ -1897,6 +1908,7 @@ mod host { options, vcd_path, injected_components, + _target, } = self; initialize_native_image( image, @@ -1909,6 +1921,38 @@ mod host { } } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { + /// Load the image into executable memory and start a timed + /// simulation of it. + pub fn initialize( + self, + ) -> Result, SimulatorError> + { + let Self { + image, + program, + warnings, + options, + vcd_path, + injected_components, + _target, + } = self; + SimulatorBuilder::::start_native_image( + image, + program.into_runtime(), + warnings, + options, + vcd_path, + injected_components, + ) + } + } + impl Default for SimulatorOptions { fn default() -> Self { let opt = crate::optimizer::OptimizeOptions::default(); @@ -3175,6 +3219,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }) } @@ -3230,6 +3275,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }, trace, )) @@ -3716,6 +3762,68 @@ mod host { ) } + /// Compiles a timed simulation into a native image without loading + /// it. The image carries the process kernels and the compiled + /// scheduler; [`NativeCompilation::initialize`] or + /// [`Self::build_native_from_image`] starts a simulation of it. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn compile_native( + mut self, + ) -> Result, SimulatorError> { + self.options.emit_triggers = true; + let (laid_out, mut warnings, options, vcd_path, injected_components) = self + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + )?; + let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + Ok(NativeCompilation { + image, + program: laid_out, + warnings, + options, + vcd_path, + injected_components, + _target: std::marker::PhantomData, + }) + } + + /// Starts a timed simulation of a native image from + /// [`Self::compile_native`], without code generation. The design's + /// runtime metadata comes from `image`; the sources of this builder + /// are not used, its runtime options (scheduler, DPI symbols, + /// plusargs, VCD output) are. + /// + /// An image from [`Simulator::builder`] has no compiled scheduler, + /// so every time slot runs in the reference loop. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn build_native_from_image( + self, + image: crate::backend::native::NativeProgramImage, + ) -> Result, SimulatorError> + { + let mut options = self.options; + options.four_state = image.four_state(); + options.emit_triggers = true; + let program = image.runtime_program(); + Self::start_native_image( + image, + program, + Vec::new(), + options, + self.vcd_path, + self.injected_components, + ) + } + /// Compiles a timed simulation using the Wasmtime WASM backend. pub fn build_wasm( self, @@ -3758,36 +3866,116 @@ mod host { self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - let shadow = if !matches!( + let shadow = Self::start_shadow( + |shadow_options| compile(&laid_out, shadow_options), + &laid_out.runtime, + &options, + &injected_components, + )?; + let mut simulation = Self::start_simulation( + backend, + laid_out.into_runtime(), + warnings, + &options, + vcd_path, + injected_components, + )?; + if let Some(shadow) = shadow { + simulation.set_shadow(shadow); + } + Ok(simulation) + } + + /// The reference-loop shadow of a differential simulation of + /// `program`, with `backend` providing its own copy of the code, or + /// why it has none. Other scheduler modes have no shadow. + #[allow(clippy::type_complexity)] + fn start_shadow( + backend: impl FnOnce(&SimulatorOptions) -> Result, + program: &crate::ir::RuntimeProgram, + options: &SimulatorOptions, + injected_components: &crate::InjectedComponents, + ) -> Result>, &'static str>>, SimulatorError> + { + if !matches!( options.scheduler, crate::SchedulerMode::Differential | crate::SchedulerMode::DifferentialRuns ) { - None - } else if !injected_components.definitions.is_empty() { - Some(Err("the design has external components")) - } else { - let mut shadow_options = options.clone(); - shadow_options.trace = Default::default(); - shadow_options.scheduler = crate::SchedulerMode::Reference; - let backend = compile(&laid_out, &shadow_options)?; - let shadow = Self::start_simulation( - backend, - laid_out.runtime.clone(), - Vec::new(), - &shadow_options, - None, - Default::default(), - )?; - // Host state outside the memory image, such as open files, - // cannot be shared with a shadow. - Some(match shadow.simulator.check_host_checkpoint_support() { + return Ok(None); + } + if !injected_components.definitions.is_empty() { + return Ok(Some(Err("the design has external components"))); + } + let mut shadow_options = options.clone(); + shadow_options.trace = Default::default(); + shadow_options.scheduler = crate::SchedulerMode::Reference; + let backend = backend(&shadow_options)?; + let shadow = Self::start_simulation( + backend, + program.clone(), + Vec::new(), + &shadow_options, + None, + Default::default(), + )?; + // Host state outside the memory image, such as open files, + // cannot be shared with a shadow. + Ok(Some( + match shadow.simulator.check_host_checkpoint_support() { Ok(()) => Ok(Box::new(shadow)), Err(_) => Err("the design keeps host state outside its memory image"), - }) + }, + )) + } + + /// Load `image` into executable memory and start a timed simulation + /// of `program`, its runtime metadata. A differential simulation + /// loads a second copy of the image for its shadow. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + #[allow(unreachable_code)] + fn start_native_image( + image: crate::backend::native::NativeProgramImage, + program: crate::ir::RuntimeProgram, + mut warnings: Vec, + options: SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> + { + #[cfg(any( + all(feature = "arm64-codegen", not(target_arch = "aarch64")), + all(feature = "x86_64-codegen", not(target_arch = "x86_64")) + ))] + { + let _ = (image, program, options, vcd_path, injected_components); + return Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(warnings)); + } + + let load = |image, options: &SimulatorOptions| { + // Safety: callers either produced the image in this process + // or loaded it from an explicitly trusted native-image + // artifact, and `from_image` validates its structure first. + unsafe { + crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi) + } }; + let shadow = Self::start_shadow( + |shadow_options| load(image.clone(), shadow_options), + &program, + &options, + &injected_components, + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + let backend = load(image, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut simulation = Self::start_simulation( backend, - laid_out.into_runtime(), + program, warnings, &options, vcd_path, diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f10ac99fc15..772ad6c685a 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -301,6 +301,18 @@ fn build(design: &Design, backend: &str) -> Result> { ); return Ok(match backend { "native" => Box::new(TimedBackend::new(builder.build_native()?)), + // The image goes through its container bytes, as an attached + // image does, and the simulation takes its metadata from it. + "native-image" => { + let image = builder.compile_native()?.into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes()?)?; + Box::new(TimedBackend::new( + Simulation::from_sv_sources(Vec::new(), &design.top) + .scheduler_mode(scheduler_mode()) + .build_native_from_image(image)?, + )) + } "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), "native-parallel" => Box::new(TimedBackend::new( builder diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 96516fab864..a7afb9772eb 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -2,7 +2,8 @@ //! processes, driven through the timed `Simulation`. //! //! Every exclusion names what Celox lacks for the case, so the change that -//! adds it removes the exclusion. Supported cases run on every backend. +//! adds it removes the exclusion. Supported cases run on every backend, +//! and natively also from a serialized native image. macro_rules! timed_cases { () => {}; @@ -25,6 +26,13 @@ macro_rules! timed_cases { crate::suite::run_case($case, "cranelift"); } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + $(#[$attr])* + fn native_image() { + crate::suite::run_case($case, "native-image"); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] #[test] $(#[$attr])* diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs new file mode 100644 index 00000000000..5f6808ff839 --- /dev/null +++ b/crates/celox/tests/native_simulation_image.rs @@ -0,0 +1,196 @@ +//! A timed `Simulation` built from a native image: the image carries the +//! process kernels and the compiled scheduler, so a serialized image runs as +//! the in-process build does (#1730). +#![cfg(all( + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) +))] + +use std::path::Path; + +use celox::{ + NativeProgramImage, NativeProgramInstance, RuntimeEvent, SchedulerMode, Simulation, + SimulatorErrorKind, +}; + +const PROCESSES: &str = r#"`timescale 1ns/1ns +module Top(output logic [7:0] count, output logic [7:0] seen); + logic clk = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 1; + initial begin + count = 0; + seen = 0; + #12 $display("at %0t count=%0d", $time, count); + @(posedge clk) seen = count; + #20 $display("at %0t seen=%0d count=%0d", $time, seen, count); + end +endmodule +"#; + +fn builder(source: &str) -> celox::SimulatorBuilder<'_, Simulation> { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") +} + +/// The image, through its container bytes. +fn reloaded(image: &NativeProgramImage) -> NativeProgramImage { + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap() +} + +/// What a simulation shows up to `end`: its events and outputs. +fn transcript( + sim: &mut Simulation, + end: u64, +) -> (Vec, u64, u64) { + sim.run_until(end).unwrap(); + let count = sim.get(sim.signal("count")).try_into().unwrap(); + let seen = sim.get(sim.signal("seen")).try_into().unwrap(); + (sim.drain_runtime_events(), count, seen) +} + +#[test] +fn a_serialized_native_image_runs_its_processes() { + let expected = transcript(&mut builder(PROCESSES).build_native().unwrap(), 60); + assert_eq!( + expected.0, + vec![ + RuntimeEvent::Display { + message: b"at 12 count=1".to_vec() + }, + RuntimeEvent::Display { + message: b"at 35 seen=1 count=3".to_vec() + }, + ] + ); + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); + assert!(sim.scheduler_stats().compiled_slots > 0); + let mut sim = builder(PROCESSES) + .compile_native() + .unwrap() + .initialize() + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); +} + +#[test] +fn a_differential_simulation_loads_its_shadow_from_the_image() { + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native_from_image(image) + .unwrap(); + let (events, count, _) = transcript(&mut sim, 60); + assert_eq!(events.len(), 2); + assert_eq!(count, 6); + assert!(sim.scheduler_stats().checked_steps > 0); +} + +/// An image from `Simulator` has no compiled scheduler: every slot runs in +/// the reference loop, to the same state as a fresh `Simulation` build. +#[test] +fn an_untimed_image_runs_as_a_simulation_in_the_reference_loop() { + let source = "module Top(input logic clk, input logic [7:0] step, output logic [7:0] count, + output logic [7:0] sum); + always_ff @(posedge clk) count <= count + 1; + always_ff @(negedge clk) sum <= sum + count + step; + endmodule"; + let run = |sim: &mut Simulation| { + let step = sim.signal("step"); + sim.modify(|io| io.set(step, 3u8)).unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(97).unwrap(); + sim.save_state().unwrap() + }; + let mut fresh = builder(source).build_native().unwrap(); + let expected = run(&mut fresh); + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(reloaded(&image)) + .unwrap(); + assert_eq!(run(&mut sim), expected); + assert_eq!(sim.get(sim.signal("count")), 10u8.into()); + assert_eq!(sim.scheduler_stats().compiled_slots, 0); +} + +#[test] +fn process_images_do_not_load_as_untimed_programs() { + let image = builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = + celox::Simulator::from_sv_sources(Vec::new(), "Top").build_native_from_image(image.clone()) + else { + panic!("a Simulator runs no process"); + }; + assert!(matches!( + error.kind(), + SimulatorErrorKind::ProcessRequiresSimulation(_) + )); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance runs no process"); + }; + assert!(error.to_string().contains("is a process"), "{error}"); +} + +#[test] +fn advance_to_stops_before_the_slot_and_its_host_writes_join_it() { + let source = r#"`timescale 1ns/1ns +module Top(input logic [7:0] value, output logic [7:0] seen); + initial begin + seen = 0; + #5 seen = value; + $display("at %0t value=%0d", $time, value); + end +endmodule +"#; + let image = reloaded( + &builder(source) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // The write is the host's at time 5, before the process resumes there. + let value = sim.signal("value"); + sim.modify(|io| io.set(value, 7u8)).unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 7u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"at 5 value=7".to_vec() + }] + ); + sim.advance_to(3).unwrap(); + assert_eq!(sim.time(), 5); +} From 7e97e2ef65ebf42e06831581c9cebcc270f27cd9 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:47:38 +0900 Subject: [PATCH 3/3] fix(sim): reject VCD runs of strided timed images build_native_from_image and NativeCompilation::initialize now make the packed-array check of the untimed native loader, through one shared validate_native_vcd_layout: an image compiled without VCD cannot record element-strided unpacked arrays. Change-Id: I4d968bb5136d9fe772ec0afedb8f648161900f3a --- crates/celox/src/simulator/builder.rs | 51 +++++++++++++------ crates/celox/tests/native_simulation_image.rs | 47 +++++++++++++++++ 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 2335c89efa3..bb675f04160 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1745,6 +1745,37 @@ mod host { )) } + /// A native image records waveforms only if its arrays are packed, + /// which an image compiled with VCD enabled has: a VCD file of the host + /// (`vcd_path`) or of the design (`$dumpvars`) needs one. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + fn validate_native_vcd_layout( + layout: &crate::MemoryLayout, + program: &crate::ir::RuntimeProgram, + vcd_path: &Option, + ) -> Result<(), SimulatorError> { + let source_vcd = program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if (vcd_path.is_some() || source_vcd) + && layout.unpacked_arrays.values().any(|array| { + !array.element_width.is_multiple_of(8) + || array.element_stride != array.element_width / 8 + }) + { + return Err(SimulatorError::from(crate::CodegenError::message( + "VCD requires packed array storage; compile this native image with VCD enabled", + ))); + } + Ok(()) + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1763,22 +1794,8 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - let source_vcd = sim - .program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Vcd); - if vcd_path.is_some() || source_vcd { - if sim.layout().unpacked_arrays.values().any(|array| { - !array.element_width.is_multiple_of(8) - || array.element_stride != array.element_width / 8 - }) { - return Err(SimulatorError::from(crate::CodegenError::message( - "VCD requires packed array storage; compile this native image with VCD enabled", - )) - .with_warnings(std::mem::take(&mut sim.warnings))); - } + if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { + return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); } if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3956,6 +3973,8 @@ mod host { .with_warnings(warnings)); } + validate_native_vcd_layout(image.layout(), &program, &vcd_path) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let load = |image, options: &SimulatorOptions| { // Safety: callers either produced the image in this process // or loaded it from an explicitly trusted native-image diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index 5f6808ff839..aab956b1f94 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -194,3 +194,50 @@ endmodule sim.advance_to(3).unwrap(); assert_eq!(sim.time(), 5); } + +/// Element-strided unpacked arrays cannot be dumped: an image compiled +/// without VCD is rejected for a VCD run, as `Simulator` rejects it, and one +/// compiled with VCD records the elements. +#[test] +fn a_vcd_run_needs_an_image_compiled_with_vcd() { + let source = r#"`timescale 1ns/1ns +module Top; + logic [2:0] values [4]; + initial begin + values[2] = 3'd0; + #1 values[2] = 3'd5; + end +endmodule +"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("top.vcd"); + let strided = builder(source) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&strided)) + else { + panic!("a strided image cannot record VCD"); + }; + assert!( + error + .to_string() + .contains("compile this native image with VCD enabled"), + "{error}" + ); + let packed = builder(source) + .vcd(&path) + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&packed)) + .unwrap(); + sim.run_until(2).unwrap(); + drop(sim); + let vcd = std::fs::read_to_string(&path).unwrap(); + assert!(vcd.contains("b101"), "{vcd}"); +}