diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index f1b9fbe01c7..50e687c8a08 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -457,6 +457,9 @@ pub struct ProcessSlots { pub is_initializer: bool, /// This kernel originated from an edge procedure and must execute in Simulation. pub requires_timed_simulation: bool, + /// Every delay the kernel suspends for is a constant of at least one + /// time unit. + pub const_delays: bool, pub resume: A, pub status: A, pub delay: A, @@ -467,6 +470,7 @@ impl ProcessSlots { ProcessSlots { is_initializer: self.is_initializer, requires_timed_simulation: self.requires_timed_simulation, + const_delays: self.const_delays, resume: map(self.resume), status: map(self.status), delay: map(self.delay), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index a34363cb372..8f8c1373831 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -72,12 +72,21 @@ impl ProcessKernelBuilder { let start = builder.current_block(); Self { builder, - slots, + slots: ProcessSlots { + const_delays: true, + ..slots + }, resume_blocks: vec![start], wait_site: None, } } + /// The kernel's control slots, with [`ProcessSlots::const_delays`] set + /// for the delays lowered so far. + pub fn slots(&self) -> ProcessSlots { + self.slots + } + /// The SIR builder positioned where the process continues. After /// [`Self::finish`] no block is open until the caller switches to one. pub fn builder(&mut self) -> &mut SIRBuilder { @@ -135,8 +144,15 @@ impl ProcessKernelBuilder { /// Suspend for the number of time units in `amount`, an unsigned /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at /// a new resume point. A zero delay resumes after the nonblocking - /// assignments of the time are published. - pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + /// assignments of the time are published. `constant` is the amount's + /// value when the frontend knows it, which it records in + /// [`ProcessSlots::const_delays`]. + pub fn delay( + &mut self, + amount: RegisterId, + constant: Option, + ) -> Result<(), ProcessKernelError> { + self.note_delay(constant); self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); self.suspend(ProcessStatus::Delay) } @@ -144,11 +160,20 @@ impl ProcessKernelBuilder { /// A delay with the scheduling of IEEE 1800-2023: a zero delay resumes /// in the inactive region of the same time (4.4.2.3), before /// nonblocking assignments are published. - pub fn inactive_delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + pub fn inactive_delay( + &mut self, + amount: RegisterId, + constant: Option, + ) -> Result<(), ProcessKernelError> { + self.note_delay(constant); self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); self.suspend(ProcessStatus::InactiveDelay) } + fn note_delay(&mut self, constant: Option) { + self.slots.const_delays &= constant.is_some_and(|amount| amount > 0); + } + /// Return to the runtime, which charges its time-slot budget and /// resumes the process at once. Frontends place this in loops without /// timing controls so that a runaway process is reported, not hung in. diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 2a5196e29ef..f3da9a7af9f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -481,6 +481,23 @@ fn coerce_sir_register( Ok(current) } +/// The value of expression `id` as a delay amount, if it is a two-state +/// constant whose coercion to [`PROCESS_DELAY_WIDTH`] bits keeps its value. +fn constant_delay(artifact: &FrontendArtifact, id: ExprId) -> Option { + let expression = artifact.expression(id)?; + let ExprNode::Constant(value) = expression.node() else { + return None; + }; + let value_type = expression.value_type(); + let negative = value_type.is_signed() + && value_type.width() > 0 + && value.payload().bit(value_type.width() as u64 - 1); + if value.mask().bits() != 0 || negative { + return None; + } + u64::try_from(value.payload()).ok() +} + fn coerce_sir_expression( artifact: &FrontendArtifact, id: ExprId, @@ -1319,6 +1336,7 @@ fn lower_statements( return Ok(false); } Statement::Delay { amount } | Statement::InactiveDelay { amount } => { + let constant = constant_delay(artifact, *amount); let amount = coerce_sir_expression( artifact, *amount, @@ -1327,9 +1345,9 @@ fn lower_statements( &mut cache, )?; if matches!(statement, Statement::Delay { .. }) { - kernel.delay(amount)?; + kernel.delay(amount, constant)?; } else { - kernel.inactive_delay(amount)?; + kernel.inactive_delay(amount, constant)?; } } Statement::WaitEvent { terms } => { @@ -1713,6 +1731,7 @@ fn lower_processes( let slots = ProcessSlots { is_initializer: false, requires_timed_simulation: false, + const_delays: false, resume: lowering .hidden .declare(name("resume"), PROCESS_RESUME_WIDTH, false), @@ -1728,6 +1747,7 @@ fn lower_processes( lowering.process_nba_sites = 0; let mut kernel = ProcessKernelBuilder::new(slots); lower_statements(&mut lowering, &mut kernel, process.body())?; + let slots = kernel.slots(); let kernel = kernel.build(); candidates.extend(crate::watch::multi_store_candidates(&kernel, |address| { stable_signal(address, artifact.signals().len()) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 751a066eef8..440413e53e0 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4089,6 +4089,7 @@ fn lower_initial_processes( ProcessSlots { is_initializer: process.is_initializer(), requires_timed_simulation: process.is_scheduled_edge(), + const_delays: false, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), @@ -4133,7 +4134,7 @@ fn lower_initial_processes( })); Ok(SymbolicProcess { kernel: kernel.unit, - slots, + slots: kernel.slots, origin: process_origin(process), }) }) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3a992de49cd..5ed7466401a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4288,10 +4288,12 @@ impl Ff<'_, '_> { self.exec_block(body)?; let mut kernel = self.kernel.take().expect("lowering a process kernel"); std::mem::swap(&mut self.b, kernel.builder()); + let slots = kernel.slots(); let mut unit = kernel.build(); prune_unreachable_blocks(&mut unit); Ok(KernelUnit { unit, + slots, wait_sites: self.wait_sites, nba_sites: self.nba_sites, host_request_sites: self.host_request_sites, @@ -4434,6 +4436,9 @@ impl Ff<'_, '_> { ticks_per_unit: u64, ticks_per_precision: u64, ) -> Result<(), sv::AnalyzerError> { + // Only integral constants are recorded; a real delay counts as + // variable. + let mut constant = None; let (mut delay, ticks_per_step) = match self.m.expr_float_precision(amount) { Some(precision) => ( self.real_delay(amount, precision, ticks_per_unit / ticks_per_precision)?, @@ -4441,6 +4446,13 @@ impl Ff<'_, '_> { ), None => { let signed = self.expr_signed(amount); + constant = self + .eval_const(amount)? + .filter(|(value, width)| { + !(signed && *width > 0 && value.bit(*width as u64 - 1)) + }) + .and_then(|(value, _)| u64::try_from(&value).ok()) + .and_then(|value| value.checked_mul(ticks_per_unit)); let mut arena = SLTNodeArena::new(); let node = self.expr_slt(amount, None, &mut arena)?; let original = self.lower_slt(&arena, node)?; @@ -4489,7 +4501,7 @@ impl Ff<'_, '_> { )); delay = product; } - self.with_kernel(|kernel| kernel.inactive_delay(delay)) + self.with_kernel(|kernel| kernel.inactive_delay(delay, constant)) .map_err(kernel_error) } @@ -4849,6 +4861,7 @@ impl Ff<'_, '_> { /// The kernel of a process and its wait and nonblocking assignment sites. pub(super) struct KernelUnit { pub unit: ExecutionUnit, + pub slots: ProcessSlots, pub wait_sites: Vec>, pub nba_sites: Vec>, pub host_request_sites: Vec>, diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 09ebcd75fa8..644e75b2a20 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -150,6 +150,16 @@ impl Heap { self.strings.contains_key(&handle) } + /// Whether `other` holds the same strings under the same handles, the + /// same strings under construction, and names new strings alike. + pub fn same_contents(&self, other: &Heap) -> bool { + self.strings == other.strings + && self.next == other.next + && self.buffers == other.buffers + && self.free_buffers == other.free_buffers + && self.pinned == other.pinned + } + /// The number of live strings, including `""`. pub fn len(&self) -> usize { self.strings.len() diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2d2b872cc15..f0c637d01e0 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -35,8 +35,9 @@ pub use reflection::{ }; pub use schedule::{ResolvedSchedule, host_watch}; pub use simulation::{ - EventInfo, HostBoundary, ScheduleParts, SimulationExecutor, SimulationSnapshot, - SimulationState, UnitExecutor, + EventInfo, HostBoundary, KernelSchedule, ScheduleKey, ScheduleParts, SchedulerMode, + SchedulerStats, SimulationExecutor, SimulationSnapshot, SimulationState, StepObserver, + UnitExecutor, }; pub use state_file::{ BaselineRecord, NbaRecord, ProcessRecord, ScheduleRecord, ScheduledEvent, StateDifference, diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 5a6766970e6..81e6885be18 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -8,6 +8,7 @@ mod nba; mod persist; mod process; mod round; +mod stats; mod time; mod wait; @@ -19,7 +20,8 @@ use celox_design::CounterKind; pub(crate) use batch::{edge_level, event_level}; pub use host::{HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; -pub use persist::{ScheduleParts, SimulationSnapshot}; +pub use persist::{ScheduleKey, ScheduleParts, SimulationSnapshot}; +pub use stats::{KernelSchedule, SchedulerMode, SchedulerStats}; pub use wait::{Baseline, Waiter, Waiters}; use self::round::Round; @@ -82,6 +84,38 @@ struct Suspended { levels: Vec, } +/// Sees the steps of [`SimulationState::run_until_observed`] and +/// [`SimulationState::step_until_observed`]. +pub trait StepObserver { + /// Called before a step, with the state it starts from. + fn before_step(&mut self, state: &SimulationState, executor: &mut E); + + /// Called after a step to at most `limit` that returned `result`. An + /// error replaces the step's result. + fn after_step( + &mut self, + state: &SimulationState, + executor: &mut E, + limit: u64, + result: &Result, SimulatorErrorCode>, + ) -> Result<(), SimulatorErrorCode>; +} + +/// No observer. +impl StepObserver for () { + fn before_step(&mut self, _: &SimulationState, _: &mut E) {} + + fn after_step( + &mut self, + _: &SimulationState, + _: &mut E, + _: u64, + _: &Result, SimulatorErrorCode>, + ) -> Result<(), SimulatorErrorCode> { + Ok(()) + } +} + /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, @@ -118,6 +152,8 @@ pub struct SimulationState { return_budget: u64, /// Rounds and process-phase passes the current time slot has run. slot_passes: u64, + /// The loop that runs time slots, and the slots each loop ran. + stats: SchedulerStats, } impl SimulationState { @@ -169,7 +205,12 @@ impl SimulationState { round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, + stats: SchedulerStats::default(), }; + state.stats.kernels = vec![ + KernelSchedule::Reference("the design has no compiled scheduler"); + state.model.processes.len() + ]; state.synchronize_event_values(backend); state } @@ -215,6 +256,92 @@ impl SimulationState { } } + /// Run every time slot with work up to and including `end`, then move + /// to `end`. A target before the current time changes nothing. Returns + /// whether the simulation is at `end` afterwards; it is not when a + /// process stopped it (`$stop`) or finished it on the way. + pub fn run_until(&mut self, executor: &mut E, end: u64) -> Result + where + E: SimulationExecutor, + { + self.run_until_observed(executor, end, &mut ()) + } + + /// [`Self::run_until`], showing every step to `observer`. + pub fn run_until_observed( + &mut self, + executor: &mut E, + end: u64, + observer: &mut O, + ) -> Result + where + E: SimulationExecutor, + O: StepObserver, + { + if end < self.scheduler.time { + // Time only moves forward. Moving the timestamp back while the + // design keeps the state it reached would leave the two + // describing different moments, so an earlier target is a no-op. + return Ok(false); + } + while let Some(next_time) = self.next_event_time() { + if next_time > end { + break; + } + self.step_until_observed(executor, end, observer)?; + if self.stopped { + return Ok(false); + } + } + if self.finished { + return Ok(false); + } + self.advance_time(executor.backend_mut(), end); + Ok(true) + } + + /// Select the loop that runs time slots. + pub fn set_scheduler_mode(&mut self, mode: SchedulerMode) { + self.stats.mode = mode; + } + + /// The loop that runs time slots, what it ran and how each process + /// kernel is scheduled. + pub fn scheduler_stats(&self) -> &SchedulerStats { + &self.stats + } + + /// [`Self::step_until`], showing the step to `observer`. An error of + /// the observer replaces the step's result. + pub fn step_until_observed( + &mut self, + executor: &mut E, + limit: u64, + observer: &mut O, + ) -> Result, SimulatorErrorCode> + where + E: SimulationExecutor, + O: StepObserver, + { + observer.before_step(self, executor); + let result = self.step_until(executor, limit); + observer.after_step(self, executor, limit, &result)?; + result + } + + /// Whether the host changed state that the next step settles at the + /// current time first. + pub fn host_pending(&self) -> bool { + self.host_pending + } + + /// Set whether the next step settles host changes at the current time + /// first, as when copying another simulation's state. + #[doc(hidden)] + pub fn set_host_pending(&mut self, pending: bool) { + self.host_pending = pending; + } + /// Complete a boundary reached from an entry point that returns runtime /// errors rather than scheduler control halts. fn finish_timed_boundary( diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index c7d8a0d81cb..696d04ec5e1 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -240,3 +240,86 @@ impl SimulationSnapshot { self.time } } + +impl SimulationState { + /// The scheduling state in a form that compares equal between two + /// simulations of the same design exactly when they would continue + /// alike: events by id rather than handle, queues in order, and only the + /// waiting processes' waits. + #[doc(hidden)] + pub fn schedule_key(&self) -> ScheduleKey { + let mut events: Vec<_> = self + .scheduler + .event_queue + .iter() + .map(|event| { + ( + event.time, + event.event_ref.id(), + event.signal, + event.next_val, + event.periodic, + ) + }) + .collect(); + events.sort_unstable(); + let mut process_wakeups: Vec<_> = self + .process_wakeups + .iter() + .map(|Reverse(wakeup)| *wakeup) + .collect(); + process_wakeups.sort_unstable(); + let state = &self.process_state; + ScheduleKey { + time: self.scheduler.time, + clocks: self + .scheduler + .clocks + .iter() + .map(|clock| clock.as_ref().map(|clock| clock.period)) + .collect(), + events, + high_events: self.last_clock_values.iter().collect(), + unknown_events: self.last_clock_unknown.iter().collect(), + process_wakeups, + waiters: state + .waiters + .iter() + .map(|(process, waiter)| (process, waiter.clone())) + .collect(), + ready: state.ready.iter().copied().collect(), + inactive: state.inactive.iter().copied().collect(), + nba_queue: state.nba_queue.clone(), + domain_counters: state.domain_counters.clone(), + declarations_pending: self.declarations_pending, + host_pending: self.host_pending, + finished: self.finished, + stopped: self.stopped, + suspended: self.suspended.is_some(), + } + } +} + +/// See [`SimulationState::schedule_key`]. +#[doc(hidden)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScheduleKey { + pub time: u64, + pub clocks: Vec>, + /// Pending events as (time, event id, signal, value, periodic). + pub events: Vec<(u64, usize, crate::SignalRef, u8, bool)>, + pub high_events: Vec, + pub unknown_events: Vec, + /// Processes waiting for a time, as (time, process). + pub process_wakeups: Vec<(u64, usize)>, + pub waiters: Vec<(usize, super::Waiter)>, + pub ready: Vec, + pub inactive: Vec, + pub nba_queue: Vec, + pub domain_counters: Vec<[u32; 3]>, + pub declarations_pending: bool, + pub host_pending: bool, + pub finished: bool, + pub stopped: bool, + pub suspended: bool, +} diff --git a/crates/celox-runtime/src/simulation/stats.rs b/crates/celox-runtime/src/simulation/stats.rs new file mode 100644 index 00000000000..bb8d9316138 --- /dev/null +++ b/crates/celox-runtime/src/simulation/stats.rs @@ -0,0 +1,44 @@ +//! Which loop runs the time slots of a timed simulation, and what it ran. + +/// Which loop runs the time slots of a timed simulation. A test option. +#[doc(hidden)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum SchedulerMode { + /// The runtime's loop runs every time slot. + #[default] + Reference, + /// The design's compiled scheduler runs the time slots it can, and the + /// runtime's loop the others. A design without a compiled scheduler + /// runs as in [`Self::Reference`]. + Compiled, + /// [`Self::Compiled`], checked after every time slot against a shadow + /// simulation of the same design in [`Self::Reference`]. + Differential, +} + +/// How one process kernel is scheduled. +#[doc(hidden)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KernelSchedule { + /// The compiled scheduler runs it. + Compiled, + /// The runtime's loop runs it, for the reason given. + Reference(&'static str), +} + +/// The loop that runs time slots and how each process kernel is scheduled. +#[doc(hidden)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SchedulerStats { + pub mode: SchedulerMode, + /// Time slots the compiled scheduler ran. + pub compiled_slots: u64, + /// Steps checked against the shadow simulation in + /// [`SchedulerMode::Differential`]. Steps of the reference loop are not + /// counted otherwise, which would cost every step. + pub checked_steps: u64, + /// Why [`SchedulerMode::Differential`] checks no step of this design. + pub unchecked: Option<&'static str>, + /// How each process kernel is scheduled, by process index. + pub kernels: Vec, +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 5d47dda384e..3a7780001a7 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 = 27; +const CONTAINER_VERSION: u16 = 28; 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/lib.rs b/crates/celox/src/lib.rs index 0eea3828822..e16d6ae2eb7 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -58,6 +58,8 @@ pub use celox_runtime::{ StateDifference, StateFile, StateFileError, StateObject, StateRole, WaiterRecord, format_state_value, }; +#[doc(hidden)] +pub use celox_runtime::{KernelSchedule, SchedulerMode, SchedulerStats}; pub use celox_slt::scheduler::SchedulerError; pub use celox_state_layout::STATE_HEADER_SIZE; pub use debug::{CompilationTrace, NativeProfileBlock, TraceOptions}; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3ad82f1402a..8eea263c394 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -11,6 +11,7 @@ use celox_runtime::{ UnitExecutor, host_watch, }; +mod differential; mod vcd_tasks; /// Saved state of a [`Simulation`], created by [`Simulation::checkpoint`]: @@ -64,6 +65,13 @@ impl std::fmt::Debug for SimulationCheckpoint { pub struct Simulation { pub(crate) simulator: Simulator, pub(crate) state: SimulationState, + /// The reference simulation every step is checked against in + /// [`crate::SchedulerMode::Differential`]. + shadow: Option>>, + /// Steps checked against the shadow. + checked_steps: u64, + /// Why [`crate::SchedulerMode::Differential`] has no shadow. + unchecked: Option<&'static str>, } impl std::fmt::Debug for Simulation { @@ -316,7 +324,13 @@ impl Simulation { simulator.finish_sites = simulator.schedule.finish_sites; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; - Ok(Self { simulator, state }) + Ok(Self { + simulator, + state, + shadow: None, + checked_steps: 0, + unchecked: None, + }) } /// Returns warnings emitted during compilation. @@ -528,13 +542,22 @@ impl Simulation { /// Returns the new simulation time, the current time when only host /// writes were settled, or None if nothing was to do. pub fn step(&mut self) -> Result, RuntimeErrorCode> { - self.state.step(&mut self.simulator) + self.step_until(u64::MAX) } /// [`Self::step`] that, after settling host writes at the current time, /// does not advance past `end_time`. fn step_until(&mut self, end_time: u64) -> Result, RuntimeErrorCode> { - self.state.step_until(&mut self.simulator, end_time) + let Some(mut shadow) = self.shadow.take() else { + return self.state.step_until(&mut self.simulator, end_time); + }; + let mut check = differential::ShadowCheck::new(&mut shadow); + let result = self + .state + .step_until_observed(&mut self.simulator, end_time, &mut check); + self.checked_steps += check.checked; + self.shadow = Some(shadow); + result } /// Advance time and run until `end_time` (inclusive). @@ -543,26 +566,21 @@ impl Simulation { /// 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 - // design keeps the state it reached would leave the two describing - // different moments, so an earlier target is a no-op. - return Ok(()); - } - while let Some(next_time) = self.state.next_event_time() { - if next_time > end_time { - break; - } - self.step_until(end_time)?; - if self.state.is_stopped() { - return Ok(()); + let reached = match self.shadow.take() { + None => self.state.run_until(&mut self.simulator, end_time)?, + Some(mut shadow) => { + let mut check = differential::ShadowCheck::new(&mut shadow); + let result = + self.state + .run_until_observed(&mut self.simulator, end_time, &mut check); + self.checked_steps += check.checked; + self.shadow = Some(shadow); + result? } - } - if self.state.is_finished() { + }; + if !reached { return Ok(()); } - self.state - .advance_time(&mut self.simulator.backend, end_time); if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { if matches!(&error, crate::simulator::DumpError::Runtime(_)) { self.flush_error_output(); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs new file mode 100644 index 00000000000..acdaefda40b --- /dev/null +++ b/crates/celox/src/simulation/differential.rs @@ -0,0 +1,300 @@ +//! [`SchedulerMode::Differential`]: every step is checked against a shadow +//! simulation of the same design that runs the reference loop. +//! +//! The primary runs its own loop, [`SimulationState::run_until_observed`] +//! or [`SimulationState::step_until_observed`], with a [`ShadowCheck`] as the +//! observer. Before each step the shadow takes the primary's design state, +//! scheduling state and undrained runtime events, so host calls between +//! steps need no mirroring. In a time slot suspended at `$stop` the +//! scheduling state cannot be copied: the shadow then takes the design state +//! and host changes, and continues the slot in lockstep. +//! +//! [`SchedulerMode::Differential`]: crate::SchedulerMode::Differential + +use celox_runtime::{SimulationState, StepObserver}; + +use super::Simulation; +use crate::{ + RuntimeErrorCode, Simulator, + backend::{EventHandle, SimBackend}, +}; + +impl Simulation { + /// In [`crate::SchedulerMode::Differential`], check every step against + /// `shadow`, a simulation of the same design, or record why no step is + /// checked. + pub(crate) fn set_shadow(&mut self, shadow: Result>, &'static str>) { + match shadow { + Ok(shadow) => self.shadow = Some(shadow), + Err(reason) => self.unchecked = Some(reason), + } + } + + /// The scheduler mode, the steps checked against a shadow and how each + /// process kernel is scheduled. + #[doc(hidden)] + pub fn scheduler_stats(&self) -> crate::SchedulerStats { + crate::SchedulerStats { + checked_steps: self.checked_steps, + unchecked: self.unchecked, + ..self.state.scheduler_stats().clone() + } + } +} + +/// Checks each step of a primary simulation against a shadow. +pub(super) struct ShadowCheck<'a, B: SimBackend> { + shadow: &'a mut Simulation, + /// The time the step in progress started from. + start: u64, + /// Steps checked. + pub(super) checked: u64, +} + +impl<'a, B: SimBackend> ShadowCheck<'a, B> { + pub(super) fn new(shadow: &'a mut Simulation) -> Self { + Self { + shadow, + start: 0, + checked: 0, + } + } +} + +impl StepObserver> for ShadowCheck<'_, B> { + fn before_step(&mut self, state: &SimulationState, primary: &mut Simulator) { + self.start = state.time(); + let shadow = &mut *self.shadow; + shadow.simulator.mirror(primary); + if state.is_suspended() { + shadow.state.set_host_pending(state.host_pending()); + return; + } + // Pending events take the shadow's own handles, which run the + // shadow's compiled code. + let events = shadow.simulator.backend.id_to_event_slice(); + shadow + .state + .restore(&state.snapshot(), |event| events.get(event.id()).copied()) + .unwrap_or_else(|_| unreachable!("the shadow has the same events")); + } + + fn after_step( + &mut self, + state: &SimulationState, + primary: &mut Simulator, + limit: u64, + result: &Result, RuntimeErrorCode>, + ) -> Result<(), RuntimeErrorCode> { + let shadow = &mut *self.shadow; + let reference = shadow.state.step_until(&mut shadow.simulator, limit); + self.checked += 1; + match difference(state, primary, shadow, result, &reference) { + None => Ok(()), + Some(difference) => Err(RuntimeErrorCode::Runtime { + message: format!( + "the scheduler diverged from the reference in the step from time {}: \ + {difference}", + self.start + ), + signals: Vec::new(), + }), + } + } +} + +/// What differs between a primary simulation and `shadow` after a step with +/// results `primary_result` and `reference`, if anything. +fn difference( + state: &SimulationState, + primary: &mut Simulator, + shadow: &mut Simulation, + primary_result: &Result, RuntimeErrorCode>, + reference: &Result, RuntimeErrorCode>, +) -> Option { + let result = |result: &Result, RuntimeErrorCode>| match result { + Ok(time) => format!("{time:?}"), + Err(error) => format!("error: {error}"), + }; + let (returned, reference) = (result(primary_result), result(reference)); + if returned != reference { + return Some(format!( + "the step returned {returned}, the reference {reference}" + )); + } + let (key, reference) = (state.schedule_key(), shadow.state.schedule_key()); + if key != reference { + return Some(format!( + "scheduling state {key:?}, the reference {reference:?}" + )); + } + if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend) { + let signal = primary + .named_signals() + .into_iter() + .find(|named| { + let start = named.signal.offset; + (start..start + named.signal.width.div_ceil(8)).contains(&offset) + }) + .map_or_else(|| "no named signal".to_string(), |named| named.name); + return Some(format!("state byte {offset} ({signal})")); + } + if !primary + .backend + .heap() + .same_contents(shadow.simulator.backend.heap()) + { + return Some("the string heap".to_string()); + } + let (events, reference) = ( + primary.peek_runtime_events(), + shadow.simulator.peek_runtime_events(), + ); + if events != reference { + return Some(format!( + "runtime events {events:?}, the reference {reference:?}" + )); + } + None +} + +/// The first byte of design state that differs between two backends of the +/// same design. +fn first_difference(primary: &B, shadow: &B) -> Option { + let range = celox_state_layout::STATE_HEADER_SIZE..primary.layout().total_size; + let bytes = |backend: &B| { + let (ptr, len) = backend.memory_as_ptr(); + assert!(range.end <= len, "state exceeds the memory image"); + // Safety: the backend exposes `len` readable bytes at `ptr`. + let memory = unsafe { std::slice::from_raw_parts(ptr, len) }; + memory[range.clone()].to_vec() + }; + let (primary, shadow) = (bytes(primary), bytes(shadow)); + primary + .iter() + .zip(&shadow) + .position(|(a, b)| a != b) + .map(|index| range.start + index) +} + +#[cfg(all(test, feature = "systemverilog"))] +mod tests { + use std::path::Path; + + use crate::{SchedulerMode, Simulation}; + + const SOURCE: &str = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] count, output logic flag); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin + count = 8'd0; + flag = $test$plusargs("fast"); + forever @(posedge clk) count <= count + (flag ? 8'd2 : 8'd1); + end + endmodule + "#; + + fn build(mode: SchedulerMode) -> Simulation { + Simulation::from_sv_sources(vec![(SOURCE, Path::new("top.sv"))], "Top") + .scheduler_mode(mode) + .build() + .unwrap() + } + + #[test] + fn differential_mode_checks_every_step_against_the_reference() { + let mut sim = build(SchedulerMode::Differential); + sim.run_until(100).unwrap(); + // A host write between runs reaches the shadow too. + let count = sim.signal("count"); + sim.modify(|io| io.set(count, 100u8)).unwrap(); + sim.run_until(200).unwrap(); + let mut reference = build(SchedulerMode::Reference); + reference.run_until(100).unwrap(); + reference.modify(|io| io.set(count, 100u8)).unwrap(); + reference.run_until(200).unwrap(); + assert_eq!(sim.get(count), reference.get(count)); + let stats = sim.scheduler_stats(); + assert_eq!(stats.mode, SchedulerMode::Differential); + assert!(stats.checked_steps > 0); + assert_eq!(reference.scheduler_stats().checked_steps, 0); + } + + #[test] + fn differential_mode_mirrors_host_writes_in_a_stopped_slot() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic [7:0] a, output logic [7:0] seen); + logic [7:0] y; + assign y = a + 8'd1; + initial begin + seen = 8'd0; + #5 $stop; + seen = y; + end + endmodule + "#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build() + .unwrap(); + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 3u8)).unwrap(); + sim.run_until(10).unwrap(); + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), 4u8.into()); + assert!(sim.scheduler_stats().checked_steps >= 2); + } + + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + #[test] + fn the_shadow_runs_its_own_compiled_events() { + use crate::backend::{EventHandle as _, SimBackend as _}; + let source = r#" + module Top(input logic clk, output logic [7:0] count); + initial count = 8'd0; + always_ff @(posedge clk) count <= count + 8'd1; + endmodule + "#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(100).unwrap(); + let shadow = sim.shadow.as_ref().unwrap(); + let own = shadow.simulator.backend.id_to_event_slice(); + let primary = sim.simulator.backend.id_to_event_slice(); + let events = shadow + .state + .export_schedule(&shadow.simulator.backend) + .events; + assert!(!events.is_empty()); + for event in events { + let id = event.event_ref.id(); + assert_eq!(event.event_ref.func as usize, own[id].func as usize); + assert_ne!(event.event_ref.func as usize, primary[id].func as usize); + } + } + + #[test] + fn differential_mode_reports_a_diverging_step() { + let mut sim = build(SchedulerMode::Differential); + // The shadow sees other plusargs, which a copy of the state does not + // carry, so its first step computes another flag. + sim.shadow.as_mut().unwrap().simulator.plusargs = + celox_runtime::plusargs::Plusargs(vec!["+fast".to_string()]); + let error = sim.run_until(100).unwrap_err().to_string(); + assert!( + error.contains("diverged from the reference in the step from time 0"), + "{error}" + ); + } +} diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 53e0d326276..0eff469ac73 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -172,6 +172,33 @@ fn value(sim: &mut Simulation, name: &str) -> u64 { u64::try_from(value).unwrap() } +#[test] +fn kernels_record_whether_every_delay_is_a_constant_time() { + let mut d = Design::new("Delays", false); + let x = d.internal("x", 8, 0); + let amount = d.input("amount", 8); + let constant = vec![d.inactive_delay(5), d.set(x, 1), d.delay(2)]; + d.module.process(constant).unwrap(); + let zero = vec![d.inactive_delay(0), d.set(x, 2)]; + d.module.process(zero).unwrap(); + let variable = Statement::InactiveDelay { + amount: d.read(amount), + }; + d.module.process(vec![variable]).unwrap(); + let none = vec![d.set(x, 3)]; + d.module.process(none).unwrap(); + let sim = builder(&d.finish(), false).build_interpreter().unwrap(); + let flags: Vec<_> = sim + .simulator + .program + .runtime_schema + .processes + .iter() + .map(|slots| slots.const_delays) + .collect(); + assert_eq!(flags, [true, false, false, true]); +} + #[test] fn process_optimization_preserves_state_changes_between_continuations() { for four_state in [false, true] { @@ -740,6 +767,41 @@ module Top(input logic a, b, output logic y, output logic [31:0] r, output logic endmodule "#; + #[test] + fn sv_kernels_record_whether_every_delay_is_a_constant_time() { + let source = r#" +`timescale 1ns/1ps +module Top(input logic [7:0] d); + localparam int HALF = 5; + logic clk, a, b, c, e; + initial clk = 1'b0; + always #HALF clk = ~clk; + initial #(d) a = 1'b1; + initial #0 b = 1'b1; + initial #2.5 e = 1'b1; + initial #(-1) c = 1'b1; +endmodule +"#; + let sim = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("delays.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let flags: Vec<_> = sim + .simulator + .program + .runtime_schema + .processes + .iter() + .filter(|slots| !slots.is_initializer) + .map(|slots| slots.const_delays) + .collect(); + // `initial clk = 1'b0` folds into an initial value. A real delay + // and a negative one count as variable. + assert_eq!(flags, [true, false, false, false, false]); + } + #[test] fn imperative_comb_units_pulse_only_when_an_input_changes() { for four_state in [false, true] { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 9651f481f31..da45194afbd 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -320,7 +320,7 @@ mod host { /// A bounded continuation of the backend ring. Records remain unformatted /// until the eventual consumer supplies its scope/time context. - #[derive(Default)] + #[derive(Clone, Default)] struct PendingRuntimeEvents { events: std::collections::VecDeque, missed: u64, @@ -1189,6 +1189,44 @@ mod host { ); } + /// The runtime events [`Self::drain_runtime_events`] would return + /// next, without taking them. + pub(crate) fn peek_runtime_events(&mut self) -> Vec { + self.stash_runtime_events(); + let raw = self.pending_host_events.lock().unwrap().clone().drain(); + raw.into_iter() + .filter_map(|raw| { + render_raw_runtime_event( + raw, + &self.program.runtime_schema.runtime_event_sites, + RuntimeFormatContext::default(), + ) + }) + .collect() + } + + /// Make the design state, the host state design code observes and + /// the undrained runtime events those of `other`, a simulator of the + /// same design. Host state outside the memory image, such as open + /// files, is not copied. + pub(crate) fn mirror(&mut self, other: &mut Self) { + other.stash_runtime_events(); + self.stash_runtime_events(); + let pending = other.pending_host_events.lock().unwrap().clone(); + *self.pending_host_events.lock().unwrap() = pending; + let fingerprint = self.state_fingerprint(); + crate::simulator::StateImage::capture(&other.backend, other.state_fingerprint()) + .restore_into(&mut self.backend, fingerprint) + .expect("a simulator of the same design"); + self.frozen = other.frozen; + self.dirty = other.dirty; + self.declaration_phase = other.declaration_phase; + self.comb_observer_snapshots + .clone_from(&other.comb_observer_snapshots); + self.comb_observer_initial_eval = other.comb_observer_initial_eval; + self.host_watch.set_log(other.host_watch.log().to_vec()); + } + /// Move the events in the backend's buffer to the queue that /// [`Self::drain_runtime_events`] reads. pub(crate) fn stash_runtime_events(&mut self) { diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 919968af2c9..9c44bf4a7d1 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1697,6 +1697,9 @@ mod host { pub dpi: crate::DpiSymbols, /// Ordered command-line arguments for SystemVerilog plusargs queries. pub plusargs: Vec, + /// The loop that runs the time slots of a [`crate::Simulation`]. + #[doc(hidden)] + pub scheduler: crate::SchedulerMode, } /// A code-generated native program that has not been loaded into @@ -1929,6 +1932,7 @@ mod host { allow_inferred_latches: false, dpi: crate::DpiSymbols::default(), plusargs: Vec::new(), + scheduler: crate::SchedulerMode::default(), } } } @@ -3614,6 +3618,15 @@ mod host { } } + /// Select the loop that runs time slots. A test option: + /// [`crate::SchedulerMode::Differential`] compiles the design twice + /// and checks every step against a shadow simulation. + #[doc(hidden)] + pub fn scheduler_mode(mut self, mode: crate::SchedulerMode) -> Self { + self.options.scheduler = mode; + self + } + /// Compiles the design using the host's default backend. pub fn build(self) -> Result { #[cfg(any( @@ -3701,23 +3714,65 @@ mod host { fn build_with_backend( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, - compile: impl FnOnce( - &crate::ir::LaidOutProgram, - &SimulatorOptions, - ) -> Result, + compile: impl Fn(&crate::ir::LaidOutProgram, &SimulatorOptions) -> Result, ) -> Result, SimulatorError> { self.options.emit_triggers = true; let (laid_out, mut warnings, options, vcd_path, injected_components) = self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - // Initial kernels must keep their time-zero gates until the timed - // scheduler starts them; ordinary Simulator builders release them. - let mut sim = Simulator::with_backend_and_program_for_simulation( + let shadow = if options.scheduler != crate::SchedulerMode::Differential { + 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() { + Ok(()) => Ok(Box::new(shadow)), + Err(_) => Err("the design keeps host state outside its memory image"), + }) + }; + 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) + } + + /// Initialize a timed simulation of `program` compiled into + /// `backend`. + fn start_simulation( + backend: B, + program: crate::ir::RuntimeProgram, + warnings: Vec, + options: &SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> { + // Initial kernels must keep their time-zero gates until the timed + // scheduler starts them; ordinary Simulator builders release them. + let mut sim = + Simulator::with_backend_and_program_for_simulation(backend, program, warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); @@ -3751,6 +3806,7 @@ mod host { match crate::Simulation::try_new(sim) { Ok(mut simulation) => { simulation.simulator.warnings = warnings; + simulation.state.set_scheduler_mode(options.scheduler); Ok(simulation) } Err(error) => Err(SimulatorError::from(error).with_warnings(warnings)), diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 74b4e09475d..79c4a1193ab 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -1,6 +1,6 @@ //! Runs SystemVerilog suite cases on the Celox backends. -use celox::{BigUint, RuntimeEvent, SimBackend, Simulation, Simulator}; +use celox::{BigUint, RuntimeEvent, SchedulerMode, SimBackend, Simulation, Simulator}; use celox_test_suite::{Backend, CompilationRejected, Design, Result, SignalPath}; struct CeloxBackend(Simulator); @@ -91,6 +91,27 @@ impl TimedBackend { } } +/// In differential mode, a case either checked its steps against the shadow +/// or reports why none was checked; it never passes unchecked silently. +impl Drop for TimedBackend { + #[allow(clippy::disallowed_macros)] // The skip report goes to the test log. + fn drop(&mut self) { + if std::thread::panicking() || scheduler_mode() != SchedulerMode::Differential { + return; + } + let stats = self.sim.scheduler_stats(); + match stats.unchecked { + Some(reason) => eprintln!("differential: unchecked: {reason}"), + // A design without processes, waits or scheduled events may + // settle host writes on read and only move time. + None if stats.checked_steps == 0 => { + eprintln!("differential: unchecked: the case took no scheduler step") + } + None => {} + } + } +} + fn collect_output(events: Vec) -> Result> { let mut output = Vec::new(); for event in events { @@ -233,6 +254,19 @@ impl Backend for CeloxBackend { } } +/// The scheduler mode of timed cases: `CELOX_SCHEDULER` set to +/// `reference`, `compiled` or `differential`, by default the library's. +#[allow(clippy::disallowed_methods)] // Opt-in test configuration is environment-driven. +fn scheduler_mode() -> SchedulerMode { + match std::env::var("CELOX_SCHEDULER").as_deref() { + Ok("reference") => SchedulerMode::Reference, + Ok("compiled") => SchedulerMode::Compiled, + Ok("differential") => SchedulerMode::Differential, + Ok(other) => panic!("unknown CELOX_SCHEDULER mode `{other}`"), + Err(_) => SchedulerMode::default(), + } +} + fn build(design: &Design, backend: &str) -> Result> { celox_test_suite::validate_timed_design(design)?; let sources = design @@ -243,6 +277,7 @@ fn build(design: &Design, backend: &str) -> Result> { if design.timed { let builder = design.parameters.iter().fold( Simulation::from_sv_sources(sources, &design.top) + .scheduler_mode(scheduler_mode()) .four_state(design.four_state) .allow_inferred_latches(design.allow_inferred_latches), |builder, (name, value)| builder.param(name, *value),