From 8ade1aa0b77bf9a4c47b896b5b10655fc8864388 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 04:37:00 +0900 Subject: [PATCH] perf(testbench)!: roll up compiled Veryl testbench execution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Land the Veryl testbench execution stack as one queue entry; its members are not merged into master individually. Lower Veryl testbench expressions and resumable processes into shared SIR before optimization and state layout, and run them through the native, interpreter, Cranelift and Wasm backends, so tiered execution promotes DUT and TB kernels together. The separate TB VM, Cranelift compiler, scalar assembler and runtime loop evaluator are removed. Concurrent TB continuation dispatch, clock waits and multi-clock time progression are generated as ordinary SIR composed with the shared compiled clock-domain scheduler, so process arithmetic, settlement and eligible clock slots execute together between host services and tiering safe points. The shared scheduler no longer invalidates clean combinational state for unchanged clocks and internal clock-alias notifications. Native SIR/MIR traces now include process entries, including compiled testbench and scheduler code. Tiered circuit and Heliodor comparisons publish only total workload time; startup and execution intervals stay in diagnostic reports. The tree is identical to #2483 at the SHA below. The source PRs are held with release:hold while this rollup is active. Their changes are squashed here; they close automatically when this PR lands on master. If a source head changes, rebuild the rollup before queueing it. Removing this rollup requires releasing those holds before resuming individual stack merges. Source PRs and pinned heads: - #2445: a26c0a41f6f526581469d94c1c406079e8471353 — perf(testbench)!: compile Veryl testbenches through the HDL backends - #2462: 544ca13ea72d36f2576157d3b468fa00f225e0fc — fix(bench): compare tiered simulators by total completion time - #2482: 7a0ee192494976a31b5e091971b6a8507058c602 — fix(trace): include native process kernels in codegen traces - #2483: 387fb869718e6498327f28c80abfe53c53f3a7a9 — perf(testbench)!: compile concurrent Veryl scheduling through SIR Validation (from the source PRs, same tree as #2483): - 281 Celox library tests; 98 native TB tests (1 existing ignored); 9 native MIR tests including a native testbench process trace; 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, WASI and ARM64 code-generation checks; formatting and the default-dependency guard. - SHA-256, FFT and LZ77 pass both positive and deliberately broken oracle qualification. Rica completes all 16 replays with identical cycle and retirement counts. - Benchmark publication and runner tests, Heliodor conversion fixtures, and the VitePress production build. Performance status: no end-to-end speedup over Veryl simulator has been established; this rollup makes no performance claim. No large Heliodor workload was run. BREAKING CHANGE: CompiledExpr no longer evaluates expressions against a raw memory pointer; compile testbenches with the simulator pipeline and invoke their bound backend kernels. Serialized testbench metadata gains scheduler state, and appended native images use container version 55 and must be regenerated. Change-Id: If61ef7bfc9c47ddc0c3bf3e81cf6bdbce4d62a28 --- Cargo.lock | 3 + crates/celox-design/src/lib.rs | 3 +- crates/celox-runtime/src/schedule.rs | 2 + .../src/simulation/activation.rs | 2 +- .../celox-runtime/src/simulation/compiled.rs | 3 + crates/celox-runtime/src/simulation/edges.rs | 8 + crates/celox-runtime/src/testbench.rs | 89 +- crates/celox-testbench/Cargo.toml | 5 + crates/celox-testbench/src/expression.rs | 46 + .../celox-testbench/src/expression_tests.rs | 52 + crates/celox-testbench/src/lib.rs | 197 ++- crates/celox-testbench/src/lowering.rs | 711 +++++++++ .../src/lowering_native_tests.rs | 369 +++++ crates/celox-testbench/src/scheduler.rs | 68 + crates/celox-testbench/src/value.rs | 51 + .../src/value/arithmetic_oracle.rs | 326 ++++ crates/celox-testbench/src/visit.rs | 204 +++ crates/celox-testbench/src/vm.rs | 1191 --------------- crates/celox/src/backend/native/backend.rs | 102 +- 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/component.rs | 61 +- crates/celox/src/ir.rs | 91 +- crates/celox/src/lib.rs | 2 + crates/celox/src/parser.rs | 30 +- crates/celox/src/scheduler.rs | 367 ++++- crates/celox/src/scheduler/testbench.rs | 679 +++++++++ crates/celox/src/simulator.rs | 15 +- crates/celox/src/simulator/builder.rs | 155 +- crates/celox/src/testbench.rs | 1327 +++++------------ crates/celox/src/testbench/clock_batch.rs | 121 ++ crates/celox/src/testbench/compiled.rs | 389 +++++ crates/celox/src/testbench/native.rs | 165 ++ crates/celox/src/testbench_compile.rs | 130 ++ crates/celox/src/testbench_compile/memory.rs | 155 ++ crates/celox/src/testbench_compile/process.rs | 785 ++++++++++ crates/celox/tests/native_mir.rs | 32 + crates/celox/tests/native_testbench.rs | 168 ++- crates/celox/tests/slot_observer.rs | 40 + .../celox/tests/testbench_reset_polarity.rs | 33 + crates/celox/tests/testbench_string.rs | 70 + .../components/BenchmarkDashboard.vue | 26 +- docs/benchmarks/collection.md | 10 +- docs/benchmarks/heliodor.md | 9 +- docs/benchmarks/index.md | 4 +- docs/internals/architecture.md | 24 + docs/internals/compiler-crate-architecture.md | 2 +- scripts/convert-heliodor-bench.mjs | 7 +- scripts/publish-collection-bench.mjs | 2 +- scripts/publish-collection-bench.test.mjs | 5 +- scripts/publish-crates.sh | 4 +- scripts/publish-heliodor-bench.test.mjs | 24 +- scripts/tests/convert-heliodor-bench.sh | 13 +- 54 files changed, 5989 insertions(+), 2397 deletions(-) create mode 100644 crates/celox-testbench/src/expression.rs create mode 100644 crates/celox-testbench/src/expression_tests.rs create mode 100644 crates/celox-testbench/src/lowering.rs create mode 100644 crates/celox-testbench/src/lowering_native_tests.rs create mode 100644 crates/celox-testbench/src/scheduler.rs create mode 100644 crates/celox-testbench/src/value.rs create mode 100644 crates/celox-testbench/src/value/arithmetic_oracle.rs create mode 100644 crates/celox-testbench/src/visit.rs delete mode 100644 crates/celox-testbench/src/vm.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 create mode 100644 crates/celox/src/testbench/native.rs create mode 100644 crates/celox/src/testbench_compile/memory.rs create mode 100644 crates/celox/src/testbench_compile/process.rs diff --git a/Cargo.lock b/Cargo.lock index 426be8bcbd1..26e4741a733 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -819,8 +819,11 @@ dependencies = [ name = "celox-testbench" version = "0.12.0" dependencies = [ + "celox-backend-x86", "celox-design", "celox-heap", + "celox-sir", + "celox-state-layout", "num-bigint", "num-traits", "serde", diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5835fadc4a1..74cd4d8ab7f 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1358,7 +1358,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/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index 7f9b0803fd4..3555e9b2deb 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -254,7 +254,7 @@ impl SimulationState { } } } - let live_cancelled = cancelled + let live_cancelled: Vec = cancelled .iter() .enumerate() .filter_map(|(id, &cancelled)| { 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 058643a6e30..588c81fecce 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -284,39 +284,6 @@ fn bind_statement( .into_iter() .map(|statement| bind_statement(backend, statement)) .collect::>>()?; - // A constant loop that only waits does not need a host wakeup at - // each iteration. clock_gen keeps running while this process - // sleeps; the induction variable is scoped to the empty body. - if !inclusive - && !reverse - && step == 1 - && step_op.is_none() - && let (Some(0), Some(iterations)) = (constant_bound(&start), constant_bound(&end)) - && let [ - GenericTestbenchStatement::ClockNext { - clock_event, - count, - period, - }, - ] = body.as_slice() - && let Some(count) = match count { - GenericClockCount::Static(n) => Some(*n), - GenericClockCount::Dynamic(expr) => expr.constant_u64(), - } - && count != 0 - && iterations != 0 - && loop_var.as_ref().is_none_or(|(_, width, signed)| { - let bits = width.saturating_sub(usize::from(*signed)); - bits >= 64 || iterations < (1u64 << bits) - }) - && let Some(count) = iterations.checked_mul(count) - { - return Some(GenericTestbenchStatement::ClockNext { - clock_event: *clock_event, - count: GenericClockCount::Static(count), - period: *period, - }); - } Some(GenericTestbenchStatement::For { loop_var: loop_var.map(|(signal, width, signed)| { (backend.resolve_signal(&signal.address), width, signed) @@ -405,25 +372,6 @@ fn bind_statement( } } -fn constant_bound(bound: &ExecutableLoopBound) -> Option { - match bound { - GenericLoopBound::Static(value) => u64::try_from(*value).ok(), - GenericLoopBound::Dynamic { - expr, - width, - signed, - } if *width <= 64 => { - let value = expr.constant_u64()?; - if *signed && (*width == 0 || value >> (*width - 1) != 0) { - None - } else { - Some(value) - } - } - _ => None, - } -} - pub fn bind_testbench_program( backend: &B, program: TestbenchProgram, @@ -443,6 +391,37 @@ pub fn bind_testbench_program( hardware.sort_unstable_by_key(|range| (range.start, range.end)); hardware.dedup(); let backend = &Binding { backend, hardware }; + let kernels = program + .kernels() + .iter() + .map(|kernel| celox_testbench::TestbenchKernel { + entry: kernel.entry, + resume: backend.resolve_signal(&kernel.resume), + status: backend.resolve_signal(&kernel.status), + request: backend.resolve_signal(&kernel.request), + requests: kernel + .requests + .iter() + .map(|request| match request { + celox_testbench::KernelRequest::Statement(site) => { + celox_testbench::KernelRequest::Statement(*site) + } + celox_testbench::KernelRequest::Settle => { + celox_testbench::KernelRequest::Settle + } + celox_testbench::KernelRequest::Written { address, width } => { + celox_testbench::KernelRequest::Written { + address: backend.resolve_signal(address), + width: *width, + } + } + celox_testbench::KernelRequest::Error(message) => { + celox_testbench::KernelRequest::Error(message.clone()) + } + }) + .collect(), + }) + .collect(); let lengths = program.process_lengths().to_vec(); if lengths .iter() @@ -497,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() @@ -509,6 +492,8 @@ pub fn bind_testbench_program( .collect(); 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/Cargo.toml b/crates/celox-testbench/Cargo.toml index 866bf086d7d..f964b9e843b 100644 --- a/crates/celox-testbench/Cargo.toml +++ b/crates/celox-testbench/Cargo.toml @@ -11,10 +11,15 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-sir = { workspace = true } celox-heap = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } serde = { workspace = true } +[target.'cfg(target_arch = "x86_64")'.dev-dependencies] +celox-backend-x86 = { workspace = true } +celox-state-layout = { workspace = true } + [lints] workspace = true diff --git a/crates/celox-testbench/src/expression.rs b/crates/celox-testbench/src/expression.rs new file mode 100644 index 00000000000..32d1a5ee85b --- /dev/null +++ b/crates/celox-testbench/src/expression.rs @@ -0,0 +1,46 @@ +//! A binding to an expression compiled as an ordinary SIR kernel. +//! Machine code is owned by the simulator backend and its program image. +use crate::{ExprBytecode, ExprOpcode as Opcode, ExpressionKernel}; + +#[derive(Clone, Debug)] +pub struct CompiledExpr { + bytecode: ExprBytecode, + observes_hardware: bool, +} +impl CompiledExpr { + pub fn new(bytecode: ExprBytecode) -> Self { + Self { + bytecode, + observes_hardware: true, + } + } + pub fn bytecode(&self) -> &ExprBytecode { + &self.bytecode + } + pub fn kernel(&self) -> Option<&ExpressionKernel> { + self.bytecode.kernel() + } + pub fn classify_hardware_access(mut self, mut hardware: impl FnMut(usize) -> bool) -> Self { + self.observes_hardware = self.bytecode.ops().iter().any(|op| match op { + Opcode::LoadU64 { location, .. } + | Opcode::LoadWide { location, .. } + | Opcode::LoadIndexed { location, .. } + | Opcode::LoadBitSelect { location, .. } + | Opcode::LoadString { location, .. } + | Opcode::StoreString { location, .. } + | Opcode::StoreU64 { location, .. } => hardware(*location), + _ => false, + }); + self + } + pub fn observes_hardware(&self) -> bool { + self.observes_hardware + } + /// Literal folding for conservative binding-time overlap checks. General + /// constant folding belongs to the shared SIR optimizer. + pub fn constant_u64(&self) -> Option { + self.kernel() + .and_then(|kernel| kernel.constant) + .or_else(|| self.bytecode.literal_u64()) + } +} diff --git a/crates/celox-testbench/src/expression_tests.rs b/crates/celox-testbench/src/expression_tests.rs new file mode 100644 index 00000000000..37b9065256c --- /dev/null +++ b/crates/celox-testbench/src/expression_tests.rs @@ -0,0 +1,52 @@ +use crate::lowering::native_tests::evaluate; +use crate::{ExprOpcode as TbOpcode, TestbenchOperator as Op}; +use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; + +#[test] +fn deep_expression_compiles_without_a_runtime_operand_stack() { + for depth in [1, 8, 9, 32, 128, 129, 256] { + let mut ops: Vec<_> = (1..=depth).map(TbOpcode::ConstU64).collect(); + ops.extend((1..depth).map(|_| TbOpcode::BinOp(Op::Add))); + + assert_eq!( + evaluate(ops, &[]), + num_bigint::BigUint::from(depth * (depth + 1) / 2) + ); + } +} + +#[test] +fn floating_bytecode_keeps_precision_and_numeric_conversions() { + for (precision, expected) in [ + (FloatPrecision::F32, 16777216), + (FloatPrecision::F64, 16777217), + ] { + let ops = vec![ + TbOpcode::ConstU64(16777216), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::ConstU64(1), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::FloatBinary { + op: FloatBinaryOp::Add, + precision, + }, + TbOpcode::FloatUnary { + op: FloatUnaryOp::ToUnsigned { + width: 32, + round: true, + }, + precision, + }, + ]; + assert_eq!( + evaluate(ops, &[]), + num_bigint::BigUint::from(expected as u64) + ); + } +} diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index b5f5a840fa3..4f4aca0d10b 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -4,17 +4,25 @@ //! 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; +mod expression; +#[cfg(all(test, target_arch = "x86_64"))] +mod expression_tests; mod format; -mod vm; +pub mod lowering; +mod value; +pub use expression::CompiledExpr; pub use format::{ DisplayFormatArg, FieldSpec, MAX_FIELD_WIDTH, format_display_arg, format_sized_display_arg, format_sv_display_arg, format_veryl_display_arg, pad_veryl_field, }; -pub use vm::{CompiledExpr, TestbenchValue}; +pub use value::TestbenchValue; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { @@ -281,8 +289,26 @@ pub struct TestbenchClock { pub period: u64, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum KernelRequest { + Statement(usize), + Settle, + Written { address: A, width: usize }, + Error(String), +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestbenchKernel { + pub entry: usize, + pub resume: A, + pub status: A, + pub request: A, + pub requests: Vec>, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TestbenchProgram { + kernels: Vec>, + scheduler: Option>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -297,6 +323,8 @@ pub struct TestbenchProgram { impl Default for TestbenchProgram { fn default() -> Self { Self { + kernels: Vec::new(), + scheduler: None, statements: Vec::new(), process_lengths: Vec::new(), clocks: Vec::new(), @@ -311,8 +339,23 @@ 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 + } + pub fn set_kernels(&mut self, kernels: Vec>) { + self.kernels = kernels; + } + pub fn new(statements: Vec>) -> Self { Self { + kernels: Vec::new(), + scheduler: None, process_lengths: vec![statements.len()], clocks: Vec::new(), private_variables: Vec::new(), @@ -353,6 +396,13 @@ impl TestbenchProgram { &self.private_variables } + pub fn processes(&self) -> impl Iterator]> { + self.process_lengths.iter().scan(0, |offset, &length| { + let start = *offset; + *offset += length; + Some(&self.statements[start..*offset]) + }) + } pub fn process_lengths(&self) -> &[usize] { &self.process_lengths } @@ -367,6 +417,14 @@ impl TestbenchProgram { self } + pub fn statements_mut(&mut self) -> &mut [SemanticStatement] { + &mut self.statements + } + + pub fn component_bindings_mut(&mut self) -> &mut [SemanticComponentBinding] { + &mut self.component_bindings + } + pub fn statements(&self) -> &[SemanticStatement] { &self.statements } @@ -555,15 +613,66 @@ pub enum ExprOpcode { } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(bound(serialize = "L: Serialize", deserialize = "L: Deserialize<'de>"))] pub struct ExprBytecode { ops: Vec>, + #[serde(default)] + kernel: Option>, } impl ExprBytecode { pub fn new(ops: Vec>) -> Self { - Self { ops } + Self { ops, kernel: None } } + pub fn kernel(&self) -> Option<&ExpressionKernel> { + self.kernel.as_ref() + } + pub fn set_kernel(&mut self, kernel: ExpressionKernel) { + self.kernel = Some(kernel); + } + + /// Fold literal casts without executing a testbench expression. + pub fn literal_u64(&self) -> Option { + let [ExprOpcode::ConstU64(value), rest @ ..] = self.ops.as_slice() else { + return None; + }; + let mut value = *value; + for op in rest { + let ExprOpcode::Resize { + source_width, + target_width, + signed, + } = op + else { + return None; + }; + if *source_width > 64 || *target_width > 64 { + return None; + } + let mask = |width: usize| { + if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + } + }; + if *source_width == 0 { + value = if value & 1 != 0 { + mask(*target_width) + } else { + 0 + }; + } else { + value &= mask(*source_width); + if *signed && *target_width > *source_width && value >> (source_width - 1) != 0 { + value |= !mask(*source_width); + } + value &= mask(*target_width); + } + } + Some(value) + } pub fn ops(&self) -> &[ExprOpcode] { &self.ops } @@ -573,6 +682,17 @@ impl ExprBytecode { } } +/// A native expression entry point and its ordinary state result slot. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExpressionKernel { + pub constant: Option, + pub entry: usize, + pub result: L, + pub width: usize, + pub is_string: bool, + pub writes: Vec<(L, usize)>, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct BindError { pub address: A, @@ -599,6 +719,8 @@ pub type ExecutableStatement = TestbenchStatement< pub type ExecutableComponentBinding = ComponentBinding; pub struct ExecutableTestbench { + kernels: Vec>, + scheduler: Option>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -611,6 +733,21 @@ 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 + } + pub fn with_kernels(mut self, kernels: Vec>) -> Self { + self.kernels = kernels; + self + } + pub fn new(statements: Vec>, random_seed: u64) -> Self { Self::new_with_random_seed(statements, Some(random_seed)) } @@ -620,6 +757,8 @@ impl ExecutableTestbench { random_seed: Option, ) -> Self { Self { + kernels: Vec::new(), + scheduler: None, process_lengths: vec![statements.len()], clocks: Vec::new(), private_signals: Vec::new(), @@ -718,21 +857,21 @@ impl ExecutableTestbench { } } -impl ExprBytecode> { - pub fn bind_with( +impl ExprBytecode { + pub fn try_map_locations( self, - mut resolve: impl FnMut(&A) -> Option, - ) -> Result> { + mut map: impl FnMut(L) -> Result, + ) -> Result, E> { let mut ops = Vec::with_capacity(self.ops.len()); for op in self.ops { let bound = match op { ExprOpcode::ConstString(value) => ExprOpcode::ConstString(value), ExprOpcode::LoadString { location, elements } => ExprOpcode::LoadString { - location: bind_location(location, &mut resolve)?, + location: map(location)?, elements, }, ExprOpcode::StoreString { location } => ExprOpcode::StoreString { - location: bind_location(location, &mut resolve)?, + location: map(location)?, }, ExprOpcode::ConstU64(value) => ExprOpcode::ConstU64(value), ExprOpcode::ConstWide(value) => ExprOpcode::ConstWide(value), @@ -741,7 +880,7 @@ impl ExprBytecode> { byte_size, mask, } => ExprOpcode::LoadU64 { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, mask, }, @@ -750,7 +889,7 @@ impl ExprBytecode> { byte_size, width, } => ExprOpcode::LoadWide { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, width, }, @@ -810,7 +949,7 @@ impl ExprBytecode> { base_bit_offset, element_width, } => ExprOpcode::LoadIndexed { - location: bind_location(location, &mut resolve)?, + location: map(location)?, stride_bits, base_bit_offset, element_width, @@ -820,7 +959,7 @@ impl ExprBytecode> { base_byte_size, select_width, } => ExprOpcode::LoadBitSelect { - location: bind_location(location, &mut resolve)?, + location: map(location)?, base_byte_size, select_width, }, @@ -828,13 +967,39 @@ impl ExprBytecode> { location, byte_size, } => ExprOpcode::StoreU64 { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, }, }; ops.push(bound); } - Ok(ExprBytecode::new(ops)) + let kernel = self + .kernel + .map(|kernel| -> Result<_, E> { + Ok(ExpressionKernel { + constant: kernel.constant, + entry: kernel.entry, + result: map(kernel.result)?, + width: kernel.width, + is_string: kernel.is_string, + writes: kernel + .writes + .into_iter() + .map(|(location, size)| Ok((map(location)?, size))) + .collect::>()?, + }) + }) + .transpose()?; + Ok(ExprBytecode { ops, kernel }) + } +} + +impl ExprBytecode> { + pub fn bind_with( + self, + mut resolve: impl FnMut(&A) -> Option, + ) -> Result> { + self.try_map_locations(|location| bind_location(location, &mut resolve)) } } @@ -933,3 +1098,5 @@ mod tests { assert!(matches!(statement, SemanticStatement::If { .. })); } } + +mod visit; diff --git a/crates/celox-testbench/src/lowering.rs b/crates/celox-testbench/src/lowering.rs new file mode 100644 index 00000000000..2130b85a62c --- /dev/null +++ b/crates/celox-testbench/src/lowering.rs @@ -0,0 +1,711 @@ +//! Lower testbench expressions into the same SIR operations as HDL processes. +//! Widths remain explicit through native instruction selection, including +//! values wider than a host register. Strings use the existing heap ABI. +use crate::{ExprBytecode, ExprOpcode, StateLocation, TestbenchOperator as Op}; +use celox_design::{BinaryOp, UnaryOp}; +use celox_sir::{ + RegisterId, SIRBuilder, SIRInstruction as Inst, SIROffset, SIRTerminator, SIRValue, +}; +use num_bigint::BigUint; + +#[derive(Clone, Copy, Debug)] +pub struct Value { + pub register: RegisterId, + pub string: bool, +} + +pub struct Expressions<'a, A> { + pub builder: &'a mut SIRBuilder, +} +impl Expressions<'_, A> { + fn bits(&mut self, width: usize, value: impl Into) -> Value { + let register = self.builder.alloc_bit(width.max(1), false); + self.builder.emit(Inst::Imm(register, SIRValue::new(value))); + Value { + register, + string: false, + } + } + fn unary(&mut self, op: UnaryOp, value: Value, width: usize, signed: bool) -> Value { + let register = self.builder.alloc_bit(width.max(1), signed); + if op == UnaryOp::Ident && width < self.builder.register(&value.register).width() { + self.builder + .emit(Inst::Slice(register, value.register, 0, width.max(1))); + } else { + self.builder.emit(Inst::Unary(register, op, value.register)); + } + Value { + register, + string: false, + } + } + fn binary(&mut self, op: BinaryOp, lhs: Value, rhs: Value, width: usize) -> Value { + let register = self.builder.alloc_bit(width.max(1), false); + self.builder + .emit(Inst::Binary(register, lhs.register, op, rhs.register)); + Value { + register, + string: false, + } + } + fn resize(&mut self, value: Value, source: usize, target: usize, signed: bool) -> Value { + if target == 0 { + return self.bits(1, 0u8); + } + if source == 0 { + let value = self.unary(UnaryOp::Ident, value, 1, false); + let value = self.unary(UnaryOp::Ident, value, target, false); + return self.unary(UnaryOp::Minus, value, target, false); + } + let value = self.unary(UnaryOp::Ident, value, source, signed); + let value = self.unary(UnaryOp::Ident, value, target, false); + if signed && target > source { + let shift = self.bits(64, (target - source) as u64); + let value = self.binary(BinaryOp::Shl, value, shift, target); + self.binary(BinaryOp::Sar, value, shift, target) + } else { + value + } + } + fn heap(&mut self, operation: u64, args: &[Value]) -> Value { + let op = self.bits(64, operation); + let zero = self.bits(64, 0u8); + let mut inputs = vec![op.register]; + inputs.extend(args.iter().map(|arg| arg.register)); + inputs.resize(4, zero.register); + let register = self.builder.alloc_bit(64, false); + self.builder.emit(Inst::ExternCall { + dst: Some(register), + func: celox_sir::extern_abi::HEAP_HELPER_ID, + args: inputs, + }); + Value { + register, + string: true, + } + } + fn pop(stack: &mut Vec) -> Result { + stack + .pop() + .ok_or_else(|| "testbench expression stack underflow".into()) + } + pub fn compile( + &mut self, + expression: &ExprBytecode>, + ) -> Result { + let mut stack = Vec::new(); + self.block(expression.ops(), &mut stack)?; + if stack.len() != 1 { + return Err("testbench expression must produce one value".into()); + } + let value = Self::pop(&mut stack)?; + if value.string { + let width = self.builder.register(&value.register).width(); + let mut value = self.resize(value, width, celox_design::HANDLE_WIDTH, false); + value.string = true; + Ok(value) + } else { + Ok(value) + } + } + fn block( + &mut self, + code: &[ExprOpcode>], + stack: &mut Vec, + ) -> Result<(), String> { + let mut cursor = 0; + while cursor < code.len() { + let instruction = &code[cursor]; + cursor += 1; + let value = match instruction { + ExprOpcode::ConstU64(value) => self.bits(64, *value), + ExprOpcode::ConstWide(value) => { + self.bits((value.bits() as usize).max(65), value.clone()) + } + ExprOpcode::LoadU64 { + location, + byte_size, + mask, + } => { + let register = self.builder.alloc_bit((byte_size * 8).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + byte_size * 8, + )); + let value = Value { + register, + string: false, + }; + let mask = self.bits(64, *mask); + self.binary(BinaryOp::And, value, mask, 64) + } + ExprOpcode::LoadWide { + location, width, .. + } => { + let register = self.builder.alloc_bit((*width).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + *width, + )); + Value { + register, + string: false, + } + } + ExprOpcode::BinOp(op) => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + let width = self + .builder + .register(&lhs.register) + .width() + .max(self.builder.register(&rhs.register).width()); + self.operation(*op, lhs, rhs, width, width, width, false, false)? + } + ExprOpcode::TypedBinOp { + op, + lhs_width, + rhs_width, + result_width, + lhs_signed, + rhs_signed, + } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + self.operation( + *op, + lhs, + rhs, + *lhs_width, + *rhs_width, + *result_width, + *lhs_signed, + *rhs_signed, + )? + } + ExprOpcode::TypedUnary { + op, + operand_width, + result_width, + } => { + let operand = Self::pop(stack)?; + let operand = self.resize(operand, *operand_width, *operand_width, false); + let (op, invert) = match op { + Op::Add => (UnaryOp::Ident, false), + Op::Sub => (UnaryOp::Minus, false), + Op::LogicNot => (UnaryOp::LogicNot, false), + Op::BitNot => (UnaryOp::BitNot, false), + Op::BitAnd => (UnaryOp::And, false), + Op::BitNand => (UnaryOp::And, true), + Op::BitOr => (UnaryOp::Or, false), + Op::BitNor => (UnaryOp::Or, true), + Op::BitXor => (UnaryOp::Xor, false), + Op::BitXnor => (UnaryOp::Xor, true), + _ => return Err("invalid testbench unary operator".into()), + }; + let value = self.unary(op, operand, *result_width, false); + if invert { + self.unary(UnaryOp::LogicNot, value, 1, false) + } else { + value + } + } + ExprOpcode::FloatBinary { op, precision } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + let lhs = self.resize(lhs, precision.width(), precision.width(), false); + let rhs = self.resize(rhs, precision.width(), precision.width(), false); + let op = BinaryOp::Float { + op: *op, + precision: *precision, + }; + let width = match op { + BinaryOp::Float { + op: + celox_design::FloatBinaryOp::Eq + | celox_design::FloatBinaryOp::Ne + | celox_design::FloatBinaryOp::Lt + | celox_design::FloatBinaryOp::Le + | celox_design::FloatBinaryOp::Gt + | celox_design::FloatBinaryOp::Ge, + .. + } => 1, + _ => precision.width(), + }; + self.binary(op, lhs, rhs, width) + } + ExprOpcode::FloatUnary { op, precision } => { + let value = Self::pop(stack)?; + let input_width = match op { + celox_design::FloatUnaryOp::FromSigned { width } + | celox_design::FloatUnaryOp::FromUnsigned { width } => *width, + _ => precision.width(), + }; + let value = self.resize(value, input_width, input_width, false); + let op = UnaryOp::Float { + op: *op, + precision: *precision, + }; + self.unary(op, value, op.result_width(precision.width()), false) + } + ExprOpcode::Resize { + source_width, + target_width, + signed, + } => { + let value = Self::pop(stack)?; + self.resize(value, *source_width, *target_width, *signed) + } + ExprOpcode::ConcatPart { + part_width, + result_width, + } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + if *part_width >= *result_width { + self.resize(rhs, *part_width, *result_width, false) + } else { + let rhs = self.resize(rhs, *part_width, *part_width, false); + let lhs = self.resize( + lhs, + self.builder.register(&lhs.register).width(), + result_width - part_width, + false, + ); + let register = self.builder.alloc_bit((*result_width).max(1), false); + self.builder + .emit(Inst::Concat(register, vec![lhs.register, rhs.register])); + Value { + register, + string: false, + } + } + } + ExprOpcode::Ternary { then_len, else_len } => { + let condition = Self::pop(stack)?; + let end = cursor + .checked_add(*then_len) + .and_then(|x| x.checked_add(*else_len)) + .filter(|x| *x <= code.len()) + .ok_or("invalid testbench conditional lengths")?; + let yes = self.builder.new_block(); + let no = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: condition.register, + true_block: (yes, vec![]), + false_block: (no, vec![]), + }); + self.builder.switch_to_block(yes); + let mut left = stack.clone(); + self.block(&code[cursor..cursor + then_len], &mut left)?; + let yes_end = self.builder.current_block(); + self.builder.seal_block(SIRTerminator::Return); + self.builder.switch_to_block(no); + let mut right = stack.clone(); + self.block(&code[cursor + then_len..end], &mut right)?; + if left.len() != right.len() || left.len() != stack.len() + 1 { + return Err("testbench conditional stack mismatch".into()); + } + let no_end = self.builder.current_block(); + self.builder.seal_block(SIRTerminator::Return); + let mut params = Vec::new(); + let mut merged = Vec::new(); + for (l, r) in left.iter().zip(&right) { + if l.string != r.string { + return Err("testbench conditional value kind mismatch".into()); + } + let width = self + .builder + .register(&l.register) + .width() + .max(self.builder.register(&r.register).width()); + let register = self.builder.alloc_bit(width, false); + params.push(register); + merged.push(Value { + register, + string: l.string, + }); + } + let join = self.builder.new_block_with(params); + for (block, values) in [(yes_end, left), (no_end, right)] { + self.builder.switch_to_block(block); + let values = values + .into_iter() + .zip(&merged) + .map(|(value, target)| { + self.unary( + UnaryOp::Ident, + value, + self.builder.register(&target.register).width(), + false, + ) + .register + }) + .collect(); + self.builder.seal_block(SIRTerminator::Jump(join, values)); + } + self.builder.switch_to_block(join); + *stack = merged; + cursor = end; + continue; + } + ExprOpcode::LoadIndexed { + location, + stride_bits, + base_bit_offset, + element_width, + } => { + let index = Self::pop(stack)?; + let stride = self.bits(64, *stride_bits as u64); + let offset = self.binary(BinaryOp::Mul, index, stride, 64); + let base = self.bits(64, (location.byte_offset * 8 + base_bit_offset) as u64); + let offset = self.binary(BinaryOp::Add, offset, base, 64); + let register = self.builder.alloc_bit((*element_width).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Dynamic(offset.register), + *element_width, + )); + Value { + register, + string: false, + } + } + ExprOpcode::LoadBitSelect { + location, + base_byte_size, + select_width, + } => { + // Select from the value, not from an unchecked dynamic + // memory address. A selection may extend past the object. + let offset = Self::pop(stack)?; + let width = base_byte_size.saturating_mul(8); + if width == 0 || *select_width == 0 { + self.bits((*select_width).max(1), 0u8) + } else { + let register = self.builder.alloc_bit(width, false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + width, + )); + let value = Value { + register, + string: false, + }; + let value = self.binary(BinaryOp::Shr, value, offset, width); + self.resize(value, width, *select_width, false) + } + } + ExprOpcode::StoreU64 { + location, + byte_size, + } => { + let value = Self::pop(stack)?; + self.builder.emit(Inst::Store( + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + byte_size * 8, + value.register, + vec![], + vec![], + )); + continue; + } + ExprOpcode::ConstString(bytes) => { + let mut value = self.heap(celox_heap::ops::NEW, &[]); + for chunk in bytes.chunks(8) { + let bits = chunk + .iter() + .fold(0u64, |v, byte| (v << 8) | u64::from(*byte)); + let bits = self.bits(64, bits); + let count = self.bits(64, chunk.len() as u64); + value = self.heap(celox_heap::ops::APPEND_BYTES, &[value, bits, count]); + } + self.heap(celox_heap::ops::FREEZE, &[value]) + } + ExprOpcode::LoadString { location, elements } => { + let offset = Self::pop(stack)?; + let shift = self.bits(64, celox_design::HANDLE_WIDTH.trailing_zeros() as u64); + let index = self.binary(BinaryOp::Shr, offset, shift, 64); + let limit = self.bits(64, *elements as u64); + let valid = self.binary(BinaryOp::LtU, index, limit, 1); + let present = self.builder.new_block(); + let absent = self.builder.new_block(); + let result = self.builder.alloc_bit(celox_design::HANDLE_WIDTH, false); + let join = self.builder.new_block_with(vec![result]); + self.builder.seal_block(SIRTerminator::Branch { + cond: valid.register, + true_block: (present, vec![]), + false_block: (absent, vec![]), + }); + self.builder.switch_to_block(present); + let shift = self.bits(64, celox_design::HANDLE_WIDTH.trailing_zeros() as u64); + let offset = self.binary(BinaryOp::Shl, index, shift, 64); + let base = self.bits(64, (location.byte_offset * 8) as u64); + let offset = self.binary(BinaryOp::Add, offset, base, 64); + let register = self.builder.alloc_bit(celox_design::HANDLE_WIDTH, false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Dynamic(offset.register), + celox_design::HANDLE_WIDTH, + )); + self.builder + .seal_block(SIRTerminator::Jump(join, vec![register])); + self.builder.switch_to_block(absent); + let zero = self.bits(celox_design::HANDLE_WIDTH, 0u8); + self.builder + .seal_block(SIRTerminator::Jump(join, vec![zero.register])); + self.builder.switch_to_block(join); + Value { + register: result, + string: true, + } + } + ExprOpcode::StoreString { location } => { + let value = Self::pop(stack)?; + let width = self.builder.register(&value.register).width(); + let value = self.resize(value, width, celox_design::HANDLE_WIDTH, false); + self.builder.emit(Inst::Store( + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + celox_design::HANDLE_WIDTH, + value.register, + vec![], + vec![], + )); + continue; + } + }; + stack.push(value); + } + Ok(()) + } + fn operation( + &mut self, + op: Op, + mut lhs: Value, + mut rhs: Value, + lw: usize, + rw: usize, + width: usize, + ls: bool, + rs: bool, + ) -> Result { + if lhs.string && rhs.string { + lhs = self.heap(celox_heap::ops::COMPARE, &[lhs, rhs]); + rhs = self.bits(64, 0u8); + return self.operation( + op, + Value { + string: false, + ..lhs + }, + rhs, + 64, + 64, + 1, + true, + true, + ); + } + lhs = self.resize(lhs, lw, lw, ls); + rhs = self.resize(rhs, rw, rw, rs); + let signed = ls && rs; + if op == Op::Pow { + let mut result = self.bits(width, 1u8); + let mut factor = self.resize(lhs, lw, width, false); + for bit in 0..rw { + let predicate = self.builder.alloc_bit(1, false); + self.builder + .emit(Inst::Slice(predicate, rhs.register, bit, 1)); + let product = self.binary(BinaryOp::Mul, result, factor, width); + let register = self.builder.alloc_bit(width.max(1), false); + self.builder.emit(Inst::Mux( + register, + predicate, + product.register, + result.register, + )); + result = Value { + register, + string: false, + }; + if bit + 1 < rw { + factor = self.binary(BinaryOp::Mul, factor, factor, width); + } + } + return Ok(result); + } + let (binary, boolean, invert) = match op { + Op::Add => (BinaryOp::Add, false, false), + Op::Sub => (BinaryOp::Sub, false, false), + Op::Mul => (BinaryOp::Mul, false, false), + Op::Div => ( + if signed { + BinaryOp::DivS + } else { + BinaryOp::DivU + }, + false, + false, + ), + Op::Rem => ( + if signed { + BinaryOp::RemS + } else { + BinaryOp::RemU + }, + false, + false, + ), + Op::BitAnd | Op::BitNand => (BinaryOp::And, false, op == Op::BitNand), + Op::BitOr | Op::BitNor => (BinaryOp::Or, false, op == Op::BitNor), + Op::BitXor | Op::BitXnor => (BinaryOp::Xor, false, op == Op::BitXnor), + Op::LogicShiftL | Op::ArithShiftL => (BinaryOp::Shl, false, false), + Op::LogicShiftR => (BinaryOp::Shr, false, false), + Op::ArithShiftR => (if ls { BinaryOp::Sar } else { BinaryOp::Shr }, false, false), + Op::Eq | Op::EqWildcard => (BinaryOp::Eq, true, false), + Op::Ne | Op::NeWildcard => (BinaryOp::Ne, true, false), + Op::Less => ( + if signed { BinaryOp::LtS } else { BinaryOp::LtU }, + true, + false, + ), + Op::LessEq => ( + if signed { BinaryOp::LeS } else { BinaryOp::LeU }, + true, + false, + ), + Op::Greater => ( + if signed { BinaryOp::GtS } else { BinaryOp::GtU }, + true, + false, + ), + Op::GreaterEq => ( + if signed { BinaryOp::GeS } else { BinaryOp::GeU }, + true, + false, + ), + Op::LogicAnd => (BinaryOp::LogicAnd, true, false), + Op::LogicOr => (BinaryOp::LogicOr, true, false), + _ => return Err("invalid testbench binary operator".into()), + }; + let result = self.binary(binary, lhs, rhs, if boolean { 1 } else { width }); + Ok(if invert { + self.unary(UnaryOp::BitNot, result, width, false) + } else { + result + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn lower(ops: Vec>>) -> celox_sir::ExecutionUnit { + let mut builder = SIRBuilder::new(); + let value = Expressions { + builder: &mut builder, + } + .compile(&ExprBytecode::new(ops)) + .unwrap(); + let width = builder.register(&value.register).width(); + builder.emit(Inst::Store( + 0, + SIROffset::Static(0), + width, + value.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let unit = celox_sir::ExecutionUnit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + }; + unit.verify_result().unwrap(); + unit + } + #[test] + fn wide_arithmetic_uses_sir_instead_of_value_callbacks() { + let unit = lower(vec![ + ExprOpcode::ConstWide(BigUint::from(1u8) << 170), + ExprOpcode::ConstU64(37), + ExprOpcode::TypedBinOp { + op: Op::Mul, + lhs_width: 192, + rhs_width: 192, + result_width: 192, + lhs_signed: false, + rhs_signed: false, + }, + ]); + assert!(unit.blocks.values().flat_map(|b|&b.instructions).any(|i|matches!(i,Inst::Binary(dst,_,BinaryOp::Mul,_) if unit.register_map[dst].width()==192))); + assert!( + !unit + .blocks + .values() + .flat_map(|b| &b.instructions) + .any(|i| matches!(i, Inst::ExternCall { .. })) + ); + } + #[test] + fn floating_point_uses_the_shared_sir_operator() { + let unit = lower(vec![ + ExprOpcode::ConstU64(1.5f64.to_bits()), + ExprOpcode::ConstU64(2.0f64.to_bits()), + ExprOpcode::FloatBinary { + op: celox_design::FloatBinaryOp::Mul, + precision: celox_design::FloatPrecision::F64, + }, + ]); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .any(|i| matches!(i, Inst::Binary(_, _, BinaryOp::Float { .. }, _))) + ); + } + #[test] + fn strings_use_the_existing_hdl_heap_abi() { + let unit = lower(vec![ExprOpcode::ConstString(b"native testbench".to_vec())]); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .filter_map(|i| if let Inst::ExternCall { func, .. } = i { + Some(*func) + } else { + None + }) + .all(|id| id == celox_sir::extern_abi::HEAP_HELPER_ID) + ); + } + #[test] + fn conditional_side_effects_remain_in_separate_blocks() { + let unit = lower(vec![ + ExprOpcode::ConstU64(1), + ExprOpcode::Ternary { + then_len: 1, + else_len: 1, + }, + ExprOpcode::ConstWide(BigUint::from(1u8) << 127), + ExprOpcode::ConstU64(42), + ]); + assert_eq!(unit.blocks.len(), 4); + } +} + +#[cfg(all(test, target_arch = "x86_64"))] +#[path = "lowering_native_tests.rs"] +pub(crate) mod native_tests; diff --git a/crates/celox-testbench/src/lowering_native_tests.rs b/crates/celox-testbench/src/lowering_native_tests.rs new file mode 100644 index 00000000000..5ed6e4459d7 --- /dev/null +++ b/crates/celox-testbench/src/lowering_native_tests.rs @@ -0,0 +1,369 @@ +//! Execute lowered expressions through the HDL native pipeline. +use super::*; +use celox_backend_x86::native::{emit, jit_mem::JitCode, scalar_pipeline}; +use celox_design::{InstanceId, RegionedStateAddr, STABLE_REGION, StateAddr, StateObjectId}; +use celox_state_layout::{ + LayoutInput, LayoutSource, MemoryLayout, MemoryLayoutMode, StateObjectLayout, +}; + +struct Objects(Vec>); +impl LayoutSource for Objects { + fn layout_input(&self, _: MemoryLayoutMode) -> LayoutInput { + LayoutInput { + state_objects: self.0.clone(), + working_addresses: vec![], + sparse_addresses: vec![], + unpacked_arrays: Default::default(), + requirements: Default::default(), + ff_referenced_addresses: Default::default(), + num_events: 0, + runtime_event_sites: vec![], + lane_writers: Default::default(), + access_rank: Default::default(), + } + } +} +fn address(id: u32) -> StateAddr { + StateAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(id), + } +} +pub(crate) fn evaluate(ops: Vec>>, input: &[u8]) -> BigUint { + evaluate_with_state(ops, input).0 +} +fn evaluate_with_state( + ops: Vec>>, + input: &[u8], +) -> (BigUint, Vec) { + let mut builder = SIRBuilder::new(); + let result = Expressions { + builder: &mut builder, + } + .compile(&ExprBytecode::new(ops)) + .unwrap(); + let width = builder.register(&result.register).width(); + builder.emit(Inst::Store( + 0, + SIROffset::Static(0), + width, + result.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let unit = celox_sir::ExecutionUnit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + } + .into_map_addr(&mut |id| RegionedStateAddr::from_absolute_addr(STABLE_REGION, address(id))); + let source = Objects(vec![ + StateObjectLayout { + address: address(0), + width, + is_4state: false, + }, + StateObjectLayout { + address: address(1), + width: (input.len() * 8).max(64), + is_4state: false, + }, + ]); + let layout = MemoryLayout::build(&source, false, MemoryLayoutMode::Packed); + let prepared = + scalar_pipeline::prepare_scalar_eu(&unit, &layout, false, "testbench-expression").unwrap(); + let code = emit::emit( + &prepared.function, + &prepared.allocation, + prepared.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&code.code).unwrap(); + let mut state = vec![0u128; (code.required_state_size as usize).div_ceil(16)]; + // The aligned allocation includes the complete native spill arena. Both + // semantic objects were allocated by the ordinary HDL state layout. + let bytes = unsafe { + std::slice::from_raw_parts_mut(state.as_mut_ptr().cast::(), state.len() * 16) + }; + let table = [celox_sir::float::evaluate as *const () as usize]; + let pointer = table.as_ptr().wrapping_add(1) as u64; + let header = celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET; + bytes[header..header + 8].copy_from_slice(&pointer.to_le_bytes()); + let offset = layout.offsets[&address(1)]; + bytes[offset..offset + input.len()].copy_from_slice(input); + unsafe { + (jit.fn_ptr)(bytes.as_mut_ptr()); + } + let offset = layout.offsets[&address(0)]; + ( + BigUint::from_bytes_le(&bytes[offset..offset + width.div_ceil(8)]), + bytes[layout.offsets[&address(1)]..layout.offsets[&address(1)] + input.len()].to_vec(), + ) +} +fn operation(op: Op, width: usize, signed: bool) -> ExprOpcode> { + ExprOpcode::TypedBinOp { + op, + lhs_width: width, + rhs_width: width, + result_width: width, + lhs_signed: signed, + rhs_signed: signed, + } +} +#[test] +fn wide_native_multiply_preserves_high_limbs() { + let lhs = (BigUint::from(1u8) << 171) + BigUint::from(17u8); + let rhs = (BigUint::from(1u8) << 67) + BigUint::from(3u8); + let expected = (&lhs * &rhs) & ((BigUint::from(1u8) << 256) - BigUint::from(1u8)); + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstWide(lhs), + ExprOpcode::ConstWide(rhs), + operation(Op::Mul, 256, false) + ], + &[] + ), + expected + ); +} +#[test] +fn native_signed_division_and_comparison() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(0xf9), + ExprOpcode::ConstU64(2), + operation(Op::Div, 8, true) + ], + &[] + ), + BigUint::from(0xfdu8) + ); + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(0xf9), + ExprOpcode::ConstU64(2), + operation(Op::Less, 8, true) + ], + &[] + ), + BigUint::from(1u8) + ); +} +#[test] +fn native_float_multiply() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(1.5f64.to_bits()), + ExprOpcode::ConstU64((-2.0f64).to_bits()), + ExprOpcode::FloatBinary { + op: celox_design::FloatBinaryOp::Mul, + precision: celox_design::FloatPrecision::F64 + } + ], + &[] + ), + BigUint::from((-3.0f64).to_bits()) + ); +} +#[test] +fn bit_selection_does_not_read_the_next_object() { + for shift in [4, 8, 63, 64, 65, u64::MAX] { + let expected = if shift == 4 { 0xau8 } else { 0 }; + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(shift), + ExprOpcode::LoadBitSelect { + location: StateLocation { + address: 1, + byte_offset: 0 + }, + base_byte_size: 1, + select_width: 8 + } + ], + &[0xa5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ), + BigUint::from(expected) + ); + } +} +#[test] +fn out_of_bounds_string_index_returns_empty_handle() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(u64::MAX), + ExprOpcode::LoadString { + location: StateLocation { + address: 1, + byte_offset: 0 + }, + elements: 1 + } + ], + &[0xff; 8] + ), + BigUint::ZERO + ); +} + +#[test] +fn native_typed_arithmetic_matches_expression_contract() { + use crate::value::eval_typed_binop; + for width in [1usize, 8, 33, 64, 65, 129] { + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + for (lhs, rhs) in [ + (mask.clone(), BigUint::from(2u8)), + (BigUint::from(7u8), BigUint::ZERO), + ] { + for signed in [false, true] { + for op in [ + Op::Add, + Op::Sub, + Op::Mul, + Op::Div, + Op::Rem, + Op::Eq, + Op::Ne, + Op::Less, + Op::LessEq, + Op::Greater, + Op::GreaterEq, + Op::BitAnd, + Op::BitOr, + Op::BitXor, + Op::BitNand, + Op::BitNor, + Op::BitXnor, + Op::LogicAnd, + Op::LogicOr, + Op::LogicShiftL, + Op::LogicShiftR, + Op::ArithShiftR, + ] { + let expected = eval_typed_binop( + crate::TestbenchValue::Wide(lhs.clone()), + op, + crate::TestbenchValue::Wide(rhs.clone()), + width, + width, + width, + signed, + signed, + ) + .to_biguint(); + let actual = evaluate( + vec![ + ExprOpcode::ConstWide(lhs.clone()), + ExprOpcode::ConstWide(rhs.clone()), + operation(op, width, signed), + ], + &[], + ); + assert_eq!( + actual, expected, + "{op:?}, width={width}, signed={signed}, lhs={lhs}, rhs={rhs}" + ); + } + } + } + } +} + +#[test] +fn conditional_kernel_writes_only_the_selected_branch() { + let loc = |byte_offset| StateLocation { + address: 1, + byte_offset, + }; + let ops = vec![ + ExprOpcode::ConstU64(100), + ExprOpcode::LoadU64 { + location: loc(0), + byte_size: 1, + mask: 1, + }, + ExprOpcode::Ternary { + then_len: 4, + else_len: 4, + }, + ExprOpcode::ConstU64(11), + ExprOpcode::StoreU64 { + location: loc(1), + byte_size: 1, + }, + ExprOpcode::ConstU64(20), + ExprOpcode::Resize { + source_width: 8, + target_width: 129, + signed: false, + }, + ExprOpcode::ConstU64(22), + ExprOpcode::StoreU64 { + location: loc(2), + byte_size: 1, + }, + ExprOpcode::ConstU64(30), + ExprOpcode::Resize { + source_width: 8, + target_width: 129, + signed: false, + }, + ExprOpcode::BinOp(Op::Add), + ]; + for condition in [0, 1] { + let (value, state) = evaluate_with_state(ops.clone(), &[condition, 0, 0]); + assert_eq!( + value, + BigUint::from(if condition == 1 { 120u64 } else { 130 }) + ); + assert_eq!( + state, + if condition == 1 { + vec![1, 11, 0] + } else { + vec![0, 0, 22] + } + ); + } +} + +#[test] +fn string_handles_use_the_shared_heap_width() { + let location = StateLocation { + address: 1, + byte_offset: 0, + }; + let input = [0x12, 0, 0, 0, 0x34, 0, 0, 0]; + for (index, expected) in [(0, 0x12u8), (1, 0x34), (2, 0)] { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(index * celox_design::HANDLE_WIDTH as u64), + ExprOpcode::LoadString { + location, + elements: 2 + }, + ], + &input + ), + BigUint::from(expected) + ); + } + let (_, state) = evaluate_with_state( + vec![ + ExprOpcode::ConstU64(0x56), + ExprOpcode::StoreString { location }, + ExprOpcode::ConstU64(0), + ], + &input, + ); + assert_eq!(state, [0x56, 0, 0, 0, 0x34, 0, 0, 0]); +} 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-testbench/src/value.rs b/crates/celox-testbench/src/value.rs new file mode 100644 index 00000000000..e0f96483624 --- /dev/null +++ b/crates/celox-testbench/src/value.rs @@ -0,0 +1,51 @@ +use num_bigint::BigUint; + +/// Testbench value: integer bits or a dynamically sized byte string. +#[derive(Clone, Debug)] +pub enum TestbenchValue { + U64(u64), + Wide(BigUint), + String(Vec), +} + +impl TestbenchValue { + #[inline] + pub fn to_u64(&self) -> u64 { + match self { + TestbenchValue::String(v) => v + .iter() + .rev() + .take(8) + .enumerate() + .fold(0, |value, (i, byte)| value | (u64::from(*byte) << (i * 8))), + TestbenchValue::U64(v) => *v, + TestbenchValue::Wide(v) => { + let digits = v.to_u64_digits(); + digits.first().copied().unwrap_or(0) + } + } + } + + #[inline] + pub fn is_zero(&self) -> bool { + match self { + TestbenchValue::String(v) => v.is_empty(), + TestbenchValue::U64(v) => *v == 0, + TestbenchValue::Wide(v) => *v == BigUint::ZERO, + } + } + + #[inline] + pub fn to_biguint(&self) -> BigUint { + match self { + TestbenchValue::String(v) => BigUint::from_bytes_be(v), + TestbenchValue::U64(v) => BigUint::from(*v), + TestbenchValue::Wide(v) => v.clone(), + } + } +} + +#[cfg(test)] +mod arithmetic_oracle; +#[cfg(test)] +pub(crate) use arithmetic_oracle::eval_typed_binop; diff --git a/crates/celox-testbench/src/value/arithmetic_oracle.rs b/crates/celox-testbench/src/value/arithmetic_oracle.rs new file mode 100644 index 00000000000..afbd71f18cb --- /dev/null +++ b/crates/celox-testbench/src/value/arithmetic_oracle.rs @@ -0,0 +1,326 @@ +//! Test-only arithmetic oracle for native lowering differential tests. +use super::TestbenchValue; +use crate::TestbenchOperator as Op; +use num_bigint::{BigInt, BigUint, Sign}; +use num_traits::ToPrimitive as _; + +pub(crate) fn width_mask(width: usize) -> BigUint { + if width == 0 { + BigUint::ZERO + } else { + (BigUint::from(1u8) << width) - BigUint::from(1u8) + } +} + +#[inline] +pub(crate) fn width_mask_u64(width: usize) -> u64 { + match width { + 0 => 0, + 1..=63 => (1u64 << width) - 1, + _ => u64::MAX, + } +} + +#[inline] +pub(crate) fn signed_i128(value: u64, width: usize) -> i128 { + let value = value & width_mask_u64(width); + if width == 0 || width >= 64 { + (value as i64) as i128 + } else if value & (1u64 << (width - 1)) == 0 { + value as i128 + } else { + value as i128 - (1i128 << width) + } +} + +pub(crate) fn normalized_bits(value: &TestbenchValue, width: usize) -> BigUint { + value.to_biguint() & width_mask(width) +} + +pub(crate) fn tb_value_from_bits(value: BigUint, width: usize) -> TestbenchValue { + let value = value & width_mask(width); + if width <= 64 { + TestbenchValue::U64(value.to_u64().unwrap_or(0)) + } else { + TestbenchValue::Wide(value) + } +} + +pub(crate) fn signed_bigint(value: &TestbenchValue, width: usize) -> BigInt { + let raw = normalized_bits(value, width); + if width == 0 || !raw.bit((width - 1) as u64) { + BigInt::from(raw) + } else { + BigInt::from(raw) - (BigInt::from(1u8) << width) + } +} + +pub(crate) fn signed_bits(value: BigInt, width: usize) -> BigUint { + if width == 0 { + return BigUint::ZERO; + } + let modulus = BigUint::from(1u8) << width; + match value.sign() { + Sign::Minus => { + let magnitude = (-value).to_biguint().unwrap_or_default() % &modulus; + if magnitude == BigUint::ZERO { + BigUint::ZERO + } else { + modulus - magnitude + } + } + _ => value.to_biguint().unwrap_or_default() % modulus, + } +} + +pub(crate) fn eval_typed_binop_u64( + l: u64, + op: Op, + r: u64, + lhs_width: usize, + rhs_width: usize, + result_width: usize, + lhs_signed: bool, + rhs_signed: bool, +) -> u64 { + let l = l & width_mask_u64(lhs_width); + let r = r & width_mask_u64(rhs_width); + let result_mask = width_mask_u64(result_width); + let signed = lhs_signed && rhs_signed; + let bool_value = |value: bool| u64::from(value); + + match op { + Op::Eq | Op::EqWildcard => bool_value(l == r), + Op::Ne | Op::NeWildcard => bool_value(l != r), + Op::Less if signed => bool_value(signed_i128(l, lhs_width) < signed_i128(r, rhs_width)), + Op::Less => bool_value(l < r), + Op::LessEq if signed => bool_value(signed_i128(l, lhs_width) <= signed_i128(r, rhs_width)), + Op::LessEq => bool_value(l <= r), + Op::Greater if signed => bool_value(signed_i128(l, lhs_width) > signed_i128(r, rhs_width)), + Op::Greater => bool_value(l > r), + Op::GreaterEq if signed => { + bool_value(signed_i128(l, lhs_width) >= signed_i128(r, rhs_width)) + } + Op::GreaterEq => bool_value(l >= r), + Op::LogicAnd => bool_value(l != 0 && r != 0), + Op::LogicOr => bool_value(l != 0 || r != 0), + Op::Add => l.wrapping_add(r) & result_mask, + Op::Sub => l.wrapping_sub(r) & result_mask, + Op::Mul => l.wrapping_mul(r) & result_mask, + Op::Div if signed => { + let divisor = signed_i128(r, rhs_width); + if divisor == 0 { + 0 + } else { + (signed_i128(l, lhs_width) / divisor) as u64 & result_mask + } + } + Op::Div => l.checked_div(r).unwrap_or(0) & result_mask, + Op::Rem if signed => { + let divisor = signed_i128(r, rhs_width); + if divisor == 0 { + 0 + } else { + (signed_i128(l, lhs_width) % divisor) as u64 & result_mask + } + } + Op::Rem => l.checked_rem(r).unwrap_or(0) & result_mask, + Op::Pow => { + let mut exponent = r; + let mut base = l & result_mask; + let mut value = 1u64 & result_mask; + while exponent != 0 { + if exponent & 1 != 0 { + value = ((value as u128 * base as u128) as u64) & result_mask; + } + exponent >>= 1; + if exponent != 0 { + base = ((base as u128 * base as u128) as u64) & result_mask; + } + } + value + } + Op::BitAnd => (l & r) & result_mask, + Op::BitOr => (l | r) & result_mask, + Op::BitXor => (l ^ r) & result_mask, + Op::BitXnor => (!(l ^ r)) & result_mask, + Op::BitNand => (!(l & r)) & result_mask, + Op::BitNor => (!(l | r)) & result_mask, + Op::LogicShiftL | Op::ArithShiftL => { + if r >= result_width as u64 { + 0 + } else { + l.wrapping_shl(r as u32) & result_mask + } + } + Op::LogicShiftR => { + if r >= result_width as u64 { + 0 + } else { + (l >> r) & result_mask + } + } + Op::ArithShiftR if lhs_signed => { + let value = signed_i128(l, lhs_width); + if r >= result_width as u64 { + if value < 0 { result_mask } else { 0 } + } else { + ((value >> r) as u64) & result_mask + } + } + Op::ArithShiftR => { + if r >= result_width as u64 { + 0 + } else { + (l >> r) & result_mask + } + } + _ => unreachable!("operator is not a source-language binary op: {op:?}"), + } +} + +pub(crate) fn eval_typed_binop( + l: TestbenchValue, + op: Op, + r: TestbenchValue, + lhs_width: usize, + rhs_width: usize, + result_width: usize, + lhs_signed: bool, + rhs_signed: bool, +) -> TestbenchValue { + if let (TestbenchValue::U64(l), TestbenchValue::U64(r)) = (&l, &r) + && lhs_width <= 64 + && rhs_width <= 64 + && result_width <= 64 + { + return TestbenchValue::U64(eval_typed_binop_u64( + *l, + op, + *r, + lhs_width, + rhs_width, + result_width, + lhs_signed, + rhs_signed, + )); + } + let lb = normalized_bits(&l, lhs_width); + let rb = normalized_bits(&r, rhs_width); + let signed = lhs_signed && rhs_signed; + + let comparison = |value: bool| TestbenchValue::U64(u64::from(value)); + match op { + Op::Eq | Op::EqWildcard => comparison(lb == rb), + Op::Ne | Op::NeWildcard => comparison(lb != rb), + Op::Less if signed => { + comparison(signed_bigint(&l, lhs_width) < signed_bigint(&r, rhs_width)) + } + Op::Less => comparison(lb < rb), + Op::LessEq if signed => { + comparison(signed_bigint(&l, lhs_width) <= signed_bigint(&r, rhs_width)) + } + Op::LessEq => comparison(lb <= rb), + Op::Greater if signed => { + comparison(signed_bigint(&l, lhs_width) > signed_bigint(&r, rhs_width)) + } + Op::Greater => comparison(lb > rb), + Op::GreaterEq if signed => { + comparison(signed_bigint(&l, lhs_width) >= signed_bigint(&r, rhs_width)) + } + Op::GreaterEq => comparison(lb >= rb), + Op::LogicAnd => comparison(lb != BigUint::ZERO && rb != BigUint::ZERO), + Op::LogicOr => comparison(lb != BigUint::ZERO || rb != BigUint::ZERO), + Op::Add => tb_value_from_bits(lb + rb, result_width), + Op::Sub => tb_value_from_bits( + signed_bits(BigInt::from(lb) - BigInt::from(rb), result_width), + result_width, + ), + Op::Mul => tb_value_from_bits(lb * rb, result_width), + Op::Div if signed => { + let divisor = signed_bigint(&r, rhs_width); + if divisor == BigInt::from(0u8) { + TestbenchValue::U64(0) + } else { + let quotient = signed_bigint(&l, lhs_width) / divisor; + tb_value_from_bits(signed_bits(quotient, result_width), result_width) + } + } + Op::Div => { + if rb == BigUint::ZERO { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb / rb, result_width) + } + } + Op::Rem if signed => { + let divisor = signed_bigint(&r, rhs_width); + if divisor == BigInt::from(0u8) { + TestbenchValue::U64(0) + } else { + let remainder = signed_bigint(&l, lhs_width) % divisor; + tb_value_from_bits(signed_bits(remainder, result_width), result_width) + } + } + Op::Rem => { + if rb == BigUint::ZERO { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb % rb, result_width) + } + } + Op::Pow => { + if result_width == 0 { + TestbenchValue::U64(0) + } else { + let modulus = BigUint::from(1u8) << result_width; + tb_value_from_bits(lb.modpow(&rb, &modulus), result_width) + } + } + Op::BitAnd => tb_value_from_bits(lb & rb, result_width), + Op::BitOr => tb_value_from_bits(lb | rb, result_width), + Op::BitXor => tb_value_from_bits(lb ^ rb, result_width), + Op::BitXnor => tb_value_from_bits((lb ^ rb) ^ width_mask(result_width), result_width), + Op::LogicShiftL | Op::ArithShiftL => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb << shift, result_width) + } + } + Op::LogicShiftR => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb >> shift, result_width) + } + } + Op::ArithShiftR if lhs_signed => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + let value = signed_bigint(&l, lhs_width); + let shifted = if shift >= result_width { + if value.sign() == Sign::Minus { + BigInt::from(-1) + } else { + BigInt::from(0) + } + } else { + value >> shift + }; + tb_value_from_bits(signed_bits(shifted, result_width), result_width) + } + Op::ArithShiftR => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb >> shift, result_width) + } + } + Op::BitNand => tb_value_from_bits((lb & rb) ^ width_mask(result_width), result_width), + Op::BitNor => tb_value_from_bits((lb | rb) ^ width_mask(result_width), result_width), + _ => unreachable!("operator is not a source-language binary op: {op:?}"), + } +} diff --git a/crates/celox-testbench/src/visit.rs b/crates/celox-testbench/src/visit.rs new file mode 100644 index 00000000000..5bf18035c28 --- /dev/null +++ b/crates/celox-testbench/src/visit.rs @@ -0,0 +1,204 @@ +//! Compiler traversal of expressions in a semantic testbench. +use crate::*; +impl TestbenchProgram { + pub fn try_visit_expressions( + &mut self, + mut visit: impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + fn target( + value: &mut TestbenchTarget, ExprBytecode>>, + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + if let Some(selection) = &mut value.selection { + visit(&mut selection.offset)?; + } + Ok(()) + } + fn message( + value: &mut Option>>, + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + if let Some(AssertMessage::Formatted { args, .. } | AssertMessage::DynamicArgs(args)) = + value + { + for argument in args { + visit(&mut argument.expr)?; + } + } + Ok(()) + } + fn block( + statements: &mut [SemanticStatement], + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + for statement in statements { + match statement { + TestbenchStatement::ClockNext { count, .. } + | TestbenchStatement::ResetAssert { + duration: count, .. + } => { + if let ClockCount::Dynamic(expr) = count { + visit(expr)?; + } + } + TestbenchStatement::Assert { + expr, + message: value, + .. + } => { + visit(expr)?; + message(value, visit)?; + } + TestbenchStatement::Display { message: value, .. } => message(value, visit)?, + TestbenchStatement::If { + expr, + then_block, + else_block, + } => { + visit(expr)?; + block(then_block, visit)?; + block(else_block, visit)?; + } + TestbenchStatement::For { + start, end, body, .. + } => { + for bound in [start, end] { + if let LoopBound::Dynamic { expr, .. } = bound { + visit(expr)?; + } + } + block(body, visit)?; + } + TestbenchStatement::Assign { dst, expr } => { + visit(expr)?; + target(dst, visit)?; + } + TestbenchStatement::RandomSeed { value, .. } => visit(value)?, + TestbenchStatement::RandomGet { ret, .. } + | TestbenchStatement::RandomGetSeed { ret, .. } => { + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::RandomGetRange { min, max, ret, .. } => { + visit(min)?; + visit(max)?; + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::ComponentMethod { args, ret, .. } => { + for arg in args { + visit(&mut arg.expr)?; + } + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::Break + | TestbenchStatement::Finish + | TestbenchStatement::WriteMemory { .. } => {} + } + } + Ok(()) + } + block(&mut self.statements, &mut visit)?; + for binding in &mut self.component_bindings { + for connection in &mut binding.connections { + if let Some(input) = &mut connection.input { + visit(input)?; + } + if let Some(input) = &mut connection.input_target { + target(input, &mut visit)?; + } + if let Some(output) = &mut connection.output { + target(output, &mut visit)?; + } + } + } + Ok(()) + } +} + +impl TestbenchProgram { + /// Fuse pure constant clock waits before assigning native request sites. + pub fn fold_clock_waits(&mut self) { + fn constant(expr: &ExprBytecode>) -> Option { + expr.kernel() + .and_then(|kernel| kernel.constant) + .or_else(|| expr.literal_u64()) + } + fn bound(bound: &LoopBound>>) -> Option { + match bound { + LoopBound::Static(value) => Some(*value as u64), + LoopBound::Dynamic { + expr, + width, + signed, + } if *width <= 64 => { + let value = constant(expr)?; + (!*signed || (*width != 0 && value >> (width - 1) == 0)).then_some(value) + } + _ => None, + } + } + fn block(statements: &mut [SemanticStatement]) { + for statement in statements { + match statement { + TestbenchStatement::If { + then_block, + else_block, + .. + } => { + block(then_block); + block(else_block); + } + TestbenchStatement::For { + loop_var, + start, + end, + inclusive, + step, + step_op, + reverse, + body, + } => { + block(body); + if !*inclusive + && !*reverse + && *step == 1 + && step_op.is_none() + && let (Some(0), Some(iterations)) = (bound(start), bound(end)) + && let [ + TestbenchStatement::ClockNext { + clock_event, + count, + period, + }, + ] = body.as_slice() + && let Some(count) = match count { + ClockCount::Static(count) => Some(*count), + ClockCount::Dynamic(expr) => constant(expr), + } + && count != 0 + && iterations != 0 + && loop_var.as_ref().is_none_or(|(_, width, signed)| { + let bits = width.saturating_sub(usize::from(*signed)); + bits >= 64 || iterations < (1u64 << bits) + }) + && let Some(count) = iterations.checked_mul(count) + { + *statement = TestbenchStatement::ClockNext { + clock_event: *clock_event, + count: ClockCount::Static(count), + period: *period, + }; + } + } + _ => {} + } + } + } + block(&mut self.statements); + } +} diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs deleted file mode 100644 index 291c45a81ce..00000000000 --- a/crates/celox-testbench/src/vm.rs +++ /dev/null @@ -1,1191 +0,0 @@ -use num_bigint::{BigInt, BigUint, Sign}; -use num_traits::ToPrimitive as _; - -use crate::{ExprBytecode, ExprOpcode as TbOpcode, TestbenchOperator as Op}; - -// ── Bytecode VM ──────────────────────────────────────────────────────── - -/// A compiled expression: flat bytecode evaluated on a stack VM. -#[derive(Clone, Debug)] -pub struct CompiledExpr { - bytecode: ExprBytecode, - observes_hardware: bool, -} - -/// Stack value: integer bits or a dynamically sized byte string. -#[derive(Clone, Debug)] -pub enum TestbenchValue { - U64(u64), - Wide(BigUint), - String(Vec), -} - -// Most expressions need only two or three operands. Keep their stack local; -// deeply nested expressions can still spill without imposing a depth limit. -struct ValueStack { - inline: [Option; 8], - len: usize, - spill: Vec, -} - -impl ValueStack { - fn new() -> Self { - Self { - inline: [const { None }; 8], - len: 0, - spill: Vec::new(), - } - } - - fn push(&mut self, value: TestbenchValue) { - if self.len < self.inline.len() { - self.inline[self.len] = Some(value); - } else { - self.spill.push(value); - } - self.len += 1; - } - - fn pop(&mut self) -> Option { - self.len = self.len.checked_sub(1)?; - if self.len < self.inline.len() { - self.inline[self.len].take() - } else { - self.spill.pop() - } - } - - fn last_mut(&mut self) -> Option<&mut TestbenchValue> { - if self.len <= self.inline.len() { - self.inline.get_mut(self.len.checked_sub(1)?)?.as_mut() - } else { - self.spill.last_mut() - } - } -} - -impl TestbenchValue { - #[inline] - pub fn to_u64(&self) -> u64 { - match self { - TestbenchValue::String(v) => v - .iter() - .rev() - .take(8) - .enumerate() - .fold(0, |value, (i, byte)| value | (u64::from(*byte) << (i * 8))), - TestbenchValue::U64(v) => *v, - TestbenchValue::Wide(v) => { - let digits = v.to_u64_digits(); - digits.first().copied().unwrap_or(0) - } - } - } - - #[inline] - pub fn is_zero(&self) -> bool { - match self { - TestbenchValue::String(v) => v.is_empty(), - TestbenchValue::U64(v) => *v == 0, - TestbenchValue::Wide(v) => *v == BigUint::ZERO, - } - } - - #[inline] - pub fn to_biguint(&self) -> BigUint { - match self { - TestbenchValue::String(v) => BigUint::from_bytes_be(v), - TestbenchValue::U64(v) => BigUint::from(*v), - TestbenchValue::Wide(v) => v.clone(), - } - } -} - -impl CompiledExpr { - pub fn new(bytecode: ExprBytecode) -> Self { - Self { - bytecode, - observes_hardware: true, - } - } - - /// Classify reads after binding against the hardware's state objects. - /// Include stores conservatively: a function expression can overwrite - /// an RTL result as well as read it. - pub fn classify_hardware_access(mut self, mut hardware: impl FnMut(usize) -> bool) -> Self { - self.observes_hardware = self.bytecode.ops().iter().any(|op| match op { - TbOpcode::LoadU64 { location, .. } - | TbOpcode::LoadWide { location, .. } - | TbOpcode::LoadIndexed { location, .. } - | TbOpcode::LoadBitSelect { location, .. } - | TbOpcode::LoadString { location, .. } - | TbOpcode::StoreString { location, .. } - | TbOpcode::StoreU64 { location, .. } => hardware(*location), - _ => false, - }); - self - } - - /// Whether evaluating this expression can observe an RTL-written object. - /// Unclassified expressions conservatively return true. - pub fn observes_hardware(&self) -> bool { - self.observes_hardware - } - - /// Evaluate against raw simulator memory, returning the result as u64. - /// For wide results, returns the low 64 bits. - pub fn eval_u64(&self, memory: *mut u8) -> u64 { - self.eval(memory).to_u64() - } - - /// Evaluate and return the full `TestbenchValue` (preserves wide results). - pub fn eval_value(&self, memory: *mut u8) -> TestbenchValue { - self.eval(memory) - } - - pub fn eval_bool(&self, memory: *mut u8) -> bool { - !self.eval(memory).is_zero() - } - - /// Returns the value when this expression does not read simulator memory. - pub fn constant_u64(&self) -> Option { - if self.bytecode.ops().iter().any(|op| { - matches!( - op, - TbOpcode::StoreString { .. } - | TbOpcode::LoadString { .. } - | TbOpcode::LoadU64 { .. } - | TbOpcode::LoadWide { .. } - | TbOpcode::LoadIndexed { .. } - | TbOpcode::LoadBitSelect { .. } - | TbOpcode::StoreU64 { .. } - ) - }) { - return None; - } - Some(self.eval_u64(std::ptr::null_mut())) - } - - /// Core evaluation loop. Uses `TestbenchValue` to handle both u64 and wide - /// signals on a single stack. The common case (all ≤64-bit operands) - /// stays in the `TestbenchValue::U64` variant and never allocates. - fn eval(&self, memory: *mut u8) -> TestbenchValue { - self.eval_value_with_write_observer(memory, |_, _| {}) - } - - /// Evaluate with a notification for each executed memory write. Expression - /// function calls can store arguments and results; ordinary reads do not - /// notify the observer or require a retained mutable view of the image. - pub fn eval_value_with_write_observer( - &self, - memory: *mut u8, - on_write: impl FnMut(usize, usize), - ) -> TestbenchValue { - self.eval_with_heap(memory, None, on_write) - } - - fn eval_leaf(&self, memory: *mut u8) -> Option { - match self.bytecode.ops() { - [TbOpcode::ConstU64(value)] => Some(TestbenchValue::U64(*value)), - [ - TbOpcode::LoadU64 { - location, - byte_size, - mask, - }, - ] => { - // SAFETY: bound bytecode addresses valid simulator memory. - Some(TestbenchValue::U64( - unsafe { read_le_u64(memory.add(*location), *byte_size) } & mask, - )) - } - _ => None, - } - } - - /// Evaluate with the simulator's heap, which string variables refer to. - /// Without a heap, string variables read as `""` and string stores are - /// dropped instead of writing a handle no heap knows. - pub fn eval_with_heap( - &self, - memory: *mut u8, - mut heap: Option<&mut celox_heap::Heap>, - mut on_write: impl FnMut(usize, usize), - ) -> TestbenchValue { - if let Some(value) = self.eval_leaf(memory) { - return value; - } - let mut stack = ValueStack::new(); - let mut pc: usize = 0; - let ops = self.bytecode.ops(); - - while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, &mut heap, &mut on_write); - } - stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: stack empty after evaluation"); - TestbenchValue::U64(0) - }) - } - - /// Execute the opcode at `pc` and advance `pc` past it. - /// Handles all opcodes including `Ternary` (with recursive sub-block - /// evaluation), so there is no separate `step()` function. - fn exec_at( - &self, - ops: &[TbOpcode], - pc: &mut usize, - stack: &mut ValueStack, - memory: *mut u8, - heap: &mut Option<&mut celox_heap::Heap>, - on_write: &mut impl FnMut(usize, usize), - ) { - match &ops[*pc] { - TbOpcode::ConstString(value) => { - stack.push(TestbenchValue::String(value.clone())); - *pc += 1; - } - TbOpcode::LoadString { location, elements } => { - let index = stack.pop().expect("string element offset").to_u64() as usize - / celox_design::HANDLE_WIDTH; - let value = match heap { - Some(heap) if index < *elements => { - let offset = location + index * celox_heap::HANDLE_BYTES; - // SAFETY: bound bytecode addresses a handle slot of - // `elements` handles in this memory image. - let handle = unsafe { read_handle(memory, offset) }; - heap.string(handle).to_vec() - } - _ => Vec::new(), - }; - stack.push(TestbenchValue::String(value)); - *pc += 1; - } - TbOpcode::StoreString { location } => { - let TestbenchValue::String(value) = stack.pop().expect("string store value") else { - unreachable!("string store requires a string value"); - }; - if let Some(heap) = heap { - let handle = heap.intern(&value); - // SAFETY: bound bytecode addresses a handle slot in this - // memory image. - unsafe { - std::ptr::copy_nonoverlapping( - handle.to_le_bytes().as_ptr(), - memory.add(*location), - celox_heap::HANDLE_BYTES, - ); - } - on_write(*location, celox_heap::HANDLE_BYTES); - } - *pc += 1; - } - TbOpcode::ConstU64(v) => { - stack.push(TestbenchValue::U64(*v)); - *pc += 1; - } - TbOpcode::ConstWide(v) => { - stack.push(TestbenchValue::Wide(v.clone())); - *pc += 1; - } - TbOpcode::LoadU64 { - location, - byte_size, - mask, - } => { - // SAFETY: caller guarantees `memory` is valid simulator memory - let val = unsafe { read_le_u64(memory.add(*location), *byte_size) } & mask; - stack.push(TestbenchValue::U64(val)); - *pc += 1; - } - TbOpcode::LoadWide { - location, - byte_size, - width, - } => { - let val = unsafe { read_le_wide(memory.add(*location), *byte_size, *width) }; - stack.push(TestbenchValue::Wide(val)); - *pc += 1; - } - TbOpcode::BinOp(op) => { - let r = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: BinOp rhs underflow"); - TestbenchValue::U64(0) - }); - let l = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: BinOp lhs underflow"); - TestbenchValue::U64(0) - }); - stack.push(eval_binop(l, *op, r)); - *pc += 1; - } - TbOpcode::FloatBinary { op, precision } => { - let r = stack.pop().unwrap_or(TestbenchValue::U64(0)); - let l = stack.pop().unwrap_or(TestbenchValue::U64(0)); - stack.push(TestbenchValue::U64(celox_design::eval_float_binary( - *op, - *precision, - l.to_u64(), - r.to_u64(), - ))); - *pc += 1; - } - TbOpcode::FloatUnary { op, precision } => { - if let Some(top) = stack.last_mut() { - *top = TestbenchValue::U64(celox_design::eval_float_unary( - *op, - *precision, - top.to_u64(), - )); - } - *pc += 1; - } - TbOpcode::TypedBinOp { - op, - lhs_width, - rhs_width, - result_width, - lhs_signed, - rhs_signed, - } => { - let r = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: TypedBinOp rhs underflow"); - TestbenchValue::U64(0) - }); - let l = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: TypedBinOp lhs underflow"); - TestbenchValue::U64(0) - }); - stack.push(eval_typed_binop( - l, - *op, - r, - *lhs_width, - *rhs_width, - *result_width, - *lhs_signed, - *rhs_signed, - )); - *pc += 1; - } - TbOpcode::TypedUnary { - op, - operand_width, - result_width, - } => { - if let Some(top) = stack.last_mut() { - *top = eval_typed_unop(*op, top, *operand_width, *result_width); - } else { - debug_assert!(false, "testbench bytecode: TypedUnary underflow"); - } - *pc += 1; - } - TbOpcode::Resize { - source_width, - target_width, - signed, - } => { - if let Some(top) = stack.last_mut() { - *top = resize_tb_value(top, *source_width, *target_width, *signed); - } else { - debug_assert!(false, "testbench bytecode: Resize underflow"); - } - *pc += 1; - } - TbOpcode::ConcatPart { - part_width, - result_width, - } => { - let part = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: ConcatPart value underflow"); - TestbenchValue::U64(0) - }); - let accumulator = stack.pop().unwrap_or_else(|| { - debug_assert!( - false, - "testbench bytecode: ConcatPart accumulator underflow" - ); - TestbenchValue::U64(0) - }); - if let (TestbenchValue::U64(accumulator), TestbenchValue::U64(part)) = - (&accumulator, &part) - && *result_width <= 64 - { - let shifted = if *part_width >= 64 { - 0 - } else { - accumulator << part_width - }; - stack.push(TestbenchValue::U64( - shifted | (part & width_mask_u64(*part_width)), - )); - } else { - let value = (accumulator.to_biguint() << part_width) - | normalized_bits(&part, *part_width); - stack.push(tb_value_from_bits(value, *result_width)); - } - *pc += 1; - } - TbOpcode::Ternary { then_len, else_len } => { - let cond = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: Ternary cond underflow"); - TestbenchValue::U64(0) - }); - *pc += 1; // skip past Ternary opcode - if !cond.is_zero() { - let then_end = *pc + then_len; - while *pc < then_end { - self.exec_at(ops, pc, stack, memory, heap, on_write); - } - *pc += else_len; // skip else block - } else { - *pc += then_len; // skip then block - let else_end = *pc + else_len; - while *pc < else_end { - self.exec_at(ops, pc, stack, memory, heap, on_write); - } - } - } - TbOpcode::LoadIndexed { - location, - stride_bits, - base_bit_offset, - element_width, - } => { - let idx = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: LoadIndexed underflow"); - TestbenchValue::U64(0) - }); - let i = idx.to_u64() as usize; - let bit_offset = base_bit_offset.saturating_add(i.saturating_mul(*stride_bits)); - let val = unsafe { read_bits(memory.add(*location), bit_offset, *element_width) }; - stack.push(val); - *pc += 1; - } - TbOpcode::LoadBitSelect { - location, - base_byte_size, - select_width, - } => { - let bit_idx = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: LoadBitSelect underflow"); - TestbenchValue::U64(0) - }); - let shift = bit_idx.to_u64() as usize; - if *base_byte_size <= 8 && *select_width <= 64 { - let full_val = unsafe { read_le_u64(memory.add(*location), *base_byte_size) }; - let mask = if *select_width == 64 { - u64::MAX - } else { - (1u64 << select_width) - 1 - }; - stack.push(TestbenchValue::U64((full_val >> shift) & mask)); - } else { - let full_width = base_byte_size.saturating_mul(8); - let full_val = - unsafe { read_le_wide(memory.add(*location), *base_byte_size, full_width) }; - let val = (full_val >> shift) & width_mask(*select_width); - stack.push(tb_value_from_bits(val, *select_width)); - } - *pc += 1; - } - TbOpcode::StoreU64 { - location, - byte_size, - } => { - let val = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: StoreU64 underflow"); - TestbenchValue::U64(0) - }); - let v = val.to_u64(); - let bytes = v.to_le_bytes(); - let n = (*byte_size).min(8); - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), memory.add(*location), n); - } - on_write(*location, n); - *pc += 1; - } - } - } -} - -/// # Safety -/// `ptr` must be valid for `byte_size` bytes of read access. -#[inline(always)] -unsafe fn read_le_u64(ptr: *const u8, byte_size: usize) -> u64 { - let mut buf = [0u8; 8]; - unsafe { - std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), byte_size.min(8)); - } - u64::from_le_bytes(buf) -} - -/// # Safety -/// `ptr` must be valid for `byte_size` bytes of read access. -unsafe fn read_le_wide(ptr: *const u8, byte_size: usize, width: usize) -> BigUint { - let mut buf = vec![0u8; byte_size]; - unsafe { - std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), byte_size); - } - let mut val = BigUint::from_bytes_le(&buf); - let extra_bits = byte_size * 8 - width; - if extra_bits > 0 { - val &= (BigUint::from(1u32) << width) - BigUint::from(1u32); - } - val -} - -/// # Safety -/// `ptr` must be valid for the byte span containing `bit_offset..bit_offset + width`. -unsafe fn read_bits(ptr: *const u8, bit_offset: usize, width: usize) -> TestbenchValue { - let byte_offset = bit_offset / 8; - let sub = bit_offset % 8; - let span_width = sub.saturating_add(width); - let byte_size = span_width.div_ceil(8); - if span_width <= 64 { - let value = unsafe { read_le_u64(ptr.add(byte_offset), byte_size) } >> sub; - TestbenchValue::U64(value & width_mask_u64(width)) - } else { - let value = unsafe { read_le_wide(ptr.add(byte_offset), byte_size, span_width) } >> sub; - tb_value_from_bits(value & width_mask(width), width) - } -} - -// ── Typed evaluation ─────────────────────────────────────────────────── - -/// Binary operation on `TestbenchValue`. When both operands are `U64` the fast -/// path runs entirely in registers; otherwise we promote to `BigUint`. -#[inline] -fn eval_binop(l: TestbenchValue, op: Op, r: TestbenchValue) -> TestbenchValue { - match (&l, &r) { - (TestbenchValue::String(l), TestbenchValue::String(r)) => { - let result = match op { - Op::Eq => l == r, - Op::Ne => l != r, - Op::Less => l < r, - Op::LessEq => l <= r, - Op::Greater => l > r, - Op::GreaterEq => l >= r, - _ => unreachable!("invalid string operator: {op:?}"), - }; - TestbenchValue::U64(u64::from(result)) - } - (TestbenchValue::U64(lv), TestbenchValue::U64(rv)) => { - TestbenchValue::U64(eval_binop_u64(*lv, op, *rv)) - } - _ => { - let lv = l.to_biguint(); - let rv = r.to_biguint(); - // Comparison / logic ops always return u64 - match op { - Op::Eq - | Op::Ne - | Op::Less - | Op::LessEq - | Op::Greater - | Op::GreaterEq - | Op::LogicAnd - | Op::LogicOr => TestbenchValue::U64(eval_binop_wide_cmp(&lv, op, &rv)), - _ => TestbenchValue::Wide(eval_binop_wide(lv, op, rv)), - } - } - } -} - -fn width_mask(width: usize) -> BigUint { - if width == 0 { - BigUint::ZERO - } else { - (BigUint::from(1u8) << width) - BigUint::from(1u8) - } -} - -#[inline] -fn width_mask_u64(width: usize) -> u64 { - match width { - 0 => 0, - 1..=63 => (1u64 << width) - 1, - _ => u64::MAX, - } -} - -#[inline] -fn signed_i128(value: u64, width: usize) -> i128 { - let value = value & width_mask_u64(width); - if width == 0 || width >= 64 { - (value as i64) as i128 - } else if value & (1u64 << (width - 1)) == 0 { - value as i128 - } else { - value as i128 - (1i128 << width) - } -} - -fn normalized_bits(value: &TestbenchValue, width: usize) -> BigUint { - value.to_biguint() & width_mask(width) -} - -fn tb_value_from_bits(value: BigUint, width: usize) -> TestbenchValue { - let value = value & width_mask(width); - if width <= 64 { - TestbenchValue::U64(value.to_u64().unwrap_or(0)) - } else { - TestbenchValue::Wide(value) - } -} - -fn signed_bigint(value: &TestbenchValue, width: usize) -> BigInt { - let raw = normalized_bits(value, width); - if width == 0 || !raw.bit((width - 1) as u64) { - BigInt::from(raw) - } else { - BigInt::from(raw) - (BigInt::from(1u8) << width) - } -} - -fn signed_bits(value: BigInt, width: usize) -> BigUint { - if width == 0 { - return BigUint::ZERO; - } - let modulus = BigUint::from(1u8) << width; - match value.sign() { - Sign::Minus => { - let magnitude = (-value).to_biguint().unwrap_or_default() % &modulus; - if magnitude == BigUint::ZERO { - BigUint::ZERO - } else { - modulus - magnitude - } - } - _ => value.to_biguint().unwrap_or_default() % modulus, - } -} - -fn resize_tb_value( - value: &TestbenchValue, - source_width: usize, - target_width: usize, - signed: bool, -) -> TestbenchValue { - if target_width == 0 { - return TestbenchValue::U64(0); - } - if source_width == 0 { - let fill = if value.to_u64() & 1 == 0 { - BigUint::ZERO - } else { - width_mask(target_width) - }; - return tb_value_from_bits(fill, target_width); - } - - if let TestbenchValue::U64(value) = value - && source_width <= 64 - && target_width <= 64 - { - let mut value = value & width_mask_u64(source_width); - if target_width > source_width && signed && value & (1u64 << (source_width - 1)) != 0 { - value |= width_mask_u64(target_width) ^ width_mask_u64(source_width); - } - return TestbenchValue::U64(value & width_mask_u64(target_width)); - } - - let mut value = normalized_bits(value, source_width); - if target_width > source_width && signed && value.bit((source_width - 1) as u64) { - value |= width_mask(target_width) ^ width_mask(source_width); - } - tb_value_from_bits(value, target_width) -} - -fn eval_typed_binop_u64( - l: u64, - op: Op, - r: u64, - lhs_width: usize, - rhs_width: usize, - result_width: usize, - lhs_signed: bool, - rhs_signed: bool, -) -> u64 { - let l = l & width_mask_u64(lhs_width); - let r = r & width_mask_u64(rhs_width); - let result_mask = width_mask_u64(result_width); - let signed = lhs_signed && rhs_signed; - let bool_value = |value: bool| u64::from(value); - - match op { - Op::Eq | Op::EqWildcard => bool_value(l == r), - Op::Ne | Op::NeWildcard => bool_value(l != r), - Op::Less if signed => bool_value(signed_i128(l, lhs_width) < signed_i128(r, rhs_width)), - Op::Less => bool_value(l < r), - Op::LessEq if signed => bool_value(signed_i128(l, lhs_width) <= signed_i128(r, rhs_width)), - Op::LessEq => bool_value(l <= r), - Op::Greater if signed => bool_value(signed_i128(l, lhs_width) > signed_i128(r, rhs_width)), - Op::Greater => bool_value(l > r), - Op::GreaterEq if signed => { - bool_value(signed_i128(l, lhs_width) >= signed_i128(r, rhs_width)) - } - Op::GreaterEq => bool_value(l >= r), - Op::LogicAnd => bool_value(l != 0 && r != 0), - Op::LogicOr => bool_value(l != 0 || r != 0), - Op::Add => l.wrapping_add(r) & result_mask, - Op::Sub => l.wrapping_sub(r) & result_mask, - Op::Mul => l.wrapping_mul(r) & result_mask, - Op::Div if signed => { - let divisor = signed_i128(r, rhs_width); - if divisor == 0 { - 0 - } else { - (signed_i128(l, lhs_width) / divisor) as u64 & result_mask - } - } - Op::Div => l.checked_div(r).unwrap_or(0) & result_mask, - Op::Rem if signed => { - let divisor = signed_i128(r, rhs_width); - if divisor == 0 { - 0 - } else { - (signed_i128(l, lhs_width) % divisor) as u64 & result_mask - } - } - Op::Rem => l.checked_rem(r).unwrap_or(0) & result_mask, - Op::Pow => { - let mut exponent = r; - let mut base = l & result_mask; - let mut value = 1u64 & result_mask; - while exponent != 0 { - if exponent & 1 != 0 { - value = ((value as u128 * base as u128) as u64) & result_mask; - } - exponent >>= 1; - if exponent != 0 { - base = ((base as u128 * base as u128) as u64) & result_mask; - } - } - value - } - Op::BitAnd => (l & r) & result_mask, - Op::BitOr => (l | r) & result_mask, - Op::BitXor => (l ^ r) & result_mask, - Op::BitXnor => (!(l ^ r)) & result_mask, - Op::BitNand => (!(l & r)) & result_mask, - Op::BitNor => (!(l | r)) & result_mask, - Op::LogicShiftL | Op::ArithShiftL => { - if r >= result_width as u64 { - 0 - } else { - l.wrapping_shl(r as u32) & result_mask - } - } - Op::LogicShiftR => { - if r >= result_width as u64 { - 0 - } else { - (l >> r) & result_mask - } - } - Op::ArithShiftR if lhs_signed => { - let value = signed_i128(l, lhs_width); - if r >= result_width as u64 { - if value < 0 { result_mask } else { 0 } - } else { - ((value >> r) as u64) & result_mask - } - } - Op::ArithShiftR => { - if r >= result_width as u64 { - 0 - } else { - (l >> r) & result_mask - } - } - _ => unreachable!("operator is not a source-language binary op: {op:?}"), - } -} - -fn eval_typed_binop( - l: TestbenchValue, - op: Op, - r: TestbenchValue, - lhs_width: usize, - rhs_width: usize, - result_width: usize, - lhs_signed: bool, - rhs_signed: bool, -) -> TestbenchValue { - if let (TestbenchValue::U64(l), TestbenchValue::U64(r)) = (&l, &r) - && lhs_width <= 64 - && rhs_width <= 64 - && result_width <= 64 - { - return TestbenchValue::U64(eval_typed_binop_u64( - *l, - op, - *r, - lhs_width, - rhs_width, - result_width, - lhs_signed, - rhs_signed, - )); - } - let lb = normalized_bits(&l, lhs_width); - let rb = normalized_bits(&r, rhs_width); - let signed = lhs_signed && rhs_signed; - - let comparison = |value: bool| TestbenchValue::U64(u64::from(value)); - match op { - Op::Eq | Op::EqWildcard => comparison(lb == rb), - Op::Ne | Op::NeWildcard => comparison(lb != rb), - Op::Less if signed => { - comparison(signed_bigint(&l, lhs_width) < signed_bigint(&r, rhs_width)) - } - Op::Less => comparison(lb < rb), - Op::LessEq if signed => { - comparison(signed_bigint(&l, lhs_width) <= signed_bigint(&r, rhs_width)) - } - Op::LessEq => comparison(lb <= rb), - Op::Greater if signed => { - comparison(signed_bigint(&l, lhs_width) > signed_bigint(&r, rhs_width)) - } - Op::Greater => comparison(lb > rb), - Op::GreaterEq if signed => { - comparison(signed_bigint(&l, lhs_width) >= signed_bigint(&r, rhs_width)) - } - Op::GreaterEq => comparison(lb >= rb), - Op::LogicAnd => comparison(lb != BigUint::ZERO && rb != BigUint::ZERO), - Op::LogicOr => comparison(lb != BigUint::ZERO || rb != BigUint::ZERO), - Op::Add => tb_value_from_bits(lb + rb, result_width), - Op::Sub => tb_value_from_bits( - signed_bits(BigInt::from(lb) - BigInt::from(rb), result_width), - result_width, - ), - Op::Mul => tb_value_from_bits(lb * rb, result_width), - Op::Div if signed => { - let divisor = signed_bigint(&r, rhs_width); - if divisor == BigInt::from(0u8) { - TestbenchValue::U64(0) - } else { - let quotient = signed_bigint(&l, lhs_width) / divisor; - tb_value_from_bits(signed_bits(quotient, result_width), result_width) - } - } - Op::Div => { - if rb == BigUint::ZERO { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb / rb, result_width) - } - } - Op::Rem if signed => { - let divisor = signed_bigint(&r, rhs_width); - if divisor == BigInt::from(0u8) { - TestbenchValue::U64(0) - } else { - let remainder = signed_bigint(&l, lhs_width) % divisor; - tb_value_from_bits(signed_bits(remainder, result_width), result_width) - } - } - Op::Rem => { - if rb == BigUint::ZERO { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb % rb, result_width) - } - } - Op::Pow => { - if result_width == 0 { - TestbenchValue::U64(0) - } else { - let modulus = BigUint::from(1u8) << result_width; - tb_value_from_bits(lb.modpow(&rb, &modulus), result_width) - } - } - Op::BitAnd => tb_value_from_bits(lb & rb, result_width), - Op::BitOr => tb_value_from_bits(lb | rb, result_width), - Op::BitXor => tb_value_from_bits(lb ^ rb, result_width), - Op::BitXnor => tb_value_from_bits((lb ^ rb) ^ width_mask(result_width), result_width), - Op::LogicShiftL | Op::ArithShiftL => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb << shift, result_width) - } - } - Op::LogicShiftR => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb >> shift, result_width) - } - } - Op::ArithShiftR if lhs_signed => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - let value = signed_bigint(&l, lhs_width); - let shifted = if shift >= result_width { - if value.sign() == Sign::Minus { - BigInt::from(-1) - } else { - BigInt::from(0) - } - } else { - value >> shift - }; - tb_value_from_bits(signed_bits(shifted, result_width), result_width) - } - Op::ArithShiftR => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb >> shift, result_width) - } - } - Op::BitNand => tb_value_from_bits((lb & rb) ^ width_mask(result_width), result_width), - Op::BitNor => tb_value_from_bits((lb | rb) ^ width_mask(result_width), result_width), - _ => unreachable!("operator is not a source-language binary op: {op:?}"), - } -} - -fn eval_typed_unop( - op: Op, - value: &TestbenchValue, - operand_width: usize, - result_width: usize, -) -> TestbenchValue { - if let TestbenchValue::U64(value) = value - && operand_width <= 64 - && result_width <= 64 - { - let bits = value & width_mask_u64(operand_width); - let value = match op { - Op::LogicNot => u64::from(bits == 0), - Op::BitAnd => u64::from(bits == width_mask_u64(operand_width)), - Op::BitNand => u64::from(bits != width_mask_u64(operand_width)), - Op::BitOr => u64::from(bits != 0), - Op::BitNor => u64::from(bits == 0), - Op::BitXor => u64::from(!bits.count_ones().is_multiple_of(2)), - Op::BitXnor => u64::from(bits.count_ones().is_multiple_of(2)), - Op::Add => bits & width_mask_u64(result_width), - Op::Sub => bits.wrapping_neg() & width_mask_u64(result_width), - Op::BitNot => !bits & width_mask_u64(result_width), - _ => unreachable!("operator is not a source-language unary op: {op:?}"), - }; - return TestbenchValue::U64(value); - } - - let bits = normalized_bits(value, operand_width); - let reduced = match op { - Op::LogicNot => Some(bits == BigUint::ZERO), - Op::BitAnd => Some(bits == width_mask(operand_width)), - Op::BitNand => Some(bits != width_mask(operand_width)), - Op::BitOr => Some(bits != BigUint::ZERO), - Op::BitNor => Some(bits == BigUint::ZERO), - Op::BitXor | Op::BitXnor => { - let odd = bits.iter_u64_digits().map(u64::count_ones).sum::() % 2 != 0; - Some(if matches!(op, Op::BitXor) { odd } else { !odd }) - } - _ => None, - }; - if let Some(value) = reduced { - return TestbenchValue::U64(u64::from(value)); - } - - match op { - Op::Add => tb_value_from_bits(bits, result_width), - Op::Sub => tb_value_from_bits(signed_bits(-BigInt::from(bits), result_width), result_width), - Op::BitNot => tb_value_from_bits(bits ^ width_mask(operand_width), result_width), - _ => unreachable!("operator is not a source-language unary op: {op:?}"), - } -} - -#[inline] -fn eval_binop_u64(l: u64, op: Op, r: u64) -> u64 { - match op { - Op::Add => l.wrapping_add(r), - Op::Sub => l.wrapping_sub(r), - Op::Mul => l.wrapping_mul(r), - Op::Div => l.checked_div(r).unwrap_or(0), - Op::Rem => l.checked_rem(r).unwrap_or(0), - Op::BitAnd => l & r, - Op::BitOr => l | r, - Op::BitXor => l ^ r, - Op::LogicShiftL => { - if r >= 64 { - 0 - } else { - l << r - } - } - Op::LogicShiftR => { - if r >= 64 { - 0 - } else { - l >> r - } - } - Op::ArithShiftL => { - if r >= 64 { - 0 - } else { - l << r - } - } - Op::ArithShiftR => { - if r >= 64 { - ((l as i64) >> 63) as u64 - } else { - ((l as i64) >> r) as u64 - } - } - Op::Eq => (l == r) as u64, - Op::Ne => (l != r) as u64, - Op::Less => (l < r) as u64, - Op::LessEq => (l <= r) as u64, - Op::Greater => (l > r) as u64, - Op::GreaterEq => (l >= r) as u64, - Op::LogicAnd => ((l != 0) && (r != 0)) as u64, - Op::LogicOr => ((l != 0) || (r != 0)) as u64, - _ => unreachable!("operator is not testbench bytecode plumbing: {op:?}"), - } -} - -fn eval_binop_wide(l: BigUint, op: Op, r: BigUint) -> BigUint { - match op { - Op::Add => l + r, - Op::Sub => { - if l >= r { - l - r - } else { - BigUint::ZERO - } - } - Op::Mul => l * r, - Op::Div => { - if r == BigUint::ZERO { - BigUint::ZERO - } else { - l / r - } - } - Op::Rem => { - if r == BigUint::ZERO { - BigUint::ZERO - } else { - l % r - } - } - Op::BitAnd => l & r, - Op::BitOr => l | r, - Op::BitXor => l ^ r, - Op::LogicShiftL => { - let s: u64 = (&r).try_into().unwrap_or(256); - l << s - } - Op::LogicShiftR => { - let s: u64 = (&r).try_into().unwrap_or(256); - l >> s - } - _ => unreachable!("operator is not wide testbench bytecode plumbing: {op:?}"), - } -} - -fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { - match op { - Op::Eq => (l == r) as u64, - Op::Ne => (l != r) as u64, - Op::Less => (l < r) as u64, - Op::LessEq => (l <= r) as u64, - Op::Greater => (l > r) as u64, - Op::GreaterEq => (l >= r) as u64, - Op::LogicAnd => ((*l != BigUint::ZERO) && (*r != BigUint::ZERO)) as u64, - Op::LogicOr => ((*l != BigUint::ZERO) || (*r != BigUint::ZERO)) as u64, - _ => unreachable!("operator is not testbench comparison plumbing: {op:?}"), - } -} - -/// Read the handle stored at `offset`. -/// -/// # Safety -/// -/// `memory + offset` must be valid for reading a handle. -unsafe fn read_handle(memory: *const u8, offset: usize) -> celox_heap::Handle { - let mut bytes = [0; celox_heap::HANDLE_BYTES]; - // SAFETY: guaranteed by the caller. - unsafe { - std::ptr::copy_nonoverlapping(memory.add(offset), bytes.as_mut_ptr(), bytes.len()); - } - celox_heap::Handle::from_le_bytes(bytes) -} - -#[cfg(test)] -mod float_tests { - use super::*; - use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; - - #[test] - fn expression_stack_spills_and_returns_to_inline_operands() { - for depth in [1, 8, 9, 32, 128] { - let mut ops: Vec<_> = (1..=depth).map(TbOpcode::ConstU64).collect(); - ops.extend((1..depth).map(|_| TbOpcode::BinOp(Op::Add))); - let expression = CompiledExpr::new(ExprBytecode::new(ops)); - assert_eq!( - expression.eval_u64(std::ptr::null_mut()), - depth * (depth + 1) / 2 - ); - } - let mut stack = ValueStack::new(); - for i in 0..20 { - stack.push(TestbenchValue::String(vec![i])); - } - for i in (0..20).rev() { - let Some(TestbenchValue::String(bytes)) = stack.last_mut() else { - panic!() - }; - bytes.push(i); - let Some(TestbenchValue::String(bytes)) = stack.pop() else { - panic!() - }; - assert_eq!(bytes, [i, i]); - } - assert!(stack.pop().is_none()); - assert!(stack.last_mut().is_none()); - assert!(stack.inline.iter().all(Option::is_none)); - } - - #[test] - fn floating_bytecode_keeps_precision_and_numeric_conversions() { - for (precision, expected) in [ - (FloatPrecision::F32, 16777216), - (FloatPrecision::F64, 16777217), - ] { - let expression = CompiledExpr::new(ExprBytecode::new(vec![ - TbOpcode::ConstU64(16777216), - TbOpcode::FloatUnary { - op: FloatUnaryOp::FromUnsigned { width: 32 }, - precision, - }, - TbOpcode::ConstU64(1), - TbOpcode::FloatUnary { - op: FloatUnaryOp::FromUnsigned { width: 32 }, - precision, - }, - TbOpcode::FloatBinary { - op: FloatBinaryOp::Add, - precision, - }, - TbOpcode::FloatUnary { - op: FloatUnaryOp::ToUnsigned { - width: 32, - round: true, - }, - precision, - }, - ])); - assert_eq!(expression.eval_u64(std::ptr::null_mut()), expected); - } - } -} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index dda7a05dfeb..913f937e2cc 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -358,7 +358,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()) @@ -866,7 +866,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() @@ -878,10 +896,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()); } @@ -1878,6 +1942,7 @@ fn format_native_codegen_trace( comb: &CompiledNativeFunction, ff_codes: &HashMap, tasks: &[NativeCompileTask<'_>], + processes: &[CompiledNativeFunction], ) -> NativeCodegenTrace { let mut optimized_sir = String::from("=== Optimized SIR used by native emission ===\n"); let mut mir = String::from("=== MIR used by native emission ===\n"); @@ -1924,6 +1989,20 @@ fn format_native_codegen_trace( .expect("explicit native trace must capture every FF function"), ); } + for (index, process) in processes.iter().enumerate() { + append_native_function_trace( + &mut optimized_sir, + &mut mir, + &mut reactive_graph, + &mut state_layout, + &format!("process[{index}]"), + &[], + process + .trace + .as_ref() + .expect("explicit native trace must capture every process"), + ); + } NativeCodegenTrace { optimized_sir, mir, @@ -2791,7 +2870,7 @@ fn compile_program_with_outlining_threshold( NativeMergeKind::Complete, None, &process_options, - false, + capture_trace, &options.optimize_options.diagnostics, cancel, ) @@ -2806,8 +2885,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, @@ -2822,8 +2901,9 @@ fn compile_program_with_outlining_threshold( } } } - let codegen_trace = capture_trace - .then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks)); + let codegen_trace = capture_trace.then(|| { + format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks, &process_jits) + }); let semantic_memory_size = layout .merged_total_size .checked_add(layout.triggered_bits_total_size) @@ -4357,11 +4437,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 d3e948fe8a4..d9fb258b368 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 = 52; +// Images retain generated TB scheduler continuations and clock state. +const CONTAINER_VERSION: u16 = 55; const TRAILER_SIZE: usize = 32; // This optional prefix descriptor does not change the Postcard payload. Older // readers ignore framing flags and continue to locate the payload at EOF. diff --git a/crates/celox/src/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index f8ba60caa24..0708a259b7e 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 code_bytes; mod compile_resources; #[cfg(target_os = "linux")] 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/component.rs b/crates/celox/src/component.rs index 71356d5fc44..7e363ec1405 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -43,6 +43,10 @@ struct LiveInput { port: u32, expr: CompiledExpr, mask_source: Option>, + // Direct input bindings permit a chain of bitwise complements. Preserve + // the source payload under X/Z at the component ABI, even though HDL + // evaluation may canonicalize those unobservable payload bits. + invert_unknown_payload: bool, width: usize, } @@ -302,20 +306,22 @@ fn take_output_writes(component: &mut LiveComponent) -> Vec { fn stage_component_inputs(component: &mut LiveComponent, backend: &mut B) { for input in &component.inputs { - let value = eval_backend_expr(backend, &input.expr).to_biguint(); - let mask_xz = input - .mask_source - .as_ref() - .map(|source| { - let (_, mut mask) = backend.get_four_state(source.signal); - if let Some(selection) = &source.selection { - let offset = eval_backend_expr(backend, &selection.offset).to_u64() as usize; - mask >>= offset; - mask &= width_mask(selection.width); - } - mask - }) - .unwrap_or_default(); + let mut value = eval_backend_expr(backend, &input.expr).to_biguint(); + let mask_xz = if let Some(source) = &input.mask_source { + let (mut raw, mut mask) = backend.get_four_state(source.signal); + if let Some(selection) = &source.selection { + let offset = eval_backend_expr(backend, &selection.offset).to_u64() as usize; + raw = (raw >> offset) & width_mask(selection.width); + mask = (mask >> offset) & width_mask(selection.width); + } + if input.invert_unknown_payload { + raw ^= &mask; + } + value = (value & (width_mask(input.width) ^ &mask)) | (raw & &mask); + mask + } else { + num_bigint::BigUint::ZERO + }; let mut words: Vec<_> = value.iter_u64_digits().collect(); let mut mask_words: Vec<_> = mask_xz.iter_u64_digits().collect(); words.resize(input.width.div_ceil(64).max(1), 0); @@ -463,6 +469,33 @@ impl ComponentRuntime { port, expr: expr.clone(), mask_source: binding.input_target.clone(), + invert_unknown_payload: expr + .bytecode() + .ops() + .iter() + .rev() + .take_while(|op| { + matches!( + op, + celox_testbench::ExprOpcode::Resize { .. } + | celox_testbench::ExprOpcode::TypedUnary { + op: celox_testbench::TestbenchOperator::BitNot, + .. + } + ) + }) + .filter(|op| { + matches!( + op, + celox_testbench::ExprOpcode::TypedUnary { + op: celox_testbench::TestbenchOperator::BitNot, + .. + } + ) + }) + .count() + % 2 + != 0, width: connection.width as usize, }); if connection.is_clock || connection.is_reset { diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index c8e46388fbe..3f5a11a7e97 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -1,6 +1,4 @@ -use crate::HashMap; -#[cfg(feature = "host-runtime")] -use crate::HashSet; +use crate::{HashMap, HashSet}; pub use celox_design::PortTypeKind; pub(crate) use celox_design::{ AbsoluteAddrBase, BitAccess, InstanceId, ModuleId, RegionedAbsoluteAddrBase, @@ -109,6 +107,80 @@ impl std::ops::Deref for RuntimeDesign { } impl RuntimeDesign { + /// Add compiler-owned storage after source hierarchy projection. The slot + /// remains an ordinary state object for layout, roots, images and snapshots. + pub(crate) fn allocate_testbench_slot( + &mut self, + width: usize, + is_string: bool, + ) -> AbsoluteAddr { + let instance_id = *self + .instances + .keys() + .min() + .expect("testbench root instance"); + let object = self + .semantic + .state_objects + .keys() + .map(|a| a.var_id.0) + .max() + .unwrap_or(0) + + 1; + let source = self + .variables + .values() + .map(|v| v.source_id.0) + .max() + .unwrap_or(0) + + 1; + let address = AbsoluteAddr { + instance_id, + var_id: celox_design::StateObjectId(object), + }; + let source_id = SourceVarId(source); + let path = vec![format!("__celox_tb_{object}")]; + self.semantic.state_objects.insert( + address, + celox_design::VariableMetadata { + width: width.max(1), + is_4state: false, + kind: celox_design::DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: vec![], + value_kind: if is_string { + celox_design::ValueKind::StrRef + } else { + Default::default() + }, + }, + ); + self.variables.insert( + address, + RuntimeVariable { + address, + source_id, + path: path.clone(), + var_kind: VariableKind::Variable, + signed: false, + packed_dims: vec![width.max(1)], + unpacked_ranges: vec![], + }, + ); + let instance = self.instances.get_mut(&instance_id).unwrap(); + instance.state_addresses.push(address); + instance.source_variables.insert(source_id, address); + // Compiler storage is deliberately absent from source lookup and VCD. + 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, @@ -460,7 +532,6 @@ pub struct RuntimeProgram { pub testbench: Option>, /// Objects accessed by RTL before optimization. Retained so host-side /// testbench writes can distinguish private variables from hardware. - #[cfg(feature = "host-runtime")] pub(crate) rtl_accesses: HashSet, } @@ -845,7 +916,15 @@ fn rebuild_rtl_writes(program: &mut OptimizedSir) { .iter() .flat_map(|parallel| parallel.units().map(|unit| &unit.unit)), ) - .chain(&program.sir.processes) + .chain( + program + .sir + .processes + .iter() + .zip(&program.runtime.runtime_schema.processes) + .filter(|(_, slots)| slots.kind != celox_design::ProcessKind::Callable) + .map(|(unit, _)| unit), + ) { for block in unit.blocks.values() { for instruction in &block.instructions { @@ -1169,7 +1248,6 @@ impl RuntimeProgram { scheduled: celox_frontend_core::ScheduledRtl, ) -> Result<(SirProgram, Self), DesignProjectionError> { let design = RuntimeDesign::from_projection(scheduled.design, scheduled.frontend_lookup)?; - #[cfg(feature = "host-runtime")] let rtl_accesses = { let mut rtl_accesses = HashSet::default(); for unit in scheduled @@ -1212,7 +1290,6 @@ impl RuntimeProgram { design, runtime_schema: scheduled.runtime_schema, testbench: None, - #[cfg(feature = "host-runtime")] rtl_accesses, }, )) 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 646d3e33a05..120cc5cc4fe 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -369,7 +369,7 @@ pub(crate) fn project_scheduled_rtl( diagnostics, )?; scheduled.scheduled.inject_triggers(); - let testbench = if let Some(testbench_source) = testbench_source { + let mut testbench = if let Some(testbench_source) = testbench_source { testbench_source.component_libraries = component_libraries; testbench_source.component_file_base = component_file_base; crate::testbench_compile::project_observability( @@ -386,10 +386,36 @@ pub(crate) fn project_scheduled_rtl( } else { None }; - let (sir, mut runtime) = + let (mut sir, mut runtime) = RuntimeProgram::from_scheduled(scheduled.scheduled).map_err(|error| { ParserError::illegal_context("runtime design projection", error.to_string(), None) })?; + if let Some(testbench) = &mut testbench { + crate::testbench_compile::lower_expressions(&mut sir, &mut runtime, testbench) + .and_then(|()| { + testbench.fold_clock_waits(); + crate::testbench_compile::lower_processes(&mut sir, &mut runtime, testbench) + }) + .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..e5af7b66f94 --- /dev/null +++ b/crates/celox/src/scheduler/testbench.rs @@ -0,0 +1,679 @@ +//! 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); + // A lone process on one clock ends the run when it completes, as the + // synchronous runner does, without dispatching another edge. + if m.processes.len() == 1 && m.clocks.len() <= 1 { + jump(&mut g, end); + } else { + 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.rs b/crates/celox/src/simulator.rs index f386554d3b5..b377030be13 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -147,7 +147,9 @@ mod host { pub(crate) declaration_phase: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, - pub(crate) component_simulation: Option>, + // Temporarily detached while advancing the simulator. Keep the queue + // in place instead of copying its entire state at every clock edge. + pub(crate) component_simulation: Option>>, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, pub(super) comb_observer_snapshots: Vec, @@ -1581,6 +1583,17 @@ mod host { ) -> Vec { let queue = Arc::clone(&self.pending_host_events); let mut pending = queue.lock().unwrap(); + // Most clock boundaries produce no reports. Preserve queued host + // records, losses and deferred string snapshots, but avoid the + // collector and formatter when neither queue has any new work. + if pending.events.is_empty() + && pending.missed == 0 + && pending.deferred.waiting.is_empty() + && self.runtime_event_read_seq.load(Ordering::Acquire) + == self.runtime_event_write_seq() + { + return Vec::new(); + } pending.extend( self.collect_backend_runtime_events(), self.backend.layout().runtime_event_capacity, 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 bc349a8953d..3f43784c2a7 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1,9 +1,9 @@ //! Native testbench execution for Veryl `#[test]` modules. //! -//! Testbench expressions are compiled to a flat bytecode (`TbOpcode`) and -//! evaluated by a stack-based VM that reads directly from the simulator's -//! memory buffer. Signals ≤64 bits use native `u64` arithmetic with zero -//! heap allocation; wider signals fall back to `BigUint`. +//! Processes and expressions execute generated host machine code. Persistent +//! continuations retain ordinary state slots across clock waits. Expressions +//! and loop arithmetic use the shared SIR backend; host requests provide timing, +//! diagnostics and external component services. use crate::HashMap; use crate::RuntimeErrorCode; @@ -20,19 +20,18 @@ pub use celox_testbench::SourceLocation; use celox_testbench::{ DisplayFormatArg, ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound, ExecutableStatement, ExecutableTestbench, FieldSpec, - TestbenchOperator as Op, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, - TestbenchValue as TbValue, format_veryl_display_arg, pad_veryl_field, + TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, TestbenchValue as TbValue, + format_veryl_display_arg, pad_veryl_field, }; -use num_bigint::{BigInt, BigUint, Sign}; -use num_traits::ToPrimitive as _; +use num_bigint::BigUint; use rand::{RngExt as _, SeedableRng as _}; use rand_pcg::Pcg64; use std::sync::atomic::{AtomicU64, Ordering}; -use std::{ - cell::RefCell, - future::Future, - task::{Context, Poll, Waker}, -}; +use std::task::Poll; + +mod clock_batch; +mod compiled; +mod native; // ── Public types ─────────────────────────────────────────────────────── @@ -85,8 +84,6 @@ enum TestbenchEvaluationError { #[source] source: RuntimeErrorCode, }, - #[error("dynamic signed for-loop bound exceeds host i128")] - SignedLoopBoundOutOfRange, } pub(crate) type TestbenchStatement = ExecutableStatement<::Event, SignalRef>; @@ -115,16 +112,32 @@ fn eval_backend_expr_tracked( backend: &mut B, expr: &celox_testbench::CompiledExpr, ) -> (TbValue, Vec<(usize, usize)>) { - // This pointer is used only during evaluation, never exposed to a host. - // Observe VM stores explicitly instead of disabling tracking for reads; - // they are marked once the heap is no longer borrowed. + let kernel = expr + .kernel() + .expect("expression was compiled before state layout"); + backend + .run_process(kernel.entry) + .unwrap_or_else(|error| panic!("testbench expression kernel: {error}")); let (memory, _) = backend.memory_as_ptr(); - let mut writes = Vec::new(); - let value = expr.eval_with_heap( - memory.cast_mut(), - Some(backend.heap_mut()), - |offset, len| writes.push((offset, len)), - ); + // The kernel result is an ordinary, layout-owned state slot. + let bytes = + unsafe { std::slice::from_raw_parts(memory.add(kernel.result), kernel.width.div_ceil(8)) }; + let value = if kernel.is_string { + let handle = + celox_heap::Handle::from_le_bytes(bytes.try_into().expect("string handle width")); + TbValue::String(backend.heap().string(handle as celox_heap::Handle).to_vec()) + } else if kernel.width <= 64 { + let mut value = [0u8; 8]; + value[..bytes.len()].copy_from_slice(bytes); + TbValue::U64(u64::from_le_bytes(value)) + } else { + TbValue::Wide(BigUint::from_bytes_le(bytes)) + }; + let writes = kernel + .writes + .iter() + .map(|(offset, size)| (*offset, *size)) + .collect::>(); if let Some(trace) = backend.layout().trace.as_ref() { for &(offset, len) in &writes { // SAFETY: bound bytecode writes valid locations in this image, and @@ -525,21 +538,14 @@ fn sign_extend_random(raw: u64, width: u32) -> i64 { enum ExecResult { Continue, - Break, Finished, Fail(String), } -impl ExecResult { - fn should_stop(&self) -> bool { - !matches!(self, ExecResult::Continue) - } -} - impl From for TestResult { fn from(r: ExecResult) -> Self { match r { - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => TestResult::Pass, + ExecResult::Continue | ExecResult::Finished => TestResult::Pass, ExecResult::Fail(m) => TestResult::Fail(m), } } @@ -560,177 +566,6 @@ fn eval_clock_count( }) } -fn eval_loop_bound( - sim: &mut Simulator, - bound: &LoopBound, -) -> Result { - match bound { - // Unsigned Veryl constants are represented as typed Dynamic bytecode; - // Static retains signed induction-variable semantics. - LoopBound::Static(v) => Ok(EvaluatedLoopBound::Signed(*v as i128)), - LoopBound::Dynamic { - expr, - width, - signed, - } => { - settle_testbench_expr(sim, expr) - .map_err(|source| TestbenchEvaluationError::EvalComb { source })?; - let value = eval_expr(sim, expr); - if *signed { - decode_signed_loop_bound(value, *width) - } else { - match value { - TbValue::String(_) => unreachable!("string loop bound"), - TbValue::U64(v) => match usize::try_from(v) { - Ok(v) => Ok(EvaluatedLoopBound::Unsigned(v)), - Err(_) => Ok(EvaluatedLoopBound::UnsignedWide(BigUint::from(v))), - }, - TbValue::Wide(v) => match v.to_usize() { - Some(v) => Ok(EvaluatedLoopBound::Unsigned(v)), - None => Ok(EvaluatedLoopBound::UnsignedWide(v)), - }, - } - } - } - } -} - -enum EvaluatedLoopBound { - Unsigned(usize), - UnsignedWide(BigUint), - Signed(i128), - SignedWide(BigInt), -} - -fn decode_signed_loop_bound( - value: TbValue, - width: usize, -) -> Result { - let width = width.max(1); - match value { - TbValue::String(_) => unreachable!("string loop bound"), - TbValue::U64(v) => { - let raw = if width >= 64 { - v as u128 - } else { - (v as u128) & ((1u128 << width) - 1) - }; - Ok(EvaluatedLoopBound::Signed(sign_extend_u128(raw, width))) - } - TbValue::Wide(v) => { - if width > 128 { - let signed = sign_extend_biguint(v, width); - return Ok(match signed.to_i128() { - Some(v) => EvaluatedLoopBound::Signed(v), - None => EvaluatedLoopBound::SignedWide(signed), - }); - } - let raw = v - .to_u128() - .ok_or(TestbenchEvaluationError::SignedLoopBoundOutOfRange)?; - Ok(EvaluatedLoopBound::Signed(sign_extend_u128(raw, width))) - } - } -} - -fn sign_extend_u128(raw: u128, width: usize) -> i128 { - let width = width.max(1); - if width >= 128 { - raw as i128 - } else { - let sign_bit = 1u128 << (width - 1); - if raw & sign_bit == 0 { - raw as i128 - } else { - raw as i128 - ((1u128 << width) as i128) - } - } -} - -fn truncate_i128_to_width(value: i128, width: usize, signed: bool) -> i128 { - let width = width.max(1); - if width >= 128 { - return value; - } - let raw = (value as u128) & ((1u128 << width) - 1); - if signed { - sign_extend_u128(raw, width) - } else { - raw as i128 - } -} - -fn truncate_bigint_to_width(value: BigInt, width: usize, signed: bool) -> BigInt { - let width = width.max(1); - let modulus = BigInt::from(1u8) << width; - let mut wrapped = value % &modulus; - if wrapped.sign() == Sign::Minus { - wrapped += &modulus; - } - if signed && wrapped >= (BigInt::from(1u8) << (width - 1)) { - wrapped - modulus - } else { - wrapped - } -} - -fn advance_bigint_counter( - current: &BigInt, - step: usize, - step_op: Option, - reverse: bool, - width: usize, - signed: bool, -) -> BigInt { - let step_value = BigInt::from(step); - let raw = if reverse { - current - &step_value - } else { - match step_op { - Some(Op::Mul) => current * &step_value, - Some(Op::BitOr) => current | &step_value, - Some(Op::BitXor) => current ^ &step_value, - Some(Op::LogicShiftL | Op::ArithShiftL) => { - if step >= width.max(1) { - BigInt::from(0u8) - } else { - current << step - } - } - _ => current + &step_value, - } - }; - truncate_bigint_to_width(raw, width, signed) -} - -fn truncate_usize_to_width(value: usize, width: usize) -> usize { - if width >= usize::BITS as usize { - value - } else if width == 0 { - 0 - } else { - value & ((1usize << width) - 1) - } -} - -fn sign_extend_biguint(raw: BigUint, width: usize) -> BigInt { - let width = width.max(1); - let sign_bit = BigUint::from(1u8) << (width - 1); - if raw < sign_bit { - BigInt::from(raw) - } else { - BigInt::from(raw) - (BigInt::from(1u8) << width) - } -} - -fn mask_to_width(value: BigUint, width: usize) -> BigUint { - if width == 0 { - BigUint::from(0u8) - } else { - value & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) - } -} - fn width_mask(width: usize) -> BigUint { if width == 0 { BigUint::from(0u8) @@ -739,35 +574,6 @@ fn width_mask(width: usize) -> BigUint { } } -fn sim_set_i128( - sim: &mut crate::Simulator, - sig: SignalRef, - width: usize, - value: i128, -) { - if width <= 64 { - sim_set_u64(sim, sig, value as u64); - } else if value >= 0 { - write_testbench_signal(sim, sig, |sim| { - sim.set_wide(sig, BigUint::from(value as u128)) - }); - } else { - let modulus = BigUint::from(1u8) << width; - let mag = BigUint::from(value.unsigned_abs()); - write_testbench_signal(sim, sig, |sim| sim.set_wide(sig, modulus - mag)); - } -} - -fn sim_set_biguint(sim: &mut crate::Simulator, sig: SignalRef, value: BigUint) { - if sig.width <= 64 { - sim_set_u64(sim, sig, value.to_u64().unwrap_or(0)); - } else { - write_testbench_signal(sim, sig, |sim| { - sim.set_wide(sig, mask_to_width(value, sig.width)) - }); - } -} - fn random_value_for_destination( value: u64, source_width: u32, @@ -801,428 +607,6 @@ fn sim_set_random_target( sim_set_target(sim, target, TbValue::Wide(value)); } -fn sim_set_bigint( - sim: &mut crate::Simulator, - sig: SignalRef, - width: usize, - value: BigInt, -) { - if width <= 128 { - sim_set_i128(sim, sig, width, value.try_into().unwrap_or(0)); - return; - } - if value.sign() != Sign::Minus { - sim_set_biguint( - sim, - sig, - value.try_into().unwrap_or_else(|_| BigUint::from(0u8)), - ); - } else { - let modulus = BigUint::from(1u8) << width; - sim_set_biguint(sim, sig, modulus - value.magnitude().clone()); - } -} - -fn as_bigint_bound(bound: &EvaluatedLoopBound) -> Option { - match bound { - EvaluatedLoopBound::Unsigned(v) => Some(BigInt::from(*v)), - EvaluatedLoopBound::UnsignedWide(v) => Some(BigInt::from(v.clone())), - EvaluatedLoopBound::Signed(v) => Some(BigInt::from(*v)), - EvaluatedLoopBound::SignedWide(v) => Some(v.clone()), - } -} - -fn exec_for_loop( - sim: &mut Simulator, - loop_var: &Option<(SignalRef, usize, bool)>, - start: &LoopBound, - end: &LoopBound, - inclusive: bool, - step: usize, - step_op: Option, - reverse: bool, - mut exec_body: impl FnMut(&mut Simulator) -> ExecResult, -) -> ExecResult { - let sim = RefCell::new(sim); - let mut future = std::pin::pin!(exec_for_loop_async( - &sim, - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - || std::future::ready(exec_body(&mut sim.borrow_mut())), - )); - match future - .as_mut() - .poll(&mut Context::from_waker(Waker::noop())) - { - Poll::Ready(result) => result, - Poll::Pending => unreachable!("synchronous loop body cannot suspend"), - } -} - -async fn exec_for_loop_async>( - sim: &RefCell<&mut Simulator>, - loop_var: &Option<(SignalRef, usize, bool)>, - start: &LoopBound, - end: &LoopBound, - inclusive: bool, - step: usize, - step_op: Option, - reverse: bool, - mut exec_body: impl FnMut() -> F, -) -> ExecResult { - let continuation_bound = if reverse { start } else { end }; - let (bound_width, bound_signed) = match continuation_bound { - LoopBound::Static(value) => ( - (usize::BITS as usize - value.leading_zeros() as usize).max(32), - true, - ), - LoopBound::Dynamic { width, signed, .. } => (*width, *signed), - }; - let (counter_width, counter_signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, true), |(_, width, signed)| { - (*width, *signed) - }); - let comparison_signed = counter_signed && bound_signed; - let unsigned_value = |value: i128, width: usize| { - let mask = if width >= u128::BITS as usize { - u128::MAX - } else { - (1u128 << width.max(1)) - 1 - }; - (value as u128) & mask - }; - let in_range = |value: i128, limit: i128| { - if comparison_signed { - if reverse { - value >= limit - } else if inclusive { - value <= limit - } else { - value < limit - } - } else { - let value = unsigned_value(value, counter_width); - let limit = unsigned_value(limit, bound_width); - if reverse { - value >= limit - } else if inclusive { - value <= limit - } else { - value < limit - } - } - }; - - let mut start = match eval_loop_bound(&mut sim.borrow_mut(), start) { - Ok(v) => v, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - let mut end = match eval_loop_bound(&mut sim.borrow_mut(), end) { - Ok(v) => v, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - - let initially_wide = matches!(start, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(end, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(start, EvaluatedLoopBound::SignedWide(_)) - || matches!(end, EvaluatedLoopBound::SignedWide(_)); - if let Some((_, width, true)) = loop_var.as_ref() - && !initially_wide - { - let width = (*width).max(1); - let unsigned_max = if width <= usize::BITS as usize { - Some((1usize << (width - 1)) - 1) - } else { - None - }; - let unsigned_value = |bound: &EvaluatedLoopBound| match bound { - EvaluatedLoopBound::Unsigned(value) => Some(*value), - _ => None, - }; - let start_out_of_range = unsigned_max - .zip(unsigned_value(&start)) - .is_some_and(|(max, value)| value > max); - let end_out_of_range = - unsigned_max - .zip(unsigned_value(&end)) - .is_some_and(|(max, value)| { - value > max && !(!inclusive && value == max.saturating_add(1)) - }); - if start_out_of_range || end_out_of_range { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - start = match start { - EvaluatedLoopBound::Unsigned(value) => EvaluatedLoopBound::Signed(value as i128), - other => other, - }; - end = match end { - EvaluatedLoopBound::Unsigned(value) => EvaluatedLoopBound::Signed(value as i128), - other => other, - }; - } - - let has_unsigned_wide = matches!(start, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(end, EvaluatedLoopBound::UnsignedWide(_)); - let has_signed_wide = matches!(start, EvaluatedLoopBound::SignedWide(_)) - || matches!(end, EvaluatedLoopBound::SignedWide(_)); - if has_unsigned_wide || has_signed_wide { - let start = as_bigint_bound(&start).expect("big loop bound"); - let end = as_bigint_bound(&end).expect("big loop bound"); - let mut step_body = |i: BigInt| { - if let Some((sig, width, _)) = loop_var { - sim_set_bigint(&mut sim.borrow_mut(), *sig, *width, i); - } - exec_body() - }; - if reverse { - if inclusive { - if end < start { - return ExecResult::Continue; - } - if end == start { - let (width, signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, false), |(_, width, signed)| { - (*width, *signed) - }); - let current = truncate_bigint_to_width(end, width, signed); - let result = step_body(current.clone()).await; - if matches!(result, ExecResult::Break) { - return ExecResult::Continue; - } - if result.should_stop() { - return result; - } - let next = - advance_bigint_counter(¤t, step, step_op, reverse, width, signed); - return if next >= current { - ExecResult::Fail("non-progressing stepped for loop".to_string()) - } else { - ExecResult::Continue - }; - } - } else if end <= start { - return ExecResult::Continue; - } - } else if inclusive { - if start > end { - return ExecResult::Continue; - } - if start == end { - let (width, signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, false), |(_, width, signed)| { - (*width, *signed) - }); - let current = truncate_bigint_to_width(start, width, signed); - let result = step_body(current.clone()).await; - if matches!(result, ExecResult::Break) { - return ExecResult::Continue; - } - if result.should_stop() { - return result; - } - let next = advance_bigint_counter(¤t, step, step_op, reverse, width, signed); - return if next <= current { - ExecResult::Fail("non-progressing stepped for loop".to_string()) - } else { - ExecResult::Continue - }; - } - } else if start >= end { - return ExecResult::Continue; - } - return ExecResult::Fail(if loop_var.as_ref().is_some_and(|(_, _, signed)| *signed) { - "dynamic signed for-loop bound exceeds host i128".to_string() - } else { - "dynamic for-loop bound exceeds host usize".to_string() - }); - } - - let (start_signed, end_signed) = match (start, end) { - (EvaluatedLoopBound::Unsigned(start), EvaluatedLoopBound::Unsigned(end)) => { - (None, Some((start, end))) - } - (EvaluatedLoopBound::Signed(start), EvaluatedLoopBound::Signed(end)) => { - (Some((start, end)), None) - } - (EvaluatedLoopBound::Signed(start), EvaluatedLoopBound::Unsigned(end)) => { - (Some((start, end as i128)), None) - } - (EvaluatedLoopBound::Unsigned(start), EvaluatedLoopBound::Signed(end)) => { - (Some((start as i128, end)), None) - } - _ => unreachable!("wide loop bounds handled above"), - }; - - if let Some((start, end)) = start_signed { - let truncate_counter = |value| { - loop_var.as_ref().map_or(value, |(_, width, signed)| { - truncate_i128_to_width(value, *width, *signed) - }) - }; - let mut step_body = |i: i128| { - if let Some((sig, width, _)) = loop_var { - sim_set_i128(&mut sim.borrow_mut(), *sig, *width, i); - } - exec_body() - }; - - let step_i = step as i128; - if reverse { - let mut i = truncate_counter(if inclusive { end } else { end.wrapping_sub(1) }); - while in_range(i, start) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = truncate_counter(i.wrapping_sub(step_i)); - if next >= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } else if let Some(op) = step_op { - let mut i = truncate_counter(start); - while in_range(i, end) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let new_i = match op { - Op::Mul => i.wrapping_mul(step_i), - Op::BitOr => i | step_i, - Op::BitXor => i ^ step_i, - Op::LogicShiftL | Op::ArithShiftL => { - if step >= i128::BITS as usize { - 0 - } else { - i.checked_shl(step as u32).unwrap_or(0) - } - } - _ => i.wrapping_add(step_i), - }; - let new_i = truncate_counter(new_i); - if new_i <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = new_i; - } - } else { - let mut i = truncate_counter(start); - while in_range(i, end) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = i.wrapping_add(step_i); - let next = truncate_counter(next); - if next <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } - - return ExecResult::Continue; - } - - let (start, end) = end_signed.expect("unsigned loop bounds expected"); - let truncate_counter = |value| { - loop_var.as_ref().map_or(value, |(_, width, _)| { - truncate_usize_to_width(value, *width) - }) - }; - - let mut step_body = |i: usize| { - if let Some((sig, _, _)) = loop_var { - sim_set_u64(&mut sim.borrow_mut(), *sig, i as u64); - } - exec_body() - }; - - if reverse { - let mut i = truncate_counter(if inclusive { end } else { end.wrapping_sub(1) }); - while i >= start { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = truncate_counter(i.wrapping_sub(step)); - if next >= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } else if let Some(op) = step_op { - let mut i = truncate_counter(start); - while if inclusive { i <= end } else { i < end } { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let new_i = match op { - Op::Mul => i.wrapping_mul(step), - Op::BitOr => i | step, - Op::BitXor => i ^ step, - Op::LogicShiftL | Op::ArithShiftL => { - if step >= usize::BITS as usize { - 0 - } else { - i << step - } - } - _ => i.wrapping_add(step), - }; - let new_i = truncate_counter(new_i); - if new_i <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = new_i; - } - } else { - let mut i = truncate_counter(start); - while if inclusive { i <= end } else { i < end } { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = i.wrapping_add(step); - let next = truncate_counter(next); - if next <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } - - ExecResult::Continue -} - pub(crate) fn run_testbench( sim: &mut Simulator, testbench: &CompiledTestbench, @@ -1270,7 +654,7 @@ fn run_testbench_limited( sim.component_simulation = sim .components .has_scheduled_components() - .then(|| crate::simulation::simulation_state(sim)); + .then(|| Box::new(crate::simulation::simulation_state(sim))); let mut ctx = DetailedExecContext { assertions: Vec::new(), current_time: 0, @@ -1314,7 +698,7 @@ fn run_testbench_limited( TestResult::Fail(combined.join("\n")) } } - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => { + ExecResult::Continue | ExecResult::Finished => { if !failed_messages.is_empty() { TestResult::Fail(failed_messages.join("\n")) } else if require_finish && !finished { @@ -1418,7 +802,7 @@ pub(crate) fn run_testbench_detailed( sim.component_simulation = sim .components .has_scheduled_components() - .then(|| crate::simulation::simulation_state(sim)); + .then(|| Box::new(crate::simulation::simulation_state(sim))); let mut ctx = DetailedExecContext { assertions: Vec::new(), current_time: 0, @@ -1434,7 +818,7 @@ pub(crate) fn run_testbench_detailed( }; let mut error = match result { ExecResult::Fail(message) => Some(message), - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => None, + ExecResult::Continue | ExecResult::Finished => None, }; if let Err(message) = sim.components.finish(ctx.simulation_time()) && error.is_none() @@ -1646,9 +1030,6 @@ fn drain_runtime_assertions( } } -// Futures retain each process's control stack (including evaluated loop bounds) -// while no simulator borrow is held. Only this deterministic scheduler polls -// them; no threads, executor, or background work are involved. struct ProcessWait { clock: Event, remaining: u64, @@ -1657,129 +1038,6 @@ struct ProcessWait { reset: Option<(SignalRef, Option, u8)>, } -async fn exec_process<'a, B: SimBackend>( - sim: &'a RefCell<&mut Simulator>, - ctx: &'a RefCell<&mut DetailedExecContext>, - wait: &'a RefCell>>, - reset_edges: &'a RefCell>, - stmts: &'a [TestbenchStatement], -) -> ExecResult { - for stmt in stmts { - let result = match stmt { - GenericTestbenchStatement::ClockNext { - clock_event, - count, - period, - } => { - let count = match eval_clock_count(&mut sim.borrow_mut(), count) { - Ok(count) => count, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - *wait.borrow_mut() = (count != 0).then_some(ProcessWait { - clock: *clock_event, - remaining: count, - reset: None, - period: *period, - resume_at: None, - }); - std::future::poll_fn(|_| { - if wait.borrow().is_none() { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - ExecResult::Continue - } - GenericTestbenchStatement::ResetAssert { - reset_signal, - reset_event, - clock_event, - duration, - assert_value, - deassert_value, - period, - } => { - let duration = match eval_clock_count(&mut sim.borrow_mut(), duration) { - Ok(count) => count.max(1), - Err(error) => return ExecResult::Fail(error.to_string()), - }; - sim_set_u64(&mut sim.borrow_mut(), *reset_signal, (*assert_value).into()); - if let Some(event) = reset_event { - reset_edges.borrow_mut().push((*event, *assert_value)); - } - *wait.borrow_mut() = Some(ProcessWait { - clock: *clock_event, - remaining: duration, - period: *period, - resume_at: None, - reset: Some((*reset_signal, *reset_event, *deassert_value)), - }); - std::future::poll_fn(|_| { - if wait.borrow().is_none() { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - ExecResult::Continue - } - GenericTestbenchStatement::If { - expr, - then_block, - else_block, - } => { - let condition = { - let mut sim = sim.borrow_mut(); - if let Err(error) = settle_testbench_expr(&mut sim, expr) { - return ExecResult::Fail(format!("eval_comb: {error}")); - } - !eval_expr(&mut sim, expr).is_zero() - }; - let block = if condition { then_block } else { else_block }; - if block.is_empty() { - ExecResult::Continue - } else { - Box::pin(exec_process(sim, ctx, wait, reset_edges, block)).await - } - } - GenericTestbenchStatement::For { - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - body, - } => { - // Break recursive future sizing at the loop, once per loop - // invocation. Its body future stays inline across iterations; - // boxing the body instead allocates on every simulated cycle. - Box::pin(exec_for_loop_async( - sim, - loop_var, - start, - end, - *inclusive, - *step, - *step_op, - *reverse, - || exec_process(sim, ctx, wait, reset_edges, body), - )) - .await - } - _ => exec_one_detailed(&mut sim.borrow_mut(), stmt, &mut ctx.borrow_mut()), - }; - if !matches!(result, ExecResult::Continue) { - return result; - } - } - ExecResult::Continue -} - struct ProcessClock { event: Event, period: u64, @@ -1833,18 +1091,33 @@ fn exec_testbench( testbench: &CompiledTestbench, ctx: &mut DetailedExecContext, ) -> ExecResult { - let blocks: Vec<_> = testbench - .processes() - .filter(|block| !block.is_empty()) - .collect(); + let blocks: Vec<_> = testbench.processes().collect(); let clocks = initialize_process_clocks(sim, testbench); + // A finished kernel returns without passing a collection point, so + // collect its temporaries here; no process is suspended anymore. + if let Some(result) = compiled::run(sim, testbench, ctx) { + sim.heap_safepoint(); + 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() || (blocks.len() == 1 && clocks.len() <= 1) { - return exec_detailed(sim, testbench.statements(), ctx); + if blocks.is_empty() { + return ExecResult::Continue; + } + if blocks.len() == 1 && clocks.len() <= 1 { + let mut process = match native::Process::::compile(blocks[0], &testbench.kernels()[0]) { + Ok(process) => process, + Err(error) => return ExecResult::Fail(format!("testbench compilation: {error}")), + }; + let result = match process.resume(sim, ctx, &mut None, &mut Vec::new(), false) { + Poll::Ready(result) => result, + Poll::Pending => unreachable!("synchronous clock execution cannot suspend"), + }; + sim.heap_safepoint(); + return result; } // Suspended processes keep their temporaries outside state memory, so - // only the poll loop collects, with those temporaries as roots. + // only the scheduler loop collects, with those temporaries as roots. let blocked = std::mem::replace(&mut sim.heap_safepoints_blocked, true); let result = exec_processes(sim, testbench, ctx, &blocks); sim.heap_safepoints_blocked = blocked; @@ -1866,23 +1139,17 @@ fn exec_processes( .map(|&signal| sim.backend.get_four_state(signal)) .collect(); let mut locals = vec![initial_locals; blocks.len()]; - let sim = RefCell::new(sim); - let ctx = RefCell::new(ctx); - let waits: Vec<_> = blocks.iter().map(|_| RefCell::new(None)).collect(); - let reset_edges = RefCell::new(Vec::new()); - let mut processes: Vec<_> = blocks + let mut waits: Vec>> = blocks.iter().map(|_| None).collect(); + let mut reset_edges = Vec::new(); + let mut processes = match blocks .iter() - .zip(&waits) - .map(|(block, wait)| { - Some(Box::pin(exec_process( - &sim, - &ctx, - wait, - &reset_edges, - block, - ))) - }) - .collect(); + .zip(testbench.kernels()) + .map(|(block, kernel)| native::Process::::compile(block, kernel).map(Some)) + .collect::, _>>() + { + Ok(processes) => processes, + Err(error) => return ExecResult::Fail(format!("testbench compilation: {error}")), + }; // Every clock generator runs from time 0, whether or not a process // waits on it. let mut clocks: Vec> = testbench @@ -1900,21 +1167,20 @@ fn exec_processes( // their clock's next edge is still in the future. Rebasing after the // writes would silently absorb the asynchronous transition. { - let mut sim = sim.borrow_mut(); if sim.dirty - && let Err(error) = settle_testbench(&mut sim) + && let Err(error) = settle_testbench(sim) { return ExecResult::Fail(format!("eval_comb: {error}")); } let mut state = sim .component_simulation .take() - .unwrap_or_else(|| crate::simulation::simulation_state(&sim)); + .unwrap_or_else(|| Box::new(crate::simulation::simulation_state(sim))); state.synchronize_event_values(&sim.backend); sim.component_simulation = Some(state); } + let clock_batch = clock_batch::ClockBatch::new(sim); let mut now = 0; - let mut task_context = Context::from_waker(Waker::noop()); // Reuse per-slot batches instead of allocating on each rising and falling // edge; their capacities can grow when a wait introduces another clock. let mut falling = Vec::with_capacity(clocks.len()); @@ -1923,18 +1189,16 @@ fn exec_processes( let mut events = Vec::with_capacity(clocks.len() + waits.len()); let mut moves = Vec::with_capacity(clocks.len()); loop { - ctx.borrow_mut().scheduler_time = Some(now); - let draining = ctx.borrow().at_tick_limit(); + ctx.scheduler_time = Some(now); + let draining = ctx.at_tick_limit(); if draining { - ctx.borrow_mut().tick_limit_reached = true; + ctx.tick_limit_reached = true; // Stop starting work, but finish edges/releases already scheduled // by the final permitted tick before returning the simulator state. if clocks.iter().all(|clock| clock.falling_edge.is_none()) - && waits.iter().all(|wait| { - wait.borrow() - .as_ref() - .is_none_or(|wait| wait.resume_at.is_none()) - }) + && waits + .iter() + .all(|wait| wait.as_ref().is_none_or(|wait| wait.resume_at.is_none())) { return ExecResult::Finished; } @@ -1950,52 +1214,52 @@ fn exec_processes( None } })); - for wait in &waits { - let mut wait = wait.borrow_mut(); + for wait in &mut waits { if let Some(pending) = wait.as_ref() && pending.resume_at == Some(now) { if let Some((signal, event, value)) = pending.reset { - sim_set_u64(&mut sim.borrow_mut(), signal, value.into()); + sim_set_u64(sim, signal, value.into()); if let Some(event) = event { - reset_edges.borrow_mut().push((event, value)); + reset_edges.push((event, value)); } } *wait = None; } } - // Poll only ready processes, in declaration order, until their next - // wait, completion, or a global stop. No simulator borrow crosses await. + // Resume ready processes in declaration order until their next wait, + // completion, or a global stop. Each native call returns before another + // process or a clock domain can run. let mut stopped = false; - for ((process, wait), locals) in processes.iter_mut().zip(&waits).zip(&mut locals) { - if draining || wait.borrow().is_some() { + for ((process, wait), locals) in processes.iter_mut().zip(&mut waits).zip(&mut locals) { + if draining || wait.is_some() { continue; } - let Some(future) = process else { continue }; + let Some(executable) = process else { continue }; for (&signal, (value, mask)) in testbench.private_signals().iter().zip(locals.iter()) { - write_testbench_signal(&mut sim.borrow_mut(), signal, |sim| { + write_testbench_signal(sim, signal, |sim| { sim.set_four_state(signal, value.clone(), mask.clone()); }); } - let result = future.as_mut().poll(&mut task_context); + let result = executable.resume(sim, ctx, wait, &mut reset_edges, true); for (&signal, value) in testbench.private_signals().iter().zip(locals.iter_mut()) { - *value = sim.borrow().backend.get_four_state(signal); + *value = sim.backend.get_four_state(signal); } match result { - Poll::Ready(ExecResult::Continue | ExecResult::Break) => *process = None, + Poll::Ready(ExecResult::Continue) => *process = None, Poll::Ready(ExecResult::Finished) => { stopped = true; break; } Poll::Ready(result) => return result, - Poll::Pending => debug_assert!(wait.borrow().is_some()), + Poll::Pending => debug_assert!(wait.is_some()), } } // No process is running, so every string handle is in state memory or // in a suspended process's saved temporaries. - collect_testbench_heap(&mut sim.borrow_mut(), testbench.private_signals(), &locals); + collect_testbench_heap(sim, testbench.private_signals(), &locals); for wait in &waits { - if let Some(wait) = wait.borrow().as_ref() + if let Some(wait) = wait.as_ref() && wait.remaining != 0 { if let Some(clock) = clocks @@ -2023,7 +1287,6 @@ fn exec_processes( { resets.clear(); resets.extend(waits.iter().filter_map(|wait| { - let wait = wait.borrow(); let wait = wait.as_ref()?; wait.reset.map(|(_, event, _)| (wait.clock, event)) })); @@ -2033,16 +1296,17 @@ fn exec_processes( .iter() .map(|&event| (event, 0)) .chain(fired.iter().map(|&event| (event, 1))) - .chain(reset_edges.borrow_mut().drain(..)), + .chain(reset_edges.drain(..)), ); let result = step_process_events( - &mut sim.borrow_mut(), + sim, &events, &resets, now, !fired.is_empty(), - &mut ctx.borrow_mut(), + ctx, &mut moves, + clock_batch.as_ref(), ); if !matches!(result, ExecResult::Continue) { return result; @@ -2056,8 +1320,8 @@ fn exec_processes( clock.falling_edge = Some(now + clock.period - clock.period / 2); } } - for wait in &waits { - if let Some(wait) = wait.borrow_mut().as_mut() + for wait in &mut waits { + if let Some(wait) = wait.as_mut() && wait.remaining != 0 && let Some(clock) = clocks .iter() @@ -2079,13 +1343,13 @@ fn exec_processes( } let next_edge = clocks .iter() - .filter(|_| !ctx.borrow().at_tick_limit()) + .filter(|_| !ctx.at_tick_limit()) .map(|clock| clock.next_edge) .min(); let next_falling = clocks.iter().filter_map(|clock| clock.falling_edge).min(); let next_resume = waits .iter() - .filter_map(|wait| wait.borrow().as_ref().and_then(|wait| wait.resume_at)) + .filter_map(|wait| wait.as_ref().and_then(|wait| wait.resume_at)) .min(); if let Some(next) = [next_edge, next_falling, next_resume] .into_iter() @@ -2093,8 +1357,8 @@ fn exec_processes( .min() { now = next; - } else if ctx.borrow().at_tick_limit() { - ctx.borrow_mut().tick_limit_reached = true; + } else if ctx.at_tick_limit() { + ctx.tick_limit_reached = true; return ExecResult::Finished; } else { unreachable!("a live process has a pending wait"); @@ -2102,6 +1366,7 @@ fn exec_processes( } } +#[allow(clippy::too_many_arguments)] fn step_process_events( sim: &mut Simulator, events: &[(B::Event, u8)], @@ -2110,11 +1375,12 @@ 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 .take() - .unwrap_or_else(|| crate::simulation::simulation_state(sim)); + .unwrap_or_else(|| Box::new(crate::simulation::simulation_state(sim))); let edges = sim.event_edges(); let schema = &sim.program.runtime_schema; // Plain RTL needs simultaneous edge evaluation, not the timed process @@ -2171,10 +1437,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); @@ -2213,30 +1479,6 @@ fn step_process_events( ExecResult::Continue } -/// Like [`exec`] but collects assertion results into `ctx` instead of -/// short-circuiting on the first failure. -fn exec_detailed( - sim: &mut Simulator, - stmts: &[TestbenchStatement], - ctx: &mut DetailedExecContext, -) -> ExecResult { - for stmt in stmts { - let r = exec_one_detailed(sim, stmt, ctx); - // Only a single process runs here, so between statements every string - // handle is in state memory. - sim.maybe_collect_heap([]); - // Stop on control-flow transfers or hard errors. Assertion failures that - // are allowed to continue return `Continue` and are recorded in `ctx`. - if matches!( - r, - ExecResult::Break | ExecResult::Finished | ExecResult::Fail(_) - ) { - return r; - } - } - ExecResult::Continue -} - fn exec_one_detailed( sim: &mut Simulator, stmt: &TestbenchStatement, @@ -2420,52 +1662,11 @@ fn exec_one_detailed( forward_display(&rendered, *newline); ExecResult::Continue } - GenericTestbenchStatement::If { - expr, - then_block, - else_block, - } => { - if let Err(e) = settle_testbench_expr(sim, expr) { - return ExecResult::Fail(format!("eval_comb: {e}")); - } - if !eval_expr(sim, expr).is_zero() { - exec_detailed(sim, then_block, ctx) - } else { - exec_detailed(sim, else_block, ctx) - } - } - GenericTestbenchStatement::For { - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - body, - } => exec_for_loop( - sim, - loop_var, - start, - end, - *inclusive, - *step, - *step_op, - *reverse, - |sim| exec_detailed(sim, body, ctx), - ), - GenericTestbenchStatement::Assign { dst, expr } => { - let settle = if dst.selection.is_some() { - settle_testbench(sim) - } else { - settle_testbench_expr(sim, expr) - }; - if let Err(e) = settle { - return ExecResult::Fail(format!("eval_comb: {e}")); - } - let val = eval_expr(sim, expr); - sim_set_target(sim, dst, val); - ExecResult::Continue + GenericTestbenchStatement::If { .. } + | GenericTestbenchStatement::For { .. } + | GenericTestbenchStatement::Assign { .. } + | GenericTestbenchStatement::Break => { + unreachable!("statement is compiled into the process kernel") } GenericTestbenchStatement::WriteMemory { signal, writes } => { if let Err(e) = settle_testbench(sim) { @@ -2601,7 +1802,6 @@ fn exec_one_detailed( ); ExecResult::Continue } - GenericTestbenchStatement::Break => ExecResult::Break, GenericTestbenchStatement::Finish => ExecResult::Finished, } } @@ -2871,6 +2071,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#" @@ -2999,7 +2362,7 @@ mod tests { var q: logic<32>; inst dut: Counter(clk, q); initial { - for _i in 0..8 { clk.next(1); } + for _i in 0..(2 * (2 + 2)) { clk.next(1); } $assert(q == 8); $finish(); } @@ -3016,6 +2379,45 @@ mod tests { .. }) )); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass, + "q={}, counters={:?}", + sim.get_as::(sim.signal("q")), + compiled::take_counters() + ); + } + + #[test] + fn compiled_reads_share_settlement_until_the_next_hardware_write() { + let mut sim = Simulator::builder( + r#" + #[test(Top)] module Top { + var a: logic<8>; var q: logic<8>; + var x: logic<8>; var y: logic<8>; var z: logic<8>; + assign q = a + 1; + initial { + a = 1; + x = q; + y = q; + a = 7; + z = q; + $assert(x == 2 && y == 2 && z == 8); + $finish(); + } + } + "#, + "Top", + ) + .build() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let settlements = tb.kernels()[0] + .requests + .iter() + .filter(|request| matches!(request, celox_testbench::KernelRequest::Settle)) + .count(); + assert_eq!(settlements, 2); assert_eq!( run_compiled_testbench_to_finish(&mut sim, &tb), TestResult::Pass @@ -3023,53 +2425,57 @@ mod tests { } #[test] - fn expression_stores_invalidate_settled_hardware() { - use celox_testbench::{CompiledExpr, ExprBytecode, ExprOpcode}; + fn compiled_kernel_stores_invalidate_settled_hardware() { let mut sim = Simulator::builder( - "module Top(a: input logic<8>, q: output logic<8>) { assign q = a + 1; }", + r#" + #[test(Top)] module Top { + var a: logic<8>; var q: logic<8>; + assign q = a + 1; + initial { a = 7; $finish(); } + } + "#, "Top", ) + .dead_store_policy(crate::DeadStorePolicy::Off) .build_interpreter() .unwrap(); - let a = sim.signal("a"); let q = sim.signal("q"); + let tb = compile_initial_testbench(&sim).unwrap(); settle_testbench(&mut sim).unwrap(); - let pure = CompiledExpr::new(ExprBytecode::new(vec![ExprOpcode::ConstU64(42)])); - assert_eq!(eval_expr(&mut sim, &pure).to_u64(), 42); + let GenericTestbenchStatement::Assign { expr, .. } = &tb.statements()[0] else { + panic!("assignment") + }; + assert_eq!(eval_expr(&mut sim, expr).to_u64(), 7); assert!(!sim.dirty); - let store = CompiledExpr::new(ExprBytecode::new(vec![ - ExprOpcode::ConstU64(7), - ExprOpcode::StoreU64 { - location: a.offset, - byte_size: 1, - }, - ExprOpcode::ConstU64(7), - ])); - assert_eq!(eval_expr(&mut sim, &store).to_u64(), 7); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); assert!(sim.dirty); settle_testbench(&mut sim).unwrap(); assert_eq!(sim.get_as::(q), 8); } #[test] - fn expression_stores_notify_vcd_without_exposing_memory() { + fn compiled_kernel_stores_notify_vcd_without_exposing_memory() { let dir = tempfile::tempdir().unwrap(); - let mut sim = Simulator::builder("module Top (a: input logic<8>) {}", "Top") - .vcd(dir.path().join("expression.vcd")) - .build() - .unwrap(); + let mut sim = Simulator::builder( + r#" + #[test(Top)] module Top {var a: logic<8>; initial {a=7; $finish();}} + "#, + "Top", + ) + .vcd(dir.path().join("expression.vcd")) + .build() + .unwrap(); let a = sim.signal("a"); - let expr = celox_testbench::CompiledExpr::new(celox_testbench::ExprBytecode::new(vec![ - celox_testbench::ExprOpcode::ConstU64(7), - celox_testbench::ExprOpcode::StoreU64 { - location: a.offset, - byte_size: 1, - }, - celox_testbench::ExprOpcode::ConstU64(7), - ])); + let tb = compile_initial_testbench(&sim).unwrap(); sim.dump(0); let before = sim.vcd_statistics().unwrap(); - assert_eq!(eval_expr(&mut sim, &expr).to_u64(), 7); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); assert_eq!(sim.get_as::(a), 7); sim.dump(1); let after = sim.vcd_statistics().unwrap(); @@ -3131,4 +2537,23 @@ mod tests { } ); } + #[test] + fn zero_tick_limit_does_not_evaluate_compiled_control_flow() { + let source = r#" + #[test(Top)] module Top { + var touched: u32; + function touch() -> u32 { touched = 1; return 1; } + initial { if touch() == 1 { $finish(); } } + } + "#; + let mut sim = Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(); + let touched = sim.signal("touched"); + let program = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &program, 0); + assert!(result.tick_limit_reached); + assert_eq!(result.ticks, 0); + assert_eq!(sim.get_as::(touched), 0); + } } 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..9b56010ff16 --- /dev/null +++ b/crates/celox/src/testbench/compiled.rs @@ -0,0 +1,389 @@ +//! 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) + // Several addresses can resolve to one event, e.g. a port that + // copies the clock. Only the event's own signal holds its level: + // a copy may not be settled when the baseline is saved. + .filter_map(|((a, _), (_, saved))| { + let event = sim.backend.resolve_event_opt(a)?; + (sim.backend.resolve_signal(a) == sim.backend.resolve_signal(&event.addr())) + .then_some((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); + // The last tick whose progress was reported. + let mut reported = ctx.current_time; + 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]); + // Report each progress interval the run crossed, as the host tick + // batches do. + if let Some(every) = sim + .diagnostics + .testbench_progress_every + .filter(|every| *every != 0) + { + let mut tick = reported - reported % every; + while let Some(next) = tick.checked_add(every) + && next <= ctx.current_time + { + tracing::debug!("[testbench-progress] tick={next}"); + tick = next; + } + } + reported = ctx.current_time; + 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/native.rs b/crates/celox/src/testbench/native.rs new file mode 100644 index 00000000000..d4712786d6d --- /dev/null +++ b/crates/celox/src/testbench/native.rs @@ -0,0 +1,165 @@ +//! Invoke ordinary compiled SIR processes and service their suspension requests. +use super::*; +use celox_design::{HostRequestKind, ProcessStatus}; +use celox_testbench::{KernelRequest, TestbenchKernel}; + +pub(super) struct Process<'a, B: SimBackend> { + kernel: &'a TestbenchKernel, + sites: Vec<&'a TestbenchStatement>, + started: bool, +} +impl<'a, B: SimBackend> Process<'a, B> { + pub(super) fn compile( + statements: &'a [TestbenchStatement], + kernel: &'a TestbenchKernel, + ) -> Result { + fn collect<'a, B: SimBackend>( + statements: &'a [TestbenchStatement], + sites: &mut Vec<&'a TestbenchStatement>, + ) { + for statement in statements { + sites.push(statement); + match statement { + GenericTestbenchStatement::If { + then_block, + else_block, + .. + } => { + collect::(then_block, sites); + collect::(else_block, sites); + } + GenericTestbenchStatement::For { body, .. } => collect::(body, sites), + _ => {} + } + } + } + let mut sites = Vec::new(); + collect::(statements, &mut sites); + Ok(Self { + kernel, + sites, + started: false, + }) + } + pub(super) fn resume( + &mut self, + sim: &mut Simulator, + ctx: &mut DetailedExecContext, + wait: &mut Option>, + reset_edges: &mut Vec<(B::Event, u8)>, + scheduled: bool, + ) -> Poll { + if !self.started { + sim.backend.set(self.kernel.resume, 0u16); + self.started = true; + } + loop { + if !scheduled && ctx.at_tick_limit() { + ctx.tick_limit_reached = true; + return Poll::Ready(ExecResult::Finished); + } + if let Err(error) = sim.backend.run_process(self.kernel.entry) { + return Poll::Ready(ExecResult::Fail(format!("testbench kernel: {error}"))); + } + let status = ProcessStatus::from_code(sim.backend.get_as::(self.kernel.status)); + if status == Some(ProcessStatus::Done) { + return Poll::Ready(ExecResult::Continue); + } + if status != Some(ProcessStatus::HostRequest) { + return Poll::Ready(ExecResult::Fail(format!( + "invalid testbench kernel status: {status:?}" + ))); + } + let encoded = sim.backend.get_as::(self.kernel.request); + let Some((HostRequestKind::Testbench, index)) = HostRequestKind::decode(encoded) else { + return Poll::Ready(ExecResult::Fail("invalid testbench host request".into())); + }; + let Some(request) = self.kernel.requests.get(index as usize) else { + return Poll::Ready(ExecResult::Fail( + "testbench host request out of range".into(), + )); + }; + match request { + KernelRequest::Settle => { + if let Err(error) = settle_testbench(sim) { + return Poll::Ready(ExecResult::Fail(format!("eval_comb: {error}"))); + } + } + KernelRequest::Written { address, width } => { + let bytes = width.div_ceil(8); + sim.backend.mark_settle_range(address.offset, bytes); + sim.dirty |= !private_testbench_range(sim, address.offset, bytes); + } + KernelRequest::Error(message) => { + return Poll::Ready(ExecResult::Fail(message.clone())); + } + KernelRequest::Statement(site) => { + let statement = self.sites[*site]; + if scheduled { + match statement { + GenericTestbenchStatement::ClockNext { + clock_event, + count, + period, + } => { + let count = match eval_clock_count(sim, count) { + Ok(count) => count, + Err(error) => { + return Poll::Ready(ExecResult::Fail(error.to_string())); + } + }; + if count != 0 { + *wait = Some(ProcessWait { + clock: *clock_event, + remaining: count, + period: *period, + resume_at: None, + reset: None, + }); + return Poll::Pending; + } + continue; + } + GenericTestbenchStatement::ResetAssert { + reset_signal, + reset_event, + clock_event, + duration, + period, + assert_value, + deassert_value, + } => { + let count = match eval_clock_count(sim, duration) { + Ok(count) => count.max(1), + Err(error) => { + return Poll::Ready(ExecResult::Fail(error.to_string())); + } + }; + sim_set_u64(sim, *reset_signal, (*assert_value).into()); + if let Some(event) = reset_event { + reset_edges.push((*event, *assert_value)); + } + *wait = Some(ProcessWait { + clock: *clock_event, + remaining: count, + period: *period, + resume_at: None, + reset: Some((*reset_signal, *reset_event, *deassert_value)), + }); + return Poll::Pending; + } + _ => {} + } + } + let result = exec_one_detailed(sim, statement, ctx); + if !matches!(result, ExecResult::Continue) { + return Poll::Ready(result); + } + } + } + if !scheduled { + sim.maybe_collect_heap([]); + } + } + } +} diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index d24f9981047..e25015e3b9f 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -27,3 +27,133 @@ pub(crate) fn compile_semantic_testbench( random_seed, ) } + +/// Compile every expression at the ordinary pre-layout SIR boundary. Runtime +/// bindings carry entry indices and result slots, never executable bytecode. +pub(crate) fn lower_expressions( + sir: &mut crate::ir::SirProgram, + runtime: &mut crate::ir::RuntimeProgram, + program: &mut TestbenchProgram, +) -> Result<(), String> { + use celox_design::{ProcessKind, ProcessSlots, RegionedStateAddr, STABLE_REGION}; + use celox_sir::{BlockId, ExecutionUnit, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator}; + use celox_testbench::{ExprOpcode, ExpressionKernel, StateLocation}; + let control = ProcessSlots { + kind: ProcessKind::Callable, + requires_timed_simulation: false, + const_delays: false, + program: None, + resume: runtime.design.allocate_testbench_slot(16, false), + status: runtime.design.allocate_testbench_slot(8, false), + delay: runtime.design.allocate_testbench_slot(64, false), + }; + for slot in [control.resume, control.status, control.delay] { + runtime.runtime_schema.testbench_read_roots.insert(slot); + } + program.try_visit_expressions(|expression| { + let mut builder = SIRBuilder::new(); + let value = celox_testbench::lowering::Expressions { + builder: &mut builder, + } + .compile(expression)?; + let width = builder.register(&value.register).width(); + let result = runtime.design.allocate_testbench_slot(width, value.string); + runtime.runtime_schema.testbench_read_roots.insert(result); + builder.emit(SIRInstruction::Store( + result, + SIROffset::Static(0), + width, + value.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + .into_map_addr(&mut |address| { + RegionedStateAddr::from_absolute_addr(STABLE_REGION, address) + }); + memory::normalize(&mut unit, &runtime.design); + unit.verify_result().map_err(|error| error.to_string())?; + let mut writes = Vec::new(); + for op in expression.ops() { + match op { + ExprOpcode::StoreU64 { + location, + byte_size, + } => writes.push((*location, *byte_size)), + ExprOpcode::StoreString { location } => { + writes.push((*location, celox_heap::HANDLE_BYTES)) + } + _ => {} + } + } + let constant = if width <= 64 + && !value.string + && writes.is_empty() + && !unit + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!( + inst, + SIRInstruction::Load(..) | SIRInstruction::ExternCall { .. } + ) + }) { + celox_sir_opt::optimizer::optimize_merged_chain( + &mut unit, + std::sync::Arc::new(Default::default()), + |_, _, _| true, + false, + false, + &Default::default(), + || false, + ) + .map_err(|error| error.to_string())?; + let constants = celox_sir::analysis::collect_unique_exact_u64_constants(&unit); + unit.blocks + .values() + .flat_map(|block| &block.instructions) + .find_map(|inst| match inst { + SIRInstruction::Store(address, _, _, value, _, _) + if address.absolute_addr() == result => + { + constants.get(value).map(|value| value.value) + } + _ => None, + }) + } else { + None + }; + let entry = sir.processes.len(); + sir.processes.push(unit); + runtime.runtime_schema.processes.push(control); + runtime + .runtime_schema + .process_origins + .push(Default::default()); + runtime.runtime_schema.process_frames.push(None); + expression.set_kernel(ExpressionKernel { + constant, + entry, + result: StateLocation { + address: result, + byte_offset: 0, + }, + width, + is_string: value.string, + writes, + }); + Ok(()) + }) +} + +mod process; +pub(crate) use process::lower as lower_processes; + +mod memory; diff --git a/crates/celox/src/testbench_compile/memory.rs b/crates/celox/src/testbench_compile/memory.rs new file mode 100644 index 00000000000..ed1c19be800 --- /dev/null +++ b/crates/celox/src/testbench_compile/memory.rs @@ -0,0 +1,155 @@ +//! Preserve unpacked element addressing when consuming flattened TB offsets. +use crate::HashMap; +use crate::ir::{AbsoluteAddr, RuntimeDesign}; +use celox_design::{BinaryOp, RegionedStateAddr, UnaryOp}; +use celox_sir::{ + ExecutionUnit, RegisterId, RegisterType, SIRInstruction as Inst, SIROffset, SIRValue, +}; + +pub(super) fn normalize(unit: &mut ExecutionUnit, design: &RuntimeDesign) { + let elements: HashMap = design + .state_objects + .iter() + .filter(|(_, info)| !info.array_dims.is_empty()) + .map(|(address, info)| { + ( + *address, + info.width / info.array_dims.iter().product::(), + ) + }) + .collect(); + let mut next = unit.register_map.keys().map(|reg| reg.0).max().unwrap_or(0) + 1; + let mut alloc = |width| { + let register = RegisterId(next); + next += 1; + unit.register_map.insert( + register, + RegisterType::Bit { + width, + signed: false, + }, + ); + register + }; + for block in unit.blocks.values_mut() { + let old = std::mem::take(&mut block.instructions); + for instruction in old { + let (address, offset, width) = match &instruction { + Inst::Load(_, address, offset, width) + | Inst::Store(address, offset, width, _, _, _) => { + (*address, offset.clone(), *width) + } + _ => { + block.instructions.push(instruction); + continue; + } + }; + let Some(&element_width) = elements.get(&address.absolute_addr()) else { + block.instructions.push(instruction); + continue; + }; + let static_start = if let SIROffset::Static(start) = offset { + Some(start) + } else { + None + }; + let start = match offset { + SIROffset::Dynamic(value) => value, + SIROffset::Static(offset) => { + if width == 0 || offset / element_width == (offset + width - 1) / element_width + { + block.instructions.push(instruction); + continue; + } + let reg = alloc(64); + block + .instructions + .push(Inst::Imm(reg, SIRValue::new(offset as u64))); + reg + } + _ => { + block.instructions.push(instruction); + continue; + } + }; + let stride = alloc(64); + block + .instructions + .push(Inst::Imm(stride, SIRValue::new(element_width as u64))); + let mut parts = Vec::new(); + let mut bit = 0; + while bit < width { + // Source packed selections are confined to their unpacked + // element; wider accesses select complete unpacked elements. + let available = static_start.map_or(element_width, |start| { + element_width - (start + bit) % element_width + }); + let count = available.min(width - bit); + let offset = if bit == 0 { + start + } else { + let add = alloc(64); + block + .instructions + .push(Inst::Imm(add, SIRValue::new(bit as u64))); + let sum = alloc(64); + block + .instructions + .push(Inst::Binary(sum, start, BinaryOp::Add, add)); + sum + }; + let index = alloc(64); + block + .instructions + .push(Inst::Binary(index, offset, BinaryOp::DivU, stride)); + let within = alloc(64); + block + .instructions + .push(Inst::Binary(within, offset, BinaryOp::RemU, stride)); + let offset = SIROffset::Element { + index, + element_width, + bit_offset: 0, + dynamic_bit_offset: Some(within), + }; + let part = alloc(count); + match &instruction { + Inst::Load(..) => { + block + .instructions + .push(Inst::Load(part, address, offset, count)); + parts.push(part); + } + Inst::Store(_, _, _, value, triggers, probes) => { + block + .instructions + .push(Inst::Slice(part, *value, bit, count)); + block.instructions.push(Inst::Store( + address, + offset, + count, + part, + triggers.clone(), + probes.clone(), + )); + } + _ => unreachable!(), + } + bit += count; + } + if let Inst::Load(result, ..) = instruction { + let value = if parts.len() == 1 { + parts[0] + } else { + let value = alloc(width); + parts.reverse(); + block.instructions.push(Inst::Concat(value, parts)); + value + }; + block + .instructions + .push(Inst::Unary(result, UnaryOp::Ident, value)); + } + } + } +} diff --git a/crates/celox/src/testbench_compile/process.rs b/crates/celox/src/testbench_compile/process.rs new file mode 100644 index 00000000000..d3c9bb2bcce --- /dev/null +++ b/crates/celox/src/testbench_compile/process.rs @@ -0,0 +1,785 @@ +//! Veryl statements lowered with the same resumable SIR builder as SV. +use crate::ir::{AbsoluteAddr as Addr, RuntimeProgram, SirProgram}; +use celox_design::{ + BinaryOp, ProcessKind, ProcessSlots, RegionedVarAddrBase, STABLE_REGION, UnaryOp, +}; +use celox_frontend_core::process::ProcessKernelBuilder; +use celox_sir::{ + BlockId, RegisterId, SIRInstruction as Inst, SIROffset, SIRTerminator as Term, SIRValue, +}; +use celox_testbench::*; +use num_bigint::BigUint; + +type Expr = ExprBytecode>; +fn stable(var_id: Addr) -> RegionedVarAddrBase { + RegionedVarAddrBase { + region: STABLE_REGION, + var_id, + } +} +struct Lower<'a> { + runtime: &'a mut RuntimeProgram, + kernel: ProcessKernelBuilder, + requests: Vec>, + site: usize, + external_observers: bool, + settled: bool, +} +impl Lower<'_> { + fn slot(&mut self, width: usize, string: bool) -> Addr { + let address = self.runtime.design.allocate_testbench_slot(width, string); + self.runtime + .runtime_schema + .testbench_read_roots + .insert(address); + address + } + fn imm(&mut self, width: usize, value: impl Into) -> RegisterId { + let reg = self.kernel.builder().alloc_bit(width.max(1), false); + self.kernel.builder().emit(Inst::Imm( + reg, + SIRValue::new( + value.into() & ((BigUint::from(1u8) << width.max(1)) - BigUint::from(1u8)), + ), + )); + reg + } + fn load(&mut self, address: Addr, width: usize, signed: bool) -> RegisterId { + let reg = self.kernel.builder().alloc_bit(width.max(1), signed); + self.kernel.builder().emit(Inst::Load( + reg, + stable(address), + SIROffset::Static(0), + width.max(1), + )); + reg + } + fn store(&mut self, address: Addr, width: usize, value: RegisterId) { + self.kernel.builder().emit(Inst::Store( + stable(address), + SIROffset::Static(0), + width.max(1), + value, + vec![], + vec![], + )); + } + /// Store `width` bits saved in `saved` at the dynamic bit `offset` of + /// a `total`-bit object. An offset past the object writes nothing, and a + /// selection that runs past its end writes only its in-range bits, as a + /// selected write does (IEEE 1800-2023 7.4.6, 11.5.1). + fn selected_store( + &mut self, + address: Addr, + total: usize, + width: usize, + offset: RegisterId, + saved: Addr, + string: bool, + ) { + let offset_width = self.kernel.builder().register(&offset).width(); + let bound = self.cast(offset, offset_width.max(64), false); + let last_full = self.imm(offset_width.max(64), total.saturating_sub(width) as u64); + let fits = self.binary(BinaryOp::LeU, bound, last_full, 1); + let full = self.kernel.builder().new_block(); + let partial_check = self.kernel.builder().new_block(); + let join = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: fits, + true_block: (full, vec![]), + false_block: (partial_check, vec![]), + }); + self.kernel.builder().switch_to_block(full); + let value = self.load(saved, width, false); + self.kernel.builder().emit(Inst::Store( + stable(address), + SIROffset::Dynamic(offset), + width, + value, + vec![], + vec![], + )); + self.kernel.builder().seal_block(Term::Jump(join, vec![])); + self.kernel.builder().switch_to_block(partial_check); + // Only a multi-bit selection can overlap the end. A string element + // is a whole handle and never does. + if width > 1 && total > width && !string { + let end = self.imm(offset_width.max(64), total as u64); + let inside = self.binary(BinaryOp::LtU, bound, end, 1); + let partial = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: inside, + true_block: (partial, vec![]), + false_block: (join, vec![]), + }); + self.kernel.builder().switch_to_block(partial); + // The overlap lies in the last `width` bits: merge into them. + let tail = total - width; + let start = self.imm(offset_width.max(64), tail as u64); + let shift = self.binary(BinaryOp::Sub, bound, start, offset_width.max(64)); + let shift = self.cast(shift, 64, false); + let old = self.kernel.builder().alloc_bit(width, false); + self.kernel.builder().emit(Inst::Load( + old, + stable(address), + SIROffset::Static(tail), + width, + )); + let ones = self.imm(width, (BigUint::from(1u8) << width) - BigUint::from(1u8)); + let mask = self.binary(BinaryOp::Shl, ones, shift, width); + let keep = self.kernel.builder().alloc_bit(width, false); + self.kernel + .builder() + .emit(Inst::Unary(keep, UnaryOp::BitNot, mask)); + let old = self.binary(BinaryOp::And, old, keep, width); + let value = self.load(saved, width, false); + let value = self.binary(BinaryOp::Shl, value, shift, width); + let merged = self.binary(BinaryOp::Or, old, value, width); + self.kernel.builder().emit(Inst::Store( + stable(address), + SIROffset::Static(tail), + width, + merged, + vec![], + vec![], + )); + } + if self.kernel.builder().has_open_block() { + self.kernel.builder().seal_block(Term::Jump(join, vec![])); + } + self.kernel.builder().switch_to_block(join); + } + fn cast(&mut self, value: RegisterId, width: usize, signed: bool) -> RegisterId { + let source = self.kernel.builder().register(&value).width(); + let extend = self.kernel.builder().register(&value).is_signed() && width > source; + let reg = self.kernel.builder().alloc_bit(width.max(1), signed); + if width < source { + self.kernel + .builder() + .emit(Inst::Slice(reg, value, 0, width.max(1))); + } else { + self.kernel + .builder() + .emit(Inst::Unary(reg, UnaryOp::Ident, value)); + } + if extend { + let shift = self.imm(64, (width - source) as u64); + let reg = self.binary(BinaryOp::Shl, reg, shift, width); + let reg = self.binary(BinaryOp::Sar, reg, shift, width); + let typed = self.kernel.builder().alloc_bit(width.max(1), signed); + self.kernel + .builder() + .emit(Inst::Unary(typed, UnaryOp::Ident, reg)); + typed + } else { + reg + } + } + fn binary( + &mut self, + op: BinaryOp, + mut l: RegisterId, + mut r: RegisterId, + width: usize, + ) -> RegisterId { + if matches!( + op, + BinaryOp::Eq + | BinaryOp::Ne + | BinaryOp::LtS + | BinaryOp::LtU + | BinaryOp::LeS + | BinaryOp::LeU + | BinaryOp::GtS + | BinaryOp::GtU + | BinaryOp::GeS + | BinaryOp::GeU + ) { + let signed = matches!( + op, + BinaryOp::LtS | BinaryOp::LeS | BinaryOp::GtS | BinaryOp::GeS + ); + let lw = self.kernel.builder().register(&l).width(); + let rw = self.kernel.builder().register(&r).width(); + l = self.cast(l, lw, signed); + r = self.cast(r, rw, signed); + l = self.cast(l, lw.max(rw), signed); + r = self.cast(r, lw.max(rw), signed); + } + let reg = self.kernel.builder().alloc_bit(width.max(1), false); + self.kernel.builder().emit(Inst::Binary(reg, l, op, r)); + reg + } + fn request(&mut self, request: KernelRequest) -> Result<(), String> { + self.settled = matches!(request, KernelRequest::Settle); + let index = self.requests.len(); + self.requests.push(request); + self.kernel + .host_request(celox_design::HostRequestKind::Testbench, index as u32) + .map_err(|e| e.to_string()) + } + fn expression(&mut self, expr: &Expr) -> Result { + let expr = expr.clone().try_map_locations(|location| { + Ok::<_, String>(StateLocation { + address: stable(location.address), + byte_offset: location.byte_offset, + }) + })?; + let value = lowering::Expressions { + builder: self.kernel.builder(), + } + .compile(&expr)?; + let writes: Vec<_> = expr + .ops() + .iter() + .filter_map(|op| { + let address = match op { + ExprOpcode::StoreU64 { location, .. } + | ExprOpcode::StoreString { location } => location.address.var_id, + _ => return None, + }; + self.writes_observable(address).then_some(address) + }) + .collect(); + if writes.is_empty() { + return Ok(value); + } + // Host requests resume through a fresh kernel entry. Preserve the + // expression result in layout-owned state across that boundary. + let width = self.kernel.builder().register(&value.register).width(); + let saved = self.slot(width, value.string); + self.store(saved, width, value.register); + for address in writes { + let width = self.runtime.design.state_objects[&address].width; + self.request(KernelRequest::Written { address, width })?; + } + Ok(lowering::Value { + register: self.load(saved, width, false), + string: value.string, + }) + } + fn writes_observable(&self, address: Addr) -> bool { + self.external_observers || self.runtime.rtl_accesses.contains(&address) + } + fn observes(&self, expr: &Expr) -> bool { + self.external_observers + || expr.ops().iter().any(|op| match op { + ExprOpcode::LoadU64 { location, .. } + | ExprOpcode::LoadWide { location, .. } + | ExprOpcode::LoadIndexed { location, .. } + | ExprOpcode::LoadBitSelect { location, .. } + | ExprOpcode::LoadString { location, .. } => { + self.runtime.rtl_accesses.contains(&location.address) + } + _ => false, + }) + } + fn settled_expression(&mut self, expr: &Expr) -> Result { + // Reads within one straight-line segment see the same settled DUT. + // A write, host service or control-flow boundary invalidates this fact. + if self.observes(expr) && (!self.settled || self.external_observers) { + self.request(KernelRequest::Settle)?; + } + self.expression(expr) + } + fn block( + &mut self, + body: &[SemanticStatement], + break_to: Option, + ) -> Result<(), String> { + for statement in body { + let site = self.site; + self.site += 1; + if !self.kernel.builder().has_open_block() { + let dead = self.kernel.builder().new_block(); + self.kernel.builder().switch_to_block(dead); + } + match statement { + TestbenchStatement::If { + expr, + then_block, + else_block, + } => { + let cond = self.settled_expression(expr)?.register; + let yes = self.kernel.builder().new_block(); + let no = self.kernel.builder().new_block(); + let join = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond, + true_block: (yes, vec![]), + false_block: (no, vec![]), + }); + for (block, body) in [(yes, then_block), (no, else_block)] { + self.kernel.builder().switch_to_block(block); + self.settled = false; + self.block(body, break_to)?; + if self.kernel.builder().has_open_block() { + self.kernel.builder().seal_block(Term::Jump(join, vec![])); + } + } + self.kernel.builder().switch_to_block(join); + self.settled = false; + } + TestbenchStatement::Assign { dst, expr } => { + let expression = self.settled_expression(expr)?; + let value = self.cast(expression.register, dst.width, false); + let saved = if dst.selection.is_some() { + let saved = self.slot(dst.width, expression.string); + self.store(saved, dst.width, value); + Some(saved) + } else { + None + }; + if let Some(selection) = &dst.selection { + let offset = self.settled_expression(&selection.offset)?.register; + let saved = saved.expect("selected assignments save their value"); + self.selected_store( + dst.signal.address, + dst.signal.width, + dst.width, + offset, + saved, + expression.string, + ); + } else { + self.store(dst.signal.address, dst.width, value); + } + if self.writes_observable(dst.signal.address) { + self.request(KernelRequest::Written { + address: dst.signal.address, + width: dst.signal.width, + })?; + } + } + TestbenchStatement::For { + loop_var, + start, + end, + inclusive, + step, + step_op, + reverse, + body, + } => { + self.for_loop( + *loop_var, start, end, *inclusive, *step, *step_op, *reverse, body, + break_to, + )?; + } + TestbenchStatement::Break => { + if let Some(target) = break_to { + self.kernel.builder().seal_block(Term::Jump(target, vec![])); + } else { + self.kernel.complete(); + } + } + _ => self.request(KernelRequest::Statement(site))?, + } + } + Ok(()) + } + fn bound(&mut self, bound: &LoopBound) -> Result<(RegisterId, usize, bool), String> { + Ok(match bound { + LoopBound::Static(value) => { + let width = (usize::BITS as usize - value.leading_zeros() as usize).max(32); + let value = self.imm(width, *value as u64); + (self.cast(value, width, true), width, true) + } + LoopBound::Dynamic { + expr, + width, + signed, + } => { + let value = self.settled_expression(expr)?.register; + (self.cast(value, *width, *signed), *width, *signed) + } + }) + } + fn bound_fits( + &mut self, + value: RegisterId, + width: usize, + signed: bool, + extra: bool, + ) -> RegisterId { + let source = self.kernel.builder().register(&value).clone(); + let common = source.width().max(width + 1); + let value = self.cast(value, common, source.is_signed()); + let max = (BigUint::from(1u8) << (width - usize::from(signed))) - BigUint::from(1u8) + + BigUint::from(u8::from(extra)); + let max = self.imm(common, max); + let upper = self.binary( + if source.is_signed() { + BinaryOp::LeS + } else { + BinaryOp::LeU + }, + value, + max, + 1, + ); + if source.is_signed() { + let min = if signed { + (BigUint::from(1u8) << common) - (BigUint::from(1u8) << (width - 1)) + } else { + BigUint::ZERO + }; + let min = self.imm(common, min); + let lower = self.binary(BinaryOp::GeS, value, min, 1); + self.binary(BinaryOp::And, upper, lower, 1) + } else { + upper + } + } + #[allow(clippy::too_many_arguments)] + fn for_loop( + &mut self, + variable: Option<(SemanticSignal, usize, bool)>, + start: &LoopBound, + end: &LoopBound, + inclusive: bool, + step: usize, + step_op: Option, + reverse: bool, + body: &[SemanticStatement], + _outer_break: Option, + ) -> Result<(), String> { + let (first, fw, fs) = self.bound(start)?; + // A bound can call host services: save the first value across them. + let first_slot = self.slot(fw, false); + self.store(first_slot, fw, first); + let (last, lw, ls) = self.bound(end)?; + let first = self.load(first_slot, fw, fs); + let (width, signed) = variable.map_or((fw.max(lw).max(64), fs || ls), |(_, w, s)| (w, s)); + // A fixed-width induction variable cannot traverse an unrepresentable + // endpoint. Diagnose that before entering an otherwise enormous loop. + let singleton = if inclusive && fw.max(lw) > 64 { + let equal = self.binary(BinaryOp::Eq, first, last, 1); + let max = self.imm(fw.max(lw), u64::MAX); + let wide = self.binary(BinaryOp::GtU, first, max, 1); + self.binary(BinaryOp::And, equal, wide, 1) + } else { + self.imm(1, 0u8) + }; + // An empty range runs nothing, even when an endpoint does not fit the + // induction variable: run it in single mode with no iteration left. + // Compare as the loop condition does: signed only when the induction + // variable and its limit endpoint both are. + let empty = if variable.is_some() { + let common = fw.max(lw); + let compare_signed = signed && if reverse { fs } else { ls }; + let from = self.cast(first, common, fs); + let to = self.cast(last, common, ls); + let op = match (inclusive, compare_signed) { + (true, true) => BinaryOp::GtS, + (true, false) => BinaryOp::GtU, + (false, true) => BinaryOp::GeS, + (false, false) => BinaryOp::GeU, + }; + self.binary(op, from, to, 1) + } else { + self.imm(1, 0u8) + }; + let mode = self.binary(BinaryOp::Or, singleton, empty, 1); + let mode_slot = self.slot(1, false); + self.store(mode_slot, 1, mode); + let remaining_slot = self.slot(1, false); + let one = self.imm(1, 1u8); + let remaining = self.binary(BinaryOp::Xor, empty, one, 1); + self.store(remaining_slot, 1, remaining); + if variable.is_some() { + let first_fits = self.bound_fits(first, width, signed, false); + let last_fits = self.bound_fits(last, width, signed, !inclusive); + let fits = self.binary(BinaryOp::And, first_fits, last_fits, 1); + let fits = self.binary(BinaryOp::Or, fits, mode, 1); + let valid = self.kernel.builder().new_block(); + let invalid = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: fits, + true_block: (valid, vec![]), + false_block: (invalid, vec![]), + }); + self.kernel.builder().switch_to_block(invalid); + self.request(KernelRequest::Error( + "non-progressing stepped for loop".into(), + ))?; + self.kernel.complete(); + self.kernel.builder().switch_to_block(valid); + } + let limit_width = if reverse { fw } else { lw }; + let limit_signed = if reverse { fs } else { ls }; + let current_slot = self.slot(width, false); + let limit_slot = self.slot(limit_width, false); + self.store(limit_slot, limit_width, if reverse { first } else { last }); + let current = if reverse && !inclusive { + let one = self.imm(lw, 1u8); + self.binary(BinaryOp::Sub, last, one, lw) + } else if reverse { + last + } else { + first + }; + let current = self.cast(current, width, signed); + self.store(current_slot, width, current); + let check = self.kernel.builder().new_block(); + let body_entry = self.kernel.builder().new_block(); + let advance = self.kernel.builder().new_block(); + let exit = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Jump(check, vec![])); + self.kernel.builder().switch_to_block(check); + let current = self.load(current_slot, width, signed); + let limit = self.load(limit_slot, limit_width, limit_signed); + let cmp = match (reverse, inclusive, signed && limit_signed) { + (true, _, true) => BinaryOp::GeS, + (true, _, false) => BinaryOp::GeU, + (false, true, true) => BinaryOp::LeS, + (false, true, false) => BinaryOp::LeU, + (false, false, true) => BinaryOp::LtS, + (false, false, false) => BinaryOp::LtU, + }; + let cond = self.binary(cmp, current, limit, 1); + let mode = self.load(mode_slot, 1, false); + let remaining = self.load(remaining_slot, 1, false); + let selected = self.kernel.builder().alloc_bit(1, false); + self.kernel + .builder() + .emit(Inst::Mux(selected, mode, remaining, cond)); + let cond = selected; + self.kernel.builder().seal_block(Term::Branch { + cond, + true_block: (body_entry, vec![]), + false_block: (exit, vec![]), + }); + self.kernel.builder().switch_to_block(body_entry); + self.settled = false; + if let Some((var, _, _)) = variable { + self.store(var.address, width, current); + } + self.block(body, Some(exit))?; + if self.kernel.builder().has_open_block() { + self.kernel + .builder() + .seal_block(Term::Jump(advance, vec![])); + } + self.kernel.builder().switch_to_block(advance); + let current = self.load(current_slot, width, signed); + let shift = !reverse + && matches!( + step_op, + Some(TestbenchOperator::LogicShiftL | TestbenchOperator::ArithShiftL) + ); + // A shift count at or above the width shifts every bit out; clamp it + // instead of truncating it to the counter width. + let step = self.imm(width, if shift { step.min(width) } else { step } as u64); + let op = if reverse { + BinaryOp::Sub + } else { + match step_op { + Some(TestbenchOperator::Mul) => BinaryOp::Mul, + Some(TestbenchOperator::BitOr) => BinaryOp::Or, + Some(TestbenchOperator::BitXor) => BinaryOp::Xor, + Some(TestbenchOperator::LogicShiftL | TestbenchOperator::ArithShiftL) => { + BinaryOp::Shl + } + _ => BinaryOp::Add, + } + }; + let next = self.binary(op, current, step, width); + let next = self.cast(next, width, signed); + let progress = self.binary( + match (reverse, signed) { + (true, true) => BinaryOp::LtS, + (true, false) => BinaryOp::LtU, + (false, true) => BinaryOp::GtS, + (false, false) => BinaryOp::GtU, + }, + next, + current, + 1, + ); + self.store(current_slot, width, next); + let zero = self.imm(1, 0u8); + self.store(remaining_slot, 1, zero); + let failure = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: progress, + true_block: (check, vec![]), + false_block: (failure, vec![]), + }); + self.kernel.builder().switch_to_block(failure); + self.request(KernelRequest::Error( + "non-progressing stepped for loop".into(), + ))?; + self.kernel.complete(); + self.kernel.builder().switch_to_block(exit); + self.settled = false; + Ok(()) + } +} + +pub(crate) fn lower( + sir: &mut SirProgram, + runtime: &mut RuntimeProgram, + program: &mut TestbenchProgram, +) -> Result<(), String> { + let mut kernels = Vec::new(); + let external_observers = !program.component_bindings().is_empty() + || !runtime.runtime_schema.persistent_comb_state.is_empty() + || !runtime.runtime_schema.comb_observers.is_empty() + || runtime + .runtime_schema + .processes + .iter() + .any(|p| p.kind != ProcessKind::Callable); + for body in program.processes() { + let slots = ProcessSlots { + kind: ProcessKind::Callable, + requires_timed_simulation: false, + const_delays: false, + program: None, + resume: runtime.design.allocate_testbench_slot(16, false), + status: runtime.design.allocate_testbench_slot(8, false), + delay: runtime.design.allocate_testbench_slot(64, false), + }; + for slot in [slots.resume, slots.status, slots.delay] { + runtime.runtime_schema.testbench_read_roots.insert(slot); + } + let mut lower = Lower { + runtime, + kernel: ProcessKernelBuilder::new(slots), + requests: vec![], + site: 0, + external_observers, + settled: false, + }; + lower.block(body, None)?; + let entry = sir.processes.len(); + let mut unit = lower.kernel.build().into_map_addr(&mut |address| { + celox_design::RegionedStateAddr::from_absolute_addr(address.region, address.var_id) + }); + super::memory::normalize(&mut unit, &lower.runtime.design); + unit.verify_result().map_err(|error| error.to_string())?; + sir.processes.push(unit); + lower.runtime.runtime_schema.processes.push(slots); + lower.runtime.runtime_schema.process_frames.push(None); + lower + .runtime + .runtime_schema + .process_origins + .push(Default::default()); + kernels.push(TestbenchKernel { + entry, + resume: slots.resume, + status: slots.status, + request: slots.delay, + requests: lower.requests, + }); + } + 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/native_mir.rs b/crates/celox/tests/native_mir.rs index be036c33dab..bd5767f12c2 100644 --- a/crates/celox/tests/native_mir.rs +++ b/crates/celox/tests/native_mir.rs @@ -275,3 +275,35 @@ fn many_clocks_compile_the_comb_program_once() { assert_eq!(functions(2), (1, 2)); assert_eq!(functions(12), (1, 0)); } + +#[test] +fn trace_contains_native_testbench_processes() { + let code = r#" + #[test(test_top)] + module Top { + var q: logic<8>; + initial { + q = 1; + $assert(q == 1); + } + } + "#; + let result = SimulatorBuilder::new(code, "Top") + .trace_mir() + .build_with_trace(); + result.res.expect("native testbench build should succeed"); + assert!( + result + .trace + .native_optimized_sir + .unwrap() + .contains("=== Native function process[0] ===") + ); + assert!( + result + .trace + .mir + .unwrap() + .contains("=== Native function process[0] ===") + ); +} diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 61cef16d016..f9b471fe73f 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -489,6 +489,88 @@ fn test_selected_testbench_destinations_update_only_selected_targets() { } } +#[test] +fn test_destination_index_reads_settled_hardware() { + let code = r#" + module Dut (drive: input logic<2>, index: output logic<2>) { + assign index = drive + 1; + } + #[test(t)] + module t { + var drive: logic<2>; + var index: logic<2>; + var values: logic<8>[4]; + inst dut: Dut (drive, index); + initial { + for i in 0..4 { + values[i] = 0; + } + drive = 0; + values[index] = 8'h11; + drive = 2; + values[index] = 8'hff; + $assert(values[1] == 8'h11); + $assert(values[2] == 8'h00); + $assert(values[3] == 8'hff); + $finish(); + } + } + "#; + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + TestResult::Pass, + ); +} + +#[test] +fn test_out_of_range_testbench_destinations_write_nothing() { + let code = r#" + #[test(t)] + module t { + var guard_lo: logic<32>; + var bits: logic<8>; + var part: logic<8>; + var values: logic<8>[4]; + var guard_hi: logic<32>; + var index: logic<32>; + initial { + guard_lo = 0; + bits = 0; + part = 0; + values[0] = 0; + values[1] = 0; + values[2] = 0; + values[3] = 0; + guard_hi = 0; + index = 12; + bits[index] = 1; + index = 5; + values[index] = 8'hff; + index = 32'h7fff_fff0; + bits[index] = 1; + values[index] = 8'hff; + index = 6; + part[index +: 4] = 4'hf; + $assert(part == 8'hc0, "part=%h", part); + $assert(guard_lo == 0, "guard_lo=%h", guard_lo); + $assert(bits == 0, "bits=%h", bits); + $assert(values[0] == 0 && values[1] == 0, "values"); + $assert(values[2] == 0 && values[3] == 0, "values"); + $assert(guard_hi == 0, "guard_hi=%h", guard_hi); + $finish(); + } + } + "#; + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + TestResult::Pass + ); + assert_eq!( + Simulator::builder(code, "t").run_test_cranelift().unwrap(), + TestResult::Pass + ); +} + #[test] fn test_packed_prefix_and_low_bound_testbench_destinations() { let code = r#" @@ -939,6 +1021,36 @@ fn test_clock_only_self_updating_ff_advances_in_native_testbench_instance() { ); } +#[test] +fn test_fall_through_after_clock_wait_stops_after_one_period() { + let code = r#" + module ClockTickCounter ( + clk : input clock , + ticks: output logic<32>, + ) { + always_ff (clk) { + ticks += 1; + } + } + + #[test(t)] + module t { + inst clk: $tb::clock_gen; + var ticks: logic<32>; + inst dut: ClockTickCounter (clk, ticks); + + initial { + clk.next(1); + } + } + "#; + + let mut sim = Simulator::builder(code, "t").build().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get_as::(sim.signal("ticks")), 1); +} + // ── Wide signal (>64 bit) ────────────────────────────────────────────── #[test] @@ -1382,6 +1494,58 @@ fn test_for_loop_i32_or_step_with_only_existing_low_bits_fails() { assert!(message.contains("non-progressing stepped for loop")); } +#[test] +fn test_for_loop_dynamic_shift_step_wider_than_counter_reports_non_progress() { + let code = r#" + #[test(t)] + module t { + var start: logic<32>; + var end_bound: logic<32>; + var last: logic<32>; + initial { + start = 1; + end_bound = 3; + last = 0; + for i in start..end_bound step <<= 4294967297 { + last = i; + } + $finish(); + } + } + "#; + let TestResult::Fail(message) = Simulator::builder(code, "t").run_test().unwrap() else { + panic!("expected non-progressing loop failure"); + }; + assert!(message.contains("non-progressing stepped for loop")); +} + +#[test] +fn test_for_loop_empty_wide_dynamic_range_skips_body() { + let code = r#" + #[test(t)] + module t { + var bound: logic<128>; + var count: logic<32>; + initial { + bound = 128'd1 << 100; + count = 0; + for _i in bound..bound { + count += 1; + } + for _i in rev bound..bound { + count += 1; + } + $assert(count == 0, "count=%d", count); + $finish(); + } + } + "#; + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + TestResult::Pass + ); +} + #[test] fn test_for_loop_rev() { let code = format!( @@ -2030,7 +2194,7 @@ fn test_for_loop_dynamic_wide_signed_bound_small_value_still_runs() { } #[test] -fn test_expression_vm_preserves_width_signedness_and_casts() { +fn test_compiled_expression_preserves_width_signedness_and_casts() { let code = r#" #[test(t)] module t { @@ -2118,7 +2282,7 @@ fn test_expression_vm_preserves_width_signedness_and_casts() { } #[test] -fn test_expression_vm_preserves_wide_fixed_width_semantics() { +fn test_compiled_expression_preserves_wide_fixed_width_semantics() { let code = r#" #[test(t)] module t { 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/crates/celox/tests/testbench_reset_polarity.rs b/crates/celox/tests/testbench_reset_polarity.rs index e32cf6cf9c8..b2ea01ff864 100644 --- a/crates/celox/tests/testbench_reset_polarity.rs +++ b/crates/celox/tests/testbench_reset_polarity.rs @@ -139,3 +139,36 @@ fn generator_follows_declared_indices_of_sv_instance_arrays() { } } } + +/// A DUT clock port is a second address of the TB clock's event. Its copy can +/// be unsettled when the compiled scheduler saves edge baselines, so the +/// four-state interpreter (host edge path) must take the level from the +/// event's own signal or it misses every later rising edge. +#[test] +fn clock_port_copy_does_not_mask_rising_edges_after_reset() { + let source = r#" + module Counter(clk: input clock, rst: input reset_sync_high, count: output logic<8>) { + always_ff { if_reset { count = 0; } else { count += 1; } } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen; + inst rst: $tb::reset_gen(clk); + var count: logic<8>; + inst dut: Counter(clk, rst, count); + initial { + rst.assert(4); + clk.next(1); + $assert(count == 1, "count=%d", count); + clk.next(6); + $assert(count == 7, "count=%d", count); + $finish(); + } + } + "#; + for four_state in [false, true] { + run(Simulator::builder(source, "Top") + .four_state(four_state) + .build_interpreter() + .unwrap()); + } +} diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 574530a26d4..dc6f5ebc112 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -388,3 +388,73 @@ fn unsupported_string_operations_are_rejected() { ); } } + +#[test] +fn compiled_conditions_collect_temporary_string_arguments() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500) + .map(|index| format!("temporary {index}")) + .collect(); + let conditions: String = values + .iter() + .map(|value| format!("if nonempty(\"{value}\") {{ }}\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + function nonempty(value: input string) -> logic {{ return value != ""; }} + initial {{ {conditions} $finish(); }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let all_values: usize = values.iter().map(String::len).sum(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + +#[test] +fn finished_compiled_kernel_collects_temporary_strings() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500) + .map(|index| format!("temporary {index}")) + .collect(); + let assignments: String = values + .iter() + .map(|value| format!("s = \"{value}\";\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var s: string; + initial {{ {assignments} $finish(); }} + }} + "# + ); + let all_values: usize = values.iter().map(String::len).sum(); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); + let mut sim = celox::Simulator::builder(&source, "Top").build().unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} diff --git a/docs/.vitepress/components/BenchmarkDashboard.vue b/docs/.vitepress/components/BenchmarkDashboard.vue index 0159ba32fa7..3f11e9db7c3 100644 --- a/docs/.vitepress/components/BenchmarkDashboard.vue +++ b/docs/.vitepress/components/BenchmarkDashboard.vue @@ -485,15 +485,11 @@ const allSeries = computed(() => { if (isRetiredBenchmark(b.name)) continue; const seriesRuntime = runtime(b.name); if (!seriesRuntime) continue; - let benchName = normalizeBenchName(stripPrefix(b.name)); - // Historical Celox tiered points also include background compilation. - // Keep their history, but do not mix them with post-compile throughput. - if ( - seriesRuntime.includes("tiered") && - /^heliodor_(?:linux_boot|suite_.+)_execution$/.test(benchName) - ) { - benchName = benchName.replace(/_execution$/, "_tiered_execution"); - } + const benchName = normalizeBenchName(stripPrefix(b.name)); + // Keep historical phase samples in the archive, but compare tiered + // implementations only by complete workload time. + if (seriesRuntime.includes("tiered") && + !benchName.endsWith("_total") && !benchName.endsWith("_end_to_end")) continue; // Hosted runners hand out different CPU models between runs, so one // backend is one series per CPU. Merging them would read as a // regression whenever the runner happens to change model. @@ -824,17 +820,17 @@ onBeforeUnmount(() => {

