From 387fb869718e6498327f28c80abfe53c53f3a7a9 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 04:32:34 +0900 Subject: [PATCH] perf(testbench)!: compile concurrent Veryl scheduling through SIR Concurrent Veryl TBs returned to Rust for each process resume and each clock edge. Generate their continuation dispatch, clock waits and multi-clock time progression as ordinary SIR, composing the shared compiled clock-domain scheduler. Process arithmetic, settlement and eligible clock slots can now execute together between host services and tiering safe points. Preserve declaration-order resumes, wait releases before TB execution, TB execution before coincident clock edges, tick-limit draining, private function temporaries and pending asynchronous edge baselines. Observer-dependent slots retain runtime queue handling. Dynamic clock-count expressions propagate DUT writes, and TB settle continuations use their own 64-bit dispatch. The reference scheduler remains available for differential checks. The shared scheduler also avoids invalidating clean combinational state for unchanged clocks and internal clock-alias notifications. Clock wiring extraction is shared across the native backend and generated scheduler. Conservative handling remains for observable side effects and retained combinational state. Validation: - 281 Celox library tests; 98 native TB tests (1 existing ignored); 9 native MIR tests; 8 native image tests; 5 completion tests; 8 slot-observer tests; 6 tiered tests. - 81 runtime and 28 testbench library tests; affected-crate all-target clippy with systemverilog, cranelift, veryl-reference and wasm-runtime; compiler-only check; formatting. - A two-clock regression resumes both TB processes on every cycle and verifies fewer than 10 native entries and fewer than 3 host edge batches over 128 fast-clock cycles, matching reference results. Additional regressions cover dynamic count side effects, odd periods and more than 256 settle continuations. Performance status: no end-to-end speedup over Veryl has been established for this revision. The change is published for review without a performance claim. Related to #1984; its per-clock period batching does not by itself execute concurrent TB resumes. BREAKING CHANGE: serialized testbench metadata gains scheduler state. Appended native images use container version 55 and must be regenerated. Change-Id: I0700e2b4947fca3285991596e6306e7084a20020 --- crates/celox-design/src/lib.rs | 3 +- crates/celox-runtime/src/schedule.rs | 2 + .../celox-runtime/src/simulation/compiled.rs | 3 + crates/celox-runtime/src/simulation/edges.rs | 8 + crates/celox-runtime/src/testbench.rs | 5 + crates/celox-testbench/src/lib.rs | 21 + crates/celox-testbench/src/scheduler.rs | 68 ++ crates/celox/src/backend/native/backend.rs | 80 ++- crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/backend/native/mod.rs | 1 - .../src/{backend/native => }/clock_aliases.rs | 4 +- crates/celox/src/ir.rs | 7 + crates/celox/src/lib.rs | 2 + crates/celox/src/parser.rs | 18 + crates/celox/src/scheduler.rs | 367 ++++++++-- crates/celox/src/scheduler/testbench.rs | 673 ++++++++++++++++++ crates/celox/src/simulator/builder.rs | 155 +++- crates/celox/src/testbench.rs | 185 ++++- crates/celox/src/testbench/clock_batch.rs | 121 ++++ crates/celox/src/testbench/compiled.rs | 368 ++++++++++ crates/celox/src/testbench_compile/process.rs | 105 +++ crates/celox/tests/slot_observer.rs | 40 ++ docs/internals/architecture.md | 18 +- 23 files changed, 2146 insertions(+), 112 deletions(-) create mode 100644 crates/celox-testbench/src/scheduler.rs rename crates/celox/src/{backend/native => }/clock_aliases.rs (98%) create mode 100644 crates/celox/src/scheduler/testbench.rs create mode 100644 crates/celox/src/testbench/clock_batch.rs create mode 100644 crates/celox/src/testbench/compiled.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index a8e65014c28..f5791fcfe4f 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1354,7 +1354,8 @@ pub struct SchedulerSlots { /// Where a shared combinational settle continues. pub cont: A, /// Set when state combinational logic reads may have changed since its - /// last settle. + /// last settle. The caller initializes this before every scheduler run; + /// timed runs set it even after a checkpoint restore or partial-slot exit. pub dirty: A, /// The number of time slots the run ran. pub count: A, diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 8bead591e97..1d316cf7f1f 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -70,6 +70,7 @@ pub(crate) struct SchedulerRefs { pub(crate) exit: SignalRef, pub(crate) exit_arg: SignalRef, pub(crate) finish: SignalRef, + pub(crate) dirty: SignalRef, pub(crate) count: SignalRef, pub(crate) current: SignalRef, pub(crate) levels: SignalRef, @@ -426,6 +427,7 @@ impl ResolvedSchedule { exit: resolve(&slots.exit), exit_arg: resolve(&slots.exit_arg), finish: resolve(&slots.finish), + dirty: resolve(&slots.dirty), count: resolve(&slots.count), current: resolve(&slots.current), levels: resolve(&slots.levels), diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 68112afe6bc..f7709f4be57 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -191,6 +191,9 @@ impl SimulationState { backend.set(scheduler.limit, limit); backend.set(scheduler.exit, 0u8); backend.set(scheduler.finish, 0u8); + // State may have been restored or a prior slot may have exited early. + // Only hosts that prove their input state settled may enter clean. + backend.set(scheduler.dirty, 1u8); backend.set(scheduler.count, 0u64); for &(_, waiting) in scheduler.wake.iter().flatten() { backend.set(waiting, 0u8); diff --git a/crates/celox-runtime/src/simulation/edges.rs b/crates/celox-runtime/src/simulation/edges.rs index 11b11bd0be2..db639e1d462 100644 --- a/crates/celox-runtime/src/simulation/edges.rs +++ b/crates/celox-runtime/src/simulation/edges.rs @@ -22,6 +22,14 @@ impl SimulationState { self.record_all_levels(backend); } + /// Restore samples saved by a generated scheduler before it ran a slot. + /// This preserves pending asynchronous edges when execution returns to the queue. + pub fn restore_event_baselines(&mut self, levels: impl IntoIterator) { + for (event, level) in levels { + self.record_level(event, level); + } + } + /// Whether an event signal changed outside the queue since its last sample. /// Callers must settle pending combinational writes before treating `false` /// as permission to bypass the queue's transition detection. diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 010ebafc6b9..588c81fecce 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -476,6 +476,10 @@ pub fn bind_testbench_program( .into_iter() .map(|component| bind_component(backend, component, rtl_writes)) .collect::>>()?; + let scheduler = program + .scheduler() + .cloned() + .map(|s| s.map(|a| backend.resolve_signal(&a))); let statements = program .into_statements() .into_iter() @@ -489,6 +493,7 @@ pub fn bind_testbench_program( Some( ExecutableTestbench::from_processes(processes, random_seed) .with_kernels(kernels) + .with_scheduler(scheduler) .with_clocks(clocks) .with_private_signals(private_signals) .with_component_runtime( diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 5a347dc915b..4f4aca0d10b 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -4,6 +4,9 @@ //! execution. No Veryl AST, parser ID, simulator backend, or runtime handle is //! part of the bytecode representation. +mod scheduler; +pub use scheduler::*; + use num_bigint::BigUint; use serde::{Deserialize, Serialize}; use std::path::PathBuf; @@ -305,6 +308,7 @@ pub struct TestbenchKernel { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TestbenchProgram { kernels: Vec>, + scheduler: Option>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -320,6 +324,7 @@ impl Default for TestbenchProgram { fn default() -> Self { Self { kernels: Vec::new(), + scheduler: None, statements: Vec::new(), process_lengths: Vec::new(), clocks: Vec::new(), @@ -334,6 +339,12 @@ impl Default for TestbenchProgram { } impl TestbenchProgram { + pub fn scheduler(&self) -> Option<&TestbenchScheduler> { + self.scheduler.as_ref() + } + pub fn set_scheduler(&mut self, scheduler: TestbenchScheduler) { + self.scheduler = Some(scheduler); + } pub fn kernels(&self) -> &[TestbenchKernel] { &self.kernels } @@ -344,6 +355,7 @@ impl TestbenchProgram { pub fn new(statements: Vec>) -> Self { Self { kernels: Vec::new(), + scheduler: None, process_lengths: vec![statements.len()], clocks: Vec::new(), private_variables: Vec::new(), @@ -708,6 +720,7 @@ pub type ExecutableComponentBinding = ComponentBinding { kernels: Vec>, + scheduler: Option>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -720,6 +733,13 @@ pub struct ExecutableTestbench { } impl ExecutableTestbench { + pub fn scheduler(&self) -> Option<&TestbenchScheduler> { + self.scheduler.as_ref() + } + pub fn with_scheduler(mut self, scheduler: Option>) -> Self { + self.scheduler = scheduler; + self + } pub fn kernels(&self) -> &[TestbenchKernel] { &self.kernels } @@ -738,6 +758,7 @@ impl ExecutableTestbench { ) -> Self { Self { kernels: Vec::new(), + scheduler: None, process_lengths: vec![statements.len()], clocks: Vec::new(), private_signals: Vec::new(), diff --git a/crates/celox-testbench/src/scheduler.rs b/crates/celox-testbench/src/scheduler.rs new file mode 100644 index 00000000000..45a6c98ab84 --- /dev/null +++ b/crates/celox-testbench/src/scheduler.rs @@ -0,0 +1,68 @@ +//! Persistent state of the generated Veryl testbench scheduler. +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestbenchScheduler { + pub entry: Option, + /// Continuation, exit, simulation time, elapsed ticks, tick limit, + /// remaining slots before a runtime safe point, current process, edge-path + /// permission, finish state, settle-path permission, event reporting time, and settle continuation. + /// Indices are the `TB_*` constants below. + pub control: [A; 12], + /// State (ready/waiting/done/releasing), remaining cycles, clock, wake time, reset request. + pub processes: Vec<[A; 5]>, + /// Next rising edge, next falling edge, falling armed, generator enabled. + pub clocks: Vec<[A; 4]>, + pub events: Vec, + pub periods: Vec, + pub declared: usize, + /// Per-process homes for function temporaries; design variables stay shared. + pub locals: Vec>, + pub baselines: Vec<(A, A)>, +} + +impl TestbenchScheduler { + pub fn map(self, mut f: impl FnMut(A) -> B) -> TestbenchScheduler { + TestbenchScheduler { + entry: self.entry, + control: self.control.map(&mut f), + processes: self.processes.into_iter().map(|v| v.map(&mut f)).collect(), + clocks: self.clocks.into_iter().map(|v| v.map(&mut f)).collect(), + events: self.events.into_iter().map(&mut f).collect(), + periods: self.periods, + declared: self.declared, + baselines: self + .baselines + .into_iter() + .map(|(a, b)| (f(a), f(b))) + .collect(), + locals: self + .locals + .into_iter() + .map(|v| v.into_iter().map(|(a, b)| (f(a), f(b))).collect()) + .collect(), + } + } +} + +pub const TB_PHASE: usize = 0; +pub const TB_EXIT: usize = 1; +pub const TB_NOW: usize = 2; +pub const TB_TICKS: usize = 3; +pub const TB_LIMIT: usize = 4; +pub const TB_BUDGET: usize = 5; +pub const TB_CURRENT: usize = 6; +pub const TB_HOST: u64 = 1; +pub const TB_EDGES: u64 = 2; +pub const TB_SAFEPOINT: u64 = 3; +pub const TB_DONE: u64 = 4; +pub const TB_LIMITED: u64 = 5; +pub const TB_OVERFLOW: u64 = 6; + +pub const TB_RESET: u64 = 7; +pub const TB_NATIVE_EDGES: usize = 7; +pub const TB_STOPPED: usize = 8; +pub const TB_NATIVE_SETTLE: usize = 9; +pub const TB_FINISHED: u64 = 8; +pub const TB_REPORT_TIME: usize = 10; +pub const TB_SETTLE_CONT: usize = 11; diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index c9c6ca66fd4..130daa55ae5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -313,7 +313,7 @@ impl SharedNativeCode { // full settle. Export names are part of the native runtime contract. let mut clock_alias_funcs = vec![None; id_to_event.len()]; for entry in &program_image.code_entries { - if let Some(id) = entry.name.strip_prefix(super::clock_aliases::EXPORT_PREFIX) { + if let Some(id) = entry.name.strip_prefix(crate::clock_aliases::EXPORT_PREFIX) { let id = id .strip_suffix(']') .and_then(|id| id.parse::().ok()) @@ -787,7 +787,25 @@ impl NativeProgramImage { usize::MAX } }); - // The derived-edge units follow the kernels and the scheduler. + let testbench_units = self + .testbench + .as_ref() + .and_then(|tb| tb.scheduler()) + .and_then(|scheduler| scheduler.entry) + .map_or(0, |unit| { + if unit + == self + .runtime_schema + .processes + .len() + .saturating_add(scheduler_units) + { + 1 + } else { + usize::MAX + } + }); + // Derived-edge units follow process and scheduler entries. let derived_units = 2 * self.runtime_schema.derived_edges.len(); let derived_in_range = self.runtime_schema.derived_edges.iter().all(|units| { units.rising < self.process_offsets.len() && units.falling < self.process_offsets.len() @@ -799,10 +817,56 @@ impl NativeProgramImage { .processes .len() .saturating_add(scheduler_units) + .saturating_add(testbench_units) .saturating_add(derived_units) { return Err("process kernels and their control slots disagree".into()); } + if let Some(tb) = &self.testbench + && let Some(scheduler) = tb.scheduler() + { + let valid_slot = |a: &AbsoluteAddr| { + self.design + .state_objects + .get(a) + .is_some_and(|info| info.width == 64 && !info.is_4state) + }; + if scheduler.processes.len() != tb.kernels().len() + || scheduler.locals.len() != tb.kernels().len() + || scheduler.clocks.len() != scheduler.events.len() + || scheduler.clocks.len() != scheduler.periods.len() + || scheduler.declared > scheduler.clocks.len() + || scheduler.periods.iter().any(|&period| period < 2) + || !scheduler + .control + .iter() + .chain(scheduler.processes.iter().flatten()) + .chain(scheduler.clocks.iter().flatten()) + .all(valid_slot) + || scheduler + .events + .iter() + .any(|a| !self.design.state_objects.contains_key(a)) + || scheduler + .locals + .iter() + .flatten() + .chain(&scheduler.baselines) + .any(|(a, b)| { + let Some(a) = self.design.state_objects.get(a) else { + return true; + }; + let Some(b) = self.design.state_objects.get(b) else { + return true; + }; + a.width != b.width + || a.array_dims != b.array_dims + || a.is_4state != b.is_4state + }) + { + return Err("invalid testbench scheduler storage".into()); + } + } if self.runtime_schema.process_frames.len() != self.runtime_schema.processes.len() { return Err("process kernels and their activation frames disagree".into()); } @@ -2742,8 +2806,8 @@ fn compile_program_with_outlining_threshold( if !options.four_state && !options.native_force_support && force_bindings.is_empty() { let (_, clocks) = crate::backend::event_ids(sir); for (id, clock) in clocks.into_iter().enumerate() { - if let Some(units) = super::clock_aliases::extract(sir, clock) { - let name = format!("{}{}]", super::clock_aliases::EXPORT_PREFIX, id); + if let Some(units) = crate::clock_aliases::extract(sir, clock) { + let name = format!("{}{}]", crate::clock_aliases::EXPORT_PREFIX, id); let compiled = compile_units( &units, layout, @@ -4257,11 +4321,9 @@ mod tests { .unwrap() .into_program_image(); let previous = image.code_entries.len(); - image.code_entries.retain(|entry| { - !entry - .name - .starts_with(super::super::clock_aliases::EXPORT_PREFIX) - }); + image + .code_entries + .retain(|entry| !entry.name.starts_with(crate::clock_aliases::EXPORT_PREFIX)); assert_eq!(previous, image.code_entries.len() + 1); let image = NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index ac0fd63b341..193e6ba1110 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -10,8 +10,8 @@ use std::{ use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Concurrent assertion kernels suspend into Observed and Reactive regions. -const CONTAINER_VERSION: u16 = 53; +// Images retain generated TB scheduler continuations and clock state. +const CONTAINER_VERSION: u16 = 55; 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/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index 49bc3968db2..2636961b802 100644 --- a/crates/celox/src/backend/native/mod.rs +++ b/crates/celox/src/backend/native/mod.rs @@ -1,5 +1,4 @@ pub mod backend; -mod clock_aliases; mod compile_resources; #[cfg(target_os = "linux")] mod executable_mapping; diff --git a/crates/celox/src/backend/native/clock_aliases.rs b/crates/celox/src/clock_aliases.rs similarity index 98% rename from crates/celox/src/backend/native/clock_aliases.rs rename to crates/celox/src/clock_aliases.rs index 8478e3a50b1..74ed4470f70 100644 --- a/crates/celox/src/backend/native/clock_aliases.rs +++ b/crates/celox/src/clock_aliases.rs @@ -9,9 +9,9 @@ use crate::ir::{ }; use celox_sir::BasicBlock; -pub(super) const EXPORT_PREFIX: &str = "clock_alias_update["; +pub(crate) const EXPORT_PREFIX: &str = "clock_alias_update["; -pub(super) fn extract( +pub(crate) fn extract( program: &LaidOutProgram, clock: AbsoluteAddr, ) -> Option>> { diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index d0c490bd8cd..3f5a11a7e97 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -174,6 +174,13 @@ impl RuntimeDesign { address } + pub(crate) fn allocate_testbench_copy(&mut self, source: AbsoluteAddr) -> AbsoluteAddr { + let info = self.semantic.state_objects[&source].clone(); + let address = self.allocate_testbench_slot(info.width, false); + self.semantic.state_objects.insert(address, info); + address + } + fn from_projection( semantic: celox_design::ElaboratedDesign, frontend: FrontendLookup, diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 586e3424da4..e2115fbd8a9 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -36,6 +36,8 @@ mod parser; pub(crate) mod portable; // Builds without the host runtime run every slot in the reference loop. #[cfg(feature = "host-runtime")] +mod clock_aliases; +#[cfg(feature = "host-runtime")] mod scheduler; mod settle; #[cfg(feature = "host-runtime")] diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 5651b7fd33e..120cc5cc4fe 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -398,6 +398,24 @@ pub(crate) fn project_scheduled_rtl( }) .map_err(|error| ParserError::illegal_context("testbench SIR lowering", error, None))?; } + // TB expressions and processes are appended after symbolic scheduling. + // Keep its per-process control arrays aligned with the final kernel list. + if let Some(scheduler) = &mut runtime.runtime_schema.scheduler { + while scheduler.slots.wake.len() < runtime.runtime_schema.processes.len() { + scheduler + .slots + .wake + .push(runtime.design.allocate_testbench_slot(64, false)); + scheduler + .slots + .waiting + .push(runtime.design.allocate_testbench_slot(8, false)); + scheduler + .slots + .baseline + .push(runtime.design.allocate_testbench_slot(8, false)); + } + } runtime.testbench = testbench; dump_addr_map_if_requested(&runtime, diagnostics); Ok((sir, runtime)) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index e500e574b56..15ba593d19e 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -30,6 +30,8 @@ //! and every design or kernel this module does not qualify, runs in the //! reference loop. +mod testbench; + use celox_design::{ CounterKind, DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_CLOCKS, SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, STABLE_REGION, SchedulerExit, SchedulerSlots, @@ -76,52 +78,53 @@ const WAIT_STATUSES: [ProcessStatus; 4] = [ /// Generate the compiled scheduler of `program`, if it qualifies, and record /// for every process kernel whether the scheduler runs it. -pub(crate) fn attach(program: &mut LaidOutProgram) { +pub(crate) fn attach(program: &mut LaidOutProgram, wiring_clocks: bool) { let Some(schema) = program.runtime.runtime_schema.scheduler.clone() else { return; }; let kernels = program.runtime.runtime_schema.processes.len(); - let (fallback, unit, events, clocks, kernel_events) = match Plan::new(program, &schema.slots) { - Err(reason) => ( - vec![Some(reason); kernels], - None, - Vec::new(), - Vec::new(), - vec![Vec::new(); kernels], - ), - Ok(plan) => { - let fallback = plan.fallback.clone(); - // Without kernels, slots of host clocks alone. - let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) - .then(|| plan.generate(program, &schema.slots)); - let tracked = plan.tracked(); - let kernel_events = plan - .kernels - .iter() - .map(|kernel| { - kernel - .iter() - .flat_map(|kernel| &kernel.writes) - .map(|event| { - tracked - .binary_search(event) - .expect("the scheduler's kernels write tracked events") - }) - .collect() - }) - .collect(); - let events = tracked - .into_iter() - .map(|event| plan.events[event].signal) - .collect(); - let clocks = plan - .clocks - .iter() - .map(|&event| plan.events[event].signal) - .collect(); - (fallback, unit, events, clocks, kernel_events) - } - }; + let (fallback, unit, events, clocks, kernel_events) = + match Plan::new(program, &schema.slots, wiring_clocks) { + Err(reason) => ( + vec![Some(reason); kernels], + None, + Vec::new(), + Vec::new(), + vec![Vec::new(); kernels], + ), + Ok(plan) => { + let fallback = plan.fallback.clone(); + // Without kernels, slots of host clocks alone. + let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) + .then(|| plan.generate(program, &schema.slots)); + let tracked = plan.tracked(); + let kernel_events = plan + .kernels + .iter() + .map(|kernel| { + kernel + .iter() + .flat_map(|kernel| &kernel.writes) + .map(|event| { + tracked + .binary_search(event) + .expect("the scheduler's kernels write tracked events") + }) + .collect() + }) + .collect(); + let events = tracked + .into_iter() + .map(|event| plan.events[event].signal) + .collect(); + let clocks = plan + .clocks + .iter() + .map(|&event| plan.events[event].signal) + .collect(); + (fallback, unit, events, clocks, kernel_events) + } + }; let scheduler = program .runtime .runtime_schema @@ -136,6 +139,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { scheduler.unit = Some(program.sir.processes.len()); program.sir.processes.push(unit); } + testbench::attach(program); } /// An event the scheduler records edges of. @@ -148,6 +152,8 @@ struct Event { /// A clock edge rather than an asynchronous reset. clock: bool, eval_apply: Vec, + /// Wiring-only clock changes do not invalidate the datapath. + aliases: Option>, /// The units of the path of several triggered domains, which a design /// without kernels lacks; required when more than one event can have an /// edge in a slot. @@ -249,7 +255,11 @@ enum DomainSettle { } impl Plan { - fn new(program: &LaidOutProgram, slots: &SchedulerSlots) -> Result { + fn new( + program: &LaidOutProgram, + slots: &SchedulerSlots, + wiring_clocks: bool, + ) -> Result { let schema = &program.runtime.runtime_schema; let model = ScheduleModel::derive(&program.design, schema); if program.layout().four_state { @@ -319,6 +329,9 @@ impl Plan { clock, eval_apply: units(&sir.eval_apply_ffs)? .ok_or("an event domain has no separate units")?, + aliases: wiring_clocks + .then(|| crate::clock_aliases::extract(program, signal)) + .flatten(), eval_only: units(&sir.eval_only_ffs)?, apply: units(&sir.apply_ffs)?, }; @@ -403,7 +416,13 @@ impl Plan { // asynchronous resets by writes. let undriven = |signal: AbsoluteAddr| { !rtl_stores.contains(&signal) - && !kernel_stores.iter().any(|stores| stores.contains(&signal)) + && !kernel_stores + .iter() + .zip(&schema.processes) + .any(|(stores, process)| { + process.kind != celox_design::ProcessKind::Callable + && stores.contains(&signal) + }) && !nba_targets.contains_key(&signal) }; let clocks: Vec = events @@ -599,7 +618,15 @@ impl Plan { .collect(); // A settle is the same function of the state it reads every time, // unless combinational logic has effects of its own: records, - // captures, external calls or trigger marks. + // captures or external calls. Clock/reset trigger bits are internal + // notifications: this scheduler compares event levels itself, and + // its caller clears the bits before returning to the reference loop. + // Keep unknown notifications conservative. + let internal_trigger = |trigger: &celox_design::TriggerIdWithKind| { + addresses + .get(trigger.id) + .is_some_and(|signal| model.kinds.get(signal) == Some(&trigger.kind)) + }; let effects = sir.eval_comb.iter().any(|unit| { instructions(unit).any(|inst| match inst { SIRInstruction::RuntimeEvent { .. } @@ -607,9 +634,11 @@ impl Plan { | SIRInstruction::CombCaptureEnableIfChanged { .. } | SIRInstruction::ExternCall { .. } => true, SIRInstruction::Store(_, _, _, _, triggers, sites) => { - !triggers.is_empty() || !sites.is_empty() + triggers.iter().any(|trigger| !internal_trigger(trigger)) || !sites.is_empty() + } + SIRInstruction::Commit(_, _, _, _, triggers) => { + triggers.iter().any(|trigger| !internal_trigger(trigger)) } - SIRInstruction::Commit(_, _, _, _, triggers) => !triggers.is_empty(), _ => false, }) }); @@ -770,7 +799,54 @@ impl Plan { } } } - if !rtl_written.is_subset(&derived) { + // A combinational reset (or clock) driven only by host-owned inputs + // is stable throughout a compiled run. Host writes are settled and + // their edges handled before entering the scheduler. Callable kernels, + // like host writes, can only run outside this unit. + let scheduled_stores: HashSet = sir + .eval_apply_ffs + .values() + .flatten() + .chain(sir.eval_only_ffs.values().flatten()) + .chain(sir.apply_ffs.values().flatten()) + .flat_map(stores) + .chain( + kernel_stores + .iter() + .zip(&schema.processes) + .filter(|(_, process)| process.kind != celox_design::ProcessKind::Callable) + .flat_map(|(stores, _)| stores.iter().copied()), + ) + .chain(nba_targets.keys().copied()) + .collect(); + let clocked_storage: HashSet<_> = edged + .iter() + .map(|&event| storage(plan.events[event].signal)) + .collect(); + let stable_input = |address| { + let address = storage(address); + undriven(address) && !clocked_storage.contains(&address) + }; + let stable_host_events: BTreeSet = topology + .combinational_derived + .iter() + .filter(|(source, _)| stable_input(**source)) + .flat_map(|(_, clocks)| clocks) + .filter(|clock| !scheduled_stores.contains(&storage(clock.clock))) + .filter(|clock| { + clock.gate.as_ref().is_some_and(|gate| { + gate.iter().all(|op| match op { + celox_design::GateOp::Load { address, .. } => stable_input(*address), + _ => true, + }) + }) + }) + .filter_map(|clock| index_of.get(&topology.canonical(clock.clock)).copied()) + .collect(); + if rtl_written + .difference(&derived) + .any(|event| !stable_host_events.contains(event)) + { return Err("RTL logic drives an event signal".into()); } let gating: Vec<(usize, Vec)> = edged @@ -916,12 +992,9 @@ impl Plan { // The bit of each kernel in the ready mask: its place among the // kernels the scheduler runs, in kernel order. let ordinals = ordinals(&self.kernels); - // Every run starts dirty, and this mark is required, not a margin: - // it is the only cover for a unit that exited to the `$finish` exit - // partway through, whose mark after the unit never ran, and for - // state a checkpoint or a state file restored between runs, which - // no mark sees. - g.mark_dirty(); + // The caller supplies the dirty flag. Timed runs must start dirty: + // checkpoint restores and partial-slot exits need a fresh settle. + // A host clock batch may instead enter with already settled inputs. let header = g.b.new_block(); g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); @@ -1110,10 +1183,18 @@ impl Plan { let is = g.b.alloc_bit(1, false); g.b.emit(SIRInstruction::Mux(is, due, value, was)); g.store(event.signal, 1, is); - if g.settle_reads(event.signal) { - g.mark_dirty(); - } let changed = g.binary(1, was, BinaryOp::Ne, is); + if let Some(aliases) = &event.aliases { + for unit in aliases { + g.inline(unit, finish_exit); + } + } else if g.settle_reads(event.signal) { + // Other clocks in this batch may not be due. Writing + // their old level does not invalidate settled inputs. + let dirty = g.load(slots.dirty, SCHEDULER_FLAG_WIDTH); + let dirty = g.binary(SCHEDULER_FLAG_WIDTH, dirty, BinaryOp::Or, changed); + g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, dirty); + } let active = g.equals(is, u64::from(event.active)); let edge = g.binary(1, changed, BinaryOp::And, active); let edge = g.bit(edge, index); @@ -1428,7 +1509,26 @@ impl Plan { g.b.switch_to_block(unit); let units = match self.lazy.as_ref().map(|lazy| &lazy.domains[index]) { None | Some(DomainSettle::Pending) => &event.eval_apply, - Some(DomainSettle::Fused(units)) => units, + Some(DomainSettle::Fused(units)) => { + // Fusion is needed only when combinational inputs + // changed since the last settle. Otherwise the + // ordinary FF unit already has its inputs. + let dirty = g.load(slots.dirty, SCHEDULER_FLAG_WIDTH); + let fused = g.b.new_block(); + let clean = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: dirty, + true_block: (fused, Vec::new()), + false_block: (clean, Vec::new()), + }); + g.b.switch_to_block(clean); + for unit in &event.eval_apply { + g.inline_writer(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + g.b.switch_to_block(fused); + units + } Some(DomainSettle::Settled) => { let evaluate = g.b.new_block(); g.settle_then(evaluate); @@ -2322,16 +2422,13 @@ fn retains_state( | SIRInstruction::Commit(source, _, offset, width, _) => { let home = storage(source.absolute_addr()); if stores.contains(&home) { - let read = match offset { - SIROffset::Static(start) => { - covered.get(&(source.region, home)).is_some_and(|ranges| { - ranges - .iter() - .any(|&(s, e)| s <= *start && start + width <= e) - }) - } - _ => false, - }; + let read = offset.constant_bit_offset().is_some_and(|start| { + covered.get(&(source.region, home)).is_some_and(|ranges| { + ranges + .iter() + .any(|&(s, e)| s <= start && start + width <= e) + }) + }); if !read { return false; } @@ -2340,13 +2437,17 @@ fn retains_state( _ => {} } match inst { - SIRInstruction::Store(target, SIROffset::Static(start), width, ..) - | SIRInstruction::Commit(_, target, SIROffset::Static(start), width, _) => add( - covered, - (target.region, storage(target.absolute_addr())), - *start, - start + width, - ), + SIRInstruction::Store(target, offset, width, ..) + | SIRInstruction::Commit(_, target, offset, width, _) => { + if let Some(start) = offset.constant_bit_offset() { + add( + covered, + (target.region, storage(target.absolute_addr())), + start, + start + width, + ); + } + } _ => {} } } @@ -2488,3 +2589,119 @@ fn statuses_only(unit: &Unit, status: AbsoluteAddr, allowed: &[ProcessStatus]) - _ => true, }) } + +/// Instrument the generated settle after eligibility/retention analysis, so +/// measuring it does not turn a pure combinational cone into a stateful one. +#[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] +pub(crate) fn count_test_settles( + program: &mut LaidOutProgram, + counter: AbsoluteAddr, + fused_counter: AbsoluteAddr, +) -> usize { + fn counted(units: &[Unit], counter: AbsoluteAddr) -> Vec { + let mut b = Builder::new(); + let count = b.alloc_bit(64, false); + let one = b.alloc_bit(64, false); + let next = b.alloc_bit(64, false); + let address = RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, counter); + b.emit(SIRInstruction::Load( + count, + address, + SIROffset::Static(0), + 64, + )); + b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + b.emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + b.emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + 64, + next, + vec![], + vec![], + )); + for unit in units { + b.inline_execution_unit(unit); + } + b.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = b.drain(); + vec![Unit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + }] + } + let schema = program.runtime.runtime_schema.scheduler.clone().unwrap(); + let mut plan = Plan::new(program, &schema.slots, true).unwrap(); + let mut fused = 0; + if let Some(lazy) = &mut plan.lazy { + for domain in &mut lazy.domains { + if let DomainSettle::Fused(units) = domain { + *units = counted(units, fused_counter); + fused += 1; + } + } + } + let instrumented = counted(&program.sir.eval_comb, counter); + let original = std::mem::replace(&mut program.sir.eval_comb, instrumented); + let generated = plan.generate(program, &schema.slots); + program.sir.eval_comb = original; + program.sir.processes[schema.unit.unwrap()] = generated; + fused +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retention_uses_logical_ranges_for_packed_elements() { + let address = AbsoluteAddr { + instance_id: celox_design::InstanceId(0), + var_id: celox_design::StateObjectId(0), + }; + let offsets = [ + SIROffset::Static(0), + SIROffset::PackedElements { + bit_offset: 0, + element_width: 4, + }, + ]; + for store in &offsets { + for load in &offsets { + for width in [8, 32] { + let mut b = Builder::new(); + let value = b.alloc_bit(32, false); + let read = b.alloc_bit(32, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(0u32))); + b.emit(SIRInstruction::Store( + stable(address), + store.clone(), + width, + value, + vec![], + vec![], + )); + b.emit(SIRInstruction::Load( + read, + stable(address), + load.clone(), + 32, + )); + b.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = b.drain(); + let unit = Unit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + }; + assert_eq!( + retains_state(&[unit], &|a| a, &HashSet::from_iter([address])), + width < 32, + "store={store:?} load={load:?} width={width}" + ); + } + } + } + } +} diff --git a/crates/celox/src/scheduler/testbench.rs b/crates/celox/src/scheduler/testbench.rs new file mode 100644 index 00000000000..9d41313de4c --- /dev/null +++ b/crates/celox/src/scheduler/testbench.rs @@ -0,0 +1,673 @@ +//! Veryl TB continuations and clock progress in the shared SIR backend. +use super::*; +use celox_sir::BlockId; +use celox_testbench::*; + +type Meta = TestbenchScheduler; + +pub(super) fn attach(program: &mut LaidOutProgram) { + let Some(tb) = program.runtime.testbench.clone() else { + return; + }; + let Some(mut meta) = tb.scheduler().cloned() else { + return; + }; + let Some(schema) = program.runtime.runtime_schema.scheduler.clone() else { + return; + }; + let unit = generate(program, &tb, &meta, &schema.slots); + meta.entry = Some(program.sir.processes.len()); + program.sir.processes.push(unit); + program + .runtime + .testbench + .as_mut() + .unwrap() + .set_scheduler(meta); +} + +fn put(g: &mut Generator<'_>, a: AbsoluteAddr, value: u64) { + let value = g.constant(value, 64); + g.store(a, 64, value); +} +fn jump(g: &mut Generator<'_>, to: BlockId) { + g.b.seal_block(SIRTerminator::Jump(to, vec![])); +} +fn branch(g: &mut Generator<'_>, cond: RegisterId, yes: BlockId, no: BlockId) { + g.b.seal_block(SIRTerminator::Branch { + cond, + true_block: (yes, vec![]), + false_block: (no, vec![]), + }); +} +fn dispatch( + g: &mut Generator<'_>, + selector: RegisterId, + cases: Vec, + default: BlockId, +) { + for case in cases { + let constant = case.value.to_u64_digits().first().copied().unwrap_or(0); + let matched = g.equals(selector, constant); + let next = g.b.new_block(); + branch(g, matched, case.target, next); + g.b.switch_to_block(next); + } + jump(g, default); +} +// TBs can have more continuation sites than the timed scheduler's 8-bit +// continuation selector. Keep their dispatch in the TB's own 64-bit slot. +fn settle_then(g: &mut Generator<'_>, m: &Meta, target: BlockId) { + let index = match g.continuations.iter().position(|&block| block == target) { + Some(i) => i, + None => { + g.continuations.push(target); + g.continuations.len() - 1 + } + }; + put(g, m.control[TB_SETTLE_CONT], index as u64); + jump(g, g.comb); +} +fn emit_settle(g: &mut Generator<'_>, m: &Meta, units: &[Unit], finish: BlockId, invalid: BlockId) { + g.b.switch_to_block(g.comb); + let dirty = g.load(g.slots.dirty, 8); + let clean = g.equals(dirty, 0); + let evaluate = g.b.new_block(); + let settled = g.b.new_block(); + branch(g, clean, settled, evaluate); + g.b.switch_to_block(evaluate); + for unit in units { + g.inline(unit, finish); + } + let zero = g.constant(0, 8); + g.store(g.slots.dirty, 8, zero); + jump(g, settled); + g.b.switch_to_block(settled); + let continuation = g.load(m.control[TB_SETTLE_CONT], 64); + let cases = g + .continuations + .iter() + .enumerate() + .map(|(i, &target)| SIRSwitchCase { + value: (i as u64).into(), + target, + }) + .collect(); + dispatch(g, continuation, cases, invalid); +} +fn choose(g: &mut Generator<'_>, cond: RegisterId, yes: RegisterId, no: RegisterId) -> RegisterId { + let r = g.b.alloc_bit(64, false); + g.b.emit(SIRInstruction::Mux(r, cond, yes, no)); + r +} +fn equals_slot(g: &mut Generator<'_>, a: AbsoluteAddr, value: u64) -> RegisterId { + let r = g.load(a, 64); + g.equals(r, value) +} +fn equals_slot_width( + g: &mut Generator<'_>, + a: AbsoluteAddr, + width: usize, + value: u64, +) -> RegisterId { + let r = g.load(a, width); + g.equals(r, value) +} +fn copy(g: &mut Generator<'_>, program: &LaidOutProgram, from: AbsoluteAddr, to: AbsoluteAddr) { + let info = &program.design.state_objects[&from]; + let elements = info.array_dims.iter().product::().max(1); + let width = info.width / elements; + for index in 0..elements { + let r = if info.is_4state { + g.b.alloc_logic(width) + } else { + g.b.alloc_bit(width, false) + }; + g.b.emit(SIRInstruction::Load( + r, + stable(from), + SIROffset::Static(index * width), + width, + )); + g.b.emit(SIRInstruction::Store( + stable(to), + SIROffset::Static(index * width), + width, + r, + vec![], + vec![], + )); + } +} +fn sites<'a>( + body: &'a [SemanticStatement], + out: &mut Vec<&'a SemanticStatement>, +) { + for s in body { + out.push(s); + match s { + SemanticStatement::If { + then_block, + else_block, + .. + } => { + sites(then_block, out); + sites(else_block, out); + } + SemanticStatement::For { body, .. } => sites(body, out), + _ => {} + } + } +} + +fn generate( + program: &LaidOutProgram, + tb: &TestbenchProgram, + m: &Meta, + slots: &SchedulerSlots, +) -> Unit { + let mut b = Builder::new(); + let comb = b.new_block(); + let reads = HashSet::default(); + let finish_sites = program + .runtime + .runtime_schema + .runtime_event_sites + .iter() + .enumerate() + .filter(|(_, s)| matches!(s.kind, RuntimeEventKind::Finish | RuntimeEventKind::Stop)) + .map(|(i, _)| i as u32) + .collect(); + let mut g = Generator { + b, + slots, + finish_sites: &finish_sites, + exits: vec![], + settle_reads: Some(&reads), + shared: program.shared_storage(), + comb, + continuations: vec![], + }; + let initialize = g.b.new_block(); + let start = g.b.new_block(); + let edge = g.b.new_block(); + let after_edges = g.b.new_block(); + let end = g.b.new_block(); + let done = g.b.new_block(); + let limited = g.b.new_block(); + let overflow = g.b.new_block(); + let safe = g.b.new_block(); + let finish = g.b.new_block(); + let finished = g.b.new_block(); + let release_check: Vec<_> = m.processes.iter().map(|_| g.b.new_block()).collect(); + let run: Vec<_> = m.processes.iter().map(|_| g.b.new_block()).collect(); + let pick: Vec<_> = m.processes.iter().map(|_| g.b.new_block()).collect(); + let released: Vec<_> = m.processes.iter().map(|_| g.b.new_block()).collect(); + let save: Vec<_> = m.processes.iter().map(|_| g.b.new_block()).collect(); + let mut cases = vec![ + SIRSwitchCase { + value: u64::MAX.into(), + target: initialize, + }, + SIRSwitchCase { + value: 0u64.into(), + target: start, + }, + SIRSwitchCase { + value: 1u64.into(), + target: after_edges, + }, + ]; + for (i, &r) in run.iter().enumerate() { + cases.push(SIRSwitchCase { + value: (2 + 2 * i as u64).into(), + target: r, + }); + cases.push(SIRSwitchCase { + value: (3 + 2 * i as u64).into(), + target: released[i], + }); + } + for (i, &target) in save.iter().enumerate() { + cases.push(SIRSwitchCase { + value: (2 + 2 * run.len() as u64 + i as u64).into(), + target, + }); + } + let phase = g.load(m.control[TB_PHASE], 64); + dispatch(&mut g, phase, cases, overflow); + + g.b.switch_to_block(initialize); + for locals in &m.locals { + for &(source, saved) in locals { + copy(&mut g, program, source, saved); + } + } + jump(&mut g, start); + g.b.switch_to_block(start); + let now = g.load(m.control[TB_NOW], 64); + g.store(m.control[TB_REPORT_TIME], 64, now); + for &(source, saved) in &m.baselines { + copy(&mut g, program, source, saved); + } + jump(&mut g, release_check.first().copied().unwrap_or(edge)); + + for (i, kernel) in tb.kernels().iter().enumerate() { + let p = m.processes[i]; + let next = pick.get(i + 1).copied().unwrap_or(edge); + g.b.switch_to_block(release_check[i]); + let state = g.load(p[0], 64); + let releasing = g.equals(state, 3); + let wake = g.load(p[3], 64); + let now = g.load(m.control[TB_NOW], 64); + let due = g.binary(1, wake, BinaryOp::Eq, now); + let release = g.binary(1, due, BinaryOp::And, releasing); + let wake_block = g.b.new_block(); + branch(&mut g, release, wake_block, released[i]); + g.b.switch_to_block(wake_block); + put(&mut g, p[0], 0); + let reset = g.load(p[4], 64); + let has_reset = g.equals(reset, 0); + let reset_host = g.b.new_block(); + branch(&mut g, has_reset, released[i], reset_host); + g.b.switch_to_block(reset_host); + put(&mut g, m.control[TB_CURRENT], i as u64); + put(&mut g, m.control[TB_PHASE], 3 + 2 * i as u64); + put(&mut g, m.control[TB_EXIT], TB_RESET); + g.b.seal_block(SIRTerminator::Return); + g.b.switch_to_block(released[i]); + jump( + &mut g, + release_check.get(i + 1).copied().unwrap_or_else(|| pick[0]), + ); + g.b.switch_to_block(pick[i]); + let ready = equals_slot(&mut g, p[0], 0); + let ticks = g.load(m.control[TB_TICKS], 64); + let limit = g.load(m.control[TB_LIMIT], 64); + let active = g.binary(1, ticks, BinaryOp::LtU, limit); + let running = equals_slot(&mut g, m.control[TB_STOPPED], 0); + let active = g.binary(1, active, BinaryOp::And, running); + let ready = g.binary(1, ready, BinaryOp::And, active); + let restore = g.b.new_block(); + branch(&mut g, ready, restore, next); + g.b.switch_to_block(restore); + for &(source, saved) in &m.locals[i] { + copy(&mut g, program, saved, source); + } + jump(&mut g, run[i]); + g.b.switch_to_block(run[i]); + put(&mut g, m.control[TB_CURRENT], i as u64); + g.b.inline_execution_unit(&program.sir.processes[kernel.entry]); + let status = g.load(kernel.status, celox_design::PROCESS_STATUS_WIDTH); + let is_done = g.equals(status, ProcessStatus::Done.code() as u64); + let completed = g.b.new_block(); + let request = g.b.new_block(); + branch(&mut g, is_done, completed, request); + g.b.switch_to_block(completed); + put(&mut g, p[0], 2); + jump(&mut g, save[i]); + g.b.switch_to_block(request); + let request_value = g.load(kernel.request, 64); + let requests: Vec<_> = kernel.requests.iter().map(|_| g.b.new_block()).collect(); + let cases = requests + .iter() + .enumerate() + .map(|(index, &target)| SIRSwitchCase { + value: celox_design::HostRequestKind::Testbench + .encode(index as u32) + .into(), + target, + }) + .collect(); + dispatch(&mut g, request_value, cases, overflow); + let mut statements = vec![]; + sites(tb.processes().nth(i).unwrap(), &mut statements); + for (request, block) in kernel.requests.iter().zip(requests) { + g.b.switch_to_block(block); + match request { + KernelRequest::Settle => { + let native = equals_slot(&mut g, m.control[TB_NATIVE_SETTLE], 1); + let settle = g.b.new_block(); + let host = g.b.new_block(); + branch(&mut g, native, settle, host); + g.b.switch_to_block(host); + put(&mut g, m.control[TB_PHASE], 2 + 2 * i as u64); + put(&mut g, m.control[TB_EXIT], TB_HOST); + g.b.seal_block(SIRTerminator::Return); + g.b.switch_to_block(settle); + settle_then(&mut g, m, run[i]); + } + KernelRequest::Written { .. } => { + let dirty = g.constant(1, 8); + g.store(slots.dirty, 8, dirty); + jump(&mut g, run[i]); + } + KernelRequest::Statement(site) + if matches!(statements[*site], SemanticStatement::ClockNext { .. }) => + { + let SemanticStatement::ClockNext { + clock_event, count, .. + } = statements[*site] + else { + unreachable!() + }; + let clock = m.events.iter().position(|a| a == clock_event).unwrap(); + let count = match count { + ClockCount::Static(n) => g.constant(*n, 64), + ClockCount::Dynamic(expr) => { + let native = equals_slot(&mut g, m.control[TB_NATIVE_SETTLE], 1); + let evaluate = g.b.new_block(); + let host = g.b.new_block(); + branch(&mut g, native, evaluate, host); + g.b.switch_to_block(host); + put(&mut g, m.control[TB_PHASE], 2 + 2 * i as u64); + put(&mut g, m.control[TB_EXIT], TB_HOST); + g.b.seal_block(SIRTerminator::Return); + g.b.switch_to_block(evaluate); + let after = g.b.new_block(); + settle_then(&mut g, m, after); + g.b.switch_to_block(after); + let expr = expr.kernel().expect("lowered clock expression"); + g.b.inline_execution_unit(&program.sir.processes[expr.entry]); + if !expr.writes.is_empty() { + let dirty = g.constant(1, 8); + g.store(slots.dirty, 8, dirty); + } + let value = g.load_at( + expr.result.address, + expr.result.byte_offset * 8, + expr.width, + ); + let result = g.b.alloc_bit(64, false); + if expr.width > 64 { + g.b.emit(SIRInstruction::Slice(result, value, 0, 64)); + } else { + g.b.emit(SIRInstruction::Unary( + result, + celox_design::UnaryOp::Ident, + value, + )); + } + result + } + }; + let zero = g.equals(count, 0); + let wait = g.b.new_block(); + branch(&mut g, zero, run[i], wait); + g.b.switch_to_block(wait); + g.store(p[1], 64, count); + put(&mut g, p[0], 1); + put(&mut g, p[2], clock as u64); + let enabled = equals_slot(&mut g, m.clocks[clock][3], 0); + let activate = g.b.new_block(); + branch(&mut g, enabled, activate, save[i]); + g.b.switch_to_block(activate); + put(&mut g, m.clocks[clock][3], 1); + let now = g.load(m.control[TB_NOW], 64); + g.store(m.clocks[clock][0], 64, now); + jump(&mut g, save[i]); + } + _ => { + put(&mut g, m.control[TB_PHASE], 2 + 2 * i as u64); + put(&mut g, m.control[TB_EXIT], TB_HOST); + g.b.seal_block(SIRTerminator::Return); + } + } + } + g.b.switch_to_block(save[i]); + for &(source, saved) in &m.locals[i] { + copy(&mut g, program, source, saved); + } + jump(&mut g, next); + } + + // Edge execution yields to the runtime only when observers require it. + // Its continuation is independent of TB process continuations. + g.b.switch_to_block(edge); + let host_edges = g.b.new_block(); + let schema = program.runtime.runtime_schema.scheduler.as_ref().unwrap(); + let positions: Option> = m + .events + .iter() + .map(|event| { + schema.clocks.iter().position(|a| { + program.layout().offsets.get(a) == program.layout().offsets.get(event) + }) + }) + .collect(); + if let (Some(unit), Some(positions)) = (schema.unit, positions) { + let mut allowed = equals_slot(&mut g, m.control[TB_NATIVE_EDGES], 1); + let clean = equals_slot_width(&mut g, slots.dirty, 8, 0); + allowed = g.binary(1, allowed, BinaryOp::And, clean); + for &(source, saved) in &m.baselines { + let before = g.load(saved, 1); + let current = g.load(source, 1); + let same = g.binary(1, before, BinaryOp::Eq, current); + allowed = g.binary(1, allowed, BinaryOp::And, same); + } + let now = g.load(m.control[TB_NOW], 64); + let last = g.equals(now, u64::MAX); + let safe_time = g.equals(last, 0); + allowed = g.binary(1, allowed, BinaryOp::And, safe_time); + let native = g.b.new_block(); + branch(&mut g, allowed, native, host_edges); + g.b.switch_to_block(native); + let now = g.load(m.control[TB_NOW], 64); + let ticks = g.load(m.control[TB_TICKS], 64); + let limit = g.load(m.control[TB_LIMIT], 64); + let active = g.binary(1, ticks, BinaryOp::LtU, limit); + let running = equals_slot(&mut g, m.control[TB_STOPPED], 0); + let active = g.binary(1, active, BinaryOp::And, running); + let mut armed = g.constant(0, 64); + let mut values = g.constant(0, 64); + for (c, &bit) in m.clocks.iter().zip(&positions) { + let enabled = equals_slot(&mut g, c[3], 1); + let next = g.load(c[0], 64); + let rise = g.binary(1, next, BinaryOp::Eq, now); + let rise = g.binary(1, rise, BinaryOp::And, enabled); + let rise = g.binary(1, rise, BinaryOp::And, active); + let falling = equals_slot(&mut g, c[2], 1); + let next = g.load(c[1], 64); + let fall = g.binary(1, next, BinaryOp::Eq, now); + let fall = g.binary(1, fall, BinaryOp::And, falling); + let due = g.binary(1, rise, BinaryOp::Or, fall); + let set = g.bit(due, bit); + armed = g.binary(64, armed, BinaryOp::Or, set); + let set = g.bit(rise, bit); + values = g.binary(64, values, BinaryOp::Or, set); + g.store_at(slots.clock_next, bit * 64, 64, now); + let two = g.constant(2, 64); + g.store_at(slots.clock_period, bit * 64, 64, two); + } + let any = g.equals(armed, 0); + let invoke = g.b.new_block(); + branch(&mut g, any, host_edges, invoke); + g.b.switch_to_block(invoke); + g.store(slots.clock_armed, 64, armed); + g.store(slots.clock_value, 64, values); + g.store(slots.limit, 64, now); + put(&mut g, slots.count, 0); + put(&mut g, slots.ready, 0); + let zero = g.constant(0, 8); + g.store(slots.exit, 8, zero); + g.store(slots.finish, 8, zero); + g.b.inline_execution_unit(&program.sir.processes[unit]); + let exit = g.load(slots.exit, 8); + let limit = g.equals(exit, SchedulerExit::Limit as u64); + let finished = g.equals(exit, SchedulerExit::Finish as u64); + let ok = g.binary(1, limit, BinaryOp::Or, finished); + branch(&mut g, ok, after_edges, overflow); + } else { + jump(&mut g, host_edges); + } + g.b.switch_to_block(host_edges); + put(&mut g, m.control[TB_PHASE], 1); + put(&mut g, m.control[TB_EXIT], TB_EDGES); + g.b.seal_block(SIRTerminator::Return); + g.b.switch_to_block(after_edges); + let now = g.load(m.control[TB_NOW], 64); + let ticks = g.load(m.control[TB_TICKS], 64); + let limit = g.load(m.control[TB_LIMIT], 64); + let active = g.binary(1, ticks, BinaryOp::LtU, limit); + let running = equals_slot(&mut g, m.control[TB_STOPPED], 0); + let active = g.binary(1, active, BinaryOp::And, running); + let mut rising = g.constant(0, 1); + for (clock, c) in m.clocks.iter().enumerate() { + let enabled = equals_slot(&mut g, c[3], 1); + let next = g.load(c[0], 64); + let due = g.binary(1, next, BinaryOp::Eq, now); + let due = g.binary(1, due, BinaryOp::And, enabled); + let due = g.binary(1, due, BinaryOp::And, active); + rising = g.binary(1, rising, BinaryOp::Or, due); + let fall = g.load(c[1], 64); + let falling = g.binary(1, fall, BinaryOp::Eq, now); + let armed = g.load(c[2], 64); + let not_due = g.equals(falling, 0); + let zero = g.constant(0, 64); + let remain = choose(&mut g, not_due, armed, zero); + g.store(c[2], 64, remain); + let fire = g.b.new_block(); + let skip = g.b.new_block(); + branch(&mut g, due, fire, skip); + g.b.switch_to_block(fire); + let period = g.constant(m.periods[clock], 64); + let next = g.binary(64, now, BinaryOp::Add, period); + let wraps = g.binary(1, next, BinaryOp::LtU, now); + let valid = g.b.new_block(); + branch(&mut g, wraps, overflow, valid); + g.b.switch_to_block(valid); + g.store(c[0], 64, next); + let half = g.constant(m.periods[clock] - m.periods[clock] / 2, 64); + let fall = g.binary(64, now, BinaryOp::Add, half); + g.store(c[1], 64, fall); + put(&mut g, c[2], 1); + for p in &m.processes { + let waiting = equals_slot(&mut g, p[0], 1); + let this = equals_slot(&mut g, p[2], clock as u64); + let waiting = g.binary(1, waiting, BinaryOp::And, this); + let decrement = g.b.new_block(); + let after = g.b.new_block(); + branch(&mut g, waiting, decrement, after); + g.b.switch_to_block(decrement); + let left = g.load(p[1], 64); + let one = g.constant(1, 64); + let left = g.binary(64, left, BinaryOp::Sub, one); + g.store(p[1], 64, left); + let last = g.equals(left, 0); + let release = g.b.new_block(); + branch(&mut g, last, release, after); + g.b.switch_to_block(release); + put(&mut g, p[0], 3); + g.store(p[3], 64, next); + jump(&mut g, after); + g.b.switch_to_block(after); + } + jump(&mut g, skip); + g.b.switch_to_block(skip); + } + let one = g.constant(1, 64); + let zero = g.constant(0, 64); + let add = choose(&mut g, rising, one, zero); + let ticks = g.binary(64, ticks, BinaryOp::Add, add); + g.store(m.control[TB_TICKS], 64, ticks); + jump(&mut g, end); + g.b.switch_to_block(end); + let stopped = equals_slot(&mut g, m.control[TB_STOPPED], 1); + let check_done = g.b.new_block(); + branch(&mut g, stopped, finished, check_done); + g.b.switch_to_block(check_done); + let mut complete = g.constant(1, 1); + for p in &m.processes { + let is_done = equals_slot(&mut g, p[0], 2); + complete = g.binary(1, complete, BinaryOp::And, is_done); + } + let advance = g.b.new_block(); + branch(&mut g, complete, done, advance); + g.b.switch_to_block(advance); + let ticks = g.load(m.control[TB_TICKS], 64); + let limit = g.load(m.control[TB_LIMIT], 64); + let active = g.binary(1, ticks, BinaryOp::LtU, limit); + let running = equals_slot(&mut g, m.control[TB_STOPPED], 0); + let active = g.binary(1, active, BinaryOp::And, running); + let mut next = g.constant(u64::MAX, 64); + let mut pending = g.constant(0, 1); + for c in &m.clocks { + let enabled = equals_slot(&mut g, c[3], 1); + let enabled = g.binary(1, enabled, BinaryOp::And, active); + let rise = g.load(c[0], 64); + let earlier = g.binary(1, rise, BinaryOp::LtU, next); + let choose_rise = g.binary(1, earlier, BinaryOp::And, enabled); + next = choose(&mut g, choose_rise, rise, next); + pending = g.binary(1, pending, BinaryOp::Or, enabled); + let armed = equals_slot(&mut g, c[2], 1); + let fall = g.load(c[1], 64); + let earlier = g.binary(1, fall, BinaryOp::LtU, next); + let choose_fall = g.binary(1, earlier, BinaryOp::And, armed); + next = choose(&mut g, choose_fall, fall, next); + pending = g.binary(1, pending, BinaryOp::Or, armed); + } + for p in &m.processes { + let releasing = equals_slot(&mut g, p[0], 3); + let wake = g.load(p[3], 64); + let earlier = g.binary(1, wake, BinaryOp::LtU, next); + let take = g.binary(1, releasing, BinaryOp::And, earlier); + next = choose(&mut g, take, wake, next); + pending = g.binary(1, pending, BinaryOp::Or, releasing); + } + let advance = g.b.new_block(); + branch(&mut g, pending, advance, limited); + g.b.switch_to_block(advance); + g.store(m.control[TB_NOW], 64, next); + put(&mut g, m.control[TB_PHASE], 0); + let budget = g.load(m.control[TB_BUDGET], 64); + let one = g.constant(1, 64); + let budget = g.binary(64, budget, BinaryOp::Sub, one); + g.store(m.control[TB_BUDGET], 64, budget); + let exhausted = g.equals(budget, 0); + branch(&mut g, exhausted, safe, start); + for (block, code) in [ + (done, TB_DONE), + (finished, TB_FINISHED), + (limited, TB_LIMITED), + (overflow, TB_OVERFLOW), + (safe, TB_SAFEPOINT), + (finish, TB_SAFEPOINT), + ] { + g.b.switch_to_block(block); + put(&mut g, m.control[TB_EXIT], code); + g.b.seal_block(SIRTerminator::Return); + } + emit_settle(&mut g, m, &program.sir.eval_comb, finish, overflow); + let mut unit = g.finish(); + let mut next = unit.register_map.keys().map(|r| r.0).max().unwrap_or(0) + 1; + for block in unit.blocks.values_mut() { + let old = std::mem::take(&mut block.instructions); + for instruction in old { + let event = matches!(instruction, SIRInstruction::RuntimeEvent { .. }); + block.instructions.push(instruction); + if event { + let one = RegisterId(next); + next += 1; + unit.register_map.insert( + one, + celox_sir::RegisterType::Bit { + width: 64, + signed: false, + }, + ); + block + .instructions + .push(SIRInstruction::Imm(one, SIRValue::new(1u64))); + block.instructions.push(SIRInstruction::Store( + stable(m.control[TB_BUDGET]), + SIROffset::Static(0), + 64, + one, + vec![], + vec![], + )); + } + } + } + unit +} diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 597f5dd9bc0..7fa2acb2614 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2326,6 +2326,16 @@ mod host { self } + /// Select the loop that runs time slots. A test option: + /// For timed simulations, [`crate::SchedulerMode::Differential`] + /// checks every step against a shadow simulation. Veryl TB execution + /// uses this option to select compiled or reference clock batches. + #[doc(hidden)] + pub fn scheduler_mode(mut self, mode: crate::SchedulerMode) -> Self { + self.options.scheduler = mode; + self + } + /// Set per-pass optimizer flags directly. pub fn optimize_options(mut self, options: crate::optimizer::OptimizeOptions) -> Self { self.options.cranelift_options.tail_call_split = @@ -3010,10 +3020,14 @@ mod host { // A timed simulation runs the slots of kernels that only delay // in a compiled scheduler, generated from the final units. #[cfg(feature = "host-runtime")] - if self.options.emit_triggers + if (self.options.emit_triggers || laid_out.runtime.testbench.is_some()) && self.options.scheduler != crate::SchedulerMode::Reference { - crate::scheduler::attach(&mut laid_out); + crate::scheduler::attach( + &mut laid_out, + !self.options.native_force_support + && self.options.signal_access.force_signals.is_empty(), + ); } #[cfg(feature = "host-runtime")] if self @@ -3863,15 +3877,6 @@ 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( @@ -3964,8 +3969,8 @@ mod host { /// 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. + /// An untimed RTL image without a native testbench has no compiled + /// scheduler, so its time slots run in the reference loop. #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -4775,6 +4780,130 @@ endmodule"#; options.four_state, ); } + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + #[test] + fn unchanged_clock_does_not_invalidate_compiled_settle() { + assert_eq!( + count_clean_clock_batch(true, false, false).0, + 0, + "only a moved; the combinational input b did not change" + ); + } + + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + #[test] + fn clean_clock_batch_does_not_repeat_fused_comb_evaluation() { + let (evaluations, fused_domains) = count_clean_clock_batch(false, false, false); + assert!( + fused_domains > 0, + "the regression must exercise a fused domain" + ); + assert_eq!( + evaluations, 0, + "the FF's combinational inputs were already settled" + ); + } + + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + #[test] + fn clock_alias_notifications_do_not_force_datapath_evaluation() { + assert_eq!(count_clean_clock_batch(false, true, false).0, 0); + } + + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + #[test] + fn dirty_clock_batch_evaluates_new_inputs_before_ff_update() { + assert!(count_clean_clock_batch(false, false, true).0 > 0); + } + + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + fn count_clean_clock_batch(clock_data: bool, alias: bool, dirty: bool) -> (u64, usize) { + use crate::SimBackend; + let source = r#" + module Top ( + a: input 'domain_a clock, b: input 'domain_b clock, + d: input bit<8>, q: output 'domain_a bit<8>, r: output 'domain_b bit<8>, + monitor: output bit<8>, evaluations: input bit<64>, + ) { + assign monitor = __COMB__; + unsafe (cdc) { + always_ff (a) { q = __INPUT__; } + always_ff (b) { r = d; } + } + } + "#; + let mut source = source + .replace("__COMB__", if clock_data { "b as u8" } else { "d + 1" }) + .replace("__INPUT__", if clock_data { "d" } else { "monitor" }); + if alias { + source = source.replace( + "always_ff (a) { q = monitor; }", + "inst child: Child (clk: a, d: monitor, q);", + ); + source.push_str("module Child (clk: input clock, d: input bit<8>, q: output bit<8>) { always_ff { q = d; } }"); + } + let (mut program, _, options, _, _) = crate::Simulation::builder(&source, "Top") + .emit_triggers() + .four_state(false) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) + .unwrap(); + if alias { + assert!(program.sir.eval_comb.iter().flat_map(|u| u.blocks.values()) + .flat_map(|b| &b.instructions).any(|inst| matches!(inst, + crate::ir::SIRInstruction::Store(_, _, _, _, triggers, _) if !triggers.is_empty() + )), "the fixture must retain clock notifications"); + } + let counter = program.get_addr(&[], &["evaluations"]).unwrap(); + let fused = crate::scheduler::count_test_settles(&mut program, counter, counter); + let scheduler = program.runtime.runtime_schema.scheduler.clone().unwrap(); + let mut backend = crate::NativeBackend::new(&program, &options).unwrap(); + let slots = scheduler + .slots + .map(|address| backend.resolve_signal(&address)); + let count = backend.resolve_signal(&counter); + let a = program.get_addr(&[], &["a"]).unwrap(); + let bit = scheduler + .clocks + .iter() + .position(|&clock| clock == a) + .unwrap(); + let element = |mut signal: crate::SignalRef| { + signal.offset += bit * 8; + signal.width = 64; + signal + }; + if alias { + // A falling edge only publishes the clock alias: no FF output + // needs a settle to propagate back through the child boundary. + let clock = backend.resolve_signal(&a); + backend.set(clock, 1u8); + } + backend.eval_comb().unwrap(); + backend.set(count, 0u64); + backend.set(slots.limit, 0u64); + backend.set(slots.dirty, u8::from(dirty)); + if dirty { + let d = backend.resolve_signal(&program.get_addr(&[], &["d"]).unwrap()); + backend.set(d, 7u8); + } + backend.set(slots.clock_armed, 1u64 << bit); + backend.set(slots.clock_value, if alias { 0 } else { 1u64 << bit }); + backend.set(element(slots.clock_next), 0u64); + backend.set(element(slots.clock_period), 2u64); + backend.run_process(scheduler.unit.unwrap()).unwrap(); + let q = backend.resolve_signal(&program.get_addr(&[], &["q"]).unwrap()); + assert_eq!( + backend.get_as::(q), + if clock_data || alias { + 0 + } else if dirty { + 8 + } else { + 1 + } + ); + (backend.get_as::(count), fused) + } } #[cfg(feature = "host-runtime")] diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index fdfc0c6984c..0cda71b63a6 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -29,6 +29,8 @@ use rand_pcg::Pcg64; use std::sync::atomic::{AtomicU64, Ordering}; use std::task::Poll; +mod clock_batch; +mod compiled; mod native; // ── Public types ─────────────────────────────────────────────────────── @@ -1091,6 +1093,9 @@ fn exec_testbench( ) -> ExecResult { let blocks: Vec<_> = testbench.processes().collect(); let clocks = initialize_process_clocks(sim, testbench); + if let Some(result) = compiled::run(sim, testbench, ctx) { + return result; + } // One process on one clock spends time only in that clock's periods, so // stepping them in place is the whole schedule. if blocks.is_empty() { @@ -1169,6 +1174,7 @@ fn exec_processes( state.synchronize_event_values(&sim.backend); sim.component_simulation = Some(state); } + let clock_batch = clock_batch::ClockBatch::new(sim); let mut now = 0; // Reuse per-slot batches instead of allocating on each rising and falling // edge; their capacities can grow when a wait introduces another clock. @@ -1295,6 +1301,7 @@ fn exec_processes( !fired.is_empty(), ctx, &mut moves, + clock_batch.as_ref(), ); if !matches!(result, ExecResult::Continue) { return result; @@ -1354,6 +1361,7 @@ fn exec_processes( } } +#[allow(clippy::too_many_arguments)] fn step_process_events( sim: &mut Simulator, events: &[(B::Event, u8)], @@ -1362,6 +1370,7 @@ fn step_process_events( rising: bool, ctx: &mut DetailedExecContext, moves: &mut Vec<(B::Event, celox_runtime::Edge)>, + clock_batch: Option<&clock_batch::ClockBatch>, ) -> ExecResult { let mut state = sim .component_simulation @@ -1423,10 +1432,10 @@ fn step_process_events( }, ) })); - let result = sim - .edges(moves) - .map(|()| None) - .map_err(|error| error.to_string()); + let result = clock_batch + .and_then(|batch| batch.run(sim, events, time)) + .unwrap_or_else(|| sim.edges(moves).map_err(|error| error.to_string())) + .map(|()| None); // A later reset can return to the queue. Its pre-write baseline must // include every clock and derived-domain update performed here. state.synchronize_event_values(&sim.backend); @@ -2057,6 +2066,169 @@ mod tests { ); } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn native_clock_batches_preserve_odd_periods_and_tb_before_edge_order() { + let source = r#" + module Counter(clk: input clock, rst: input reset_async_low, q: output logic<8>) { + always_ff (clk, rst) { if_reset { q = 0; } else { q += 1; } } + } + #[test(Top)] module Top { + inst fast: $tb::clock_gen #(period: 3); + inst slow: $tb::clock_gen #(period: 4); + var rst_n: reset_async_low; + var enable: logic; + var gated: reset_async_low; + assign gated = rst_n && enable; + var a: logic<8>; + var b: logic<8>; + inst ca: Counter(clk: fast, rst: gated, q: a); + inst cb: Counter(clk: slow, rst: gated, q: b); + initial { + rst_n = 1; + enable = 0; + fast.next(4); + $assert(a == 0 && b == 0); + enable = 1; + fast.next(4); + // At time 24 both clocks are due, but the TB runs first. + $assert(a == 4 && b == 3); + fast.next(4); + $assert(a == 8 && b == 6); + $finish(); + } + initial { slow.next(100); } + } + "#; + for mode in [ + crate::SchedulerMode::Reference, + crate::SchedulerMode::Compiled, + ] { + let mut sim = Simulator::builder(source, "Top") + .four_state(false) + .scheduler_mode(mode) + .build_native() + .unwrap(); + let batch = clock_batch::ClockBatch::new(&sim); + assert_eq!(batch.is_some(), mode != crate::SchedulerMode::Reference); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + if let Some(batch) = batch { + assert_eq!(sim.backend.get_as::(batch.count_slot()), 1); + } + } + } + + #[test] + fn native_tb_scheduler_runs_processes_and_multiple_clocks_without_host_roundtrips() { + let source = r#" + module Counter(clk: input clock, q: output bit<32>) { + always_ff { q += 1; } + } + #[test(Top)] module Top { + inst fast: $tb::clock_gen #(period: 3); + inst slow: $tb::clock_gen #(period: 4); + var a: u32; var b: u32; var observed: u32; + inst ca: Counter(clk: fast, q: a); + inst cb: Counter(clk: slow, q: b); + initial { for i in 0..128 { fast.next(); observed = a; } $finish(); } + initial { for i in 0..128 { slow.next(); } } + } + "#; + // No clock-wait batching in the source: both TB processes resume each cycle. + let mut results = Vec::new(); + for mode in [ + crate::SchedulerMode::Reference, + crate::SchedulerMode::Compiled, + ] { + let mut sim = Simulator::builder(source, "Top") + .four_state(false) + .scheduler_mode(mode) + .build_native() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + compiled::take_counters(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + let counters = compiled::take_counters(); + results.push(( + sim.get_as::(sim.signal("a")), + sim.get_as::(sim.signal("b")), + sim.get_as::(sim.signal("observed")), + )); + if mode == crate::SchedulerMode::Compiled { + assert!(counters.0 < 10, "native entries: {counters:?}"); + assert!(counters.1 < 3, "host edge batches: {counters:?}"); + } + } + assert_eq!(results[0], results[1]); + assert_eq!(results[1], (128, 96, 128)); + } + + #[test] + fn compiled_tb_settle_continuations_are_not_limited_to_one_byte() { + let mut source = + String::from("#[test(Top)] module Top { var a: bit<8>; let q: bit<8> = a + 1; "); + for _ in 0..260 { + source.push_str("initial { $assert(q == 1); } "); + } + source.push_str("initial { $finish(); } }"); + let mut sim = Simulator::builder(&source, "Top") + .four_state(false) + .build_interpreter() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + + #[test] + fn native_tb_dynamic_clock_count_preserves_dut_writes() { + let source = r#" + module Register(clk: input clock, d: input bit<32>, q: output bit<32>) { + let next_value: bit<32> = d + 1; + always_ff { q = next_value; } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen; + var d: u32; var q: u32; + inst dut: Register(clk, d, q); + function change_input() -> u32 { d = 7; return 1; } + initial { + d=1; clk.next(); $assert(q==2); + clk.next(change_input()); $assert(q==8); $finish(); + } + } + "#; + fn run(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + run(Simulator::builder(source, "Top") + .four_state(false) + .build_native() + .unwrap()); + run(Simulator::builder(source, "Top") + .four_state(false) + .build_interpreter() + .unwrap()); + #[cfg(feature = "cranelift")] + run(Simulator::builder(source, "Top") + .four_state(false) + .build() + .unwrap()); + } + #[test] fn concurrent_tb_preserves_direct_async_reset_writes() { let source = r#" @@ -2204,7 +2376,10 @@ mod tests { )); assert_eq!( run_compiled_testbench_to_finish(&mut sim, &tb), - TestResult::Pass + TestResult::Pass, + "q={}, counters={:?}", + sim.get_as::(sim.signal("q")), + compiled::take_counters() ); } diff --git a/crates/celox/src/testbench/clock_batch.rs b/crates/celox/src/testbench/clock_batch.rs new file mode 100644 index 00000000000..15058af4045 --- /dev/null +++ b/crates/celox/src/testbench/clock_batch.rs @@ -0,0 +1,121 @@ +//! Execute an externally scheduled clock batch with the shared SIR scheduler. +//! +//! Veryl resumes its TB before clock edges at that timestamp. Only the already +//! collected edges enter this unit; periodic rearming remains with the caller. +use super::*; +use celox_design::{ProcessKind, SchedulerExit, SchedulerSlots}; + +pub(super) struct ClockBatch { + unit: usize, + slots: SchedulerSlots, + clocks: Vec, +} + +impl ClockBatch { + #[cfg(test)] + pub(super) fn count_slot(&self) -> SignalRef { + self.slots.count + } + + pub(super) fn new(sim: &Simulator) -> Option { + let schema = &sim.program.runtime_schema; + // Timed RTL processes need the runtime queue's scheduling state. The + // caller checks all other observers before using the direct edge path. + if sim.host_slot_work + || !sim.host_watch.is_empty() + || schema + .processes + .iter() + .any(|p| p.kind != ProcessKind::Callable) + { + return None; + } + let scheduler = schema.scheduler.as_ref()?; + let Some(unit) = scheduler.unit else { + tracing::debug!(reason = ?scheduler.fallback.first(), "Veryl clock batches use the edge engine"); + return None; + }; + tracing::debug!( + unit, + clocks = scheduler.clocks.len(), + "Veryl compiled clock batches enabled" + ); + Some(Self { + unit, + slots: scheduler + .slots + .clone() + .map(|addr| sim.backend.resolve_signal(&addr)), + clocks: scheduler + .clocks + .iter() + .map(|addr| sim.backend.resolve_signal(addr)) + .collect(), + }) + } + + pub(super) fn run( + &self, + sim: &mut Simulator, + events: &[(B::Event, u8)], + time: u64, + ) -> Option> { + // The shared scheduler rearms after a slot. At the last representable + // timestamp the reference path owns the caller's overflow diagnostic. + if time == u64::MAX || !sim.backend.runs_compiled_scheduler() { + return None; + } + let mut armed = 0u64; + let mut values = 0u64; + for &(event, value) in events { + let signal = sim.backend.resolve_signal(&event.addr()); + let bit = self.clocks.iter().position(|&clock| clock == signal)?; + // A batch with conflicting moves must use the runtime edge engine. + if armed & (1 << bit) != 0 { + return None; + } + armed |= 1 << bit; + values |= u64::from(value != 0) << bit; + } + let element = |mut signal: SignalRef, index: usize| { + signal.offset += index * 8; + signal.width = 64; + signal + }; + for bit in 0..self.clocks.len() { + if armed & (1 << bit) != 0 { + sim.backend.set(element(self.slots.clock_next, bit), time); + // One slot only; the caller owns the actual clock periods. + sim.backend.set(element(self.slots.clock_period, bit), 2u64); + } + } + sim.backend.set(self.slots.limit, time); + sim.backend.set(self.slots.exit, 0u8); + sim.backend.set(self.slots.finish, 0u8); + sim.backend.set(self.slots.dirty, u8::from(sim.dirty)); + sim.backend.set(self.slots.count, 0u64); + sim.backend.set(self.slots.ready, 0u64); + sim.backend.set(self.slots.clock_armed, armed); + sim.backend.set(self.slots.clock_value, values); + let result = sim + .backend + .run_process(self.unit) + .map_err(|e| e.to_string()); + sim.backend.clear_triggered_bits(); + if let Err(error) = result { + return Some(Err(error)); + } + match SchedulerExit::from_code(sim.backend.get_as(self.slots.exit)) { + Some(SchedulerExit::Limit) => { + sim.dirty = false; + Some(Ok(())) + } + // The event drain reports the finish record to the TB runner. + Some(SchedulerExit::Finish) => { + sim.dirty = true; + Some(Ok(())) + } + exit => Some(Err(format!("clock batch scheduler exited with {exit:?}"))), + } + } +} diff --git a/crates/celox/src/testbench/compiled.rs b/crates/celox/src/testbench/compiled.rs new file mode 100644 index 00000000000..0db7225ea26 --- /dev/null +++ b/crates/celox/src/testbench/compiled.rs @@ -0,0 +1,368 @@ +//! Host services for the generated TB scheduler. Clock progress and process +//! dispatch remain in SIR; returning here is a service or a tiering safe point. +use super::TestbenchStatement; +use super::*; +use celox_testbench::*; + +#[cfg(test)] +thread_local! { static COUNTERS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0,0)) }; } +#[cfg(test)] +pub(super) fn take_counters() -> (usize, usize) { + COUNTERS.with(|c| c.replace((0, 0))) +} + +pub(super) fn run( + sim: &mut Simulator, + tb: &CompiledTestbench, + ctx: &mut DetailedExecContext, +) -> Option { + let m = tb.scheduler()?; + let entry = m.entry?; + let semantic = sim.program.testbench.as_ref()?.scheduler()?; + let clocks: Vec<_> = semantic + .events + .iter() + .map(|a| sim.backend.resolve_event(a)) + .collect(); + let baselines: Vec<_> = semantic + .baselines + .iter() + .zip(&m.baselines) + .filter_map(|((a, _), (_, saved))| { + sim.backend + .resolve_event_opt(a) + .map(|event| (event.id(), *saved)) + }) + .collect(); + fn collect<'a, B: SimBackend>( + body: &'a [TestbenchStatement], + out: &mut Vec<&'a TestbenchStatement>, + ) { + for s in body { + out.push(s); + match s { + GenericTestbenchStatement::If { + then_block, + else_block, + .. + } => { + collect::(then_block, out); + collect::(else_block, out); + } + GenericTestbenchStatement::For { body, .. } => collect::(body, out), + _ => {} + } + } + } + let sites: Vec<_> = tb + .processes() + .map(|body| { + let mut v = vec![]; + collect::(body, &mut v); + v + }) + .collect(); + for &a in &m.control { + sim.backend.set(a, 0u64); + } + sim.backend.set(m.control[TB_PHASE], u64::MAX); + sim.backend + .set(m.control[TB_LIMIT], ctx.tick_limit.unwrap_or(u64::MAX)); + for p in &m.processes { + for &a in p { + sim.backend.set(a, 0u64); + } + } + for (i, c) in m.clocks.iter().enumerate() { + for &a in c { + sim.backend.set(a, 0u64); + } + sim.backend.set(c[3], u64::from(i < m.declared)); + } + for k in tb.kernels() { + sim.backend.set(k.resume, 0u16); + } + let dirty = sim + .backend + .resolve_signal(&sim.program.runtime_schema.scheduler.as_ref()?.slots.dirty); + let mut reset_edges = vec![]; + let mut moves = vec![]; + let batch = clock_batch::ClockBatch::new(sim); + loop { + let schema = &sim.program.runtime_schema; + let native_edges = !sim.host_slot_work + && sim.host_watch.is_empty() + && sim.vcd_writer.is_none() + && schema.persistent_comb_state.is_empty() + && sim.components.is_empty() + && !sim.schedule.timed + && schema.time_slots.is_empty() + && schema.watches.is_empty() + && schema.comb_observers.is_empty() + && schema.sample_shadows.is_empty() + && !sim.backend.layout().four_state; + sim.backend + .set(m.control[TB_NATIVE_EDGES], u64::from(native_edges)); + let native_settle = sim.host_watch.is_empty() + && sim.components.is_empty() + && !sim.schedule.timed + && sim.vcd_writer.is_none() + && schema.comb_observers.is_empty() + && schema.watches.is_empty(); + sim.backend + .set(m.control[TB_NATIVE_SETTLE], u64::from(native_settle)); + sim.backend.set(dirty, u8::from(sim.dirty)); + sim.backend.set( + m.control[TB_BUDGET], + if sim.backend.runs_compiled_scheduler() { + 1024u64 + } else { + 1 + }, + ); + #[cfg(test)] + COUNTERS.with(|c| { + let (runs, edges) = c.get(); + c.set((runs + 1, edges)); + }); + if let Err(e) = sim.backend.run_process(entry) { + return Some(ExecResult::Fail(e.to_string())); + } + sim.dirty = sim.backend.get_as::(dirty) != 0; + if sim.dirty { + sim.backend + .mark_settle_range(0, sim.backend.layout().total_size); + } + sim.backend.clear_triggered_bits(); + let now = sim.backend.get_as::(m.control[TB_NOW]); + ctx.scheduler_time = if m.processes.len() == 1 && clocks.len() <= 1 { + None + } else { + Some(sim.backend.get_as(m.control[TB_REPORT_TIME])) + }; + ctx.current_time = sim.backend.get_as(m.control[TB_TICKS]); + let drained = drain_runtime_assertions(sim, ctx, None); + if let Some(message) = drained.fatal_message { + return Some(ExecResult::Fail(message_diagnostic(&message))); + } + if drained.finished { + return Some(ExecResult::Finished); + } + match sim.backend.get_as::(m.control[TB_EXIT]) { + TB_DONE => return Some(ExecResult::Continue), + TB_FINISHED => return Some(ExecResult::Finished), + TB_LIMITED => { + ctx.tick_limit_reached = true; + return Some(ExecResult::Finished); + } + TB_OVERFLOW => { + return Some(ExecResult::Fail( + "testbench clock time overflow or invalid scheduler continuation".into(), + )); + } + TB_SAFEPOINT => {} + TB_HOST | TB_RESET => { + let index = sim.backend.get_as::(m.control[TB_CURRENT]) as usize; + let p = m.processes[index]; + let kernel = &tb.kernels()[index]; + let reset = sim.backend.get_as::(m.control[TB_EXIT]) == TB_RESET; + let request = if reset { + sim.backend.get_as::(p[4]) as usize - 1 + } else { + let encoded = sim.backend.get_as(kernel.request); + let Some((celox_design::HostRequestKind::Testbench, index)) = + celox_design::HostRequestKind::decode(encoded) + else { + return Some(ExecResult::Fail("invalid scheduler host request".into())); + }; + index as usize + }; + match &kernel.requests[request] { + KernelRequest::Statement(site) => { + let statement = sites[index][*site]; + if let GenericTestbenchStatement::ClockNext { + clock_event, count, .. + } = statement + { + let count = match eval_clock_count(sim, count) { + Ok(n) => n, + Err(e) => return Some(ExecResult::Fail(e.to_string())), + }; + if count != 0 { + let clock = clocks + .iter() + .position(|c| c.id() == clock_event.id()) + .unwrap(); + sim.backend.set(p[0], 1u64); + sim.backend.set(p[1], count); + sim.backend.set(p[2], clock as u64); + if sim.backend.get_as::(m.clocks[clock][3]) == 0 { + sim.backend.set(m.clocks[clock][3], 1u64); + sim.backend.set(m.clocks[clock][0], now); + } + sim.backend.set( + m.control[TB_PHASE], + 2 + 2 * m.processes.len() as u64 + index as u64, + ); + } + } else if let GenericTestbenchStatement::ResetAssert { + reset_signal, + reset_event, + clock_event, + duration, + assert_value, + deassert_value, + .. + } = statement + { + if reset { + sim_set_u64(sim, *reset_signal, (*deassert_value).into()); + if let Some(event) = reset_event { + reset_edges.push((*event, *deassert_value)); + } + sim.backend.set(p[4], 0u64); + } else { + let count = match eval_clock_count(sim, duration) { + Ok(c) => c.max(1), + Err(e) => return Some(ExecResult::Fail(e.to_string())), + }; + sim_set_u64(sim, *reset_signal, (*assert_value).into()); + if let Some(event) = reset_event { + reset_edges.push((*event, *assert_value)); + } + let clock = clocks + .iter() + .position(|c| c.id() == clock_event.id()) + .unwrap(); + sim.backend.set(p[0], 1u64); + sim.backend.set(p[1], count); + sim.backend.set(p[2], clock as u64); + sim.backend.set(p[4], request as u64 + 1); + if sim.backend.get_as::(m.clocks[clock][3]) == 0 { + sim.backend.set(m.clocks[clock][3], 1u64); + sim.backend.set(m.clocks[clock][0], now); + } + sim.backend.set( + m.control[TB_PHASE], + 2 + 2 * m.processes.len() as u64 + index as u64, + ); + } + } else { + let result = exec_one_detailed(sim, statement, ctx); + if matches!(result, ExecResult::Finished) { + if m.processes.len() == 1 && clocks.len() <= 1 { + return Some(result); + } + sim.backend.set(m.control[TB_STOPPED], 1u64); + sim.backend.set(p[0], 2u64); + sim.backend.set( + m.control[TB_PHASE], + 2 + 2 * m.processes.len() as u64 + index as u64, + ); + } else if !matches!(result, ExecResult::Continue) { + return Some(result); + } + } + } + KernelRequest::Settle => { + if let Err(e) = settle_testbench(sim) { + return Some(ExecResult::Fail(e.to_string())); + } + } + KernelRequest::Error(message) => { + return Some(ExecResult::Fail(message.clone())); + } + _ => return Some(ExecResult::Fail("unexpected scheduler host service".into())), + } + } + TB_EDGES => { + #[cfg(test)] + COUNTERS.with(|c| { + let (runs, edges) = c.get(); + c.set((runs, edges + 1)); + }); + let mut state = sim + .component_simulation + .take() + .unwrap_or_else(|| Box::new(crate::simulation::simulation_state(sim))); + let levels = baselines + .iter() + .map(|&(id, saved)| { + let (value, mask) = sim.backend.get_four_state(saved); + let value = u8::from(value != BigUint::from(0u8)); + let unknown = u8::from(mask != BigUint::from(0u8)) + * celox_design::edges::LEVEL_UNKNOWN; + (id, value | unknown) + }) + .collect::>(); + state.restore_event_baselines(levels); + sim.component_simulation = Some(state); + let mut events = vec![]; + let mut rising = false; + for (clock, c) in clocks.iter().zip(&m.clocks) { + if sim.backend.get_as::(c[2]) != 0 + && sim.backend.get_as::(c[1]) == now + { + events.push((*clock, 0)); + } + } + for (clock, c) in clocks.iter().zip(&m.clocks) { + if !ctx.at_tick_limit() + && sim.backend.get_as::(m.control[TB_STOPPED]) == 0 + && sim.backend.get_as::(c[3]) != 0 + && sim.backend.get_as::(c[0]) == now + { + events.push((*clock, 1)); + rising = true; + } + } + events.append(&mut reset_edges); + let resets = m + .processes + .iter() + .enumerate() + .filter_map(|(i, p)| { + let request = sim.backend.get_as::(p[4]); + if request == 0 { + return None; + } + let KernelRequest::Statement(site) = + tb.kernels()[i].requests[request as usize - 1] + else { + return None; + }; + let GenericTestbenchStatement::ResetAssert { + clock_event, + reset_event, + .. + } = sites[i][site] + else { + return None; + }; + Some((*clock_event, *reset_event)) + }) + .collect::>(); + let result = step_process_events( + sim, + &events, + &resets, + now, + rising, + ctx, + &mut moves, + batch.as_ref(), + ); + if !matches!(result, ExecResult::Continue) { + return Some(result); + } + } + _ => { + return Some(ExecResult::Fail( + "invalid compiled TB scheduler exit".into(), + )); + } + } + // Saved function temporaries are layout-owned roots throughout a run. + sim.maybe_collect_heap([]); + } +} diff --git a/crates/celox/src/testbench_compile/process.rs b/crates/celox/src/testbench_compile/process.rs index cf9bc7bdf31..5876b3ad2b2 100644 --- a/crates/celox/src/testbench_compile/process.rs +++ b/crates/celox/src/testbench_compile/process.rs @@ -563,5 +563,110 @@ pub(crate) fn lower( }); } program.set_kernels(kernels); + allocate_scheduler(runtime, program); Ok(()) } + +fn allocate_scheduler(runtime: &mut RuntimeProgram, program: &mut TestbenchProgram) { + fn collect(body: &[SemanticStatement], clocks: &mut Vec<(Addr, u64)>) { + for statement in body { + match statement { + SemanticStatement::ClockNext { + clock_event, + period, + .. + } + | SemanticStatement::ResetAssert { + clock_event, + period, + .. + } => { + if !clocks.iter().any(|(a, _)| a == clock_event) { + clocks.push((*clock_event, (*period).max(2))); + } + } + SemanticStatement::If { + then_block, + else_block, + .. + } => { + collect(then_block, clocks); + collect(else_block, clocks); + } + SemanticStatement::For { body, .. } => collect(body, clocks), + _ => {} + } + } + } + let mut clocks: Vec<_> = program + .clocks() + .iter() + .map(|c| (c.event, c.period.max(2))) + .collect(); + let declared = clocks.len(); + collect(program.statements(), &mut clocks); + let mut slot = || { + let a = runtime.design.allocate_testbench_slot(64, false); + runtime.runtime_schema.testbench_read_roots.insert(a); + a + }; + let control = std::array::from_fn(|_| slot()); + let processes = program + .kernels() + .iter() + .map(|_| std::array::from_fn(|_| slot())) + .collect(); + let clock_slots = clocks + .iter() + .map(|_| std::array::from_fn(|_| slot())) + .collect(); + let locals = program + .kernels() + .iter() + .map(|_| { + program + .private_variables() + .iter() + .map(|&a| { + let copy = runtime.design.allocate_testbench_copy(a); + runtime.runtime_schema.testbench_read_roots.insert(copy); + (a, copy) + }) + .collect() + }) + .collect(); + let event_sources: Vec<_> = runtime + .design + .state_objects + .iter() + .filter(|(_, m)| { + matches!( + m.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + | celox_design::DomainKind::ResetAsyncLow + | celox_design::DomainKind::ResetAsyncHigh + ) + }) + .map(|(&a, _)| a) + .collect(); + let baselines = event_sources + .into_iter() + .map(|a| { + let copy = runtime.design.allocate_testbench_copy(a); + runtime.runtime_schema.testbench_read_roots.insert(copy); + (a, copy) + }) + .collect(); + program.set_scheduler(TestbenchScheduler { + entry: None, + control, + processes, + clocks: clock_slots, + events: clocks.iter().map(|c| c.0).collect(), + periods: clocks.iter().map(|c| c.1).collect(), + declared, + locals, + baselines, + }); +} diff --git a/crates/celox/tests/slot_observer.rs b/crates/celox/tests/slot_observer.rs index 707ecaa39d5..e52aca4114b 100644 --- a/crates/celox/tests/slot_observer.rs +++ b/crates/celox/tests/slot_observer.rs @@ -273,3 +273,43 @@ fn an_observer_can_finish_before_domains_commit() { fn an_observer_can_finish_at_the_end_of_a_slot() { check_observer_finish_backends(false); } + +#[test] +fn compiled_clocks_accept_reset_gates_driven_only_between_runs() { + let source = r#"`timescale 1ns/1ns +module Top(input logic clk, rst_n, enable, output logic [7:0] q, memory); + wire cpu_rst_n = rst_n && enable; + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) memory <= 0; + else memory <= memory + 1; + always_ff @(posedge clk or negedge cpu_rst_n) + if (!cpu_rst_n) q <= 0; + else q <= q + 1; +endmodule +"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .four_state(false) + .scheduler_mode(celox::SchedulerMode::DifferentialRuns) + .build() + .unwrap(); + let rst = sim.signal("rst_n"); + let enable = sim.signal("enable"); + let q = sim.signal("q"); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + sim.modify(|io| io.set(enable, 1u8)).unwrap(); + sim.add_clock("clk", 2, 1); + sim.run_until(20).unwrap(); + assert_eq!(sim.get(q), 10u8.into()); + assert!( + sim.scheduler_stats().compiled_slots > 0, + "{:?}", + sim.scheduler_stats() + ); + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + sim.run_until(22).unwrap(); + assert_eq!(sim.get(q), 0u8.into()); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + sim.run_until(30).unwrap(); + assert_eq!(sim.get(q), 4u8.into()); + assert!(sim.scheduler_stats().checked_steps > 0); +} diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index ec791707758..ccb54714eb3 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -275,10 +275,20 @@ compiler. Tiered execution promotes the DUT and testbench kernels together. The compiled process stores its continuation before requesting a clock/reset wait or a host service such as display, assertions, random generation or component -calls. The Veryl event scheduler resumes these kernels and retains clock order, -private process state, tick limits and heap roots. This does not change -`clock_gen` or `clock.next` timing. Compiler-only builds retain the same lowering -and serialized kernel metadata without requiring a host JIT. +calls. A generated SIR scheduler resumes the TB kernels in declaration order, +tracks their clock waits, and advances all clock generators together. It composes +the same compiled clock-domain scheduler used by timed simulation. TB arithmetic, +settlement requests and ordinary clock progress stay inside generated code; +host services and bounded safe points return to the runtime so tiered compilation +can be adopted. Observed slots still use the runtime event queue when tracing, +components or other observers require it. + +Scheduler continuations, saved process-local values, event baselines and clock +state have layout-owned homes. Wait releases precede runnable TB processes, which +run before the timestamp's clock edges. Simultaneous edges sample before commits; +tick limits drain pending falling edges and reset releases. The reference +scheduler remains available for differential checks. Compiler-only builds retain +the same lowering and serialized kernel metadata without requiring a host JIT. ## Public API boundary