From 265410ca867754fc2b407c93b9a630a7679fdd38 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:44:35 +0900 Subject: [PATCH 1/5] ci: skip irrelevant PR title validation events Change-Id: Ibe7a9ecc7f44cb33293349a52278c12ff72f852f --- .github/workflows/pr-title.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml index 39d0763b605..8ab64cb3dda 100644 --- a/.github/workflows/pr-title.yml +++ b/.github/workflows/pr-title.yml @@ -12,6 +12,13 @@ permissions: jobs: conventional-title: name: Conventional Commit title + # Queue metadata comes from git notes, not the draft PR description. + # Keep base edits: retargeting can enable the default-branch release gate. + if: >- + github.event_name == 'merge_group' || + (github.event.pull_request.state == 'open' && + (github.event.action != 'edited' || + github.event.changes.title || github.event.changes.base)) runs-on: ubuntu-latest steps: - name: Check out the trusted title validator From 2ee20a119c56ac0a0921e43cf4a924c632c3850c Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:45:46 +0900 Subject: [PATCH 2/5] ci: preserve required title checks on open PR edits Change-Id: Ia857d73de2b1787a2d96cabe6d6e6a21a99a7d73 --- .github/workflows/pr-title.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml index 8ab64cb3dda..1ea1124d822 100644 --- a/.github/workflows/pr-title.yml +++ b/.github/workflows/pr-title.yml @@ -12,13 +12,11 @@ permissions: jobs: conventional-title: name: Conventional Commit title - # Queue metadata comes from git notes, not the draft PR description. - # Keep base edits: retargeting can enable the default-branch release gate. + # Edits can arrive after closure. Do not allocate a runner for those events. + # Keep all open-PR edits: a skipped required check could mask a prior failure. if: >- github.event_name == 'merge_group' || - (github.event.pull_request.state == 'open' && - (github.event.action != 'edited' || - github.event.changes.title || github.event.changes.base)) + github.event.pull_request.state == 'open' runs-on: ubuntu-latest steps: - name: Check out the trusted title validator From eff7b4d4f3172758286d37c0c9fb9179f9f64e7e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:49:53 +0900 Subject: [PATCH 3/5] ci: repair script validation prerequisites Change-Id: I51d1e0d27dd9f7efc201748da08eb1555df37c85 --- .github/workflows/ci.yml | 6 +++--- scripts/publish-crates.sh | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e2eace94df0..9b1fde462a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -175,16 +175,16 @@ jobs: cargo doc --locked --no-deps "${args[@]}" - uses: pnpm/action-setup@v6 - if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' + if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' || needs.changes.outputs.scripts == 'true' - uses: actions/setup-node@v7 - if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' + if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' || needs.changes.outputs.scripts == 'true' with: node-version: 24 cache: pnpm - name: Install dependencies - if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' + if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' || needs.changes.outputs.scripts == 'true' run: pnpm install --frozen-lockfile --ignore-scripts - name: Biome check diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 4751671c3c4..890afaef325 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -17,11 +17,11 @@ fi # already been published. Keep each adapter after the crates it links. crates=( celox-sv-syntax + celox-design celox-sv-analyzer celox-test-suite celox-analysis celox-backend-common - celox-design celox-frontend-sdk celox-macros celox-ts-gen From 80657a14c0355ad323432e8e5b83d14dd48b8a02 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:46:03 +0900 Subject: [PATCH 4/5] refactor(frontend): record whether process kernels delay by constant times ProcessKernelBuilder takes the delay amount's value when the frontend knows it and records in ProcessSlots::const_delays whether every delay of the kernel is a constant of at least one time unit. The SV frontend records integral constants; the SIR it emits is unchanged. The slots are part of the native image, so its container version moves to 28. Change-Id: I0cf80b28fd983be51686322c0562d9b664d919e1 --- crates/celox-design/src/lib.rs | 4 +++ crates/celox-frontend-core/src/process.rs | 33 ++++++++++++++++--- crates/celox-frontend-core/src/sdk.rs | 24 ++++++++++++-- crates/celox-frontend-sv/src/lowering.rs | 3 +- crates/celox-frontend-sv/src/lowering/ff.rs | 15 ++++++++- crates/celox/src/backend/native/image_file.rs | 2 +- 6 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index b283788d24b..a7e4e7aa473 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -455,6 +455,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, @@ -465,6 +468,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 742b44be619..170d86d92b0 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4083,6 +4083,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), @@ -4127,7 +4128,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 a6de1d2a32a..b519264fbb0 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4276,10 +4276,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, @@ -4422,6 +4424,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)?, @@ -4429,6 +4434,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)?; @@ -4477,7 +4489,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) } @@ -4837,6 +4849,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/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; From 2ba0d0a4bc12e9722121574b1cdae0e2be032831 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 22:46:03 +0900 Subject: [PATCH 5/5] refactor(runtime): run timed slots from SimulationState with a scheduler mode SimulationState::run_until now holds the loop Simulation::run_until ran. A hidden builder option selects the SchedulerMode, and a hidden Simulation::scheduler_stats reports the steps each loop ran and how each kernel is scheduled. Every mode runs the reference loop until a compiled scheduler exists. SchedulerMode::Differential compiles the design twice and checks every step against a reference shadow: before a step the shadow takes the design state, scheduling state and undrained runtime events; after it the step result, scheduling state, state bytes and runtime events must match. The SV suite harness selects the mode from CELOX_SCHEDULER. Change-Id: I34d2fda76a4ed59ab4a2d0efc84ca033774c9bac --- crates/celox-runtime/src/lib.rs | 4 +- crates/celox-runtime/src/simulation/mod.rs | 57 +++++- .../celox-runtime/src/simulation/persist.rs | 83 ++++++++ crates/celox-runtime/src/simulation/stats.rs | 42 ++++ crates/celox/src/lib.rs | 2 + crates/celox/src/simulation.rs | 55 +++-- crates/celox/src/simulation/differential.rs | 188 ++++++++++++++++++ .../src/simulation/runtime_core_tests.rs | 62 ++++++ crates/celox/src/simulator.rs | 40 +++- crates/celox/src/simulator/builder.rs | 71 ++++++- .../tests/frontends/systemverilog/suite.rs | 16 +- 11 files changed, 591 insertions(+), 29 deletions(-) create mode 100644 crates/celox-runtime/src/simulation/stats.rs create mode 100644 crates/celox/src/simulation/differential.rs diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2d2b872cc15..d8f0ad79b9b 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -35,8 +35,8 @@ 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, 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..07724e56eed 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; @@ -118,6 +120,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 +173,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 +224,52 @@ 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, + { + 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(executor, end)?; + 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 + } + + /// Count a step checked against a shadow simulation. + pub fn note_checked_step(&mut self) { + self.stats.checked_steps += 1; + } + /// 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..1ba9e24206a --- /dev/null +++ b/crates/celox-runtime/src/simulation/stats.rs @@ -0,0 +1,42 @@ +//! 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, + /// How each process kernel is scheduled, by process index. + pub kernels: Vec, +} 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 cef829cd455..dd789471249 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,9 @@ 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>>, } impl std::fmt::Debug for Simulation { @@ -315,7 +319,11 @@ 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, + }) } /// Returns warnings emitted during compilation. @@ -527,13 +535,18 @@ 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 result = self.differential_step_until(&mut shadow, end_time); + self.shadow = Some(shadow); + result } /// Advance time and run until `end_time` (inclusive). @@ -542,33 +555,43 @@ 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. + let reached = if self.shadow.is_some() { + self.run_until_checked(end_time)? + } else { + self.state.run_until(&mut self.simulator, end_time)? + }; + if !reached { return Ok(()); } + if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { + if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + self.flush_error_output(); + } + return Err(vcd_dump_runtime_error(error)); + } + Ok(()) + } + + /// [`SimulationState::run_until`] one checked step at a time. + fn run_until_checked(&mut self, end_time: u64) -> Result { + if end_time < self.state.time() { + return Ok(false); + } 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(()); + return Ok(false); } } if self.state.is_finished() { - return Ok(()); + return Ok(false); } 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(); - } - return Err(vcd_dump_runtime_error(error)); - } - Ok(()) + Ok(true) } /// Like [`Self::run_until`], but takes at most `max_steps` steps. diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs new file mode 100644 index 00000000000..37528d13d2b --- /dev/null +++ b/crates/celox/src/simulation/differential.rs @@ -0,0 +1,188 @@ +//! [`SchedulerMode::Differential`]: every step is checked against a shadow +//! simulation of the same design that runs the reference loop. +//! +//! 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. A step suspended at `$stop` cannot be copied; the two then +//! continue in lockstep from their last equal state. +//! +//! [`SchedulerMode::Differential`]: crate::SchedulerMode::Differential + +use super::Simulation; +use crate::{ + RuntimeErrorCode, + backend::{EventHandle, SimBackend}, +}; + +impl Simulation { + /// Check every step against `shadow`, a simulation of the same design. + pub(crate) fn set_shadow(&mut self, shadow: Option>>) { + self.shadow = shadow; + } + + /// One step of the scheduler, checked against the shadow. + pub(super) fn differential_step_until( + &mut self, + shadow: &mut Simulation, + end_time: u64, + ) -> Result, RuntimeErrorCode> { + if !self.state.is_suspended() { + shadow.simulator.mirror(&mut self.simulator); + let events = self.simulator.backend.id_to_event_slice(); + shadow + .state + .restore(&self.state.snapshot(), |event| { + events.get(event.id()).copied() + }) + .unwrap_or_else(|_| unreachable!("the shadow has the same events")); + } + let start = self.state.time(); + let primary = self.state.step_until(&mut self.simulator, end_time); + let reference = shadow.state.step_until(&mut shadow.simulator, end_time); + self.state.note_checked_step(); + if let Some(difference) = self.difference(shadow, &primary, &reference) { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "the scheduler diverged from the reference in the step from time {start}: \ + {difference}" + ), + signals: Vec::new(), + }); + } + primary + } + + /// What differs between this simulation and `shadow` after a step with + /// results `primary` and `reference`, if anything. + fn difference( + &mut self, + shadow: &mut Simulation, + primary: &Result, RuntimeErrorCode>, + reference: &Result, RuntimeErrorCode>, + ) -> Option { + let result = |result: &Result, RuntimeErrorCode>| match result { + Ok(time) => format!("{time:?}"), + Err(error) => format!("error: {error}"), + }; + let (primary, reference) = (result(primary), result(reference)); + if primary != reference { + return Some(format!( + "the step returned {primary}, the reference {reference}" + )); + } + let (key, reference) = (self.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(&self.simulator.backend, &shadow.simulator.backend) { + let signal = self + .simulator + .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})")); + } + let (events, reference) = ( + self.simulator.peek_runtime_events(), + shadow.simulator.peek_runtime_events(), + ); + if events != reference { + return Some(format!( + "runtime events {events:?}, the reference {reference:?}" + )); + } + None + } + + /// 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 { + self.state.scheduler_stats().clone() + } +} + +/// 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_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 07e2c81f497..41184dcd214 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..1a6ae7d7bf2 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,64 @@ 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 + && injected_components.definitions.is_empty() + { + 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. + shadow + .simulator + .check_host_checkpoint_support() + .is_ok() + .then(|| Box::new(shadow)) + } else { + None + }; + let mut simulation = Self::start_simulation( backend, laid_out.into_runtime(), warnings, - ); + &options, + vcd_path, + injected_components, + )?; + 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 +3805,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..49bdcad8224 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); @@ -233,6 +233,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 +256,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),