Synchronous runs finish compilation before simulation begins. Tiered runs start on the interpreter (Celox) or Cranelift (Veryl-CC), then switch to - compiled code when it is ready. Startup measures time until simulation - begins; end-to-end measures time through Linux boot completion. Both - start before design analysis. Each Veryl-CC run uses an empty C compilation + compiled code when it is ready. Tiered charts show the complete interval + from before design analysis through Linux boot completion, including + compilation while simulation is running. Each Veryl-CC run uses an empty C compilation cache. Building the benchmark executables is excluded. Execution time includes the testbench for both simulators.

- Fixed self-checking workloads, with compilation, execution and total time - shown separately. Each point is the median of three fresh processes. - Execution includes resets, stimulus and assertions. Different workload + Fixed self-checking workloads, compared by total process time including + compilation, resets, stimulus and assertions. Each point is the median + of three fresh processes. Different workload contracts and host architectures have separate charts. No SV frontend comparison is implied by the Veryl results.

diff --git a/docs/benchmarks/collection.md b/docs/benchmarks/collection.md index f6ca6090b50..0f59df1700e 100644 --- a/docs/benchmarks/collection.md +++ b/docs/benchmarks/collection.md @@ -63,8 +63,9 @@ Resets, stimulus and assertions are included in execution time. Every measured process must complete the entire fixed workload and print its completion marker. Each simulator runs three fresh processes sequentially on the same host. The primary comparison is **Celox tiered versus Veryl simulator tiered**, with the -same DUT and TB bytes. Celox starts in its interpreter and promotes to native -code (O2); Veryl starts in Cranelift with asynchronous C compilation enabled. +same DUT and TB bytes. Celox lowers both DUT and TB to the shared SIR pipeline, +starts execution in its interpreter and promotes to native code (O2). Veryl +starts in Cranelift with asynchronous C compilation enabled. Completing before promotion is valid; dispatch/promotion statistics are retained. Both use one simulation thread; compiler parallelism follows each implementation's defaults within the same host CPU allocation. @@ -72,8 +73,9 @@ defaults within the same host CPU allocation. The dashboard's **total** is the median process wall time, from launching the runner through its exit, including startup and shutdown. CLI binary builds and source preparation happen before measurement. The internal compilation/startup -and execution intervals are supplementary: background compilation overlaps -execution, so those intervals do not represent isolated compiler cost or warmed +and execution intervals remain in diagnostic logs and are not published as +comparison charts: background compilation overlaps execution, so those intervals +do not represent isolated compiler cost or warmed throughput. Every process gets a new empty Veryl AOT cache; Celox's build cache and waveform output are disabled. This `cold-tiered-process-v1` contract starts new charts, separate from the old native-only internal-timing series. diff --git a/docs/benchmarks/heliodor.md b/docs/benchmarks/heliodor.md index bacadc571ec..0eb6591f846 100644 --- a/docs/benchmarks/heliodor.md +++ b/docs/benchmarks/heliodor.md @@ -24,10 +24,9 @@ The benchmark separates three questions: while compilation overlaps simulation? Execution time includes the testbench for both simulators. -Tiered results have separate charts for startup until simulation begins, execution -with background compilation, and total time through Linux completion. The tiered -execution interval includes time on the initial backend and must not be read as -compiled-code throughput. Veryl-CC may finish on Cranelift before C compilation +Tiered charts compare only total time through Linux completion, including +startup and background compilation. Startup and execution intervals remain in +the diagnostic logs; neither is a separate tiered performance score. Veryl-CC may finish on Cranelift before C compilation completes; these runs remain valid tiered measurements. Startup and total time begin before design analysis; source-file loading and building the benchmark executables with Cargo are excluded. @@ -43,7 +42,7 @@ A run is accepted only when it: - uses the pinned Heliodor and workload revisions; - reaches the configured Linux completion marker; -- records compilation and execution separately; +- records total completion time, retaining timing details for diagnosis; - compares runners built from the intended Celox and Veryl revisions; - preserves the logs needed to diagnose a timeout or semantic mismatch; - proves that Celox tiered promoted and executed at least one generated-code diff --git a/docs/benchmarks/index.md b/docs/benchmarks/index.md index a1fefb0b614..4480f802180 100644 --- a/docs/benchmarks/index.md +++ b/docs/benchmarks/index.md @@ -53,8 +53,8 @@ publication preserves both sets of results. Only `master` publishes history. Heliodor uses an additional fixed-input acceptance workload. Its methodology is described in [Heliodor Linux Benchmark](./heliodor.md). The dashboard compares -the native backend with synchronous Veryl-CC, and shows startup and end-to-end -time separately for Celox and Veryl-CC tiered execution. Standalone Cranelift boot +the native backend with synchronous Veryl-CC, and compares Celox and Veryl-CC +tiered execution by total time through completion, including compilation. Standalone Cranelift boot results are excluded because their much longer runtime makes this chart ineffective for that comparison. Heliodor charts are separated by CPU architecture because results from different diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index 9a414b2ff7c..ccb54714eb3 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -266,6 +266,30 @@ A running simulator retains the elaborated design, source lookup, runtime schema bound testbench bytecode, and compiled backend. The backend owns the finalized layout. Frontend and optimizer state are discarded after compilation. +Veryl testbench expressions and resumable processes lower to SIR before +optimization and state layout, using the same process builder and code-generation +backends as SystemVerilog. Integer operations, including wide values, use normal +SIR instruction selection. Strings and floating-point operations use the shared +heap and numeric ABI. There is no separate testbench VM, assembler or Cranelift +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. 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 The Rust `celox` crate is a facade over the compiler and runtime components. The diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 304d2ff25a1..02e4698d614 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -189,7 +189,7 @@ for. | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | | `celox-heap` | Dynamic values referenced by handles from state memory, and their collection | Root discovery, layouts, or scheduling | -| `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | +| `celox-testbench` | Source-independent testbench contracts, values and expression lowering to shared SIR | Veryl AST traversal or simulator memory ownership | | `celox-runtime` | Events, timed scheduling, VCD output, testbench execution, and backend contracts | Frontend, SIR optimization, or concrete backend internals | | `celox` | Public API, compilation orchestration, and backend selection | New reusable compiler algorithms | diff --git a/scripts/convert-heliodor-bench.mjs b/scripts/convert-heliodor-bench.mjs index de04ee720de..9a4de319a7c 100644 --- a/scripts/convert-heliodor-bench.mjs +++ b/scripts/convert-heliodor-bench.mjs @@ -118,7 +118,7 @@ function convertPartial() { if (row.runner.endsWith("-tiered")) { const total = ns(row, "reported_elapsed_ns"); if (compile + execute > total) throw new Error(`${key}: startup and execution exceed total`); - return [milliseconds(`${base}_startup`, compile), milliseconds(`${base}_execution`, execute), milliseconds(`${base}_end_to_end`, total)]; + return [milliseconds(`${base}_end_to_end`, total)]; } const metrics = [milliseconds(`${base}_compilation`, compile), milliseconds(`${base}_execution`, execute)]; if (row.runner === "celox" && arch === "x86_64") { @@ -216,11 +216,6 @@ function convertResults(rows, arm64Rows) { } results.push( milliseconds(`heliodor-${platform}/heliodor_linux_boot_end_to_end`, total), - milliseconds(`heliodor-${platform}/heliodor_linux_boot_startup`, startup), - milliseconds( - `heliodor-${platform}/heliodor_linux_boot_execution`, - execution, - ), ); } diff --git a/scripts/publish-collection-bench.mjs b/scripts/publish-collection-bench.mjs index b397a4294ce..63f867658cd 100644 --- a/scripts/publish-collection-bench.mjs +++ b/scripts/publish-collection-bench.mjs @@ -48,7 +48,7 @@ export function metrics(report) { testbench: result.testbench, testbenchSha256: result.testbenchSha256, workUnits: result.workUnits, stateModel: result.stateModel, optimization: result.optimization, threads: result.threads }; const id = createHash("sha256").update(JSON.stringify(contract)).digest("hex").slice(0, 12); - return [["compilation", "compileNs"], ["execution", "executeNs"], ["total", "processNs"]].map(([phase, field]) => { + return [["total", "processNs"]].map(([phase, field]) => { const values = result.samples.map(s => s[field]).sort((a, b) => a - b); return { name: `collection-${result.runner}/collection_${result.circuit}_${id}_${report.host.arch}_${phase}`, unit: "ns", value: values[1], range: `${values[0]}–${values[2]}`, diff --git a/scripts/publish-collection-bench.test.mjs b/scripts/publish-collection-bench.test.mjs index d6b3ceaf40a..6b1985906ee 100644 --- a/scripts/publish-collection-bench.test.mjs +++ b/scripts/publish-collection-bench.test.mjs @@ -19,13 +19,14 @@ function report() { test("publish medians only and separate every measurement contract", () => { const input = report(); const benches = metrics(input); - assert.deepEqual(benches.map(b => b.value), [20, 40, 80, 20, 40, 80]); + assert.deepEqual(benches.map(b => b.value), [80, 80]); assert.equal(benches[0].unit, "ns"); + assert.ok(benches.every(b => b.name.endsWith("_total"))); assert.equal(JSON.parse(benches[0].extra).frontend, "veryl"); input.results.forEach(r => r.testbenchSha256 = "c".repeat(64)); assert.notEqual(metrics(input)[0].name, benches[0].name); input.host.arch = "arm64"; - assert.match(metrics(input)[0].name, /_arm64_compilation$/); + assert.match(metrics(input)[0].name, /_arm64_total$/); }); test("qualification, failures, partial samples and altered runner contracts cannot publish", () => { diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index f1e67d56bca..6d579c650bc 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -26,16 +26,16 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen - celox-testbench celox-sir celox-state-layout celox-slt celox-backend-cranelift celox-backend-wasm celox-frontend-core - celox-runtime celox-sir-opt celox-backend-x86 + celox-testbench + celox-runtime celox-backend-arm64 celox-frontend-sv celox-frontend-veryl diff --git a/scripts/publish-heliodor-bench.test.mjs b/scripts/publish-heliodor-bench.test.mjs index 48eab51d1d7..c690b01a858 100644 --- a/scripts/publish-heliodor-bench.test.mjs +++ b/scripts/publish-heliodor-bench.test.mjs @@ -45,17 +45,27 @@ test("publishes each successful backend without requiring comparison partners", for (const [runner, platform, count] of [ ["celox", `native-${arch}`, arch === "x86_64" ? 3 : 2], ["veryl-cc-sync", `veryl-cc-${arch}`, 2], - ["celox-tiered", arch === "x86_64" ? "celox-tiered" : "celox-tiered-aarch64", 3], - ["veryl-cc-tiered", `veryl-tiered-${arch}`, 3], + ["celox-tiered", arch === "x86_64" ? "celox-tiered" : "celox-tiered-aarch64", 1], + ["veryl-cc-tiered", `veryl-tiered-${arch}`, 1], ["celox-parallel", `native-parallel-${arch}`, 2], ]) { const result = convert(row(runner), arch); assert.equal(result.length, count); - assert.equal( - result.find((x) => x.name === `heliodor-${platform}/heliodor_suite_linux_boot_execution`) - .value, - 2, - ); + if (runner.endsWith("-tiered")) { + assert.equal(result[0].name, `heliodor-${platform}/heliodor_suite_linux_boot_end_to_end`); + assert.equal(result[0].value, 4); + } else { + assert.equal( + result.find((x) => x.name === `heliodor-${platform}/heliodor_suite_linux_boot_execution`) + .value, + 2, + ); + assert.equal( + result.find((x) => x.name === `heliodor-${platform}/heliodor_suite_linux_boot_compilation`) + .value, + 1, + ); + } assert.deepEqual(convert(row(runner, { success: false }), arch), []); } } diff --git a/scripts/tests/convert-heliodor-bench.sh b/scripts/tests/convert-heliodor-bench.sh index cd2752af790..9843e277217 100644 --- a/scripts/tests/convert-heliodor-bench.sh +++ b/scripts/tests/convert-heliodor-bench.sh @@ -41,8 +41,6 @@ if (values["heliodor-celox-jit/heliodor_suite_linux_boot_execution"] !== 2) proc if (values["heliodor-celox-total/heliodor_suite_linux_boot_execution"] !== 2.5) process.exit(1); if (values["heliodor-veryl/heliodor_suite_linux_boot_execution"] !== 4) process.exit(1); if (values["heliodor-celox-tiered/heliodor_suite_linux_boot_end_to_end"] !== 5.5) process.exit(1); -if (values["heliodor-celox-tiered/heliodor_suite_linux_boot_startup"] !== 0.5) process.exit(1); -if (values["heliodor-celox-tiered/heliodor_suite_linux_boot_execution"] !== 5) process.exit(1); ' "$TMP/results.json" node -e ' @@ -61,16 +59,11 @@ if (values.some((entry) => entry.name.includes("celox-tiered"))) process.exit(1) node -e ' const fs = require("fs"); const values = Object.fromEntries(JSON.parse(fs.readFileSync(process.argv[1], "utf8")).map((x) => [x.name, x.value])); -if (Object.keys(values).length !== 25) process.exit(1); +if (Object.keys(values).length !== 17) process.exit(1); +if (Object.keys(values).some(name => name.includes("tiered") && !name.endsWith("_end_to_end"))) process.exit(1); const expected = { - "heliodor-veryl-tiered-x86_64/heliodor_suite_linux_boot_startup": 1.5, - "heliodor-veryl-tiered-x86_64/heliodor_suite_linux_boot_execution": 8, "heliodor-veryl-tiered-x86_64/heliodor_suite_linux_boot_end_to_end": 9.5, - "heliodor-celox-tiered-aarch64/heliodor_suite_linux_boot_startup": 3.5, - "heliodor-celox-tiered-aarch64/heliodor_suite_linux_boot_execution": 13, "heliodor-celox-tiered-aarch64/heliodor_suite_linux_boot_end_to_end": 16.5, - "heliodor-veryl-tiered-aarch64/heliodor_suite_linux_boot_startup": 4.5, - "heliodor-veryl-tiered-aarch64/heliodor_suite_linux_boot_execution": 16, "heliodor-veryl-tiered-aarch64/heliodor_suite_linux_boot_end_to_end": 20.5, "heliodor-native-x86_64/heliodor_suite_linux_boot_compilation": 1, "heliodor-native-x86_64/heliodor_suite_linux_boot_execution": 2.5, @@ -130,7 +123,7 @@ node "$ROOT/scripts/convert-heliodor-bench.mjs" "$TMP/suite-results.tsv" "$TMP/s node - "$TMP/suite.json" <<'JS' const assert = require("node:assert/strict"); const rows = require(process.argv[2]); -assert.equal(rows.length, 25 * 4); +assert.equal(rows.length, 17 * 4); assert.equal(new Set(rows.map(row => row.name)).size, rows.length); assert.equal(rows.find(row => row.name === "heliodor-native-aarch64/heliodor_suite_71_smp_linux_boot_4hart_execution").value, 8); JS