From e24dae3def9786ce3a4678f63520ee409eb8a0f5 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 07:38:59 +0900 Subject: [PATCH 01/72] feat(veryl)!: run `#[test]` initial blocks as process kernels The initial blocks of a Veryl `#[test]` module are compiled into process kernels and run by the timed scheduler instead of the testbench bytecode interpreter, which stays as a fallback behind `SimulatorBuilder::testbench_kernels(false)`. The frontend lowers each block with the procedural expression lowering over the elaborated instance's stable state. Loop counters and bounds live in state so a wait inside a loop can suspend; each block owns a copy of the function-local variables; a hierarchical reference is a synthetic variable addressing the child's state. Clock waits become clock waits with fused ticks, `rst.assert` a clock wait with a release, random numbers and component methods host requests served through scratch state, and a read of design state after a store settles the combinational logic first through the new `Settle` status. The scheduler applies releases as events of their domain, fires the falling and rising edges of a time together after the processes ran, treats an edge from an unknown four-state value as an edge, and stops resuming processes once the tick budget is spent. Hash maps embedded in native images serialize in key order so a build cache round trip reproduces the image. BREAKING CHANGE: `%t` in a testbench and the time a component's finish hook observes are the scheduler time, in which the default process clock has period 2; single-process testbenches previously saw the tick count. --- crates/celox-design/src/lib.rs | 239 +- crates/celox-frontend-core/src/process.rs | 190 +- crates/celox-frontend-core/src/sdk.rs | 11 +- .../celox-frontend-core/src/shared/lookup.rs | 2 +- crates/celox-frontend-sv/src/lowering.rs | 9 +- crates/celox-frontend-sv/src/lowering/comb.rs | 1 + crates/celox-frontend-sv/src/lowering/ff.rs | 1 + crates/celox-frontend-veryl/src/artifact.rs | 13 +- crates/celox-frontend-veryl/src/config.rs | 5 + crates/celox-frontend-veryl/src/hierarchy.rs | 5 +- .../celox-frontend-veryl/src/lowering/ff.rs | 93 +- .../src/lowering/ff/expression.rs | 46 +- .../src/lowering/logic_tree/effect.rs | 11 +- .../celox-frontend-veryl/src/lowering/mod.rs | 1 + .../src/lowering/process.rs | 2285 +++++++++++++++++ crates/celox-frontend-veryl/src/module.rs | 2 +- crates/celox-frontend-veryl/src/schedule.rs | 17 +- crates/celox-frontend-veryl/src/source.rs | 3 + crates/celox-frontend-veryl/src/testbench.rs | 12 +- crates/celox-runtime/src/lib.rs | 4 +- crates/celox-runtime/src/simulation.rs | 478 +++- crates/celox-state-layout/src/lib.rs | 9 +- crates/celox-vpi/src/lib.rs | 1 + crates/celox/examples/sv_tests.rs | 3 +- crates/celox/src/backend/native/backend.rs | 15 + .../celox/src/backend/native/runtime_image.rs | 1 + crates/celox/src/component.rs | 23 +- crates/celox/src/ir.rs | 12 +- crates/celox/src/simulation.rs | 67 +- crates/celox/src/simulator.rs | 50 + crates/celox/src/simulator/builder.rs | 36 + crates/celox/src/simulator/state_file.rs | 1 + crates/celox/src/testbench.rs | 46 +- crates/celox/src/testbench/kernels.rs | 385 +++ crates/celox/src/testbench_compile.rs | 6 +- crates/celox/tests/component_method.rs | 45 +- .../celox/tests/concurrent_initial_runtime.rs | 2 +- crates/celox/tests/error_detection.rs | 20 +- crates/celox/tests/native_testbench.rs | 8 +- docs/internals/architecture.md | 26 +- docs/internals/compiler-crate-architecture.md | 9 +- 41 files changed, 3855 insertions(+), 338 deletions(-) create mode 100644 crates/celox-frontend-veryl/src/lowering/process.rs create mode 100644 crates/celox/src/testbench/kernels.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index e0b70d95395..39fb38f6782 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -61,6 +61,17 @@ pub enum RuntimeEventKind { AssertFatal, /// `$finish` executed by the design (IEEE 1800-2023 20.2). Finish, + /// An assertion of a testbench process that held, reported so a test + /// run can list every assertion it checked. + AssertPass, +} + +/// Where a runtime event site is written, for test reports. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventLocation { + pub file: String, + pub line: u32, + pub column: u32, } /// How a runtime event site sizes its formatted arguments. @@ -84,6 +95,9 @@ pub struct RuntimeEventSite { pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, + /// The source position of a testbench assertion, for test reports. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, } /// A function in the host's C ABI that the design calls, such as a @@ -230,8 +244,18 @@ pub enum ProcessStatus { /// [`ProcessSlots::clock`]. The runtime generates those edges: the clock /// toggles every half period from the first wait on it, and the process /// resumes one period after the last counted edge, before the edge that - /// follows. + /// follows. [`ProcessSlots::release`] names a write the runtime makes + /// when the wait is over, even if the process is not resumed. WaitClock, + /// The process needs the host: [`ProcessSlots::delay`] holds the index + /// of the [`HostRequest`] among the process's requests. The host serves + /// it through the process's scratch state and resumes the process at + /// once. + Host, + /// The process stored to design state and continues with a read of it: + /// the runtime settles the combinational logic and resumes the process + /// at once, before any other process runs. + Settle, } impl ProcessStatus { @@ -245,6 +269,8 @@ impl ProcessStatus { Self::Wait => 4, Self::Pending => 5, Self::WaitClock => 6, + Self::Host => 7, + Self::Settle => 8, } } @@ -256,6 +282,8 @@ impl ProcessStatus { 4 => Some(Self::Wait), 5 => Some(Self::Pending), 6 => Some(Self::WaitClock), + 7 => Some(Self::Host), + 8 => Some(Self::Settle), _ => None, } } @@ -279,44 +307,213 @@ impl ProcessClock { } } +/// A write the runtime makes for a process when a clock wait is over, such +/// as the release of a reset the process asserted for some cycles. It is +/// made even when the process is not resumed afterwards. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessRelease { + pub signal: A, + pub value: u64, + /// The clock the released signal is a reset of, when the wait counted + /// its edges: a host component in that clock domain takes reset cycles + /// while the signal is held. + pub clock: Option, +} + +impl ProcessRelease { + pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessRelease { + ProcessRelease { + signal: map(self.signal), + value: self.value, + clock: self.clock.map(&mut map), + } + } +} + +/// A value a host request passes or returns through the process's scratch +/// state. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HostValue { + pub signal: A, + pub width: usize, + pub signed: bool, + /// The value is the bytes of a string, most significant first. + pub is_string: bool, +} + +impl HostValue { + pub fn map(self, map: impl FnOnce(A) -> B) -> HostValue { + HostValue { + signal: map(self.signal), + width: self.width, + signed: self.signed, + is_string: self.is_string, + } + } +} + +/// What a process asks the host for with [`ProcessStatus::Host`]. Inputs are +/// read from, and results written to, scratch state of the process. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum HostRequest { + /// Seed the random stream `handle` from `value`. + RandomSeed { handle: String, value: HostValue }, + /// A random value of the result's width from the stream `handle`. + RandomGet { + handle: String, + result: HostValue, + }, + /// A random value between `min` and `max` from the stream `handle`. + RandomGetRange { + handle: String, + min: HostValue, + max: HostValue, + result: HostValue, + }, + /// The seed of the stream `handle`. + RandomGetSeed { + handle: String, + result: HostValue, + }, + /// Call `method` of the external component `instance` with `args`. + Component { + instance: String, + method: String, + args: Vec>, + result: Option>, + /// The declared width of the result, which the component must + /// return exactly. + declared_width: Option, + /// Whether a result wider than 64 bits is an error, because the + /// expression form of the call carries at most 64 bits. + strict: bool, + }, +} + +impl HostRequest { + pub fn map(self, mut map: impl FnMut(A) -> B) -> HostRequest { + match self { + Self::RandomSeed { handle, value } => HostRequest::RandomSeed { + handle, + value: value.map(&mut map), + }, + Self::RandomGet { handle, result } => HostRequest::RandomGet { + handle, + result: result.map(&mut map), + }, + Self::RandomGetRange { + handle, + min, + max, + result, + } => HostRequest::RandomGetRange { + handle, + min: min.map(&mut map), + max: max.map(&mut map), + result: result.map(&mut map), + }, + Self::RandomGetSeed { handle, result } => HostRequest::RandomGetSeed { + handle, + result: result.map(&mut map), + }, + Self::Component { + instance, + method, + args, + result, + declared_width, + strict, + } => HostRequest::Component { + instance, + method, + args: args.into_iter().map(|arg| arg.map(&mut map)).collect(), + result: result.map(|result| result.map(&mut map)), + declared_width, + strict, + }, + } + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to /// find where it stopped; before returning it stores the next resume point, /// a [`ProcessStatus`] code in `status` and, for a delay or a clock wait, the /// number of time units or edges in `delay`; a clock wait also stores the -/// index into `clocks` in `clock`. The slots are ordinary two-state state -/// objects, so checkpoints capture a suspended process. +/// index into `clocks` in `clock` and, when the wait ends with a write, one +/// plus the index into `releases` in `release`; a host request stores its +/// index into `host_requests` in `delay`. The slots are ordinary two-state +/// state objects, so checkpoints capture a suspended process. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { pub resume: A, pub status: A, pub delay: A, pub clock: A, + pub release: A, /// The clocks the process may wait on, in the order its kernel numbers /// them. #[serde(default = "Vec::new")] pub clocks: Vec>, + /// The writes a clock wait of the process may end with. + #[serde(default = "Vec::new")] + pub releases: Vec>, + /// The host requests the process may make. + #[serde(default = "Vec::new")] + pub host_requests: Vec>, } impl ProcessSlots { + /// Slots for a process without clocks, releases or host requests. + pub fn new(resume: A, status: A, delay: A, clock: A, release: A) -> Self { + Self { + resume, + status, + delay, + clock, + release, + clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), + } + } + pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { resume: map(self.resume), status: map(self.status), delay: map(self.delay), clock: map(self.clock), + release: map(self.release), clocks: self .clocks .into_iter() .map(|clock| clock.map(&mut map)) .collect(), + releases: self + .releases + .into_iter() + .map(|release| release.map(&mut map)) + .collect(), + host_requests: self + .host_requests + .into_iter() + .map(|request| request.map(&mut map)) + .collect(), } } /// The control slots, without the clock signals. pub fn iter(&self) -> impl Iterator { - [&self.resume, &self.status, &self.delay, &self.clock].into_iter() + [ + &self.resume, + &self.status, + &self.delay, + &self.clock, + &self.release, + ] + .into_iter() } } @@ -326,6 +523,36 @@ pub const PROCESS_STATUS_WIDTH: usize = 8; pub const PROCESS_DELAY_WIDTH: usize = 64; /// Width of [`ProcessSlots::clock`]. pub const PROCESS_CLOCK_WIDTH: usize = 32; +/// Width of [`ProcessSlots::release`]. +pub const PROCESS_RELEASE_WIDTH: usize = 32; + +/// Serialize hash maps and sets in key order, so an artifact that embeds +/// them has one byte representation however the map was built. +pub mod serde_sorted { + use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; + use serde::{Serialize, Serializer}; + + pub fn map(map: &HashMap, serializer: S) -> Result + where + K: Ord + Serialize, + V: Serialize, + S: Serializer, + { + let mut entries: Vec<(&K, &V)> = map.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + serializer.collect_map(entries) + } + + pub fn set(set: &HashSet, serializer: S) -> Result + where + T: Ord + Serialize, + S: Serializer, + { + let mut items: Vec<&T> = set.iter().collect(); + items.sort(); + serializer.collect_seq(items) + } +} /// Source-independent runtime diagnostics and observable event descriptions. #[derive(Clone, Debug)] @@ -375,12 +602,14 @@ impl Default for RuntimeSchema { ))] pub struct EventTopology { /// Alias event address to the canonical event-domain address. + #[serde(serialize_with = "crate::serde_sorted::map")] pub aliases: HashMap, /// Canonical event domains in evaluation order. pub ordered_events: Vec, /// Canonical clocks whose value may be changed by another event domain. pub cascaded_events: BTreeSet, /// Canonical asynchronous/synchronous reset to its canonical clock. + #[serde(serialize_with = "crate::serde_sorted::map")] pub reset_clocks: HashMap, } @@ -420,6 +649,7 @@ impl EventTopology { deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord" ))] pub struct ElaboratedDesign { + #[serde(serialize_with = "crate::serde_sorted::map")] pub state_objects: HashMap, pub events: EventTopology, pub initial_state: Vec>, @@ -829,6 +1059,7 @@ mod tests { template: Some("failed".to_string()), sizing: DisplaySizing::Minimal, scope: None, + location: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index c1c2a5abc17..a79915e4b76 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -6,18 +6,19 @@ //! suspension stores the next resume point, a [`ProcessStatus`] and its wait //! amount into the process's control slots and returns to the runtime. //! -//! A delay resumes after a time. An event or level wait resumes at a check -//! the kernel runs itself: the runtime resumes the process whenever the -//! state may have changed, and the kernel continues past the wait or -//! reports that it is still pending. +//! A delay resumes after a time, a clock wait after a number of edges of a +//! process clock, and a host request once the host has served it. An event +//! or level wait resumes at a check the kernel runs itself: the runtime +//! resumes the process whenever the state may have changed, and the kernel +//! continues past the wait or reports that it is still pending. //! //! The builder is source-independent: a frontend lowers statements and //! expressions into [`ProcessKernelBuilder::builder`] and calls the //! suspension methods where the source suspends. use celox_design::{ - PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, - RegionedVarAddrBase, STABLE_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, + ProcessSlots, ProcessStatus, RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRSwitchCase, @@ -45,45 +46,101 @@ pub enum ProcessKernelError { TooManySuspensions, #[error("a process waits on clock {0}, which its slots do not list")] UnknownClock(u32), + #[error("a process ends a wait with release {0}, which its slots do not list")] + UnknownRelease(u32), + #[error("a process makes host request {0}, which its slots do not list")] + UnknownHostRequest(u32), } -/// Builder of one process kernel. -pub struct ProcessKernelBuilder { - builder: SIRBuilder, - slots: ProcessSlots, +/// The stable-region address of a control slot. +pub fn stable_slot(var_id: SourceVarId) -> RegionedSourceAddr { + RegionedVarAddrBase { + region: STABLE_REGION, + var_id, + } +} + +/// Builder of one process kernel, addressed like its slots: `A` is the +/// stable-region address type of the kernel. +pub struct ProcessKernelBuilder { + builder: SIRBuilder, + resume: A, + status: A, + delay: A, + clock: A, + release: A, + clock_count: usize, + release_count: usize, + host_request_count: usize, /// The block each resume point continues in; point 0 is the start. resume_blocks: Vec, } -impl ProcessKernelBuilder { - /// Start a kernel. The builder is positioned at the start of the - /// process body. +impl ProcessKernelBuilder { + /// Start a kernel whose slots are module variables. The builder is + /// positioned at the start of the process body. pub fn new(slots: ProcessSlots) -> Self { + Self::with_addresses(slots.map(stable_slot)) + } +} + +impl ProcessKernelBuilder { + /// Start a kernel whose slots are the given stable addresses. The + /// builder is positioned at the start of the process body. + pub fn with_addresses(slots: ProcessSlots) -> Self { let builder = SIRBuilder::new(); let start = builder.current_block(); Self { builder, - slots, + resume: slots.resume, + status: slots.status, + delay: slots.delay, + clock: slots.clock, + release: slots.release, + clock_count: slots.clocks.len(), + release_count: slots.releases.len(), + host_request_count: slots.host_requests.len(), resume_blocks: vec![start], } } /// The SIR builder positioned where the process continues. After - /// [`Self::finish`] no block is open until the caller switches to one. - pub fn builder(&mut self) -> &mut SIRBuilder { + /// [`Self::build`] no block is open until the caller switches to one. + pub fn builder(&mut self) -> &mut SIRBuilder { &mut self.builder } - fn store_constant(&mut self, slot: SourceVarId, width: usize, value: u64) { + /// Register a further clock the process waits on, for a frontend that + /// finds the clocks while it lowers the body; returns its index. The + /// slots the frontend emits must list it at that index. + pub fn add_clock(&mut self) -> u32 { + self.clock_count += 1; + self.clock_count as u32 - 1 + } + + /// Register a further release a wait may end with; see + /// [`Self::add_clock`]. + pub fn add_release(&mut self) -> u32 { + self.release_count += 1; + self.release_count as u32 - 1 + } + + /// Register a further host request; see [`Self::add_clock`]. + pub fn add_host_request(&mut self) -> u32 { + self.host_request_count += 1; + self.host_request_count as u32 - 1 + } + + fn store_constant(&mut self, slot: A, width: usize, value: u64) { let register = self.builder.alloc_bit(width, false); self.builder .emit(SIRInstruction::Imm(register, SIRValue::new(value))); self.store(slot, width, register); } - fn store(&mut self, slot: SourceVarId, width: usize, value: RegisterId) { + fn store(&mut self, slot: A, width: usize, value: RegisterId) { self.builder.emit(SIRInstruction::Store( - stable(slot), + slot, SIROffset::Static(0), width, value, @@ -95,51 +152,78 @@ impl ProcessKernelBuilder { /// Return to the runtime with `status`, leaving no block open. fn end(&mut self, status: ProcessStatus) { self.store_constant( - self.slots.status, + self.status.clone(), PROCESS_STATUS_WIDTH, u64::from(status.code()), ); self.builder.seal_block(SIRTerminator::Return); } - /// Suspend for the number of time units in `amount`, an unsigned - /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at - /// a new resume point. - pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + /// Store the next resume point and open its block after `end` runs. + fn suspend(&mut self, status: ProcessStatus) -> Result<(), ProcessKernelError> { let point = self.resume_blocks.len(); if point > MAX_PROCESS_SUSPENSIONS { return Err(ProcessKernelError::TooManySuspensions); } - self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); - self.end(ProcessStatus::Delay); + self.store_constant(self.resume.clone(), PROCESS_RESUME_WIDTH, point as u64); + self.end(status); let resume = self.builder.new_block(); self.resume_blocks.push(resume); self.builder.switch_to_block(resume); Ok(()) } + /// Suspend for the number of time units in `amount`, an unsigned + /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at + /// a new resume point. + pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + self.store(self.delay.clone(), PROCESS_DELAY_WIDTH, amount); + self.suspend(ProcessStatus::Delay) + } + /// Suspend until `count` rising edges of the process clock `clock` (an /// index into the slots' clock list) have passed, and continue at a new /// resume point one period after the last of them. `count` is an /// unsigned two-state register of [`PROCESS_DELAY_WIDTH`] bits; a count - /// of zero continues at once. - pub fn wait_clock(&mut self, clock: u32, count: RegisterId) -> Result<(), ProcessKernelError> { - if clock as usize >= self.slots.clocks.len() { + /// of zero continues at once. With `release`, the runtime makes that + /// write of the slots' release list when the wait is over. + pub fn wait_clock( + &mut self, + clock: u32, + count: RegisterId, + release: Option, + ) -> Result<(), ProcessKernelError> { + if clock as usize >= self.clock_count { return Err(ProcessKernelError::UnknownClock(clock)); } - let point = self.resume_blocks.len(); - if point > MAX_PROCESS_SUSPENSIONS { - return Err(ProcessKernelError::TooManySuspensions); + let release = match release { + Some(release) if release as usize >= self.release_count => { + return Err(ProcessKernelError::UnknownRelease(release)); + } + Some(release) => u64::from(release) + 1, + None => 0, + }; + self.store(self.delay.clone(), PROCESS_DELAY_WIDTH, count); + self.store_constant(self.clock.clone(), PROCESS_CLOCK_WIDTH, u64::from(clock)); + self.store_constant(self.release.clone(), PROCESS_RELEASE_WIDTH, release); + self.suspend(ProcessStatus::WaitClock) + } + + /// Ask the host to serve `request` (an index into the slots' request + /// list) and continue at a new resume point once it has. + pub fn host(&mut self, request: u32) -> Result<(), ProcessKernelError> { + if request as usize >= self.host_request_count { + return Err(ProcessKernelError::UnknownHostRequest(request)); } - self.store(self.slots.delay, PROCESS_DELAY_WIDTH, count); - self.store_constant(self.slots.clock, PROCESS_CLOCK_WIDTH, u64::from(clock)); - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); - self.end(ProcessStatus::WaitClock); - let resume = self.builder.new_block(); - self.resume_blocks.push(resume); - self.builder.switch_to_block(resume); - Ok(()) + self.store_constant(self.delay.clone(), PROCESS_DELAY_WIDTH, u64::from(request)); + self.suspend(ProcessStatus::Host) + } + + /// Have the runtime settle the combinational logic, then continue at + /// once. A process stores to design state directly, so a read of a + /// combinational result after such a store needs this first. + pub fn settle(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Settle) } /// Suspend until a condition the kernel evaluates holds, and continue at @@ -148,16 +232,7 @@ impl ProcessKernelBuilder { /// there whenever the state may have changed. Sampling that an edge /// condition compares against is done by the caller before this call. pub fn begin_wait(&mut self) -> Result<(), ProcessKernelError> { - let point = self.resume_blocks.len(); - if point > MAX_PROCESS_SUSPENSIONS { - return Err(ProcessKernelError::TooManySuspensions); - } - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); - self.end(ProcessStatus::Wait); - let resume = self.builder.new_block(); - self.resume_blocks.push(resume); - self.builder.switch_to_block(resume); - Ok(()) + self.suspend(ProcessStatus::Wait) } /// At the resume point of a [`Self::begin_wait`]: continue when @@ -184,7 +259,7 @@ impl ProcessKernelBuilder { } /// Complete the kernel. If a block is still open, the process ends there. - pub fn build(mut self) -> ExecutionUnit { + pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { self.end(ProcessStatus::Done); } @@ -199,7 +274,7 @@ impl ProcessKernelBuilder { let resume = self.builder.alloc_bit(PROCESS_RESUME_WIDTH, false); self.builder.emit(SIRInstruction::Load( resume, - stable(self.slots.resume), + self.resume.clone(), SIROffset::Static(0), PROCESS_RESUME_WIDTH, )); @@ -208,7 +283,7 @@ impl ProcessKernelBuilder { .chunks(1 << SWITCH_BITS) .map(<[BlockId]>::to_vec) .collect::>(); - let byte = |builder: &mut SIRBuilder, lsb: usize| { + let byte = |builder: &mut SIRBuilder, lsb: usize| { let byte = builder.alloc_bit(SWITCH_BITS, false); builder.emit(SIRInstruction::Slice(byte, resume, lsb, SWITCH_BITS)); byte @@ -260,13 +335,6 @@ impl ProcessKernelBuilder { } } -fn stable(var_id: SourceVarId) -> RegionedSourceAddr { - RegionedSourceAddr { - region: STABLE_REGION, - var_id, - } -} - fn switch_cases(targets: &[BlockId]) -> Vec { targets .iter() diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 3f07238997f..ba236bee79c 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -2,9 +2,9 @@ use celox_design::{ BinaryOp, BitAccess, DomainKind, InitialStateData, InitialStateValue, ModuleId, - PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, - ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, - VariableMetadata, WORKING_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, + PortTypeKind, ProcessClock, ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, + UnaryOp, VarAtomBase, VariableMetadata, WORKING_REGION, }; use celox_frontend_sdk::{ ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice, @@ -1143,7 +1143,7 @@ fn lower_statements( kernel.builder(), &mut cache, )?; - kernel.wait_clock(index as u32, count)?; + kernel.wait_clock(index as u32, count, None)?; } Statement::Finish => { kernel.finish(); @@ -1199,6 +1199,9 @@ fn lower_processes( status: declare(name("status"), PROCESS_STATUS_WIDTH), delay: declare(name("delay"), PROCESS_DELAY_WIDTH), clock: declare(name("clock"), PROCESS_CLOCK_WIDTH), + release: declare(name("release"), PROCESS_RELEASE_WIDTH), + releases: Vec::new(), + host_requests: Vec::new(), clocks: clocks .iter() .map(|clock| { diff --git a/crates/celox-frontend-core/src/shared/lookup.rs b/crates/celox-frontend-core/src/shared/lookup.rs index 89d99c7e8c8..30be26406bc 100644 --- a/crates/celox-frontend-core/src/shared/lookup.rs +++ b/crates/celox-frontend-core/src/shared/lookup.rs @@ -89,7 +89,7 @@ impl fmt::Debug for VariableInfo { } } -#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct InstancePath(pub Vec<(String, usize)>); /// Source-language-independent lookup retained for diagnostics and public paths. diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 7d0d21a204d..ce12223f029 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -12,9 +12,9 @@ use std::path::Path; use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, InitialStateData, InitialStateValue, ModuleId, PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, - PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, - RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, - WORKING_REGION, + PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, + RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, + VarAtomBase, WORKING_REGION, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -2010,7 +2010,10 @@ fn lower_initial_processes( status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), clock: declare("clock", PROCESS_CLOCK_WIDTH), + release: declare("release", PROCESS_RELEASE_WIDTH), clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), } }) .collect(); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index c24a51c2a5a..40c9886aaf4 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3075,6 +3075,7 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths, arg_signed, arg_is_string, + location: None, }); let mut preceding_writes = Vec::new(); for (id, range) in store.iter() { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 2dae54e886e..3c82d1e3fdf 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1740,6 +1740,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_widths, arg_signed, arg_is_string, + location: None, }); self.b.emit(SIRInstruction::RuntimeEvent { site_id, diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index ff01fb1322d..35b09c59c27 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -27,6 +27,10 @@ pub struct VerylSymbolicRtl<'a> { pub symbolic: crate::symbolic::artifact::SymbolicRtl, pub module_ir: HashMap, pub source_id_maps: HashMap>, + /// Hidden state of each module's `initial` blocks when they are + /// compiled into process kernels. + pub process_storage: + HashMap, } #[derive(Clone)] @@ -291,6 +295,7 @@ pub(crate) fn project_module_with_ids( ( crate::symbolic::artifact::SimModule, HashMap, + crate::lowering::process::ModuleProcessStorage, ), ParserError, > { @@ -298,7 +303,7 @@ pub(crate) fn project_module_with_ids( source_variables.sort_unstable_by_key(|(id, _)| **id); let mut source_texts = HashMap::default(); - let variables = source_variables + let mut variables = source_variables .into_iter() .map(|(id, variable)| { let (dimensions, _, _) = bitaccess::get_dimensions_and_strides(ir, *id)?; @@ -347,6 +352,11 @@ pub(crate) fn project_module_with_ids( )) }) .collect::, ParserError>>()?; + let process_storage = if config.testbench_kernels { + crate::lowering::process::declare_storage(ir, &ids, &mut variables)? + } else { + Default::default() + }; let mut arena = SLTNodeArena::new(); let mut cache = HashMap::default(); @@ -488,6 +498,7 @@ pub(crate) fn project_module_with_ids( processes: Vec::new(), }, ids, + process_storage, )) } diff --git a/crates/celox-frontend-veryl/src/config.rs b/crates/celox-frontend-veryl/src/config.rs index cf32adb1e70..0a42506f8a2 100644 --- a/crates/celox-frontend-veryl/src/config.rs +++ b/crates/celox-frontend-veryl/src/config.rs @@ -7,6 +7,9 @@ pub struct BuildConfig { /// Simulation lanes requested for partitioned execution. More than one /// lane also lowers every FF trigger group as independent parts. pub parallel_lanes: u32, + /// Compile the `initial` blocks of a `#[test]` module into process + /// kernels run by the timed scheduler instead of testbench bytecode. + pub testbench_kernels: bool, } impl Default for BuildConfig { @@ -15,6 +18,7 @@ impl Default for BuildConfig { clock_type: ClockType::PosEdge, reset_type: ResetType::AsyncLow, parallel_lanes: 1, + testbench_kernels: false, } } } @@ -25,6 +29,7 @@ impl From<&veryl_metadata::Build> for BuildConfig { clock_type: build.clock_type, reset_type: build.reset_type, parallel_lanes: 1, + testbench_kernels: false, } } } diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index b08a5ac7fcf..61e5599a556 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -308,6 +308,7 @@ pub fn parse_ir_with_external_hierarchy<'a>( .collect(), ); } + let mut process_storage = HashMap::default(); for (module_id, mut sim_module) in parsed_modules { let ir_module = module_ir[&module_id]; if let Some(symbols) = &symbols @@ -332,10 +333,11 @@ pub fn parse_ir_with_external_hierarchy<'a>( .collect(); } let id_map = source_id_maps[&module_id].clone(); - let (sim_module, id_map) = + let (sim_module, id_map, storage) = project_module_with_ids(&sim_module, ir_module, config, id_map, &source_id_maps)?; modules.insert(module_id, sim_module); source_id_maps.insert(module_id, id_map); + process_storage.insert(module_id, storage); } Ok(VerylSymbolicRtl { @@ -346,6 +348,7 @@ pub fn parse_ir_with_external_hierarchy<'a>( }, module_ir, source_id_maps, + process_storage, }) } diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 8bed13de01a..57159445c25 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -21,7 +21,7 @@ use num_traits::{ToPrimitive, Zero}; use veryl_analyzer::ir::{ AssertKind, CaseStatement, Expression, FfDeclaration, FfReset, ForBound, ForRange, ForStatement, IfResetStatement, IfStatement, Module, Op, Statement, SystemFunctionCall, - SystemFunctionInput, SystemFunctionKind, TypeKind, VarId, + SystemFunctionInput, SystemFunctionKind, TypeKind, VarId, VarPath, }; use veryl_analyzer::symbol::Affiliation; use veryl_analyzer::value::Value; @@ -340,11 +340,16 @@ mod inline_call; pub enum Domain { Ff, // TODO: add clock + /// A process kernel: blocking statements over stable state only, so + /// every variable, including locals and loop variables, lives in the + /// stable region and survives the kernel's suspensions. + Process, } impl Domain { pub fn region(&self) -> u32 { match self { Domain::Ff => WORKING_REGION, + Domain::Process => STABLE_REGION, } } } @@ -422,10 +427,13 @@ pub struct FfParser<'a> { runtime_error_code_map: Option>, runtime_event_site_base: u32, config: BuildConfig, + /// Hierarchical references a process may make, as synthetic variables + /// of the module (see `lowering::process`). + hierarchical_vars: HashMap<(Vec, VarPath), VarId>, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ControlFlow { +pub(crate) enum ControlFlow { Continue, Break, } @@ -467,9 +475,61 @@ impl<'a> FfParser<'a> { runtime_error_code_map: None, runtime_event_site_base: 0, config, + hierarchical_vars: HashMap::default(), } } + /// Resolve hierarchical references through synthetic variables of the + /// module, keyed by instance path and variable path. + pub(crate) fn with_hierarchical_vars( + mut self, + vars: HashMap<(Vec, VarPath), VarId>, + ) -> Self { + self.hierarchical_vars = vars; + self + } + + /// The synthetic variable of a hierarchical reference. + pub(crate) fn hierarchical_var( + &self, + key: &(Vec, VarPath), + ) -> Option<&VarId> { + self.hierarchical_vars.get(key) + } + + /// Where the runtime event sites this parser registers start. + pub(crate) fn with_runtime_event_site_base(mut self, base: u32) -> Self { + self.runtime_event_site_base = base; + self + } + + /// The runtime event sites registered so far, for annotation. + pub(crate) fn runtime_event_sites_mut(&mut self) -> &mut Vec { + &mut self.runtime_event_sites + } + + /// The value the last expression lowering produced. + pub(crate) fn pop_value(&mut self) -> RegisterId { + self.stack.pop_back().expect("an expression value") + } + + /// Make `value` the value a following store consumes. + pub(crate) fn push_value(&mut self, value: RegisterId) { + self.stack.push_back(value); + } + + /// Forget values cached in registers: after a kernel suspension, no + /// register survives. + pub(crate) fn clear_register_cache(&mut self) { + self.local_let_values.clear(); + self.stack.clear(); + } + + /// The blocks a `break` in the process lowering leaves to. + pub(crate) fn loop_exit_blocks_mut(&mut self) -> &mut Vec { + &mut self.loop_exit_blocks + } + pub fn with_relocated_runtime_ids( mut self, runtime_error_code_map: HashMap, @@ -503,7 +563,7 @@ impl<'a> FfParser<'a> { &self.runtime_event_sites } - fn runtime_error(&mut self, message: impl Into, signals: Vec) -> i64 { + pub(crate) fn runtime_error(&mut self, message: impl Into, signals: Vec) -> i64 { let local_code = self.next_runtime_error_code; self.next_runtime_error_code += 1; let code = self @@ -521,7 +581,7 @@ impl<'a> FfParser<'a> { code } - fn static_string_expr(expr: &Expression) -> Option { + pub(crate) fn static_string_expr(expr: &Expression) -> Option { if !expr.comptime().r#type.is_string() { return None; } @@ -529,7 +589,7 @@ impl<'a> FfParser<'a> { byte_value_to_string(value) } - fn register_runtime_event_site( + pub(crate) fn register_runtime_event_site( &mut self, kind: RuntimeEventKind, args: &[SystemFunctionInput], @@ -564,6 +624,7 @@ impl<'a> FfParser<'a> { .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, }; let id = self .runtime_event_site_base @@ -573,7 +634,7 @@ impl<'a> FfParser<'a> { id } - fn parse_runtime_event_expression( + pub(crate) fn parse_runtime_event_expression( &mut self, expr: &Expression, targets: &mut Vec>, @@ -601,7 +662,7 @@ impl<'a> FfParser<'a> { result } - fn emit_runtime_event( + pub(crate) fn emit_runtime_event( &mut self, site_id: u32, args: &[SystemFunctionInput], @@ -634,7 +695,7 @@ impl<'a> FfParser<'a> { Ok(()) } - fn prepare_effectful_runtime_event_args( + pub(crate) fn prepare_effectful_runtime_event_args( &mut self, args: &[SystemFunctionInput], targets: &mut Vec>, @@ -679,7 +740,7 @@ impl<'a> FfParser<'a> { .collect() } - fn emit_runtime_event_with_prepared_args( + pub(crate) fn emit_runtime_event_with_prepared_args( &mut self, site_id: u32, args: &[SystemFunctionInput], @@ -718,7 +779,7 @@ impl<'a> FfParser<'a> { Ok(()) } - fn parse_system_task_statement( + pub(crate) fn parse_system_task_statement( &mut self, call: &SystemFunctionCall, targets: &mut Vec>, @@ -926,7 +987,7 @@ impl<'a> FfParser<'a> { eval_constexpr(expr)?.to_u64() } - fn get_constant_procedural_truth(expr: &Expression) -> Option { + pub(crate) fn get_constant_procedural_truth(expr: &Expression) -> Option { let comptime = expr.comptime(); let is_value = matches!(expr, Expression::Term(factor) if matches!(factor.as_ref(), veryl_analyzer::ir::Factor::Value(_))); if !(comptime.is_const || is_value && comptime.evaluated) { @@ -947,7 +1008,7 @@ impl<'a> FfParser<'a> { .flatten() } - fn lower_procedural_condition( + pub(crate) fn lower_procedural_condition( &self, condition: RegisterId, ir_builder: &mut SIRBuilder, @@ -996,7 +1057,7 @@ impl<'a> FfParser<'a> { } } - fn cast_reg_width_ext( + pub(crate) fn cast_reg_width_ext( &self, ir_builder: &mut SIRBuilder, reg: RegisterId, @@ -1040,7 +1101,7 @@ impl<'a> FfParser<'a> { } } - fn get_expression_width(&self, expr: &Expression) -> usize { + pub(crate) fn get_expression_width(&self, expr: &Expression) -> usize { crate::context_width::get_expr_width(expr) .or_else(|| expr.comptime().r#type.total_width()) .unwrap_or(64) @@ -1049,7 +1110,7 @@ impl<'a> FfParser<'a> { // expression / function-call lowering is split into submodules: // - parser/ff/expression.rs // - parser/ff/function_call.rs - fn parse_statement_list( + pub(crate) fn parse_statement_list( &mut self, stmts: &[Statement], targets: &mut Vec>, @@ -1619,7 +1680,7 @@ impl<'a> FfParser<'a> { } } - fn parse_for_bound( + pub(crate) fn parse_for_bound( &mut self, bound: &ForBound, canonical_width: usize, diff --git a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs index a8f2d731c83..98eb626fcb8 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs @@ -3198,7 +3198,7 @@ impl<'a> FfParser<'a> { }) } - pub(super) fn op_load( + pub(crate) fn op_load( &mut self, var_id: VarId, index: &VarIndex, @@ -3210,7 +3210,9 @@ impl<'a> FfParser<'a> { ) -> Result<(), ParserError> { let is_local_let = { let variable = &self.module.variables[&var_id]; - variable.affiliation == Affiliation::AlwaysFf && variable.kind == VarKind::Let + variable.affiliation == Affiliation::AlwaysFf + && variable.kind == VarKind::Let + && !matches!(domain, Domain::Process) }; if is_local_let && let Some(&value) = self.local_let_values.get(&var_id) { let selected = self.emit_register_select( @@ -3265,7 +3267,7 @@ impl<'a> FfParser<'a> { } let is_internal = self.local_working_vars.contains(&var_id) || self.inline_function_locals.contains(&var_id); - let load_region = if is_internal { + let load_region = if is_internal && !matches!(domain, Domain::Process) { WORKING_REGION } else { STABLE_REGION @@ -3298,7 +3300,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn op_store( + pub(crate) fn op_store( &mut self, dst: &AssignDestination, targets: &mut Vec>, @@ -3314,6 +3316,7 @@ impl<'a> FfParser<'a> { let variable = &self.module.variables[&dst.id]; variable.affiliation == Affiliation::AlwaysFf && variable.kind == VarKind::Let + && !matches!(domain, Domain::Process) && dst.index.0.is_empty() && dst.select.0.is_empty() && dst.select.1.is_none() @@ -3378,10 +3381,11 @@ impl<'a> FfParser<'a> { if self.inline_function_locals.contains(&dst.id) { // Inline function storage is blocking and call-private, so it // bypasses the FF target, seed, and commit bookkeeping. + let region = domain.region(); emit_guarded_store( ir_builder, &guard, - || convert(dst.id, WORKING_REGION), + || convert(dst.id, region), offset, target_width, src_reg, @@ -3737,7 +3741,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn parse_assign_statement( + pub(crate) fn parse_assign_statement( &mut self, assign_statement: &AssignStatement, targets: &mut Vec>, @@ -4308,14 +4312,26 @@ impl<'a> FfParser<'a> { } } Factor::HierVariable(reference) => { - return Err(ParserError::illegal_context( - "hierarchical variable reference", - format!( - "`{}` is only valid in a native testbench block", - reference.var_path - ), - Some(&reference.comptime.token), - )); + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let Some(&var_id) = self.hierarchical_vars.get(&key) else { + return Err(ParserError::illegal_context( + "hierarchical variable reference", + format!( + "`{}` is only valid in a native testbench block", + reference.var_path + ), + Some(&reference.comptime.token), + )); + }; + self.op_load( + var_id, + &reference.index, + &reference.select, + domain, + convert, + sources, + ir_builder, + )?; } Factor::Value(comptime) => { let (celox_value, mask_xz, width, _) = @@ -5154,7 +5170,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn parse_expression( + pub(crate) fn parse_expression( &mut self, expr: &Expression, targets: &mut Vec>, diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 802ee2dc5aa..42d169848ca 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -112,6 +112,7 @@ fn register_comb_runtime_event_site<'a>( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, }; let id = collector.sites.len() as u32; collector.sites.push(site); @@ -208,7 +209,10 @@ fn collect_system_function_effect( observed_inputs.extend(collector.active_guard_sources.iter().copied()); let guard = match (kind, collector.active_guard, explicit_guard) { ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::AssertPass, active, None, ) => active, @@ -227,7 +231,10 @@ fn collect_system_function_effect( Some(active) } ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::AssertPass, _, Some(_), ) => { diff --git a/crates/celox-frontend-veryl/src/lowering/mod.rs b/crates/celox-frontend-veryl/src/lowering/mod.rs index 9b2b064ebfc..76b194f294c 100644 --- a/crates/celox-frontend-veryl/src/lowering/mod.rs +++ b/crates/celox-frontend-veryl/src/lowering/mod.rs @@ -8,5 +8,6 @@ pub(crate) mod ff; mod function_return; pub(crate) mod global_ff; pub(crate) mod logic_tree; +pub(crate) mod process; pub(crate) mod registry; pub(crate) mod types; diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs new file mode 100644 index 00000000000..14c17da9eaa --- /dev/null +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -0,0 +1,2285 @@ +//! The `initial` blocks of a `#[test]` module as resumable process kernels. +//! +//! Each block becomes one kernel over the elaborated instance's stable +//! state. Expressions and assignments go through [`FfParser`] in its +//! process domain; control flow, clock and reset waits, assertions and the +//! `$tb` methods are lowered here. A loop keeps its counter and bounds in +//! state, so a wait inside its body can suspend the kernel. Random numbers +//! and component methods are host requests served through scratch state. +//! A hierarchical reference becomes a synthetic variable of the module that +//! addresses the child instance's state. + +use celox_design::{ + AbsoluteAddrBase, EventLocation, HostRequest, HostValue, PROCESS_CLOCK_WIDTH, + PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, + ProcessRelease, ProcessSlots, RegionedAbsoluteAddrBase, RuntimeErrorInfo, RuntimeEventKind, + STABLE_REGION, VarAtomBase, VariableMetadata, +}; +use celox_frontend_core::process::{PROCESS_RESUME_WIDTH, ProcessKernelBuilder}; +use celox_sir::{ + BasicBlock, BinaryOp, BlockId, ExecutionUnit, RegisterId, RegisterType, SIRInstruction, + SIROffset, SIRTerminator, SIRValue, UnaryOp, +}; +use num_bigint::BigUint; +use veryl_analyzer::ir::{ + AssertKind, AssignDestination, AssignStatement, Expression, ForBound, ForRange, Function, + FunctionBody, HierVarRef, Module, Op, Statement, SystemFunctionCall, SystemFunctionInput, + SystemFunctionKind, SystemFunctionOutput, TbMethod, TbMethodCall, VarId, VarIndex, VarSelect, +}; +use veryl_analyzer::symbol::Affiliation; +use veryl_parser::resource_table::{self, StrId}; + +use crate::{ + BuildConfig, FrontendLookup, HashMap, HashSet, ParserError, SourceVarId, VariableKind, + VerylTestbenchSource, + lowering::{ + case::case_arm_condition_expr, + context_width::expression_signed, + ff::{Domain, FfParser}, + types::resolve_total_width, + }, + symbolic::artifact::SymbolicVariable, +}; +use celox_frontend_core::ScheduledRtl; + +type SourceAddr = AbsoluteAddrBase; +type RegionedSourceAddr = RegionedAbsoluteAddrBase; + +/// A hidden state object one block needs, in the order the lowering +/// consumes them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScratchNeed { + pub purpose: &'static str, + pub width: usize, +} + +/// The hidden state of one `initial` block. +#[derive(Clone, Debug)] +pub struct BlockStorage { + pub resume: SourceVarId, + pub status: SourceVarId, + pub delay: SourceVarId, + pub clock: SourceVarId, + pub release: SourceVarId, + pub scratch: Vec<(ScratchNeed, SourceVarId)>, + /// The block's own copy of each function-local variable, so a call + /// that waits keeps its arguments and locals while another block calls + /// the function. + pub private: HashMap, +} + +/// The hidden state of a module's `initial` blocks, in declaration order. +#[derive(Clone, Debug, Default)] +pub struct ModuleProcessStorage { + pub blocks: Vec, +} + +/// Declare the hidden state the module's `initial` blocks need as +/// variables after `variables`, and describe it. +pub(crate) fn declare_storage( + ir: &Module, + ids: &HashMap, + variables: &mut HashMap, +) -> Result { + let mut function_locals: Vec = ir + .variables + .iter() + .filter(|(_, variable)| variable.affiliation == Affiliation::Function) + .map(|(id, _)| *id) + .collect(); + function_locals.sort_unstable(); + let templates = function_locals + .iter() + .map(|&local| (local, variables[&ids[&local]].clone())) + .collect::>(); + let mut next = variables.len() as u32; + let mut declare = |path: Vec, template: Option<&SymbolicVariable>, width: usize| { + let id = SourceVarId(next); + next += 1; + let variable = match template { + Some(template) => SymbolicVariable { + path, + source: None, + module_affiliated: false, + ..template.clone() + }, + None => SymbolicVariable { + path, + kind: VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: false, + kind: celox_design::DomainKind::Other, + type_kind: PortTypeKind::Bit, + array_dims: Vec::new(), + }, + packed_dims: vec![width], + source: None, + // Hidden state is not a signal of the design. + module_affiliated: false, + }, + }; + variables.insert(id, variable); + id + }; + let mut blocks = Vec::new(); + for (index, statements) in initial_blocks(ir).enumerate() { + let name = |slot: &str| vec![format!("$initial[{index}]"), slot.to_string()]; + let needs = scratch_needs(ir, statements)?; + let scratch = needs + .into_iter() + .enumerate() + .map(|(slot, need)| { + let id = declare(name(&format!("{}@{slot}", need.purpose)), None, need.width); + (need, id) + }) + .collect(); + let private = templates + .iter() + .map(|(local, template)| { + let path = name(&format!("{}@private", template.path.join("."))); + (*local, declare(path, Some(template), 0)) + }) + .collect(); + blocks.push(BlockStorage { + resume: declare(name("resume"), None, PROCESS_RESUME_WIDTH), + status: declare(name("status"), None, PROCESS_STATUS_WIDTH), + delay: declare(name("delay"), None, PROCESS_DELAY_WIDTH), + clock: declare(name("clock"), None, PROCESS_CLOCK_WIDTH), + release: declare(name("release"), None, PROCESS_RELEASE_WIDTH), + scratch, + private, + }); + } + Ok(ModuleProcessStorage { blocks }) +} + +fn initial_blocks(ir: &Module) -> impl Iterator { + ir.declarations + .iter() + .filter_map(|declaration| match declaration { + veryl_analyzer::ir::Declaration::Initial(initial) => { + Some(initial.statements.as_slice()) + } + _ => None, + }) +} + +/// Whether a range with constant bounds has no value. +fn constant_empty_range(range: &ForRange) -> bool { + let constant = |bound: &ForBound| match bound { + ForBound::Const(value, _) => Some(*value), + ForBound::Expression(_) => None, + }; + match range { + ForRange::Forward { + start, + end, + inclusive, + .. + } + | ForRange::Stepped { + start, + end, + inclusive, + .. + } => match (constant(start), constant(end)) { + (Some(start), Some(end)) => { + if *inclusive { + start > end + } else { + start >= end + } + } + _ => false, + }, + ForRange::Reverse { + start, + end, + inclusive, + .. + } => match (constant(start), constant(end)) { + (Some(start), Some(end)) => { + if *inclusive { + end < start + } else { + end <= start + } + } + _ => false, + }, + } +} + +/// How a `for` loop compares and steps, following the testbench +/// interpreter: the counter is kept at its own width, bounds compare in +/// the counter's signedness only when the bound is signed too, and a +/// step that does not move the counter is an error. +struct LoopShape<'s> { + start: &'s ForBound, + end: &'s ForBound, + inclusive: bool, + reverse: bool, + step: usize, + op: Option, + var_width: usize, + var_signed: bool, + /// The width the bounds and the counter compare in. + width: usize, + /// Whether the comparison with the bound the loop runs towards is signed. + cmp_signed: bool, + start_signed: bool, + end_signed: bool, + /// Whether an unsigned bound may hold a value above 64 bits, which the + /// interpreter only runs as a single iteration. + start_wide: bool, + end_wide: bool, +} + +impl LoopShape<'_> { + fn wide_capable(&self) -> bool { + self.start_wide || self.end_wide + } +} + +fn loop_shape<'s>( + ir: &Module, + stmt: &'s veryl_analyzer::ir::ForStatement, +) -> Result, ParserError> { + let var_width = resolve_total_width(ir, &ir.variables[&stmt.var_id])?.max(1); + let var_signed = stmt.var_type.signed; + let bound_width = |bound: &ForBound| match bound { + ForBound::Const(..) => 64, + ForBound::Expression(expr) => expr.comptime().r#type.total_width().unwrap_or(64), + }; + let bound_signed = |bound: &ForBound| match bound { + ForBound::Const(_, signed) => *signed, + ForBound::Expression(expr) => expression_signed(expr), + }; + let (start, end, inclusive, step, reverse, op) = match &stmt.range { + ForRange::Forward { + start, + end, + inclusive, + step, + } => (start, end, *inclusive, *step, false, None), + ForRange::Reverse { + start, + end, + inclusive, + step, + } => (start, end, *inclusive, *step, true, None), + ForRange::Stepped { + start, + end, + inclusive, + step, + op, + } => (start, end, *inclusive, *step, false, Some(*op)), + }; + let start_signed = bound_signed(start); + let end_signed = bound_signed(end); + let continuation_signed = if reverse { start_signed } else { end_signed }; + Ok(LoopShape { + start, + end, + inclusive, + reverse, + step, + op, + var_width, + var_signed, + width: var_width + .max(bound_width(start)) + .max(bound_width(end)) + .max(64) + + 1, + cmp_signed: var_signed && continuation_signed, + start_signed, + end_signed, + start_wide: !start_signed && bound_width(start) > 64, + end_wide: !end_signed && bound_width(end) > 64, + }) +} + +/// The width of a value passed to a component method: the width its +/// context gives it, else the width the expression evaluates in. +fn argument_width(input: &SystemFunctionInput) -> usize { + let expr = &input.0; + let context = expr.comptime().expr_context.width; + if context > 0 { + return context; + } + crate::context_width::get_expr_width(expr) + .or_else(|| expr.comptime().r#type.total_width()) + .or_else(|| expr.comptime().get_value().ok().map(|value| value.width())) + .unwrap_or(64) + .max(1) +} + +fn function_body( + functions: &HashMap, + call: &veryl_analyzer::ir::FunctionCall, +) -> Option { + let function = functions.get(&call.id)?; + match &call.index { + Some(index) => function.get_function(index), + None => function.get_function(&[]), + } +} + +/// The scratch state the statements need, in lowering order. +fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result, ParserError> { + let mut needs = Vec::new(); + let mut active = HashSet::default(); + collect_scratch_needs(ir, statements, &mut active, &mut needs)?; + Ok(needs) +} + +fn collect_scratch_needs( + ir: &Module, + statements: &[Statement], + active: &mut HashSet, + needs: &mut Vec, +) -> Result<(), ParserError> { + let need = |needs: &mut Vec, purpose: &'static str, width: usize| { + needs.push(ScratchNeed { purpose, width }); + }; + for statement in statements { + match statement { + Statement::If(stmt) => { + collect_scratch_needs(ir, &stmt.true_side, active, needs)?; + collect_scratch_needs(ir, &stmt.false_side, active, needs)?; + } + Statement::IfReset(stmt) => { + collect_scratch_needs(ir, &stmt.true_side, active, needs)?; + collect_scratch_needs(ir, &stmt.false_side, active, needs)?; + } + Statement::Case(stmt) => { + for arm in &stmt.arms { + collect_scratch_needs(ir, &arm.body, active, needs)?; + } + collect_scratch_needs(ir, &stmt.default, active, needs)?; + } + Statement::For(stmt) => { + let shape = loop_shape(ir, stmt)?; + need(needs, "for_start", shape.width); + need(needs, "for_end", shape.width); + if shape.wide_capable() { + need(needs, "for_single", 1); + } + collect_scratch_needs(ir, &stmt.body, active, needs)?; + } + Statement::FunctionCall(call) => { + if active.insert(call.id) + && let Some(body) = function_body(&ir.functions, call) + { + collect_scratch_needs(ir, &body.statements, active, needs)?; + active.remove(&call.id); + } + } + Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::RandomSeed { .. } => need(needs, "random_seed", 64), + TbMethod::RandomGet { width, .. } => { + need(needs, "random_value", (*width as usize).max(1)); + } + TbMethod::RandomGetRange { width, .. } => { + need(needs, "random_min", 64); + need(needs, "random_max", 64); + need(needs, "random_value", (*width as usize).max(1)); + } + TbMethod::RandomGetSeed => need(needs, "random_seed", 64), + TbMethod::Component { args, .. } => { + for arg in args { + need(needs, "component_arg", argument_width(arg)); + } + if tb.ret.is_some() { + need( + needs, + "component_result", + tb.ret_width.map_or(64, |w| w as usize).max(1), + ); + } + } + TbMethod::ClockNext { .. } + | TbMethod::ResetAssert { .. } + | TbMethod::FileOpen { .. } + | TbMethod::FileWrite { .. } + | TbMethod::FileClose + | TbMethod::FileFlush => {} + }, + Statement::Assign(_) + | Statement::SystemFunctionCall(_) + | Statement::Break + | Statement::Unsupported(_) + | Statement::Null => {} + } + } + Ok(()) +} + +/// Compile the `initial` blocks of every instance in `testbench` into +/// kernels appended to `scheduled`. +pub(crate) fn lower_testbench_kernels( + scheduled: &mut ScheduledRtl, + testbench: &VerylTestbenchSource, + module_ir: &HashMap, + storage: &HashMap, + config: &BuildConfig, +) -> Result<(), ParserError> { + for source in testbench.sources() { + if source.initial_statements.is_none() { + continue; + } + let instance = source.base_instance(&scheduled.frontend_lookup); + let module_id = scheduled.frontend_lookup.instance_module[&instance]; + let ir = module_ir[&module_id]; + let storage = storage.get(&module_id).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + "the module's process storage was not declared", + None, + ) + })?; + for (index, statements) in source.initial_blocks().into_iter().enumerate() { + let block = storage.blocks.get(index).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + format!("initial block {index} has no process storage"), + None, + ) + })?; + lower_block( + scheduled, testbench, source, module_ir, instance, module_id, ir, block, + statements, config, + )?; + } + } + Ok(()) +} + +enum Flow { + /// The block is open; the next statement follows. + Continue, + /// Control left the block. + Ended, +} + +struct BlockLowering<'a> { + parser: FfParser<'a>, + kernel: ProcessKernelBuilder, + ir: &'a Module, + ids: &'a HashMap, + lookup: &'a FrontendLookup, + instance: celox_design::InstanceId, + module_id: celox_design::ModuleId, + hierarchical: HashMap, + private: HashMap, + scratch: std::vec::IntoIter<(ScratchNeed, SourceVarId)>, + clocks: Vec<(StrId, ProcessClock)>, + releases: Vec>, + host_requests: Vec>, + clock_periods: &'a HashMap, + resource_prefix: String, + active_functions: HashSet, + site_base: u32, + targets: Vec>, + sources: Vec>, + /// The process stored to design state since the combinational logic + /// was last settled, so a statement that reads design state settles + /// it first. + dirty: bool, +} + +#[allow(clippy::too_many_arguments)] +fn lower_block( + scheduled: &mut ScheduledRtl, + testbench: &VerylTestbenchSource, + source: &VerylTestbenchSource, + module_ir: &HashMap, + instance: celox_design::InstanceId, + module_id: celox_design::ModuleId, + ir: &Module, + storage: &BlockStorage, + statements: &[Statement], + config: &BuildConfig, +) -> Result<(), ParserError> { + let lookup = &scheduled.frontend_lookup; + let ids = &testbench.id_map.module_variables[&module_id]; + // Hierarchical references become synthetic variables of a copy of the + // module, so the expression lowering treats them like local ones. + let mut module = ir.clone(); + let mut hierarchical_vars = HashMap::default(); + let mut hierarchical = HashMap::default(); + let mut next_synthetic = 0x4000_0000u32; + let mut references = Vec::new(); + collect_hierarchical_references( + statements, + &ir.functions, + &mut HashSet::default(), + &mut references, + ); + for reference in references { + let key = (reference.inst_path.clone(), reference.var_path.clone()); + if hierarchical_vars.contains_key(&key) { + continue; + } + let resolved = resolve_hierarchical(lookup, module_ir, testbench, instance, &reference)?; + let id = VarId::from_raw(next_synthetic); + next_synthetic += 1; + let mut variable = resolved.variable; + variable.id = id; + module.variables.insert(id, variable); + hierarchical_vars.insert(key, id); + hierarchical.insert(id, resolved.target); + } + let site_base = scheduled.runtime_schema.runtime_event_sites.len() as u32; + let parser = FfParser::new(&module, *config) + .with_hierarchical_vars(hierarchical_vars) + .with_runtime_event_site_base(site_base); + let stable = |var_id: SourceVarId| RegionedSourceAddr { + region: STABLE_REGION, + instance_id: instance, + var_id, + }; + let kernel = ProcessKernelBuilder::with_addresses(ProcessSlots::new( + stable(storage.resume), + stable(storage.status), + stable(storage.delay), + stable(storage.clock), + stable(storage.release), + )); + let resource_prefix = lookup + .instance_ids + .iter() + .find_map(|(path, &id)| { + (id == instance).then(|| lookup.instance_path_segments(path).join(".")) + }) + .unwrap_or_default(); + let mut lowering = BlockLowering { + parser, + kernel, + ir: &module, + ids, + lookup, + instance, + module_id, + hierarchical, + private: storage.private.clone(), + scratch: storage.scratch.clone().into_iter(), + clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), + clock_periods: &source.clock_periods, + resource_prefix, + active_functions: HashSet::default(), + site_base, + targets: Vec::new(), + sources: Vec::new(), + dirty: false, + }; + lowering.declare_clocks(statements); + lowering.lower_statements(statements)?; + let BlockLowering { + parser, + kernel, + clocks, + releases, + host_requests, + .. + } = lowering; + let mut unit = kernel.build(); + prune_unreachable_blocks(&mut unit); + + // Runtime errors: the parser numbers them locally from 2000. + let next_code = scheduled + .runtime_schema + .runtime_errors + .keys() + .copied() + .max() + .map_or(1, |code| code + 1); + let mut codes = HashMap::default(); + let mut errors = parser.runtime_errors().iter().collect::>(); + errors.sort_by_key(|(code, _)| **code); + for (offset, (&local, info)) in errors.into_iter().enumerate() { + let global = next_code + offset as i64; + codes.insert(local, global); + scheduled.runtime_schema.runtime_errors.insert( + global, + RuntimeErrorInfo { + message: info.message.clone(), + signals: info + .signals + .iter() + .filter_map(|var| { + let var_id = *ids.get(var)?; + lookup.state_address(&SourceAddr { + instance_id: instance, + var_id, + }) + }) + .collect(), + }, + ); + } + for site in parser.runtime_event_sites() { + scheduled + .runtime_schema + .runtime_event_sites + .push(site.clone()); + } + let to_state = |address: &SourceAddr| { + lookup.state_address(address).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + format!("{address:?} has no state object"), + None, + ) + }) + }; + let unit = map_unit(&unit, &codes, |address| { + Ok(RegionedAbsoluteAddrBase { + region: address.region, + instance_id: to_state(&SourceAddr { + instance_id: address.instance_id, + var_id: address.var_id, + })? + .instance_id, + var_id: to_state(&SourceAddr { + instance_id: address.instance_id, + var_id: address.var_id, + })? + .var_id, + }) + })?; + let slots = ProcessSlots { + resume: stable(storage.resume).into_absolute(), + status: stable(storage.status).into_absolute(), + delay: stable(storage.delay).into_absolute(), + clock: stable(storage.clock).into_absolute(), + release: stable(storage.release).into_absolute(), + clocks: clocks.into_iter().map(|(_, clock)| clock).collect(), + releases, + host_requests, + }; + let mut failure = None; + let slots = slots.map(|address| match to_state(&address) { + Ok(state) => state, + Err(error) => { + failure.get_or_insert(error); + celox_design::StateAddr { + instance_id: address.instance_id, + var_id: celox_design::StateObjectId::from_raw(0), + } + } + }); + if let Some(error) = failure { + return Err(error); + } + scheduled.sir.processes.push(unit); + scheduled.runtime_schema.processes.push(slots); + Ok(()) +} + +trait IntoAbsolute { + fn into_absolute(self) -> SourceAddr; +} + +impl IntoAbsolute for RegionedSourceAddr { + fn into_absolute(self) -> SourceAddr { + SourceAddr { + instance_id: self.instance_id, + var_id: self.var_id, + } + } +} + +struct ResolvedHierarchical { + variable: veryl_analyzer::ir::Variable, + target: SourceAddr, +} + +/// The child instance's variable a hierarchical reference names. +fn resolve_hierarchical( + lookup: &FrontendLookup, + module_ir: &HashMap, + testbench: &VerylTestbenchSource, + base_instance: celox_design::InstanceId, + reference: &HierVarRef, +) -> Result { + let (state, _) = + crate::testbench::resolve_hierarchical_reference_from(lookup, base_instance, reference)?; + let source = lookup.state_to_source.get(&state).ok_or_else(|| { + ParserError::illegal_context( + "hierarchical variable reference", + format!("`{}` has no source variable", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + let module_id = lookup.instance_module[&source.instance_id]; + let ids = &testbench.id_map.module_variables[&module_id]; + let ir = module_ir[&module_id]; + let variable = ir + .variables + .iter() + .find(|(id, _)| ids.get(id) == Some(&source.var_id)) + .map(|(_, variable)| variable.clone()) + .ok_or_else(|| { + ParserError::illegal_context( + "hierarchical variable reference", + format!("`{}` is not a variable of the instance", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + Ok(ResolvedHierarchical { + variable, + target: *source, + }) +} + +/// Every hierarchical reference the statements make, reads and writes. +fn collect_hierarchical_references( + statements: &[Statement], + functions: &HashMap, + active: &mut HashSet, + out: &mut Vec, +) { + let mut reads = Vec::new(); + crate::testbench::collect_statement_reads( + statements, + functions, + &mut HashSet::default(), + &mut reads, + ); + for read in reads { + if let crate::testbench::TestbenchRead::Hierarchical(reference) = read { + out.push(*reference); + } + } + for statement in statements { + match statement { + Statement::Assign(assign) => { + if let Some(destination) = &assign.hier_dst { + out.push(crate::testbench::hierarchical_destination_reference( + destination, + )); + } + } + Statement::SystemFunctionCall(call) => { + if let SystemFunctionKind::Readmemh(_, SystemFunctionOutput::Hier(reference)) = + &call.kind + { + out.push((**reference).clone()); + } + } + Statement::If(stmt) => { + collect_hierarchical_references(&stmt.true_side, functions, active, out); + collect_hierarchical_references(&stmt.false_side, functions, active, out); + } + Statement::IfReset(stmt) => { + collect_hierarchical_references(&stmt.true_side, functions, active, out); + collect_hierarchical_references(&stmt.false_side, functions, active, out); + } + Statement::Case(stmt) => { + for arm in &stmt.arms { + collect_hierarchical_references(&arm.body, functions, active, out); + } + collect_hierarchical_references(&stmt.default, functions, active, out); + } + Statement::For(stmt) => { + collect_hierarchical_references(&stmt.body, functions, active, out); + } + Statement::FunctionCall(call) => { + if active.insert(call.id) + && let Some(body) = function_body(functions, call) + { + collect_hierarchical_references(&body.statements, functions, active, out); + active.remove(&call.id); + } + } + Statement::TbMethodCall(_) + | Statement::Break + | Statement::Unsupported(_) + | Statement::Null => {} + } + } +} + +/// The address of a module variable, or of the child state a synthetic +/// variable stands for. A process reads and writes stable state only. +fn convert_fn<'b>( + instance: celox_design::InstanceId, + ids: &'b HashMap, + hierarchical: &'b HashMap, + private: &'b HashMap, +) -> impl Fn(VarId, u32) -> RegionedSourceAddr + 'b { + move |var_id, _region| { + let target = hierarchical + .get(&var_id) + .copied() + .unwrap_or_else(|| SourceAddr { + instance_id: instance, + var_id: private + .get(&var_id) + .copied() + .unwrap_or_else(|| ids[&var_id]), + }); + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: target.instance_id, + var_id: target.var_id, + } + } +} + +/// The parser, kernel and the operand stacks with the address mapping. +macro_rules! parts { + ($self:ident) => {{ + let BlockLowering { + parser, + kernel, + targets, + sources, + ids, + hierarchical, + private, + instance, + .. + } = $self; + let convert = convert_fn(*instance, ids, hierarchical, private); + (parser, kernel, targets, sources, convert) + }}; +} + +impl<'a> BlockLowering<'a> { + fn scratch_addr(&self, id: SourceVarId) -> RegionedSourceAddr { + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: id, + } + } + + fn take_scratch(&mut self, purpose: &'static str) -> Result<(usize, SourceVarId), ParserError> { + match self.scratch.next() { + Some((need, id)) if need.purpose == purpose => Ok((need.width, id)), + other => Err(ParserError::internal( + "testbench process lowering", + format!("scratch for {purpose} expected, found {other:?}"), + None, + )), + } + } + + fn error( + &self, + what: &'static str, + detail: impl Into, + token: Option<&veryl_parser::token_range::TokenRange>, + ) -> ParserError { + ParserError::illegal_context(what, detail.into(), token) + } + + /// The module variable named by a `$tb` instance. + fn instance_var(&self, inst: StrId) -> Result { + self.ir + .variables + .iter() + .find(|(_, variable)| variable.path.0.as_slice() == [inst]) + .map(|(id, _)| *id) + .ok_or_else(|| { + self.error( + "testbench method call", + format!("`{}` is not a variable of the module", source_name(inst)), + None, + ) + }) + } + + fn resource_name(&self, name: StrId) -> String { + let local = source_name(name); + if self.resource_prefix.is_empty() { + local + } else { + format!("{}.{local}", self.resource_prefix) + } + } + + /// The clocks the block waits on, in first-use order, with their + /// periods. + fn declare_clocks(&mut self, statements: &[Statement]) { + let mut active = HashSet::default(); + self.scan_clocks(statements, &mut active); + } + + fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) { + for statement in statements { + match statement { + Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::ClockNext { period, .. } => { + let period = self + .clock_periods + .get(&tb.inst) + .copied() + .or_else(|| period.as_deref().and_then(try_eval_const)) + .unwrap_or(2) + .max(2); + self.declare_clock(tb.inst, period); + } + TbMethod::ResetAssert { clock, .. } => { + let period = self.clock_periods.get(clock).copied().unwrap_or(2).max(2); + self.declare_clock(*clock, period); + } + _ => {} + }, + Statement::If(stmt) => { + self.scan_clocks(&stmt.true_side, active); + self.scan_clocks(&stmt.false_side, active); + } + Statement::IfReset(stmt) => { + self.scan_clocks(&stmt.true_side, active); + self.scan_clocks(&stmt.false_side, active); + } + Statement::Case(stmt) => { + for arm in &stmt.arms { + self.scan_clocks(&arm.body, active); + } + self.scan_clocks(&stmt.default, active); + } + Statement::For(stmt) => self.scan_clocks(&stmt.body, active), + Statement::FunctionCall(call) => { + if active.insert(call.id) + && let Some(body) = function_body(&self.ir.functions, call) + { + self.scan_clocks(&body.statements, active); + active.remove(&call.id); + } + } + _ => {} + } + } + } + + fn declare_clock(&mut self, inst: StrId, period: u64) { + if self.clocks.iter().any(|(name, _)| *name == inst) { + return; + } + let Ok(var) = self.instance_var(inst) else { + return; + }; + let signal = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&var], + }; + self.clocks.push((inst, ProcessClock { signal, period })); + let index = self.kernel.add_clock(); + debug_assert_eq!(index as usize + 1, self.clocks.len()); + } + + fn clock_index(&self, inst: StrId) -> Result { + self.clocks + .iter() + .position(|(name, _)| *name == inst) + .map(|index| index as u32) + .ok_or_else(|| { + self.error( + "testbench method call", + format!("`{}` is not a clock of the module", source_name(inst)), + None, + ) + }) + } + + // ------------------------------------------------------------ helpers + + fn expression(&mut self, expr: &Expression) -> Result { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_expression( + expr, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + None, + )?; + Ok(parser.pop_value()) + } + + fn condition(&mut self, expr: &Expression) -> Result { + let value = self.expression(expr)?; + Ok(self + .parser + .lower_procedural_condition(value, self.kernel.builder())) + } + + /// `value` as an unsigned two-state register of `width` bits. + fn unsigned_bits(&mut self, value: RegisterId, width: usize) -> RegisterId { + let builder = self.kernel.builder(); + let value = match *builder.register(&value) { + RegisterType::Logic { width } => { + let two_state = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(two_state, UnaryOp::ToTwoState, value)); + two_state + } + RegisterType::Bit { .. } => value, + }; + let signed = matches!( + builder.register(&value), + RegisterType::Bit { signed: true, .. } + ); + let cast = self + .parser + .cast_reg_width_ext(self.kernel.builder(), value, width, signed); + let builder = self.kernel.builder(); + match *builder.register(&cast) { + RegisterType::Bit { + width: w, + signed: false, + } if w == width => cast, + _ => { + let unsigned = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(unsigned, UnaryOp::Ident, cast)); + unsigned + } + } + } + + fn constant(&mut self, value: u64, width: usize) -> RegisterId { + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + reg + } + + fn store_scratch(&mut self, id: SourceVarId, width: usize, value: RegisterId) { + let address = self.scratch_addr(id); + self.kernel.builder().emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + width, + value, + Vec::new(), + Vec::new(), + )); + } + + fn load_scratch(&mut self, id: SourceVarId, width: usize, signed: bool) -> RegisterId { + let address = self.scratch_addr(id); + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, signed); + builder.emit(SIRInstruction::Load( + reg, + address, + SIROffset::Static(0), + width, + )); + reg + } + + fn destination( + &self, + var_id: VarId, + token: veryl_parser::token_range::TokenRange, + ) -> AssignDestination { + AssignDestination { + id: var_id, + path: self.ir.variables[&var_id].path.clone(), + index: VarIndex::default(), + select: VarSelect::default(), + comptime: Default::default(), + token, + } + } + + fn store( + &mut self, + destination: &AssignDestination, + value: RegisterId, + ) -> Result<(), ParserError> { + if !self.private.contains_key(&destination.id) { + self.dirty = true; + } + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.push_value(value); + parser.op_store( + destination, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ) + } + + /// Settle the combinational logic before a read of design state that + /// follows a store, as the statements of a testbench are sequential. + fn settle_if_dirty(&mut self) -> Result<(), ParserError> { + if !self.dirty { + return Ok(()); + } + self.kernel + .settle() + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + self.suspended(); + Ok(()) + } + + fn load_var(&mut self, var_id: VarId) -> Result { + let (parser, kernel, _targets, sources, convert) = parts!(self); + parser.op_load( + var_id, + &VarIndex::default(), + &VarSelect::default(), + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + Ok(parser.pop_value()) + } + + /// The process gave control to the runtime: registers and the settled + /// state are fresh when it resumes. + fn suspended(&mut self) { + self.parser.clear_register_cache(); + self.dirty = false; + } + + fn host_scratch( + &mut self, + purpose: &'static str, + signed: bool, + is_string: bool, + ) -> Result<(HostValue, SourceVarId), ParserError> { + let (width, id) = self.take_scratch(purpose)?; + Ok(( + HostValue { + signal: SourceAddr { + instance_id: self.instance, + var_id: id, + }, + width, + signed, + is_string, + }, + id, + )) + } + + fn host_request(&mut self, request: HostRequest) -> Result<(), ParserError> { + self.host_requests.push(request); + let index = self.kernel.add_host_request(); + debug_assert_eq!(index as usize + 1, self.host_requests.len()); + self.kernel + .host(index) + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + self.suspended(); + Ok(()) + } + + // --------------------------------------------------------- statements + + fn lower_statements(&mut self, statements: &[Statement]) -> Result { + for statement in statements { + if let Flow::Ended = self.lower_statement(statement)? { + return Ok(Flow::Ended); + } + } + Ok(Flow::Continue) + } + + fn lower_statement(&mut self, statement: &Statement) -> Result { + let reads = match statement { + Statement::Null | Statement::Break => false, + Statement::SystemFunctionCall(call) => !matches!(call.kind, SystemFunctionKind::Finish), + _ => true, + }; + if reads { + self.settle_if_dirty()?; + } + match statement { + Statement::Assign(assign) => { + self.lower_assign(assign)?; + self.dirty = true; + Ok(Flow::Continue) + } + Statement::If(stmt) => { + // A constant condition keeps the other side out of the + // kernel, as the interpreter never ran it. + match FfParser::get_constant_procedural_truth(&stmt.cond) { + Some(true) => self.lower_statements(&stmt.true_side), + Some(false) => self.lower_statements(&stmt.false_side), + None => { + let condition = self.condition(&stmt.cond)?; + self.branch(condition, &stmt.true_side, &stmt.false_side) + } + } + } + Statement::IfReset(stmt) => Err(self.error( + "statement in an initial block", + "if_reset", + Some(&stmt.token), + )), + Statement::Case(stmt) => self.lower_case(stmt), + Statement::For(stmt) => { + if constant_empty_range(&stmt.range) { + // The body never runs; its `$readmemh` files need not exist. + return Ok(Flow::Continue); + } + self.lower_for(stmt) + } + Statement::Break => { + let Some(exit) = self.parser.loop_exit_blocks_mut().last().copied() else { + return Err(self.error( + "statement in an initial block", + "break outside loop", + None, + )); + }; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(exit, Vec::new())); + Ok(Flow::Ended) + } + Statement::SystemFunctionCall(call) => self.lower_system_function(call), + Statement::FunctionCall(call) => self.lower_function_call(call), + Statement::TbMethodCall(tb) => self.lower_tb_method(tb), + Statement::Null => Ok(Flow::Continue), + Statement::Unsupported(token) => Err(self.error( + "statement in an initial block", + "unsupported statement", + Some(token), + )), + } + } + + /// Branch on `condition` into two bodies that rejoin. + fn branch( + &mut self, + condition: RegisterId, + true_side: &[Statement], + false_side: &[Statement], + ) -> Result { + let builder = self.kernel.builder(); + let then_block = builder.new_block(); + let else_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (then_block, Vec::new()), + false_block: (else_block, Vec::new()), + }); + let mut joined = false; + for (block, body) in [(then_block, true_side), (else_block, false_side)] { + self.kernel.builder().switch_to_block(block); + if let Flow::Continue = self.lower_statements(body)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = true; + } + } + self.kernel.builder().switch_to_block(join); + if joined { + Ok(Flow::Continue) + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + Ok(Flow::Ended) + } + } + + fn lower_case( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + ) -> Result { + self.lower_case_arm(stmt, 0) + } + + fn lower_case_arm( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + ) -> Result { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.lower_statements(&stmt.default); + }; + let condition_expr = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + let condition = self.condition(&condition_expr)?; + let builder = self.kernel.builder(); + let then_block = builder.new_block(); + let else_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (then_block, Vec::new()), + false_block: (else_block, Vec::new()), + }); + let mut joined = false; + self.kernel.builder().switch_to_block(then_block); + if let Flow::Continue = self.lower_statements(&case_arm.body)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = true; + } + self.kernel.builder().switch_to_block(else_block); + if let Flow::Continue = self.lower_case_arm(stmt, arm + 1)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = true; + } + self.kernel.builder().switch_to_block(join); + if joined { + Ok(Flow::Continue) + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + Ok(Flow::Ended) + } + } + + fn lower_assign(&mut self, assign: &AssignStatement) -> Result<(), ParserError> { + // A constant index or part select outside the destination is an + // error of the testbench, as it was for the interpreter. + for destination in &assign.dst { + if let Some(&var_id) = self.ids.get(&destination.id) + && let Some(info) = self.lookup.module_variables[&self.module_id].get(&var_id) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } + } + let rewritten; + let assign = if let Some(destination) = &assign.hier_dst { + let reference = crate::testbench::hierarchical_destination_reference(destination); + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let id = *self.parser.hierarchical_var(&key).ok_or_else(|| { + self.error( + "hierarchical assignment", + format!("`{}` was not resolved", destination.var_path), + Some(&destination.token), + ) + })?; + rewritten = AssignStatement { + dst: vec![AssignDestination { + id, + path: destination.var_path.clone(), + index: destination.index.clone(), + select: destination.select.clone(), + comptime: destination.comptime.clone(), + token: destination.token, + }], + hier_dst: None, + width: assign.width, + expr: assign.expr.clone(), + token: assign.token, + }; + &rewritten + } else { + assign + }; + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_assign_statement( + assign, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ) + } + + /// A `for` loop whose counter and bounds live in state, so its body + /// may suspend. See [`LoopShape`] for the semantics. + fn lower_for(&mut self, stmt: &veryl_analyzer::ir::ForStatement) -> Result { + let shape = loop_shape(self.ir, stmt)?; + let LoopShape { + inclusive, + reverse, + step, + op, + var_width, + var_signed, + width, + cmp_signed, + .. + } = shape; + let (_, start_slot) = self.take_scratch("for_start")?; + let (_, end_slot) = self.take_scratch("for_end")?; + let single_slot = if shape.wide_capable() { + Some(self.take_scratch("for_single")?.1) + } else { + None + }; + let start_reg = self.for_bound(shape.start, width, cmp_signed)?; + let end_reg = self.for_bound(shape.end, width, cmp_signed)?; + self.store_scratch(start_slot, width, start_reg); + self.store_scratch(end_slot, width, end_reg); + let var = self.destination(stmt.var_id, stmt.token); + let stall_message = format!( + "non-progressing stepped for loop (loop variable `{}`)", + source_name(stmt.var_name) + ); + + let builder = self.kernel.builder(); + let header = builder.new_block(); + let body = builder.new_block(); + let latch = builder.new_block(); + let exit = builder.new_block(); + let normal = builder.new_block(); + + // A bound above 64 bits runs the body once when the range is that + // one value, nothing when it is empty, and fails otherwise. + if let Some(single_slot) = single_slot { + let mut wide = None; + for (reg, is_wide) in [(start_reg, shape.start_wide), (end_reg, shape.end_wide)] { + if !is_wide { + continue; + } + let builder = self.kernel.builder(); + let shift = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm(shift, SIRValue::new(64u64))); + let high = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Binary(high, reg, BinaryOp::Shr, shift)); + let zero = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let nonzero = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(nonzero, high, BinaryOp::Ne, zero)); + wide = Some(match wide { + None => nonzero, + Some(previous) => { + let either = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + either, + previous, + BinaryOp::Or, + nonzero, + )); + either + } + }); + } + let wide = wide.expect("a wide bound"); + let builder = self.kernel.builder(); + let wide_block = builder.new_block(); + let single_block = builder.new_block(); + let fail_block = builder.new_block(); + let decide_block = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: wide, + true_block: (wide_block, Vec::new()), + false_block: (normal, Vec::new()), + }); + builder.switch_to_block(wide_block); + let empty = builder.alloc_bit(1, false); + let (lhs, op_empty, rhs) = match (reverse, inclusive, cmp_signed) { + (false, true, true) => (start_reg, BinaryOp::GtS, end_reg), + (false, true, false) => (start_reg, BinaryOp::GtU, end_reg), + (false, false, true) => (start_reg, BinaryOp::GeS, end_reg), + (false, false, false) => (start_reg, BinaryOp::GeU, end_reg), + (true, true, true) => (end_reg, BinaryOp::LtS, start_reg), + (true, true, false) => (end_reg, BinaryOp::LtU, start_reg), + (true, false, true) => (end_reg, BinaryOp::LeS, start_reg), + (true, false, false) => (end_reg, BinaryOp::LeU, start_reg), + }; + builder.emit(SIRInstruction::Binary(empty, lhs, op_empty, rhs)); + builder.seal_block(SIRTerminator::Branch { + cond: empty, + true_block: (exit, Vec::new()), + false_block: (decide_block, Vec::new()), + }); + builder.switch_to_block(decide_block); + let single = if inclusive { + let same = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + same, + start_reg, + BinaryOp::Eq, + end_reg, + )); + same + } else { + let never = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u64))); + never + }; + builder.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (single_block, Vec::new()), + false_block: (fail_block, Vec::new()), + }); + builder.switch_to_block(fail_block); + let code = self.parser.runtime_error( + format!( + "dynamic for-loop bound exceeds host {}", + if var_signed { "i128" } else { "usize" } + ), + vec![stmt.var_id], + ); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(single_block); + let one = self.constant(1, 1); + self.store_scratch(single_slot, 1, one); + let counter = self.parser.cast_reg_width_ext( + self.kernel.builder(), + start_reg, + var_width, + cmp_signed, + ); + self.store(&var, counter)?; + self.parser.clear_register_cache(); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(body, Vec::new())); + self.kernel.builder().switch_to_block(normal); + let zero = self.constant(0, 1); + self.store_scratch(single_slot, 1, zero); + } else { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(normal, Vec::new())); + self.kernel.builder().switch_to_block(normal); + } + + // A signed counter cannot reach an unsigned bound above its maximum. + if var_signed && var_width <= 64 { + let max = (1u64 << (var_width - 1)) - 1; + for (reg, bound_signed, is_end) in [ + (start_reg, shape.start_signed, false), + (end_reg, shape.end_signed, true), + ] { + if bound_signed { + continue; + } + let builder = self.kernel.builder(); + let limit = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(limit, SIRValue::new(max))); + let above = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(above, reg, BinaryOp::GtU, limit)); + let out_of_range = if is_end && !inclusive { + // An exclusive end one above the maximum is reachable. + let next = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(next, SIRValue::new(max + 1))); + let allowed = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(allowed, reg, BinaryOp::Eq, next)); + let not_allowed = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary( + not_allowed, + UnaryOp::LogicNot, + allowed, + )); + let out = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + out, + above, + BinaryOp::And, + not_allowed, + )); + out + } else { + above + }; + let fail_block = builder.new_block(); + let continue_block = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: out_of_range, + true_block: (fail_block, Vec::new()), + false_block: (continue_block, Vec::new()), + }); + builder.switch_to_block(fail_block); + let code = self + .parser + .runtime_error(stall_message.clone(), vec![stmt.var_id]); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(continue_block); + } + } + + // The counter starts at the first value of the range. + let initial = if reverse { + if inclusive { + end_reg + } else { + let builder = self.kernel.builder(); + let one = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + let first = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Binary(first, end_reg, BinaryOp::Sub, one)); + first + } + } else { + start_reg + }; + let initial = + self.parser + .cast_reg_width_ext(self.kernel.builder(), initial, var_width, cmp_signed); + self.store(&var, initial)?; + self.parser.clear_register_cache(); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + + // Header: compare the counter with the bound it runs towards. + self.kernel.builder().switch_to_block(header); + let current = self.load_var(stmt.var_id)?; + let current = self.extend_for_compare(current, width, cmp_signed); + let bound = if reverse { + self.load_scratch(start_slot, width, cmp_signed) + } else { + self.load_scratch(end_slot, width, cmp_signed) + }; + let builder = self.kernel.builder(); + let in_range = builder.alloc_bit(1, false); + let op_in_range = match (reverse, inclusive, cmp_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, + }; + builder.emit(SIRInstruction::Binary( + in_range, + current, + op_in_range, + bound, + )); + builder.seal_block(SIRTerminator::Branch { + cond: in_range, + true_block: (body, Vec::new()), + false_block: (exit, Vec::new()), + }); + + // Body. + self.kernel.builder().switch_to_block(body); + self.parser.clear_register_cache(); + self.parser.loop_exit_blocks_mut().push(exit); + let flow = self.lower_statements(&stmt.body); + self.parser.loop_exit_blocks_mut().pop(); + if let Flow::Continue = flow? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(latch, Vec::new())); + } + + // Latch: the step at the counter's width; a counter that does not + // move towards the bound is an error. + self.kernel.builder().switch_to_block(latch); + self.parser.clear_register_cache(); + let current = self.load_var(stmt.var_id)?; + let builder = self.kernel.builder(); + let step_bits = if var_width < 64 { + (step as u64) & ((1u64 << var_width) - 1) + } else { + step as u64 + }; + let step_reg = builder.alloc_bit(var_width, var_signed); + builder.emit(SIRInstruction::Imm(step_reg, SIRValue::new(step_bits))); + let next = builder.alloc_bit(var_width, var_signed); + let binary = match op { + None if reverse => Some(BinaryOp::Sub), + None => Some(BinaryOp::Add), + Some(Op::Add) => Some(BinaryOp::Add), + Some(Op::Sub) => Some(BinaryOp::Sub), + Some(Op::Mul) => Some(BinaryOp::Mul), + Some(Op::LogicShiftL | Op::ArithShiftL) => { + if step >= var_width { + None + } else { + Some(BinaryOp::Shl) + } + } + Some(Op::BitOr) => Some(BinaryOp::Or), + Some(Op::BitXor) => Some(BinaryOp::Xor), + Some(Op::BitAnd) => Some(BinaryOp::And), + Some(other) => { + return Err(self.error( + "for loop step operator in an initial block", + format!("{other:?}"), + Some(&stmt.token), + )); + } + }; + match binary { + Some(binary) => builder.emit(SIRInstruction::Binary(next, current, binary, step_reg)), + None => builder.emit(SIRInstruction::Imm(next, SIRValue::new(0u64))), + } + let stalled = builder.alloc_bit(1, false); + let op_stalled = match (reverse, var_signed) { + (false, true) => BinaryOp::LeS, + (false, false) => BinaryOp::LeU, + (true, true) => BinaryOp::GeS, + (true, false) => BinaryOp::GeU, + }; + builder.emit(SIRInstruction::Binary(stalled, next, op_stalled, current)); + let progress = builder.new_block(); + let stall = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: stalled, + true_block: (stall, Vec::new()), + false_block: (progress, Vec::new()), + }); + builder.switch_to_block(stall); + let code = self.parser.runtime_error(stall_message, vec![stmt.var_id]); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(progress); + self.store(&var, next)?; + self.parser.clear_register_cache(); + match single_slot { + Some(single_slot) => { + let single = self.load_scratch(single_slot, 1, false); + self.kernel.builder().seal_block(SIRTerminator::Branch { + cond: single, + true_block: (exit, Vec::new()), + false_block: (header, Vec::new()), + }); + } + None => { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + } + } + self.kernel.builder().switch_to_block(exit); + self.parser.clear_register_cache(); + Ok(Flow::Continue) + } + + /// `value` at `width` bits, sign-extended when `signed`. + fn extend_for_compare(&mut self, value: RegisterId, width: usize, signed: bool) -> RegisterId { + let value = self + .parser + .cast_reg_width_ext(self.kernel.builder(), value, width, signed); + let builder = self.kernel.builder(); + match *builder.register(&value) { + RegisterType::Bit { + width: w, + signed: s, + } if w == width && s == signed => value, + _ => { + let typed = builder.alloc_bit(width, signed); + builder.emit(SIRInstruction::Unary(typed, UnaryOp::Ident, value)); + typed + } + } + } + + fn for_bound( + &mut self, + bound: &ForBound, + width: usize, + signed: bool, + ) -> Result { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_for_bound( + bound, + width, + width, + signed, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ) + } + + fn lower_system_function(&mut self, call: &SystemFunctionCall) -> Result { + match &call.kind { + SystemFunctionKind::Finish => { + self.kernel.finish(); + Ok(Flow::Ended) + } + SystemFunctionKind::Assert { kind, cond, args } => { + self.lower_assert(call, *kind, cond, args) + } + SystemFunctionKind::Readmemh(_, SystemFunctionOutput::Local(_)) => { + self.dirty = true; + self.system_task(call) + } + SystemFunctionKind::Readmemh(filename, SystemFunctionOutput::Hier(reference)) => { + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let id = *self.parser.hierarchical_var(&key).ok_or_else(|| { + self.error( + "$readmemh destination", + format!("`{}` was not resolved", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + let local = SystemFunctionCall { + kind: SystemFunctionKind::Readmemh( + filename.clone(), + SystemFunctionOutput::Local(vec![AssignDestination { + id, + path: reference.var_path.clone(), + index: reference.index.clone(), + select: reference.select.clone(), + comptime: reference.comptime.clone(), + token: reference.comptime.token, + }]), + ), + comptime: call.comptime.clone(), + }; + self.dirty = true; + self.system_task(&local) + } + SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => self.system_task(call), + SystemFunctionKind::Bits(_) + | SystemFunctionKind::Size(..) + | SystemFunctionKind::Clog2(_) + | SystemFunctionKind::Onehot(_) + | SystemFunctionKind::Signed(_) + | SystemFunctionKind::Unsigned(_) => Ok(Flow::Continue), + } + } + + fn system_task(&mut self, call: &SystemFunctionCall) -> Result { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_system_task_statement( + call, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + Ok(Flow::Continue) + } + + fn lower_assert( + &mut self, + call: &SystemFunctionCall, + kind: AssertKind, + cond: &SystemFunctionInput, + args: &[SystemFunctionInput], + ) -> Result { + let condition = self.condition(&cond.0)?; + let location = event_location(&call.comptime.token); + let pass_site = self + .parser + .register_runtime_event_site(RuntimeEventKind::AssertPass, args); + let fail_kind = match kind { + AssertKind::Fatal => RuntimeEventKind::AssertFatal, + AssertKind::Continue => RuntimeEventKind::AssertContinue, + }; + let fail_site = self.parser.register_runtime_event_site(fail_kind, args); + for site in [pass_site, fail_site] { + let index = (site - self.site_base) as usize; + self.parser.runtime_event_sites_mut()[index].location = location.clone(); + } + let prepared = { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.prepare_effectful_runtime_event_args( + args, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )? + }; + let builder = self.kernel.builder(); + let pass_block = builder.new_block(); + let fail_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (pass_block, Vec::new()), + false_block: (fail_block, Vec::new()), + }); + for (block, site) in [(pass_block, pass_site), (fail_block, fail_site)] { + self.kernel.builder().switch_to_block(block); + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.emit_runtime_event_with_prepared_args( + site, + args, + prepared.clone(), + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + if site == fail_site && matches!(kind, AssertKind::Fatal) { + let message = args + .first() + .and_then(|arg| FfParser::static_string_expr(&arg.0)) + .unwrap_or_else(|| "assertion failed".to_string()); + let code = self.parser.runtime_error(message, Vec::new()); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + } else { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } + } + self.kernel.builder().switch_to_block(join); + Ok(Flow::Continue) + } + + /// Inline a function call statement: bind its inputs, run its body, and + /// copy its outputs back. + fn lower_function_call( + &mut self, + call: &veryl_analyzer::ir::FunctionCall, + ) -> Result { + let Some(body) = function_body(&self.ir.functions, call) else { + return Err(self.error( + "function call in an initial block", + format!("{call}"), + Some(&call.comptime.token), + )); + }; + if !self.active_functions.insert(call.id) { + return Err(self.error( + "function call in an initial block", + "recursive call", + Some(&call.comptime.token), + )); + } + for (path, expr) in &call.inputs { + if let Some(&formal) = body.arg_map.get(path) { + let value = self.expression(expr)?; + let destination = self.destination(formal, call.comptime.token); + self.store(&destination, value)?; + } + } + let flow = self.lower_statements(&body.statements)?; + self.active_functions.remove(&call.id); + if let Flow::Ended = flow { + return Ok(Flow::Ended); + } + for (path, destinations) in &call.outputs { + if let Some(&formal) = body.arg_map.get(path) { + for destination in destinations { + let value = self.load_var(formal)?; + self.store(destination, value)?; + } + } + } + Ok(Flow::Continue) + } + + fn lower_tb_method(&mut self, tb: &TbMethodCall) -> Result { + match &tb.method { + TbMethod::ClockNext { count, .. } => { + let clock = self.clock_index(tb.inst)?; + let count = match count { + Some(expr) => { + let value = self.expression(expr)?; + self.unsigned_bits(value, PROCESS_DELAY_WIDTH) + } + None => self.constant(1, PROCESS_DELAY_WIDTH), + }; + self.kernel + .wait_clock(clock, count, None) + .map_err(|error| { + self.error("testbench process lowering", error.to_string(), None) + })?; + self.suspended(); + Ok(Flow::Continue) + } + TbMethod::ResetAssert { clock, duration } => { + let clock_index = self.clock_index(*clock)?; + let reset = self.instance_var(tb.inst)?; + let reset_source = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&reset], + }; + let type_kind = self.lookup.module_variables[&self.module_id][&reset_source.var_id] + .metadata + .type_kind; + let (assert_value, deassert_value) = match type_kind { + PortTypeKind::ResetAsyncHigh | PortTypeKind::ResetSyncHigh => (1, 0), + _ => (0, 1), + }; + let value = self.constant(assert_value, 1); + let destination = self.destination( + reset, + tb.ret.as_ref().map_or(self.ir.token, |ret| ret.token), + ); + self.store(&destination, value)?; + let duration = match duration { + Some(expr) => { + let value = self.expression(expr)?; + let value = self.unsigned_bits(value, PROCESS_DELAY_WIDTH); + // A reset holds for at least one cycle. + let builder = self.kernel.builder(); + let zero = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let one = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + let is_zero = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(is_zero, value, BinaryOp::Eq, zero)); + let held = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Mux(held, is_zero, one, value)); + held + } + None => self.constant(3, PROCESS_DELAY_WIDTH), + }; + let release = match self + .releases + .iter() + .position(|release| release.signal == reset_source) + { + Some(index) => index as u32, + None => { + let clock_var = self.instance_var(*clock)?; + self.releases.push(ProcessRelease { + signal: reset_source, + value: deassert_value, + clock: Some(SourceAddr { + instance_id: self.instance, + var_id: self.ids[&clock_var], + }), + }); + let index = self.kernel.add_release(); + debug_assert_eq!(index as usize + 1, self.releases.len()); + index + } + }; + self.kernel + .wait_clock(clock_index, duration, Some(release)) + .map_err(|error| { + self.error("testbench process lowering", error.to_string(), None) + })?; + self.suspended(); + Ok(Flow::Continue) + } + TbMethod::RandomSeed { value } => { + let seed = self.expression(value)?; + let seed = self.unsigned_bits(seed, 64); + let (host_value, slot) = self.host_scratch("random_seed", false, false)?; + self.store_scratch(slot, 64, seed); + self.host_request(HostRequest::RandomSeed { + handle: self.resource_name(tb.inst), + value: host_value, + })?; + Ok(Flow::Continue) + } + TbMethod::RandomGet { width, signed } => { + let (result, slot) = self.host_scratch("random_value", *signed, false)?; + let result_width = result.width; + self.host_request(HostRequest::RandomGet { + handle: self.resource_name(tb.inst), + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + let value = self.load_scratch(slot, result_width, *signed); + let _ = width; + self.store(ret, value)?; + } + Ok(Flow::Continue) + } + TbMethod::RandomGetRange { + min, + max, + width: _, + signed, + } => { + let min_reg = self.expression(min)?; + let min_reg = self.unsigned_bits(min_reg, 64); + let max_reg = self.expression(max)?; + let max_reg = self.unsigned_bits(max_reg, 64); + let (min_value, min_slot) = self.host_scratch("random_min", *signed, false)?; + let (max_value, max_slot) = self.host_scratch("random_max", *signed, false)?; + let (result, slot) = self.host_scratch("random_value", *signed, false)?; + let result_width = result.width; + self.store_scratch(min_slot, 64, min_reg); + self.store_scratch(max_slot, 64, max_reg); + self.host_request(HostRequest::RandomGetRange { + handle: self.resource_name(tb.inst), + min: min_value, + max: max_value, + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + let value = self.load_scratch(slot, result_width, *signed); + self.store(ret, value)?; + } + Ok(Flow::Continue) + } + TbMethod::RandomGetSeed => { + let (result, slot) = self.host_scratch("random_seed", false, false)?; + self.host_request(HostRequest::RandomGetSeed { + handle: self.resource_name(tb.inst), + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + let value = self.load_scratch(slot, 64, false); + self.store(ret, value)?; + } + Ok(Flow::Continue) + } + TbMethod::Component { method, args } => { + let mut host_args = Vec::new(); + for arg in args { + let is_string = arg.0.comptime().r#type.is_string(); + let signed = expression_signed(&arg.0); + let (value, slot) = self.host_scratch("component_arg", signed, is_string)?; + let width = value.width; + let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm( + reg, + SIRValue::new(BigUint::from_bytes_be(text.as_bytes())), + )); + reg + } else { + let reg = self.expression(&arg.0)?; + self.unsigned_bits(reg, width) + }; + self.store_scratch(slot, width, reg); + host_args.push(value); + } + let result = match tb.ret.as_deref() { + Some(_) => { + let (value, slot) = + self.host_scratch("component_result", tb.ret_signed, false)?; + Some((value, slot)) + } + None => None, + }; + self.host_request(HostRequest::Component { + instance: self.resource_name(tb.inst), + method: source_name(*method), + args: host_args, + result: result.as_ref().map(|(value, _)| value.clone()), + declared_width: tb.ret_width.map(|w| w as usize), + strict: tb.ret_strict, + })?; + if let (Some(ret), Some((value, slot))) = (tb.ret.as_deref(), result) { + let reg = self.load_scratch(slot, value.width, tb.ret_signed); + self.store(ret, reg)?; + } + Ok(Flow::Continue) + } + TbMethod::FileOpen { .. } + | TbMethod::FileWrite { .. } + | TbMethod::FileClose + | TbMethod::FileFlush => Ok(Flow::Continue), + } + } +} + +fn source_name(id: StrId) -> String { + resource_table::get_str_value(id).unwrap_or_else(|| format!("{id}")) +} + +fn try_eval_const(expr: &Expression) -> Option { + if !expr.comptime().is_const { + return None; + } + expr.comptime() + .get_value() + .ok() + .map(|value| value.payload_u64()) +} + +fn event_location(token: &veryl_parser::token_range::TokenRange) -> Option { + let begin = &token.beg; + let file = begin + .source + .get_path() + .and_then(resource_table::get_path_value)?; + Some(EventLocation { + file: file.to_string_lossy().into_owned(), + line: begin.line, + column: begin.column, + }) +} + +/// Drop the blocks control never enters. +fn prune_unreachable_blocks(unit: &mut ExecutionUnit) { + let mut reachable = HashSet::default(); + let mut work = vec![unit.entry_block_id]; + while let Some(block) = work.pop() { + if !reachable.insert(block) { + continue; + } + match &unit.blocks[&block].terminator { + SIRTerminator::Jump(target, _) => work.push(*target), + SIRTerminator::Branch { + true_block, + false_block, + .. + } => { + work.push(true_block.0); + work.push(false_block.0); + } + SIRTerminator::Switch { cases, default, .. } => { + work.extend(cases.iter().map(|case| case.target)); + work.push(*default); + } + SIRTerminator::Return | SIRTerminator::Error(_) => {} + } + } + unit.blocks.retain(|id, _| reachable.contains(id)); +} + +/// Map the addresses and runtime error codes of a unit. +fn map_unit( + unit: &ExecutionUnit, + codes: &HashMap, + mut map: impl FnMut(&A) -> Result, +) -> Result, ParserError> { + let mut blocks = HashMap::default(); + let mut ids: Vec<&BlockId> = unit.blocks.keys().collect(); + ids.sort(); + for id in ids { + let block = &unit.blocks[id]; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in &block.instructions { + // Resolve every address first, then rebuild with the results. + let mut resolved = Vec::new(); + let mut failure = None; + instruction.map_addr(|address| match map(address) { + Ok(address) => resolved.push(address), + Err(error) => { + failure.get_or_insert(error); + } + }); + if let Some(error) = failure { + return Err(error); + } + let mut resolved = resolved.into_iter(); + instructions.push( + instruction + .map_addr(|_| resolved.next().expect("one resolved address per address")), + ); + } + let terminator = match &block.terminator { + SIRTerminator::Error(code) => { + SIRTerminator::Error(codes.get(code).copied().unwrap_or(*code)) + } + other => other.clone(), + }; + blocks.insert( + *id, + BasicBlock { + id: block.id, + params: block.params.clone(), + instructions, + terminator, + }, + ); + } + Ok(ExecutionUnit { + entry_block_id: unit.entry_block_id, + blocks, + register_map: unit.register_map.clone(), + }) +} diff --git a/crates/celox-frontend-veryl/src/module.rs b/crates/celox-frontend-veryl/src/module.rs index 1067a58cb57..3114aed9e16 100644 --- a/crates/celox-frontend-veryl/src/module.rs +++ b/crates/celox-frontend-veryl/src/module.rs @@ -2343,7 +2343,7 @@ pub(crate) fn readmem_image( }; index }; - if depth <= 1 { + if depth == 0 || var.r#type.array.iter().count() == 0 { return Err(ParserError::illegal_context( "$readmemh destination", "destination must be an unpacked array", diff --git a/crates/celox-frontend-veryl/src/schedule.rs b/crates/celox-frontend-veryl/src/schedule.rs index 35506392f97..739eb57d083 100644 --- a/crates/celox-frontend-veryl/src/schedule.rs +++ b/crates/celox-frontend-veryl/src/schedule.rs @@ -30,6 +30,7 @@ pub fn schedule_symbolic_rtl( symbolic, module_ir, source_id_maps, + process_storage, } = source; let root_id = symbolic.root_id; let root = module_ir.get(&root_id).copied(); @@ -62,7 +63,7 @@ pub fn schedule_symbolic_rtl( .unwrap_or_default(); let fused_ff_factory = super::lowering::global_ff::VerylFusedFfFactory::new(&module_ir, &source_id_maps, *config); - let output = assembly::schedule_symbolic_rtl( + let mut output = assembly::schedule_symbolic_rtl( symbolic, Some(&fused_ff_factory), ignored_loops, @@ -131,7 +132,7 @@ pub fn schedule_symbolic_rtl( components.append(&mut instance_components); component_bindings.append(&mut instance_bindings); } - let testbench_source = VerylTestbenchSource { + let mut testbench_source = VerylTestbenchSource { id_map: VerylIdMap { module_variables: source_id_maps, }, @@ -159,11 +160,23 @@ pub fn schedule_symbolic_rtl( component_bindings, component_libraries: Vec::new(), component_file_base: None, + kernels: false, }; + if config.testbench_kernels && !testbench_source.is_empty() { + super::lowering::process::lower_testbench_kernels( + &mut output.scheduled, + &testbench_source, + &module_ir, + &process_storage, + config, + )?; + testbench_source.kernels = true; + } // Use the exact elaborated module, including parameter specialization, for // each process owner. Resolving by root/module name loses child scopes. let mut dynamic_for_diagnostics = Vec::new(); for source in testbench_source.sources() { + let lookup = &output.scheduled.frontend_lookup; let instance = source.base_instance(lookup); let module = module_ir[&lookup.instance_module[&instance]]; dynamic_for_diagnostics.extend(super::check_elaborated_dynamic_for_bounds( diff --git a/crates/celox-frontend-veryl/src/source.rs b/crates/celox-frontend-veryl/src/source.rs index 3e441520ff5..8732afbdf46 100644 --- a/crates/celox-frontend-veryl/src/source.rs +++ b/crates/celox-frontend-veryl/src/source.rs @@ -73,6 +73,9 @@ pub struct VerylTestbenchSource { pub component_bindings: Vec, pub component_libraries: Vec, pub component_file_base: Option, + /// The `initial` blocks were compiled into process kernels: the + /// testbench program carries only the components. + pub kernels: bool, } impl VerylTestbenchSource { diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 97f6872fcca..4311d8e3dd0 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -116,6 +116,7 @@ fn runtime_event_site_for_assert( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, } } @@ -593,7 +594,7 @@ fn variable_access_width( } } -enum TestbenchRead { +pub(crate) enum TestbenchRead { Root(VarId), Hierarchical(Box), } @@ -702,7 +703,7 @@ fn collect_instance_testbench_observability( Ok((sites, reads)) } -fn collect_statement_reads( +pub(crate) fn collect_statement_reads( stmts: &[Statement], funcs: &fxhash::FxHashMap, active_functions: &mut FxHashSet, @@ -1057,7 +1058,7 @@ fn lower_testbench_operator(op: VerylOp) -> Op { } } -struct ExprCompiler<'a> { +pub(crate) struct ExprCompiler<'a> { lookup: &'a FrontendLookup, id_map: &'a VerylIdMap, functions: &'a HashMap, @@ -1967,7 +1968,7 @@ impl ExprCompiler<'_> { Self::validate_target_bounds_parts(info, &destination.index, &destination.select) } - fn validate_target_bounds_parts( + pub(crate) fn validate_target_bounds_parts( info: &VariableInfo, index: &VarIndex, select: &VarSelect, @@ -3593,6 +3594,9 @@ pub fn compile_semantic_testbench( let mut site_end = runtime_event_site_count.saturating_sub(total_sites); let mut processes = Vec::new(); for source in sources { + if source.kernels { + break; + } let initial_stmts = source.initial_statements.as_ref().unwrap(); validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?; site_end += count_assert_statements(initial_stmts, &source.functions); diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index b2971573734..a7f13c911a2 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -18,8 +18,8 @@ pub use reflection::{ SignalDirection, }; pub use simulation::{ - EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ScheduleParts, SimulationExecutor, - SimulationSnapshot, SimulationState, + EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ProcessReleaseRef, ScheduleParts, + SimulationExecutor, SimulationSnapshot, SimulationState, }; pub use state_file::{ ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index efda830f536..d6b18a0c842 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -63,6 +63,25 @@ pub trait SimulationExecutor { true } + /// Serve host request `request` of process `process` at `time`, reading + /// and writing the scratch state the request names. Returns whether the + /// process resumes; `false` ends the simulation, as when a host + /// component requested the end of the run. + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + let _ = time; + Err(SimulatorErrorCode::Runtime { + message: format!( + "process {process} made host request {request}, which this host does not serve" + ), + signals: Vec::new(), + }) + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -111,7 +130,29 @@ pub struct ProcessRefs { pub status: SignalRef, pub delay: SignalRef, pub clock: SignalRef, + pub release: SignalRef, pub clocks: Vec>, + /// The writes a clock wait may end with. + pub releases: Vec>, +} + +/// A write a clock wait ends with: the signal, the event of its domain +/// when it is the clock or reset of one, and the value. +#[derive(Debug)] +pub struct ProcessReleaseRef { + pub signal: SignalRef, + pub event: Option, + pub value: u64, +} + +impl Clone for ProcessReleaseRef { + fn clone(&self) -> Self { + Self { + signal: self.signal, + event: self.event, + value: self.value, + } + } } impl Clone for ProcessRefs { @@ -120,7 +161,9 @@ impl Clone for ProcessRefs { status: self.status, delay: self.delay, clock: self.clock, + release: self.release, clocks: self.clocks.clone(), + releases: self.releases.clone(), } } } @@ -151,11 +194,12 @@ impl Clone for TickClock { } /// A process waiting for `remaining` more rising edges of the process clock -/// with event id `clock`. +/// with event id `clock`, ending with the process's release `release`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ClockWait { clock: usize, remaining: u64, + release: Option, } /// The state of one process clock, for schedules expressed by name. @@ -228,6 +272,9 @@ pub struct SimulationState { scheduler: Scheduler, periodic_events: FxHashMap, last_clock_values: BitSet, + /// Events whose signal was x or z when edge detection last sampled it: + /// a change to a known value is an edge (IEEE 1800-2023 9.4.2). + unknown_clock_values: BitSet, topo_signals: Vec<(SignalRef, usize, usize)>, domain_kinds: Vec>, event_info: Vec>, @@ -243,24 +290,45 @@ pub struct SimulationState { clock_waits: BTreeMap, /// Processes that ran to their end. done: BTreeSet, - /// Rising edges of process clocks so far. + /// Writes to make when a process resumes from a clock wait. + pending_releases: BTreeMap, + /// Times with a rising edge of a process clock so far. ticks: u64, + /// How many more times with a rising edge of a process clock may run. + /// At zero, pending falling edges and releases still complete, but no + /// edge fires and no process resumes from a clock wait. + tick_budget: Option, /// A process requested the end of the simulation. finished: bool, } +/// Whether an event signal is nonzero, and whether it is x or z. +fn sample_event_signal(backend: &B, signal: SignalRef) -> (bool, bool) { + if backend.layout().four_state && signal.is_4state { + let (value, mask) = backend.get_four_state(signal); + (value.bits() != 0, mask.bits() != 0) + } else { + let value: u8 = backend.get_as(signal); + (value != 0, false) + } +} + impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.last_clock_values.make_empty(); + self.unknown_clock_values.make_empty(); for (signal, id, _) in &self.topo_signals { if *id == usize::MAX { continue; } - let value: u8 = backend.get_as(*signal); - if value != 0 { + let (is_nonzero, is_unknown) = sample_event_signal(backend, *signal); + if is_nonzero { self.last_clock_values.insert(*id); } + if is_unknown { + self.unknown_clock_values.insert(*id); + } } } @@ -271,16 +339,16 @@ impl SimulationState { continue; } let was_nonzero = self.last_clock_values.contains(*id); - let value: u8 = backend.get_as(*signal); - let is_nonzero = value != 0; + let was_unknown = self.unknown_clock_values.contains(*id); + let (is_nonzero, is_unknown) = sample_event_signal(backend, *signal); let triggered = match self.domain_kinds[*id] { Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - !was_nonzero && is_nonzero + (!was_nonzero || was_unknown) && is_nonzero && !is_unknown } Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - was_nonzero && !is_nonzero + (was_nonzero || was_unknown) && !is_nonzero && !is_unknown } - _ => was_nonzero != is_nonzero, + _ => (was_nonzero, was_unknown) != (is_nonzero, is_unknown), }; if triggered { backend.mark_triggered_bit(*id); @@ -297,22 +365,27 @@ impl SimulationState { processes: Vec>, ) -> Self { let mut last_clock_values = BitSet::with_capacity(backend.num_events()); + let mut unknown_clock_values = BitSet::with_capacity(backend.num_events()); let mut signal_to_id = FxHashMap::default(); for (signal, id, _) in topo_signals.iter().copied() { if id == usize::MAX { continue; } signal_to_id.insert(signal, id); - let value: u8 = backend.get_as(signal); - if value != 0 { + let (is_nonzero, is_unknown) = sample_event_signal(backend, signal); + if is_nonzero { last_clock_values.insert(id); } + if is_unknown { + unknown_clock_values.insert(id); + } } Self { scheduler: Scheduler::new(), periodic_events: FxHashMap::default(), last_clock_values, + unknown_clock_values, topo_signals, domain_kinds, event_info, @@ -325,16 +398,40 @@ impl SimulationState { tick_clocks: BTreeMap::new(), clock_waits: BTreeMap::new(), done: BTreeSet::new(), + pending_releases: BTreeMap::new(), ticks: 0, + tick_budget: None, finished: false, } } - /// Rising edges of process clocks the simulation has run so far. + /// Times with a rising edge of a process clock the simulation has run + /// so far. pub fn ticks(&self) -> u64 { self.ticks } + /// Limit the times with a rising edge of a process clock that may still + /// run; `None` lifts the limit. + pub fn set_tick_budget(&mut self, budget: Option) { + self.tick_budget = budget; + } + + /// Whether the tick budget is spent. + pub fn tick_budget_spent(&self) -> bool { + self.tick_budget == Some(0) + } + + /// Whether a process still waits for edges of a clock. + pub fn has_clock_waits(&self) -> bool { + !self.clock_waits.is_empty() + } + + /// Whether every process ran to its end. + pub fn all_processes_done(&self) -> bool { + self.done.len() == self.processes.len() + } + fn clock_has_waiters(&self, clock: usize) -> bool { self.clock_waits.values().any(|wait| wait.clock == clock) } @@ -404,18 +501,7 @@ impl SimulationState { } else { Vec::new() }; - for clock in self.tick_clocks.values_mut() { - if clock.falling_edge == Some(current_time) { - clock.falling_edge = None; - events_to_process.push(SimEvent { - time: current_time, - event_ref: clock.event, - signal: clock.signal, - next_val: 0, - }); - } - } - let ready = self.take_ready_processes(current_time); + let ready = self.take_ready_processes(executor, current_time, &mut events_to_process); self.step_round(executor, current_time, events_to_process, ready, true)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); @@ -440,66 +526,93 @@ impl SimulationState { E: SimulationExecutor, { while !self.finished { - let due: Vec = self + let due: Vec = if self.tick_budget_spent() { + Vec::new() + } else { + self.tick_clocks + .iter() + .filter(|(id, clock)| { + clock.next_edge == current_time && self.clock_has_waiters(**id) + }) + .map(|(id, _)| *id) + .collect() + }; + let falling: Vec = self .tick_clocks .iter() - .filter(|(id, clock)| { - clock.next_edge == current_time && self.clock_has_waiters(**id) - }) + .filter(|(_, clock)| clock.falling_edge == Some(current_time)) .map(|(id, _)| *id) .collect(); - if let [clock] = due[..] + if falling.is_empty() + && let [clock] = due[..] && self.fused_ticks(executor, clock, current_time, limit)? { // Time moved on; the processes that resume run in the next step. return Ok(()); } - let fired = !due.is_empty(); + let fired = !due.is_empty() || !falling.is_empty(); if fired { - self.fire_edges(executor, current_time, &due)?; + self.fire_edges(executor, current_time, &due, &falling)?; } - let ready = self.take_ready_processes(current_time); - if ready.is_empty() && self.waiting.is_empty() { + let mut events = Vec::new(); + let ready = self.take_ready_processes(executor, current_time, &mut events); + if ready.is_empty() && self.waiting.is_empty() && events.is_empty() { if fired { // The edges may have released waits that resume now. continue; } break; } - if !self.step_round(executor, current_time, Vec::new(), ready, false)? && !fired { + if !self.step_round(executor, current_time, events, ready, false)? && !fired { break; } } Ok(()) } - /// Apply the rising edges of the process clocks `due` at `time`, count - /// them against the processes waiting on them, and schedule the - /// resumptions and falling edges. + /// Apply the rising edges of the process clocks `due` and the falling + /// edges of the clocks `falling` at `time` as one set of simultaneous + /// events, count the rising edges against the processes waiting on + /// them, and schedule the resumptions and falling edges. fn fire_edges( &mut self, executor: &mut E, time: u64, due: &[usize], + falling: &[usize], ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { - let events = due + let events = falling .iter() - .map(|id| { + .map(|id| (id, 0)) + .chain(due.iter().map(|id| (id, 1))) + .map(|(id, next_val)| { let clock = &self.tick_clocks[id]; SimEvent { time, event_ref: clock.event, signal: clock.signal, - next_val: 1, + next_val, } }) .collect(); + for id in falling { + self.tick_clocks + .get_mut(id) + .expect("a process clock with a falling edge") + .falling_edge = None; + } self.step_round(executor, time, events, Vec::new(), true)?; + if due.is_empty() { + return Ok(()); + } + self.ticks += 1; + if let Some(budget) = &mut self.tick_budget { + *budget -= 1; + } for id in due { - self.ticks += 1; let clock = self.tick_clocks.get_mut(id).expect("a due process clock"); clock.next_edge = time + clock.period; clock.falling_edge = Some(time + clock.period - clock.period / 2); @@ -522,7 +635,10 @@ impl SimulationState { }) .collect(); for process in released { - self.clock_waits.remove(&process); + let wait = self.clock_waits.remove(&process).expect("a released wait"); + if let Some(release) = wait.release { + self.pending_releases.insert(process, release); + } self.process_wakeups.push(Reverse((resume_at, process))); } } @@ -562,8 +678,11 @@ impl SimulationState { (clock.event, clock.period) }; // Edges at `time`, `time + period`, ...: the last one stays at or - // before `limit`. - let count = needed.min(limit.saturating_sub(time) / period + 1); + // before `limit` and within the tick budget. + let mut count = needed.min(limit.saturating_sub(time) / period + 1); + if let Some(budget) = self.tick_budget { + count = count.min(budget); + } if count == 0 { return Ok(false); } @@ -576,6 +695,9 @@ impl SimulationState { }); } self.ticks += completed; + if let Some(budget) = &mut self.tick_budget { + *budget -= completed; + } let next_edge = time + completed * period; self.tick_clocks .get_mut(&clock) @@ -607,14 +729,46 @@ impl SimulationState { Ok(()) } - /// Remove the processes waiting for `time`, in declaration order. - fn take_ready_processes(&mut self, time: u64) -> Vec { + /// Remove the processes waiting for `time`, in declaration order. With + /// the tick budget spent, a process resuming from a clock wait only gets + /// its release and stays suspended. + /// The processes that resume at `time`, after making the releases their + /// waits ended with: a release of a signal with an event domain is an + /// event of `time`, added to `events`, so the domain and the host hooks + /// see its edge; any other is written directly. Once the tick budget + /// is spent, releases are still made but no process resumes. + fn take_ready_processes( + &mut self, + executor: &mut E, + time: u64, + events: &mut Vec>, + ) -> Vec + where + E: SimulationExecutor, + { let mut ready = Vec::new(); while let Some(&Reverse((wakeup, process))) = self.process_wakeups.peek() { if wakeup != time { break; } self.process_wakeups.pop(); + if let Some(release) = self.pending_releases.remove(&process) { + let release = self.processes[process].releases[release].clone(); + match release.event { + Some(event) => events.push(SimEvent { + time, + event_ref: event, + signal: release.signal, + next_val: release.value as u8, + }), + None => executor + .backend_mut() + .set_wide(release.signal, release.value.into()), + } + } + if self.tick_budget_spent() { + continue; + } ready.push(process); } ready @@ -648,75 +802,110 @@ impl SimulationState { } let mut any_ran = false; for process in pass.drain(..) { - executor.run_process(process)?; - let refs = &self.processes[process]; - let status: u8 = executor.backend().get_as(refs.status); - match ProcessStatus::from_code(status) { - Some(ProcessStatus::Delay) => { - let delay: u64 = executor.backend().get_as(refs.delay); - let time = current_time.checked_add(delay).ok_or_else(|| { - SimulatorErrorCode::Runtime { - message: format!( - "process {process} delay overflows simulation time" - ), - signals: Vec::new(), + // A settle resumes the same process at once. + loop { + executor.run_process(process)?; + let refs = &self.processes[process]; + let status: u8 = executor.backend().get_as(refs.status); + match ProcessStatus::from_code(status) { + Some(ProcessStatus::Settle) => { + executor.eval_comb()?; + any_ran = true; + continue; + } + Some(ProcessStatus::Delay) => { + let delay: u64 = executor.backend().get_as(refs.delay); + let time = current_time.checked_add(delay).ok_or_else(|| { + SimulatorErrorCode::Runtime { + message: format!( + "process {process} delay overflows simulation time" + ), + signals: Vec::new(), + } + })?; + self.waiting.remove(&process); + self.process_wakeups.push(Reverse((time, process))); + any_ran = true; + } + Some(ProcessStatus::Done) => { + self.waiting.remove(&process); + self.done.insert(process); + any_ran = true; + } + Some(ProcessStatus::Finish) => { + self.waiting.remove(&process); + self.done.insert(process); + self.finished = true; + return Ok(true); + } + Some(ProcessStatus::Wait) => { + self.waiting.insert(process); + any_ran = true; + } + Some(ProcessStatus::WaitClock) => { + let count: u64 = executor.backend().get_as(refs.delay); + let index: u32 = executor.backend().get_as(refs.clock); + let release: u32 = executor.backend().get_as(refs.release); + let Some(clock) = refs.clocks.get(index as usize) else { + return Err(SimulatorErrorCode::InternalError); + }; + let release = match release { + 0 => None, + index if (index as usize) <= refs.releases.len() => { + Some(index as usize - 1) + } + _ => return Err(SimulatorErrorCode::InternalError), + }; + self.waiting.remove(&process); + if count == 0 { + // Nothing to wait for: the process continues in + // the next pass, after its release. + if let Some(release) = release { + let release = refs.releases[release].clone(); + executor + .backend_mut() + .set_wide(release.signal, release.value.into()); + } + again.push(process); + } else { + let id = clock.event.id(); + let tick_clock = + self.tick_clocks.entry(id).or_insert_with(|| TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period.max(2), + next_edge: current_time, + falling_edge: None, + }); + tick_clock.next_edge = tick_clock.next_edge.max(current_time); + self.clock_waits.insert( + process, + ClockWait { + clock: id, + remaining: count, + release, + }, + ); + } + any_ran = true; + } + Some(ProcessStatus::Host) => { + let request: u64 = executor.backend().get_as(refs.delay); + self.waiting.remove(&process); + if !executor.host_request(process, request as usize, current_time)? { + self.done.insert(process); + self.finished = true; + return Ok(true); } - })?; - self.waiting.remove(&process); - self.process_wakeups.push(Reverse((time, process))); - any_ran = true; - } - Some(ProcessStatus::Done) => { - self.waiting.remove(&process); - self.done.insert(process); - any_ran = true; - } - Some(ProcessStatus::Finish) => { - self.waiting.remove(&process); - self.done.insert(process); - self.finished = true; - return Ok(true); - } - Some(ProcessStatus::Wait) => { - self.waiting.insert(process); - any_ran = true; - } - Some(ProcessStatus::WaitClock) => { - let count: u64 = executor.backend().get_as(refs.delay); - let index: u32 = executor.backend().get_as(refs.clock); - let Some(clock) = refs.clocks.get(index as usize) else { - return Err(SimulatorErrorCode::InternalError); - }; - self.waiting.remove(&process); - if count == 0 { - // Nothing to wait for: the process continues in - // the next pass. again.push(process); - } else { - let id = clock.event.id(); - let tick_clock = - self.tick_clocks.entry(id).or_insert_with(|| TickClock { - event: clock.event, - signal: clock.signal, - period: clock.period.max(2), - next_edge: current_time, - falling_edge: None, - }); - tick_clock.next_edge = tick_clock.next_edge.max(current_time); - self.clock_waits.insert( - process, - ClockWait { - clock: id, - remaining: count, - }, - ); + any_ran = true; } - any_ran = true; + // The kernel found its wait condition unmet and ran + // nothing; it stays waiting. + Some(ProcessStatus::Pending) => {} + None => return Err(SimulatorErrorCode::InternalError), } - // The kernel found its wait condition unmet and ran - // nothing; it stays waiting. - Some(ProcessStatus::Pending) => {} - None => return Err(SimulatorErrorCode::InternalError), + break; } } if !any_ran { @@ -799,24 +988,28 @@ impl SimulationState { // Processes run after this time's scheduled values are applied and // see the state settled at the previous time. The event signals they // change are edges of this time, like scheduled events. + // (event, whether the signal is nonzero now, whether it was unknown + // before): a four-state edge from x or z counts as an edge. let mut process_driven = Vec::new(); if !ready_processes.is_empty() || !self.waiting.is_empty() { - let before: Vec = self + let before: Vec<(bool, bool)> = self .topo_signals .iter() - .map(|(signal, _, _)| executor.backend().get_as(*signal)) + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect(); let progressed = self.run_processes(executor, current_time, ready_processes)?; if !progressed && !settle_idle && events_to_process.is_empty() { return Ok(false); } - for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { + for ((signal, id, _), (was_nonzero, was_unknown)) in + self.topo_signals.iter().zip(before) + { if *id == usize::MAX { continue; } - let value: u8 = executor.backend().get_as(*signal); - if value != before { - process_driven.push((*id, value != 0)); + let (is_nonzero, is_unknown) = sample_event_signal(executor.backend(), *signal); + if (is_nonzero, is_unknown) != (was_nonzero, was_unknown) { + process_driven.push((*id, is_nonzero, was_unknown)); } } } @@ -835,20 +1028,21 @@ impl SimulationState { .filter_map(|event| { self.signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, event.next_val != 0, false)) }) .chain(process_driven); - for (id, is_nonzero) in scheduled { + for (id, is_nonzero, from_unknown) in scheduled { track_stable_edges = true; let was_nonzero = self.last_clock_values.contains(id); + let from_unknown = from_unknown || self.unknown_clock_values.contains(id); let triggered = match self.domain_kinds[id] { Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - !was_nonzero && is_nonzero + (!was_nonzero || from_unknown) && is_nonzero } Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - was_nonzero && !is_nonzero + (was_nonzero || from_unknown) && !is_nonzero } - _ => !was_nonzero && is_nonzero, + _ => (!was_nonzero || from_unknown) && is_nonzero, }; if triggered { scheduled_trigger_ids.insert(id); @@ -971,12 +1165,17 @@ impl SimulationState { if *id == usize::MAX { continue; } - let value: u8 = executor.backend().get_as(*signal); - if value != 0 { + let (is_nonzero, is_unknown) = sample_event_signal(executor.backend(), *signal); + if is_nonzero { self.last_clock_values.insert(*id); } else { self.last_clock_values.remove(*id); } + if is_unknown { + self.unknown_clock_values.insert(*id); + } else { + self.unknown_clock_values.remove(*id); + } } for event in periodic_events_to_process { @@ -1009,12 +1208,13 @@ impl SimulationState { return None; } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); + let budget_spent = self.tick_budget_spent(); let clocks = self .tick_clocks .iter() .flat_map(|(id, clock)| { [ - self.clock_has_waiters(*id).then_some(clock.next_edge), + (!budget_spent && self.clock_has_waiters(*id)).then_some(clock.next_edge), clock.falling_edge, ] }) @@ -1045,11 +1245,13 @@ impl SimulationState { event_queue: self.scheduler.event_queue.clone(), periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), + unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), done: self.done.clone(), + pending_releases: self.pending_releases.clone(), ticks: self.ticks, finished: self.finished, } @@ -1083,6 +1285,8 @@ impl SimulationState { self.periodic_events.clone_from(&snapshot.periodic_events); self.last_clock_values .clone_from(&snapshot.last_clock_values); + self.unknown_clock_values + .clone_from(&snapshot.unknown_clock_values); let tick_clocks = snapshot .tick_clocks .iter() @@ -1101,6 +1305,7 @@ impl SimulationState { self.tick_clocks = tick_clocks; self.clock_waits.clone_from(&snapshot.clock_waits); self.done.clone_from(&snapshot.done); + self.pending_releases.clone_from(&snapshot.pending_releases); self.ticks = snapshot.ticks; self.finished = snapshot.finished; Ok(()) @@ -1127,8 +1332,10 @@ pub struct ScheduleParts { /// Process clocks that have been waited on. pub process_clocks: Vec>, /// Processes waiting for edges of a process clock: the process, the - /// clock's event, and the edges still to wait for. - pub clock_waits: Vec<(usize, B::Event, u64)>, + /// clock's event, the edges still to wait for, and the release index. + pub clock_waits: Vec<(usize, B::Event, u64, Option)>, + /// Releases to make when a process resumes: process and release index. + pub pending_releases: Vec<(usize, usize)>, /// Processes that ran to their end, in ascending order. pub done_processes: Vec, /// Rising edges of process clocks so far. @@ -1191,7 +1398,12 @@ impl SimulationState { clock_waits: self .clock_waits .iter() - .map(|(process, wait)| (*process, events[wait.clock], wait.remaining)) + .map(|(process, wait)| (*process, events[wait.clock], wait.remaining, wait.release)) + .collect(), + pending_releases: self + .pending_releases + .iter() + .map(|(process, release)| (*process, *release)) .collect(), done_processes: self.done.iter().copied().collect(), ticks: self.ticks, @@ -1218,6 +1430,8 @@ impl SimulationState { .map(|(event, count)| (PeriodicEventKey::from_event(&event), count as usize)) .collect(); self.last_clock_values.make_empty(); + // A state file holds known values only. + self.unknown_clock_values.make_empty(); for event in parts.high_events { self.last_clock_values.insert(event.id()); } @@ -1246,16 +1460,18 @@ impl SimulationState { self.clock_waits = parts .clock_waits .into_iter() - .map(|(process, event, remaining)| { + .map(|(process, event, remaining, release)| { ( process, ClockWait { clock: event.id(), remaining, + release, }, ) }) .collect(); + self.pending_releases = parts.pending_releases.into_iter().collect(); self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; self.finished = parts.finished; @@ -1269,11 +1485,13 @@ pub struct SimulationSnapshot { event_queue: std::collections::BinaryHeap>, periodic_events: FxHashMap, last_clock_values: BitSet, + unknown_clock_values: BitSet, process_wakeups: BinaryHeap, waiting: BTreeSet, tick_clocks: BTreeMap>, clock_waits: BTreeMap, done: BTreeSet, + pending_releases: BTreeMap, ticks: u64, finished: bool, } @@ -1286,11 +1504,13 @@ impl Clone for SimulationSnapshot { event_queue: self.event_queue.clone(), periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), + unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), done: self.done.clone(), + pending_releases: self.pending_releases.clone(), ticks: self.ticks, finished: self.finished, } diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index e07ca03c890..83a3d253cca 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -179,7 +179,7 @@ pub trait LayoutSource { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(bound( - serialize = "A: Serialize + Eq + Hash", + serialize = "A: Serialize + Eq + Hash + Ord", deserialize = "A: Deserialize<'de> + Eq + Hash" ))] pub struct MemoryLayout { @@ -188,20 +188,27 @@ pub struct MemoryLayout { pub four_state: bool, pub mode: MemoryLayoutMode, /// Stable region offsets. Includes all declared state objects. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub offsets: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub widths: HashMap, /// Whether each state object has a four-state source type. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub is_4states: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub unpacked_arrays: HashMap, /// Stable region size in bytes. pub total_size: usize, /// Working region offsets. Includes only actually-used state objects. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub working_offsets: HashMap, pub working_base_offset: usize, /// Copy-on-write next-state data for dynamically addressed FF targets. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub sparse_offsets: HashMap, pub sparse_base_offset: usize, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub sparse_layouts: HashMap, pub sparse_active_bits_offset: usize, pub sparse_active_capacity: usize, diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 88cc458d342..873c796e24a 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1303,6 +1303,7 @@ fn process_runtime_events() { RuntimeEvent::AssertContinue { message } => { let _ = writeln!(std::io::stderr().lock(), "assertion failed: {message}"); } + RuntimeEvent::AssertPass { .. } => {} RuntimeEvent::AssertFatal { message } => { let _ = writeln!( std::io::stderr().lock(), diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index 5654b358f7e..2c44b4e4b46 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -187,7 +187,8 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { for event in sim.drain_runtime_events() { match event { celox::RuntimeEvent::Display { message } - | celox::RuntimeEvent::AssertContinue { message } => { + | celox::RuntimeEvent::AssertContinue { message } + | celox::RuntimeEvent::AssertPass { message } => { writeln!(stdout, "{message}").unwrap(); } celox::RuntimeEvent::Write { message } => write!(stdout, "{message}").unwrap(), diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 9f6eceb90a7..c3682cff0d8 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -379,12 +379,15 @@ struct NativeRuntimeOptions { #[derive(Clone, Debug, Serialize, Deserialize)] pub(crate) struct NativeRuntimeSchema { + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub(crate) runtime_errors: HashMap>, pub(crate) runtime_event_sites: Vec, /// Extern functions the code calls, resolved when the image is attached. pub(crate) extern_functions: Vec, pub(crate) comb_observers: Vec>, + #[serde(serialize_with = "celox_design::serde_sorted::set")] pub(crate) testbench_read_roots: HashSet, + #[serde(serialize_with = "celox_design::serde_sorted::set")] pub(crate) rtl_writes: HashSet>, /// Ordered so that the encoded image does not depend on hash order. pub(crate) comb_writes: std::collections::BTreeSet, @@ -403,8 +406,11 @@ pub struct NativeProgramImage { /// Entry offset of each process kernel. process_offsets: Vec, required_native_features: u8, + #[serde(serialize_with = "celox_design::serde_sorted::map")] event_map: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] eval_only_event_map: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] apply_event_map: HashMap, id_to_addr: Vec, id_to_event: Vec, @@ -432,6 +438,15 @@ impl NativeProgramImage { if let Some(testbench) = &mut self.testbench { testbench.try_map_paths(&mut map)?; } + for site in &mut self.runtime_schema.runtime_event_sites { + if let Some(location) = &mut site.location + && !location.file.is_empty() + { + location.file = map(std::path::Path::new(&location.file))? + .to_string_lossy() + .into_owned(); + } + } Ok(()) } diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index d24aed9fdf8..9580a778596 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -449,6 +449,7 @@ impl NativeProgramInstance { )), RuntimeEvent::Display { .. } | RuntimeEvent::Write { .. } + | RuntimeEvent::AssertPass { .. } | RuntimeEvent::AssertContinue { .. } | RuntimeEvent::Finish => None, }) { diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 7958e262b6b..16d33713108 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -753,6 +753,20 @@ impl ComponentRuntime { result } + /// The events bound as resets of components. + pub(crate) fn reset_event_ids(&self) -> Vec { + let mut ids: Vec = self + .components + .iter() + .flat_map(|component| &component.events) + .filter(|event| event.reset) + .map(|event| event.event_id) + .collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } + pub(crate) fn begin_reset_cycles(&mut self, reset_event_id: Option) { if let Some(id) = reset_event_id { self.active_reset_events.push((None, id)); @@ -885,7 +899,14 @@ pub(crate) fn host_value_from_argument( width: usize, is_string: bool, ) -> HostValue { - let value = value.to_biguint(); + host_value_from_bits(value.to_biguint(), width, is_string) +} + +pub(crate) fn host_value_from_bits( + value: num_bigint::BigUint, + width: usize, + is_string: bool, +) -> HostValue { if is_string { let byte_len = width.div_ceil(8); let mut bytes = value.to_bytes_be(); diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 24617ac6763..2d7bf6a5064 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -87,8 +87,11 @@ impl RuntimeInstance { #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct RuntimeDesign { semantic: celox_design::ElaboratedDesign, + #[serde(serialize_with = "celox_design::serde_sorted::map")] instances: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] instance_ids: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] variables: HashMap, } @@ -723,6 +726,13 @@ fn collect_comb_writes(program: &mut OptimizedSir) { fn rebuild_rtl_writes(program: &mut OptimizedSir) { let mut rtl_writes = crate::HashSet::default(); + // The kernels of a Veryl testbench drive signals as the testbench, not + // as RTL; the processes of an SV design are RTL. + let processes = if program.runtime.testbench.is_some() { + &[][..] + } else { + &program.sir.processes[..] + }; for unit in program .sir .eval_comb @@ -738,7 +748,7 @@ fn rebuild_rtl_writes(program: &mut OptimizedSir) { .iter() .flat_map(|parallel| parallel.units().map(|unit| &unit.unit)), ) - .chain(&program.sir.processes) + .chain(processes) { for block in unit.blocks.values() { for instruction in &block.instructions { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index e6b810d7a80..59146023ec1 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -120,6 +120,20 @@ impl SimulationExecutor for Simulator { !self.components.has_scheduled_components() } + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + crate::testbench::kernels::serve_host_request(self, process, request, time).map_err( + |message| RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }, + ) + } + fn stage_external_event( &mut self, event: B::Event, @@ -134,13 +148,42 @@ impl SimulationExecutor for Simulator { event: B::Event, timestamp: u64, ) -> Result<(), RuntimeErrorCode> { - let writes = self - .components - .fire(event.id(), timestamp) - .map_err(|message| RuntimeErrorCode::Runtime { - message, - signals: Vec::new(), - })?; + // A testbench holds its resets through releases; while one is + // asserted, its components take reset cycles. + if !self.program.runtime_schema.processes.is_empty() { + for reset_event in self.components.reset_event_ids() { + let address = self.backend.id_to_addr_slice()[reset_event]; + let Some(release) = self + .program + .runtime_schema + .processes + .iter() + .flat_map(|slots| &slots.releases) + .find(|release| release.signal == address) + else { + continue; + }; + let signal = self.backend.resolve_signal(&address); + if self.backend.get(signal) == release.value.into() { + continue; + } + match release + .clock + .and_then(|clock| self.backend.resolve_event_opt(&clock)) + { + Some(clock) => self + .components + .begin_reset_clock_cycles(clock.id(), Some(reset_event)), + None => self.components.begin_reset_cycles(Some(reset_event)), + } + } + } + let fired = self.components.fire(event.id(), timestamp); + self.components.end_reset_cycles(); + let writes = fired.map_err(|message| RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + })?; for write in writes { write.apply(&mut self.backend); self.dirty = true; @@ -271,6 +314,16 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul status: simulator.backend.resolve_signal(&slots.status), delay: simulator.backend.resolve_signal(&slots.delay), clock: simulator.backend.resolve_signal(&slots.clock), + release: simulator.backend.resolve_signal(&slots.release), + releases: slots + .releases + .iter() + .map(|release| celox_runtime::ProcessReleaseRef { + signal: simulator.backend.resolve_signal(&release.signal), + event: simulator.backend.resolve_event_opt(&release.signal), + value: release.value, + }) + .collect(), clocks: slots .clocks .iter() diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 75dfecf7124..fd99eeabe4a 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -100,6 +100,8 @@ mod host { pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, pub(crate) component_simulation: Option>, + /// The random number generators of a running kernel testbench. + pub(crate) testbench_random: Option, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, pub(super) comb_observer_snapshots: Vec>, @@ -139,6 +141,10 @@ mod host { }, /// The design executed `$finish`. The host decides whether to stop. Finish, + /// An assertion of a testbench process held. + AssertPass { + message: String, + }, Missed { count: u64, }, @@ -341,6 +347,12 @@ mod host { } 'x' } + RuntimeEventKind::AssertPass => { + if args.is_empty() { + return "assertion passed".to_string(); + } + 'x' + } }; return args .iter() @@ -429,6 +441,7 @@ mod host { RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, RuntimeEventKind::Finish => RuntimeEvent::Finish, + RuntimeEventKind::AssertPass => RuntimeEvent::AssertPass { message }, }) } } @@ -644,6 +657,7 @@ mod host { warnings, components: Default::default(), component_simulation: None, + testbench_random: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_event_drain_active: Arc::new(AtomicBool::new(false)), comb_observer_snapshots: Vec::new(), @@ -821,6 +835,42 @@ mod host { self.collect_formatted_runtime_events(ctx) } + /// The runtime events with the site each came from, settling the + /// combinational observers first as + /// [`Self::drain_runtime_events_deferred_with_context`] does. + pub(crate) fn collect_sited_runtime_events( + &mut self, + ctx: RuntimeFormatContext<'_>, + ) -> Vec<(Option, RuntimeEvent)> { + assert!( + !self.runtime_event_drain_active.load(Ordering::Acquire), + "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", + ); + if !self.program.runtime_schema.comb_observers.is_empty() && self.dirty { + self.eval_comb_checked().unwrap(); + self.dirty = false; + } + if self.runtime_event_read_seq.load(Ordering::Acquire) == self.runtime_event_write_seq() + { + return Vec::new(); + } + self.collect_backend_runtime_events() + .into_iter() + .filter_map(|raw| { + let site = match &raw { + RawRuntimeEvent::Event { site_id, .. } => Some(*site_id), + RawRuntimeEvent::Missed { .. } => None, + }; + let event = render_raw_runtime_event( + raw, + &self.program.runtime_schema.runtime_event_sites, + ctx, + )?; + Some((site, event)) + }) + .collect() + } + fn collect_formatted_runtime_events( &mut self, ctx: RuntimeFormatContext<'_>, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index e048819221c..a9667da17e6 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -270,6 +270,7 @@ fn analyze( preserve_element_storage_layout: bool, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> ( Result, Vec, @@ -418,6 +419,7 @@ fn analyze( build_config.reset_type = rt; } build_config.parallel_lanes = optimize_options.parallel_lanes(); + build_config.testbench_kernels = testbench_kernels; let sir = if let Some(external) = external_frontend { parser::parse_with_external_hierarchy( &top, @@ -553,6 +555,7 @@ pub fn compile_to_sir( crate::backend::memory_layout::MemoryLayoutMode::Packed, true, false, + false, ) } @@ -667,6 +670,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { // The testbench drives time itself and never resumes process kernels. if !artifact.processes().is_empty() { @@ -698,6 +702,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -755,6 +760,7 @@ fn compile_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { let (sir, errors, frontend_diagnostics) = analyze( sources, @@ -776,6 +782,7 @@ fn compile_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -948,6 +955,7 @@ pub fn compile_mixed_to_sir( crate::backend::memory_layout::MemoryLayoutMode::Packed, true, false, + false, ) } @@ -979,6 +987,7 @@ fn compile_mixed_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { let (sir, errors, frontend_diagnostics) = analyze( sources, @@ -1000,6 +1009,7 @@ fn compile_mixed_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -1060,6 +1070,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { #[cfg(not(feature = "systemverilog"))] { @@ -1082,6 +1093,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ) } #[cfg(feature = "systemverilog")] @@ -1104,6 +1116,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ), (true, false) => compile_sv_to_sir_with_layout_mode( sv_sources, @@ -1140,6 +1153,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ), } } @@ -1215,6 +1229,10 @@ mod host { pub allow_always_ff_function_effects: bool, /// Where the C functions of DPI-C imports are found. pub dpi: crate::DpiSymbols, + /// Compile the `initial` blocks of a `#[test]` module into process + /// kernels run by the timed scheduler instead of the testbench + /// bytecode interpreter. + pub testbench_kernels: bool, } /// A code-generated native program that has not been loaded into @@ -1399,6 +1417,7 @@ mod host { tier_promotion: TierPromotion::Always, allow_always_ff_function_effects: false, dpi: crate::DpiSymbols::default(), + testbench_kernels: true, } } } @@ -1538,6 +1557,13 @@ mod host { self } + /// Run the `initial` blocks of a `#[test]` module as process kernels + /// of the timed scheduler instead of the bytecode interpreter. + pub fn testbench_kernels(mut self, enable: bool) -> Self { + self.options.testbench_kernels = enable; + self + } + /// Enable native-image support for foreign force/release operations. /// /// This emits extra combinational entry points, so ordinary simulator @@ -2121,6 +2147,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? } } else { @@ -2143,6 +2170,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? }; if let Some(start) = compile_start { @@ -2176,6 +2204,11 @@ mod host { self.options .dpi .resolve_ahead(&laid_out.runtime().runtime_schema.extern_functions)?; + // Process kernels run under the timed scheduler, which discovers + // the edges they cause through the trigger bits. + if !laid_out.runtime().runtime_schema.processes.is_empty() { + self.options.emit_triggers = true; + } Ok(( laid_out, @@ -2684,6 +2717,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, ) } } else { @@ -2706,6 +2740,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, ) }; @@ -2966,6 +3001,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? }; let mut laid_out = diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 46e20faa727..9e69b1149ae 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -445,6 +445,7 @@ impl Simulator { waiting_processes: Vec::new(), process_clocks: Vec::new(), clock_waits: Vec::new(), + pending_releases: Vec::new(), done_processes: Vec::new(), ticks: 0, finished: false, diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index b02b66830d3..42d11032268 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -246,13 +246,13 @@ fn execution_random_seed(seed: Option) -> u64 { // Keep the generator, seed derivation, and range sampling byte-for-byte // compatible with Veryl's `$tb::random` runtime. -struct RandomTable { +pub(crate) struct RandomTable { base_seed: u64, rngs: HashMap, } impl RandomTable { - fn new(base_seed: u64) -> Self { + pub(crate) fn new(base_seed: u64) -> Self { Self { base_seed, rngs: HashMap::default(), @@ -1027,6 +1027,8 @@ async fn exec_for_loop_async>( ExecResult::Continue } +pub(crate) mod kernels; + pub(crate) fn run_testbench( sim: &mut Simulator, testbench: &CompiledTestbench, @@ -1040,6 +1042,9 @@ fn run_testbench_limited( tick_limit: Option, require_finish: bool, ) -> LimitedTestbenchResult { + if kernels::enabled(sim) { + return kernels::run_limited(sim, testbench, tick_limit, require_finish); + } let test_name = root_testbench_name(sim); let use_4state = sim.backend.layout().four_state; let initial_writes = match sim.components.initialize( @@ -1187,6 +1192,9 @@ pub(crate) fn run_testbench_detailed( sim: &mut Simulator, testbench: &CompiledTestbench, ) -> TestResultDetailed { + if kernels::enabled(sim) { + return kernels::run_detailed(sim, testbench); + } let test_name = root_testbench_name(sim); let use_4state = sim.backend.layout().four_state; let initial_writes = match sim.components.initialize( @@ -1439,6 +1447,13 @@ fn drain_runtime_assertions( location: None, }); } + RuntimeEvent::AssertPass { message } => { + ctx.assertions.push(AssertionResult { + passed: true, + message: Some(message), + location: location.cloned(), + }); + } RuntimeEvent::Display { message } => forward_display(&message, true), RuntimeEvent::Write { message } => forward_display(&message, false), RuntimeEvent::Finish => finished = true, @@ -2524,20 +2539,19 @@ mod tests { } "#; let sim = Simulator::builder(code, "t").build_with_trace().unwrap(); - let tb = compile_initial_testbench(&sim).unwrap(); - - assert!(matches!( - tb.statements().first(), - Some(GenericTestbenchStatement::Display { newline: true, .. }) - )); - assert!(matches!( - tb.statements().get(1), - Some(GenericTestbenchStatement::Display { newline: false, .. }) - )); - assert!(matches!( - tb.statements().get(2), - Some(GenericTestbenchStatement::Finish) - )); + compile_initial_testbench(&sim).unwrap(); + + // The initial block is one process kernel whose output goes through + // runtime event sites. + assert_eq!(sim.program().runtime_schema.processes.len(), 1); + let kinds: Vec<_> = sim + .program() + .runtime_schema + .runtime_event_sites + .iter() + .map(|site| format!("{:?}", site.kind)) + .collect(); + assert_eq!(kinds, vec!["Display", "Write"]); } #[test] diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs new file mode 100644 index 00000000000..a0cfc36c8e9 --- /dev/null +++ b/crates/celox/src/testbench/kernels.rs @@ -0,0 +1,385 @@ +//! Running the process kernels of a `#[test]` module. +//! +//! The `initial` blocks are compiled into process kernels (see the Veryl +//! frontend's process lowering), and the timed scheduler of +//! [`celox_runtime::SimulationState`] runs them: clock waits become fused +//! ticks, a reset wait releases the reset when it ends, and the host serves +//! the random number and component requests a kernel makes through scratch +//! state. + +use super::{ + AssertionResult, CompiledTestbench, LimitedTestbenchResult, RandomTable, SourceLocation, + TestResult, TestResultDetailed, apply_component_writes, execution_random_seed, forward_display, + resize_component_return, root_testbench_name, +}; +use crate::backend::SimBackend; +use crate::simulator::{RuntimeEvent, RuntimeFormatContext, Simulator}; +use celox_design::{HostRequest, HostValue}; +use num_bigint::BigUint; +use num_traits::ToPrimitive as _; + +/// Whether the simulator's testbench runs as process kernels. +pub(crate) fn enabled(sim: &Simulator) -> bool { + !sim.program.runtime_schema.processes.is_empty() +} + +/// What a run of the kernels observed. +struct KernelRun { + assertions: Vec, + error: Option, + finished: bool, + ticks: u64, + tick_limit_reached: bool, +} + +pub(crate) fn run_limited( + sim: &mut Simulator, + testbench: &CompiledTestbench, + tick_limit: Option, + require_finish: bool, +) -> LimitedTestbenchResult { + let run = run(sim, testbench, tick_limit); + let failed_messages = run + .assertions + .iter() + .filter(|assertion| !assertion.passed) + .map(|assertion| { + assertion + .message + .clone() + .unwrap_or_else(|| "assertion failed".to_string()) + }) + .collect::>(); + let result = match run.error { + Some(message) => { + if failed_messages.is_empty() { + TestResult::Fail(message) + } else if failed_messages.last().is_some_and(|m| m == &message) { + TestResult::Fail(failed_messages.join("\n")) + } else { + let mut combined = failed_messages; + combined.push(message); + TestResult::Fail(combined.join("\n")) + } + } + None => { + if !failed_messages.is_empty() { + TestResult::Fail(failed_messages.join("\n")) + } else if require_finish && !run.finished { + TestResult::Fail("testbench returned without reaching $finish".to_string()) + } else { + TestResult::Pass + } + } + }; + LimitedTestbenchResult { + result, + ticks: run.ticks, + tick_limit_reached: run.tick_limit_reached, + } +} + +pub(crate) fn run_detailed( + sim: &mut Simulator, + testbench: &CompiledTestbench, +) -> TestResultDetailed { + let run = run(sim, testbench, None); + let passed = run.error.is_none() && run.assertions.iter().all(|a| a.passed); + TestResultDetailed { + passed, + assertions: run.assertions, + error: run.error, + } +} + +fn run( + sim: &mut Simulator, + testbench: &CompiledTestbench, + tick_limit: Option, +) -> KernelRun { + let failed = |message: String| KernelRun { + assertions: Vec::new(), + error: Some(message), + finished: false, + ticks: 0, + tick_limit_reached: false, + }; + let test_name = root_testbench_name(sim); + let use_4state = sim.backend.layout().four_state; + let seed = execution_random_seed(testbench.configured_random_seed()); + let initial_writes = match sim.components.initialize( + testbench.components(), + testbench.component_bindings(), + testbench.component_libraries(), + testbench.component_file_base(), + seed, + &test_name, + use_4state, + &mut sim.backend, + ) { + Ok(writes) => writes, + Err(message) => return failed(message), + }; + if let Some(writer) = sim.vcd_writer.as_mut() + && let Err(error) = writer.add_external_signals(&sim.components.trace_descriptors()) + { + return failed(format!("component VCD registration failed: {error}")); + } + apply_component_writes(sim, initial_writes); + sim.testbench_random = Some(RandomTable::new(seed)); + // A run starts every process at its beginning, whatever an earlier run + // of the same simulator left in the control slots. + for slots in &sim.program.runtime_schema.processes.clone() { + for slot in slots.iter() { + let signal = sim.backend.resolve_signal(slot); + sim.backend.set_wide(signal, BigUint::ZERO); + } + } + + // The scheduler samples the clocks it detects edges on from settled + // state. + if sim.dirty { + if let Err(error) = sim.eval_comb_checked() { + return failed(error.to_string()); + } + sim.dirty = false; + } + let mut state = crate::simulation::simulation_state(sim); + state.set_tick_budget(tick_limit); + let mut assertions = Vec::new(); + let mut error = None; + let mut finished = sim.components.finish_requested(); + let progress_every = sim + .diagnostics + .testbench_progress_every + .filter(|every| *every != 0); + let mut reported_ticks = 0; + while !finished { + let stepped = state.step(sim); + if let Some(every) = progress_every { + // A step may run many fused ticks; report each multiple it passed. + let mut tick = (reported_ticks / every + 1) * every; + while tick <= state.ticks() { + tracing::debug!("[testbench-progress] tick={tick}"); + tick += every; + } + reported_ticks = state.ticks(); + } + let drained = drain(sim, &mut assertions, state.time()); + if let Some(fatal) = drained.fatal { + error = Some(fatal); + finished = true; + } + match stepped { + Ok(Some(_)) => {} + Ok(None) => finished = true, + Err(code) => { + if error.is_none() { + error = Some(code.to_string()); + } + finished = true; + } + } + if drained.finished || state.is_finished() || sim.components.finish_requested() { + finished = true; + } + } + sim.testbench_random = None; + if let Err(message) = sim.components.finish(state.time()) + && error.is_none() + { + error = Some(message); + } + let finished = state.is_finished() || sim.components.finish_requested(); + KernelRun { + assertions, + error, + finished, + ticks: state.ticks(), + tick_limit_reached: tick_limit.is_some_and(|limit| state.ticks() >= limit) + && !state.all_processes_done() + && !state.is_finished(), + } +} + +struct Drained { + fatal: Option, + finished: bool, +} + +/// Record the assertions the kernels evaluated and forward their output. +fn drain( + sim: &mut Simulator, + assertions: &mut Vec, + time: u64, +) -> Drained { + let ctx = RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let mut drained = Drained { + fatal: None, + finished: false, + }; + for (site, event) in sim.collect_sited_runtime_events(ctx) { + let location = site.and_then(|site| { + sim.program + .runtime_schema + .runtime_event_sites + .get(site)? + .location + .as_ref() + .map(|location| SourceLocation { + file: location.file.clone(), + line: location.line, + column: location.column, + }) + }); + match event { + RuntimeEvent::AssertPass { message } => assertions.push(AssertionResult { + passed: true, + message: Some(message), + location, + }), + RuntimeEvent::AssertContinue { message } => assertions.push(AssertionResult { + passed: false, + message: Some(message), + location, + }), + RuntimeEvent::AssertFatal { message } => { + if drained.fatal.is_none() { + drained.fatal = Some(message.clone()); + } + assertions.push(AssertionResult { + passed: false, + message: Some(message), + location, + }); + } + RuntimeEvent::Missed { count } => assertions.push(AssertionResult { + passed: false, + message: Some(format!("missed {count} runtime events")), + location: None, + }), + RuntimeEvent::Display { message } => forward_display(&message, true), + RuntimeEvent::Write { message } => forward_display(&message, false), + RuntimeEvent::Finish => drained.finished = true, + } + } + drained +} + +/// Serve host request `request` of process `process` at `time`. +pub(crate) fn serve_host_request( + sim: &mut Simulator, + process: usize, + request: usize, + time: u64, +) -> Result { + let request = sim + .program + .runtime_schema + .processes + .get(process) + .and_then(|slots| slots.host_requests.get(request)) + .cloned() + .ok_or_else(|| format!("process {process} made unknown host request {request}"))?; + match request { + HostRequest::RandomSeed { handle, value } => { + let seed = read(sim, &value).to_u64().unwrap_or(u64::MAX); + random(sim)?.seed(&handle, seed); + } + HostRequest::RandomGet { handle, result } => { + let value = random(sim)?.get(&handle, result.width as u32); + write(sim, &result, BigUint::from(value)); + } + HostRequest::RandomGetRange { + handle, + min, + max, + result, + } => { + let min = read(sim, &min).to_u64().unwrap_or(u64::MAX); + let max = read(sim, &max).to_u64().unwrap_or(u64::MAX); + let value = + random(sim)?.get_range(&handle, min, max, result.width as u32, result.signed); + write(sim, &result, BigUint::from(value)); + } + HostRequest::RandomGetSeed { handle, result } => { + let seed = random(sim)?.get_seed(&handle); + write(sim, &result, BigUint::from(seed)); + } + HostRequest::Component { + instance, + method, + args, + result, + declared_width, + strict, + } => { + // The component reads settled design state. + sim.eval_comb_checked().map_err(|error| error.to_string())?; + let host_args = args + .iter() + .map(|arg| { + crate::component::host_value_from_bits(read(sim, arg), arg.width, arg.is_string) + }) + .collect::>(); + let (returned, writes) = sim.components.call_method( + &instance, + &method, + &host_args, + time, + &mut sim.backend, + )?; + apply_component_writes(sim, writes); + if sim.components.finish_requested() { + return Ok(false); + } + let Some(result) = result else { + return Ok(true); + }; + let Some((value, width)) = crate::component::host_bits(&returned) else { + return Err(format!( + "component method `{instance}.{method}` returned no bit value" + )); + }; + if let Some(expected) = declared_width + && width as usize != expected + { + return Err(format!( + "component method `{method}` declares a {expected}-bit return value but returned {width} bits" + )); + } + if declared_width.is_none() && strict && width > 64 { + return Err(format!( + "component method `{method}` returned {width} bits; the expression form carries at most 64 bits" + )); + } + let value = resize_component_return(value, width as usize, result.signed, result.width); + write(sim, &result, value); + } + } + Ok(true) +} + +fn random(sim: &mut Simulator) -> Result<&mut RandomTable, String> { + sim.testbench_random + .as_mut() + .ok_or_else(|| "random numbers are only available while a testbench runs".to_string()) +} + +fn read(sim: &Simulator, value: &HostValue) -> BigUint { + let signal = sim.backend.resolve_signal(&value.signal); + sim.backend.get(signal) +} + +fn write( + sim: &mut Simulator, + target: &HostValue, + value: BigUint, +) { + let signal = sim.backend.resolve_signal(&target.signal); + let mask = (BigUint::from(1u8) << target.width) - BigUint::from(1u8); + sim.backend.set_wide(signal, value & mask); +} diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index 0b35bd886ff..281254b4e98 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -9,7 +9,11 @@ pub(crate) fn project_observability( ) -> Result<(), celox_frontend_veryl::ParserError> { let (sites, read_variables) = celox_frontend_veryl::collect_testbench_observability(lookup, source)?; - runtime_schema.runtime_event_sites.extend(sites); + // Kernels register their own sites; the roots still keep the state the + // testbench reads alive. + if !source.kernels { + runtime_schema.runtime_event_sites.extend(sites); + } runtime_schema.testbench_read_roots = read_variables; Ok(()) } diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 840858afa2e..b97e45c2c53 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -1827,47 +1827,6 @@ fn synchronous_reset_without_runtime_reset_event_still_binds() { .build() .unwrap(); let testbench = celox::testbench::compile_initial_testbench(&simulator).unwrap(); - let semantic_reset = simulator - .program() - .testbench - .as_ref() - .unwrap() - .statements() - .iter() - .find_map(|statement| match statement { - celox_testbench::TestbenchStatement::ResetAssert { - reset_signal, - clock_event, - duration, - assert_value, - deassert_value, - .. - } => Some(celox_testbench::TestbenchStatement::ResetAssert { - reset_signal: *reset_signal, - reset_event: None, - clock_event: *clock_event, - duration: duration.clone(), - period: 2, - assert_value: *assert_value, - deassert_value: *deassert_value, - }), - _ => None, - }) - .unwrap(); - let isolated = celox_testbench::TestbenchProgram::new(vec![semantic_reset]); - let bound = celox_runtime::bind_testbench_program( - simulator.backend_ref(), - isolated, - &fxhash::FxHashSet::default(), - ) - .unwrap(); - assert!(matches!( - bound.statements().first(), - Some(celox_testbench::TestbenchStatement::ResetAssert { - reset_event: None, - .. - }) - )); assert_eq!( celox::testbench::run_compiled_testbench(&mut simulator, &testbench), TestResult::Pass @@ -2908,7 +2867,9 @@ fn component_finish_hook_observes_final_testbench_time() { .unwrap(), TestResult::Pass ); - assert_eq!(FINISH_TIME.load(Ordering::Relaxed), 10); + // The finish hook sees the scheduler time: ten edges of the default + // clock (period 2) end at time 18, and the process resumes at 20. + assert_eq!(FINISH_TIME.load(Ordering::Relaxed), 20); for period in [2, 10] { let code = code .replace( diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 6e6c8160129..cbb49d34d51 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -148,7 +148,7 @@ fn native_image_roundtrip_preserves_concurrent_processes_and_periods() { .build_native_from_image(image) .unwrap(); let tb = compile_initial_testbench(&restored).unwrap(); - assert!(tb.processes().count() >= 2); + assert!(restored.program().runtime_schema.processes.len() >= 2); assert_eq!( run_compiled_testbench_to_finish(&mut restored, &tb), TestResult::Pass diff --git a/crates/celox/tests/error_detection.rs b/crates/celox/tests/error_detection.rs index 30c2ff92f99..40888fed501 100644 --- a/crates/celox/tests/error_detection.rs +++ b/crates/celox/tests/error_detection.rs @@ -679,7 +679,9 @@ fn test_selected_testbench_destination_out_of_range_is_rejected() { } #[test] -fn test_expression_testbench_function_selected_destination_is_rejected() { +fn test_expression_testbench_function_selected_destination_runs() { + // A part-select store in an expression-form helper runs in the process + // kernel; the bytecode interpreter rejected it. let code = r#" module Driver (source: output logic<8>) { assign source = 8'h05; @@ -704,18 +706,10 @@ fn test_expression_testbench_function_selected_destination_is_rejected() { } "#; - let err = Simulator::builder(code, "t") - .build() - .expect_err("selected destination in an expression helper must be rejected"); - match err.kind() { - SimulatorErrorKind::SIRParser(ParserError::IllegalContext { feature, .. }) => { - assert_eq!( - *feature, - "selected destination in expression testbench function" - ); - } - other => panic!("expected expression helper selected destination error, got {other:?}"), - } + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + celox::TestResult::Pass + ); } #[test] diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index c461f83035a..0875057181f 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2692,7 +2692,9 @@ fn test_ff_runtime_events_drain_with_per_tick_time() { .iter() .map(|a| a.message.as_deref()) .collect::>(), - vec![Some("ff time=1"), Some("ff time=2"), Some("ff time=3")], + // `%t` is the scheduler time: the default clock has period 2, and + // its first edge is at time 0. + vec![Some("ff time=0"), Some("ff time=2"), Some("ff time=4")], ); } @@ -2712,7 +2714,9 @@ fn test_assert_format_args_render_current_time_for_percent_t() { let detailed = Simulator::builder(code, "t").run_test_detailed().unwrap(); assert!(!detailed.passed); assert_eq!(detailed.assertions.len(), 1); - assert_eq!(detailed.assertions[0].message.as_deref(), Some("time=3")); + // Three edges of the default clock (period 2) end at time 4; the + // process resumes one period later. + assert_eq!(detailed.assertions[0].message.as_deref(), Some("time=6")); } #[test] diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index a45d4f22c4a..4c79d5913ee 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -239,9 +239,31 @@ optimizer does not yet optimize kernels, but it treats their accesses like those of FF domains, so identity aliasing and dead-store elimination keep the state they use. +The `initial` blocks of a Veryl `#[test]` module are compiled into process +kernels in the same way (the `testbench_kernels` option, on by default). The +Veryl frontend lowers each block with its procedural expression lowering +over the elaborated instance's stable state; a hierarchical reference becomes +a synthetic variable of the module that addresses the child's state. A loop +keeps its counter and bounds in hidden state, so a wait inside its body can +suspend the kernel, and each block has its own copy of the module's +function-local variables, so a call that waits keeps its arguments. Because +a kernel writes design state directly, a statement that reads design state +after a store first reports a `settle` status, which has the runtime settle +the combinational logic and resume the kernel at once. `clk.next(n)` is a +clock wait; `rst.assert(n)` is a clock wait with a release, a write the +scheduler makes when the wait ends, so the reset is deasserted even when the +tick budget is spent. Random numbers and the methods of host components are +host requests: the kernel stores the arguments in scratch state, reports the +request's index, and the host serves it through the scratch state before +resuming the kernel. `$assert` emits a runtime event on both outcomes, so the +detailed test result lists every evaluation with its source location. +Formatted `%t` is the scheduler time, in which the default process clock has +period 2. + 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. +bound testbench components, and compiled backend. The backend owns the +finalized layout. Frontend and optimizer state are discarded after +compilation. ## Public API boundary diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 2afc09c893b..dbb618ce26f 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -186,7 +186,7 @@ for. | `celox-backend-x86` | x86 MIR, instruction selection, target allocation policy, and machine-code emission | Frontend or runtime policy | | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | -| `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | +| `celox-testbench` | Source-independent testbench components, bytecode and values | 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 | @@ -227,7 +227,7 @@ state addresses can now be resolved without consulting Veryl source objects. ### `RuntimeProgram` The source-independent metadata retained after code generation: elaborated design -metadata, public path lookup, runtime schema, and bound testbench bytecode. A +metadata, public path lookup, runtime schema, and bound testbench components. A running `Simulator` stores this artifact beside the executable backend; compiler IR and layout requirements do not remain live during simulation. @@ -249,8 +249,9 @@ The following rules define the intended architecture: their backend; target-independent allocation mechanisms belong in `celox-backend-common`. 6. Runtime code depends on backend contracts, not concrete compiler pipelines. -7. Testbench execution uses source-independent bytecode; only the frontend parses - Veryl testbench syntax. +7. Testbench execution uses process kernels of the runtime schema (or, as a + fallback, source-independent bytecode); only the frontend parses Veryl + testbench syntax. 8. The facade coordinates phases but does not become a second owner of their algorithms or data structures. From d2310eaf541fd884e00b744f0bfb20849d24ecc2 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 12:38:25 +0900 Subject: [PATCH 02/72] fix(veryl): address review findings of the testbench kernels - Track the dirty state per branch side and merge it at the join, so a read after a branch whose one side stored and whose other side waited settles the logic. - Settle the logic a component's output writes feed before the kernel resumes. - Plan scratch state like the lowering: a side a constant condition keeps out, and a loop over a constant-empty range, take none. - Resume a process at once after its host request is served, as the `Host` status documents; no other process runs inside the statement. - A `$finish` of the design's own logic completes the kernel run and is not reported as a tick limit. - Four-state edge detection follows IEEE 1800-2023 Table 9-2 in both edge paths: changes into x or z from 0 or 1 are edges too. - Validate the index and select geometry of a hierarchical destination like a local one. --- .../src/lowering/process.rs | 83 ++++++++++---- crates/celox-runtime/src/simulation.rs | 71 +++++++----- crates/celox/src/testbench/kernels.rs | 16 ++- crates/celox/tests/component_method.rs | 4 + .../celox/tests/concurrent_initial_runtime.rs | 102 ++++++++++++++++++ crates/celox/tests/error_detection.rs | 32 ++++++ crates/celox/tests/processes.rs | 68 ++++++++++++ docs/internals/architecture.md | 8 +- 8 files changed, 330 insertions(+), 54 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 14c17da9eaa..576967d4388 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -346,12 +346,19 @@ fn collect_scratch_needs( let need = |needs: &mut Vec, purpose: &'static str, width: usize| { needs.push(ScratchNeed { purpose, width }); }; + // The planning follows the lowering: a side a constant condition keeps + // out of the kernel, and a loop over a constant-empty range, take no + // scratch, as their slots would otherwise be handed to a later statement. for statement in statements { match statement { - Statement::If(stmt) => { - collect_scratch_needs(ir, &stmt.true_side, active, needs)?; - collect_scratch_needs(ir, &stmt.false_side, active, needs)?; - } + Statement::If(stmt) => match FfParser::get_constant_procedural_truth(&stmt.cond) { + Some(true) => collect_scratch_needs(ir, &stmt.true_side, active, needs)?, + Some(false) => collect_scratch_needs(ir, &stmt.false_side, active, needs)?, + None => { + collect_scratch_needs(ir, &stmt.true_side, active, needs)?; + collect_scratch_needs(ir, &stmt.false_side, active, needs)?; + } + }, Statement::IfReset(stmt) => { collect_scratch_needs(ir, &stmt.true_side, active, needs)?; collect_scratch_needs(ir, &stmt.false_side, active, needs)?; @@ -363,6 +370,9 @@ fn collect_scratch_needs( collect_scratch_needs(ir, &stmt.default, active, needs)?; } Statement::For(stmt) => { + if constant_empty_range(&stmt.range) { + continue; + } let shape = loop_shape(ir, stmt)?; need(needs, "for_start", shape.width); need(needs, "for_end", shape.width); @@ -1272,22 +1282,36 @@ impl<'a> BlockLowering<'a> { true_block: (then_block, Vec::new()), false_block: (else_block, Vec::new()), }); - let mut joined = false; + // Each side starts from the state before the branch; the join is + // dirty when any side reaching it stored. + let dirty_before = self.dirty; + let mut joined = None; for (block, body) in [(then_block, true_side), (else_block, false_side)] { self.kernel.builder().switch_to_block(block); + self.dirty = dirty_before; if let Flow::Continue = self.lower_statements(body)? { self.kernel .builder() .seal_block(SIRTerminator::Jump(join, Vec::new())); - joined = true; + joined = Some(joined.unwrap_or(false) || self.dirty); } } + self.join(join, joined) + } + + /// Continue in `join`, which `joined` sides reach with that dirty state, + /// or end the block when no side reaches it. + fn join(&mut self, join: BlockId, joined: Option) -> Result { self.kernel.builder().switch_to_block(join); - if joined { - Ok(Flow::Continue) - } else { - self.kernel.builder().seal_block(SIRTerminator::Return); - Ok(Flow::Ended) + match joined { + Some(dirty) => { + self.dirty = dirty; + Ok(Flow::Continue) + } + None => { + self.kernel.builder().seal_block(SIRTerminator::Return); + Ok(Flow::Ended) + } } } @@ -1317,28 +1341,24 @@ impl<'a> BlockLowering<'a> { true_block: (then_block, Vec::new()), false_block: (else_block, Vec::new()), }); - let mut joined = false; + let dirty_before = self.dirty; + let mut joined = None; self.kernel.builder().switch_to_block(then_block); if let Flow::Continue = self.lower_statements(&case_arm.body)? { self.kernel .builder() .seal_block(SIRTerminator::Jump(join, Vec::new())); - joined = true; + joined = Some(self.dirty); } self.kernel.builder().switch_to_block(else_block); + self.dirty = dirty_before; if let Flow::Continue = self.lower_case_arm(stmt, arm + 1)? { self.kernel .builder() .seal_block(SIRTerminator::Jump(join, Vec::new())); - joined = true; - } - self.kernel.builder().switch_to_block(join); - if joined { - Ok(Flow::Continue) - } else { - self.kernel.builder().seal_block(SIRTerminator::Return); - Ok(Flow::Ended) + joined = Some(joined.unwrap_or(false) || self.dirty); } + self.join(join, joined) } fn lower_assign(&mut self, assign: &AssignStatement) -> Result<(), ParserError> { @@ -1372,6 +1392,27 @@ impl<'a> BlockLowering<'a> { Some(&destination.token), ) })?; + // The child's variable is checked like a local destination. + if let Some(target) = self.hierarchical.get(&id) + && let Some(module) = self.lookup.instance_module.get(&target.instance_id) + && let Some(info) = self + .lookup + .module_variables + .get(module) + .and_then(|variables| variables.get(&target.var_id)) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } rewritten = AssignStatement { dst: vec![AssignDestination { id, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index d6b18a0c842..509da07a733 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -302,6 +302,21 @@ pub struct SimulationState { finished: bool, } +/// The edges of a transition between sampled values `(nonzero, unknown)`, +/// as `(posedge, negedge)` (IEEE 1800-2023 Table 9-2): a change from 0, or +/// from x or z to 1, is a posedge, and a change from 1, or from x or z to 0, +/// is a negedge; between x and z there is no edge. +fn transition_edges(was: (bool, bool), is: (bool, bool)) -> (bool, bool) { + let (was_nonzero, was_unknown) = was; + let (is_nonzero, is_unknown) = is; + match (was_unknown, is_unknown) { + (true, true) => (false, false), + (true, false) => (is_nonzero, !is_nonzero), + (false, true) => (!was_nonzero, was_nonzero), + (false, false) => (!was_nonzero && is_nonzero, was_nonzero && !is_nonzero), + } +} + /// Whether an event signal is nonzero, and whether it is x or z. fn sample_event_signal(backend: &B, signal: SignalRef) -> (bool, bool) { if backend.layout().four_state && signal.is_4state { @@ -338,17 +353,16 @@ impl SimulationState { if *id == usize::MAX { continue; } - let was_nonzero = self.last_clock_values.contains(*id); - let was_unknown = self.unknown_clock_values.contains(*id); - let (is_nonzero, is_unknown) = sample_event_signal(backend, *signal); + let was = ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ); + let is = sample_event_signal(backend, *signal); + let (posedge, negedge) = transition_edges(was, is); let triggered = match self.domain_kinds[*id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - (!was_nonzero || was_unknown) && is_nonzero && !is_unknown - } - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - (was_nonzero || was_unknown) && !is_nonzero && !is_unknown - } - _ => (was_nonzero, was_unknown) != (is_nonzero, is_unknown), + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => posedge, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => negedge, + _ => was != is, }; if triggered { backend.mark_triggered_bit(*id); @@ -889,6 +903,9 @@ impl SimulationState { } any_ran = true; } + // A served host request resumes the same process at + // once: the request is a zero-time call of the + // statement, and no other process runs in between. Some(ProcessStatus::Host) => { let request: u64 = executor.backend().get_as(refs.delay); self.waiting.remove(&process); @@ -897,8 +914,8 @@ impl SimulationState { self.finished = true; return Ok(true); } - again.push(process); any_ran = true; + continue; } // The kernel found its wait condition unmet and ran // nothing; it stays waiting. @@ -988,8 +1005,9 @@ impl SimulationState { // Processes run after this time's scheduled values are applied and // see the state settled at the previous time. The event signals they // change are edges of this time, like scheduled events. - // (event, whether the signal is nonzero now, whether it was unknown - // before): a four-state edge from x or z counts as an edge. + // (event, the sampled value now): the edge is judged against the + // sampled value before, so transitions from and into x or z count + // as IEEE 1800-2023 Table 9-2 says. let mut process_driven = Vec::new(); if !ready_processes.is_empty() || !self.waiting.is_empty() { let before: Vec<(bool, bool)> = self @@ -1007,9 +1025,9 @@ impl SimulationState { if *id == usize::MAX { continue; } - let (is_nonzero, is_unknown) = sample_event_signal(executor.backend(), *signal); - if (is_nonzero, is_unknown) != (was_nonzero, was_unknown) { - process_driven.push((*id, is_nonzero, was_unknown)); + let is = sample_event_signal(executor.backend(), *signal); + if is != (was_nonzero, was_unknown) { + process_driven.push((*id, is)); } } } @@ -1028,21 +1046,20 @@ impl SimulationState { .filter_map(|event| { self.signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0, false)) + .map(|&id| (id, (event.next_val != 0, false))) }) .chain(process_driven); - for (id, is_nonzero, from_unknown) in scheduled { + for (id, is) in scheduled { track_stable_edges = true; - let was_nonzero = self.last_clock_values.contains(id); - let from_unknown = from_unknown || self.unknown_clock_values.contains(id); + let was = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); + let (posedge, negedge) = transition_edges(was, is); let triggered = match self.domain_kinds[id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { - (!was_nonzero || from_unknown) && is_nonzero - } - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - (was_nonzero || from_unknown) && !is_nonzero - } - _ => (!was_nonzero || from_unknown) && is_nonzero, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => posedge, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => negedge, + _ => posedge, }; if triggered { scheduled_trigger_ids.insert(id); diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index a0cfc36c8e9..872f5a3986c 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -148,6 +148,9 @@ fn run( state.set_tick_budget(tick_limit); let mut assertions = Vec::new(); let mut error = None; + // A `$finish` of the design's own logic arrives as a runtime event; it + // ends the run like a kernel's. + let mut finish_observed = false; let mut finished = sim.components.finish_requested(); let progress_every = sim .diagnostics @@ -180,7 +183,8 @@ fn run( finished = true; } } - if drained.finished || state.is_finished() || sim.components.finish_requested() { + finish_observed |= drained.finished; + if finish_observed || state.is_finished() || sim.components.finish_requested() { finished = true; } } @@ -190,7 +194,7 @@ fn run( { error = Some(message); } - let finished = state.is_finished() || sim.components.finish_requested(); + let finished = finish_observed || state.is_finished() || sim.components.finish_requested(); KernelRun { assertions, error, @@ -198,7 +202,7 @@ fn run( ticks: state.ticks(), tick_limit_reached: tick_limit.is_some_and(|limit| state.ticks() >= limit) && !state.all_processes_done() - && !state.is_finished(), + && !finished, } } @@ -336,6 +340,12 @@ pub(crate) fn serve_host_request( if sim.components.finish_requested() { return Ok(false); } + // The outputs the method wrote feed the design: the process + // resumes at once and reads the logic derived from them. + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } let Some(result) = result else { return Ok(true); }; diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index b97e45c2c53..2d144cb851f 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -1686,6 +1686,7 @@ fn component_method_refreshes_inputs_and_applies_outputs_immediately() { inst clk: $tb::clock_gen; var d: logic<16>; var q: logic<16>; + let derived: logic<16> = ~q; inst component: $comp::celox_clocked #(STEP: 0) ( clk, d: d[7:0], @@ -1697,6 +1698,9 @@ fn component_method_refreshes_inputs_and_applies_outputs_immediately() { component.check_input(8'h34); component.drive(8'h5a); $assert(q == 16'hab5a, "method output must update only the selected destination: %h", q); + // The logic derived from the output is settled before the + // next statement reads it. + $assert(derived == 16'h54a5, "derived logic must see the method output: %h", derived); $finish(); } } diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index cbb49d34d51..cd09d58c75f 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -536,3 +536,105 @@ fn concurrent_runtime_assertions_use_event_time() { vec![Some("ff time=0"), Some("ff time=10"), Some("ff time=20")] ); } + +fn check_passes_on_every_backend(code: &str) { + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass, + "backend={}", + std::any::type_name::() + ); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +/// A read after a branch whose one side stored and whose other side waited +/// sees the settled logic. +#[test] +fn read_after_branch_settles_the_store_of_the_other_side() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var source: logic<8>; + var cond: logic; + let derived: logic<8> = source + 8'd1; + initial { + cond = 1; + source = 8'd1; + if cond { source = 8'd41; } else { clk.next(); } + $assert(derived == 8'd42, "derived=%d", derived); + case cond { + 1'b0: clk.next(); + default: source = 8'd7; + } + $assert(derived == 8'd8, "derived=%d", derived); + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// Constructs a constant keeps out of the kernel take no scratch state, so +/// a later statement gets the scratch planned for it. +#[test] +fn unreachable_loops_take_no_scratch_state() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var r: $tb::random::; + var x: u8; + initial { + if 1'b0 { + for i in 0..3 { clk.next(); } + } + for j in 3..3 { clk.next(); } + r.seed(7); + x = r.get_range(5, 5); + $assert(x == 8'd5, "x=%d", x); + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// A host request (a random number here) is a zero-time call: no other +/// process runs between the statements around it. +#[test] +fn host_requests_do_not_interleave_other_processes() { + let code = r#"#[test(Top)] module Top { + var r: $tb::random::; + var x: u8; + var v: u8; + var seen: u8; + initial { x = 8'd1; v = r.get(); x = 8'd2; } + initial { seen = x; $assert(seen == 8'd2, "seen=%d", seen); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +/// A `$finish` of the design's own clocked logic completes the run. +#[test] +fn finish_from_design_logic_completes_the_run() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: logic<8>; + always_ff (clk) { + if count == 8'd3 { $finish(); } + count += 1; + } + initial { clk.next(10); } + }"#; + check_passes_on_every_backend(code); + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, 100); + assert_eq!(result.result, TestResult::Pass); + assert!(!result.tick_limit_reached); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); +} diff --git a/crates/celox/tests/error_detection.rs b/crates/celox/tests/error_detection.rs index 40888fed501..867271c13fc 100644 --- a/crates/celox/tests/error_detection.rs +++ b/crates/celox/tests/error_detection.rs @@ -678,6 +678,38 @@ fn test_selected_testbench_destination_out_of_range_is_rejected() { } } +#[test] +fn test_selected_hierarchical_destination_out_of_range_is_rejected() { + let code = r#" + module Child (clk: input clock, out: output logic<8>) { + #[allow(unassign_variable)] + var word: logic<8>; + always_ff (clk) { out = word; } + } + #[test(t)] + module t { + inst clk: $tb::clock_gen; + var out: logic<8>; + inst dut: Child (clk, out); + + initial { + dut.word[6 +: 4] = 4'hf; + $finish(); + } + } + "#; + + let err = Simulator::builder(code, "t") + .build() + .expect_err("out-of-range hierarchical selected destination must be rejected"); + match err.kind() { + SimulatorErrorKind::SIRParser(ParserError::IllegalContext { feature, .. }) => { + assert_eq!(*feature, "testbench selected destination"); + } + other => panic!("expected selected destination geometry error, got {other:?}"), + } +} + #[test] fn test_expression_testbench_function_selected_destination_runs() { // A part-select store in an expression-form helper runs in the process diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 28af2c48568..429d45a22b3 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -820,3 +820,71 @@ fn clock_waits_interleave_with_delays_and_checkpoints() { assert_eq!(sim.get(seen), 10u32.into()); assert_eq!(sim.get(count), 20u32.into()); } + +/// IEEE 1800-2023 Table 9-2: a change from 0, or from x to 1, is a posedge; +/// a change from 1, or from x to 0, is a negedge. +#[test] +fn four_state_edges_count_transitions_into_and_out_of_unknown() { + let bit = ValueType::new(1, false, true).unwrap(); + let byte = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("UnknownEdges").unwrap(); + // One signal per edge kind, driven alike. + let clk_rising = module.internal("clk_rising", bit).unwrap(); + let clk_falling = module.internal("clk_falling", bit).unwrap(); + let rising = module.output("rising", byte).unwrap(); + let falling = module.output("falling", byte).unwrap(); + for clk in [clk_rising, clk_falling] { + module + .set_initial(clk, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + for signal in [rising, falling] { + module + .set_initial(signal, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + } + let one = constant(&mut module, 1, 8); + for (signal, clk, edge) in [ + (rising, clk_rising, Edge::Posedge), + (falling, clk_falling, Edge::Negedge), + ] { + let value = module.read(signal).unwrap(); + let next = module.binary(BinaryOp::Add, value, one, byte).unwrap(); + let target = module.whole(signal).unwrap(); + module + .register(target, next, clk, edge, None, None) + .unwrap(); + } + let five = constant(&mut module, 5, 8); + let targets = [ + module.whole(clk_rising).unwrap(), + module.whole(clk_falling).unwrap(), + ]; + // 0 -> x -> 1 -> x -> 0 -> x: three posedges and two negedges. + let mut body = Vec::new(); + for (payload, mask) in [(0u8, 1u8), (1, 0), (0, 1), (0, 0), (0, 1)] { + body.push(Statement::Delay { amount: five }); + let value = module.constant(Constant::four_state(payload, mask, 1).unwrap()); + for target in targets { + body.push(Statement::Assign { target, value }); + } + } + body.push(Statement::Finish); + module.process(body).unwrap(); + let artifact = module.finish(); + + fn check(mut sim: Simulation) { + let rising = sim.signal("rising"); + let falling = sim.signal("falling"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(rising), 3u8.into()); + assert_eq!(sim.get(falling), 2u8.into()); + } + let builder = || Simulation::from_frontend(artifact.clone()).four_state(true); + check(builder().build_interpreter().unwrap()); + check(builder().build_cranelift().unwrap()); + check(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap()); +} diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index 4c79d5913ee..2855d50ed87 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -213,7 +213,8 @@ while a process ran, so that a process another one wakes runs before the registers of that time evaluate; this matches the active-region order in which a process woken by a clock edge reads the registers' previous values. It detects the clock edges the processes cause by comparing event signals -before and after, and then settles as for scheduled events. Processes that +before and after (in four-state by IEEE 1800-2023 Table 9-2, so a change +into or out of x or z is an edge), and then settles as for scheduled events. Processes that waited for zero time, or that the settled state wakes, resume in a further round at the same time, which repeats the edge detection and settling; a round in which every waiting process reports a pending wait ends the time. @@ -254,8 +255,9 @@ clock wait; `rst.assert(n)` is a clock wait with a release, a write the scheduler makes when the wait ends, so the reset is deasserted even when the tick budget is spent. Random numbers and the methods of host components are host requests: the kernel stores the arguments in scratch state, reports the -request's index, and the host serves it through the scratch state before -resuming the kernel. `$assert` emits a runtime event on both outcomes, so the +request's index, and the host serves it through the scratch state, settles +the logic a component's output writes feed, and resumes the kernel at once, +so no other process runs inside the statement. `$assert` emits a runtime event on both outcomes, so the detailed test result lists every evaluation with its source location. Formatted `%t` is the scheduler time, in which the default process clock has period 2. From 1973cd963646767b52bb27940528a61860b78c6f Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 15:27:15 +0900 Subject: [PATCH 03/72] fix(veryl): address the second review round of the testbench kernels - A kernel yields to the host every 256 runtime events, and the executor takes the events out of the ring at each yield, so an uninterrupted block with many `$assert`s or `$display`s loses none. - A block that ends right after a store settles first. - `clk.next(0)` continues at once; a reset release settles before the released process reads. - The runner starts every process clock low, reads a component's completion request before the teardown, tears the components down when the initial settling fails, and runs as kernels only when the schema marks a Veryl testbench (`RuntimeSchema::testbench_kernels`), which also keeps a design's own processes among the RTL writers. --- crates/celox-design/src/lib.rs | 4 + .../src/symbolic/assembly.rs | 1 + .../src/lowering/process.rs | 130 +++++++++++++++++- crates/celox-runtime/src/simulation.rs | 22 ++- crates/celox/src/backend/native/backend.rs | 4 + crates/celox/src/ir.rs | 12 +- crates/celox/src/simulation.rs | 18 ++- crates/celox/src/simulator.rs | 5 + crates/celox/src/testbench/kernels.rs | 29 +++- .../celox/tests/concurrent_initial_runtime.rs | 83 +++++++++++ 10 files changed, 290 insertions(+), 18 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 04af4e44c48..86a766babf5 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -576,6 +576,9 @@ pub struct RuntimeSchema { pub comb_writes: HashSet, /// Control slots of the process kernels, in kernel order. pub processes: Vec>, + /// Index of the first kernel in `processes` that runs a Veryl testbench; + /// it and the kernels after it are the testbench's, not the design's. + pub testbench_kernels: Option, } impl Default for RuntimeSchema { @@ -589,6 +592,7 @@ impl Default for RuntimeSchema { rtl_writes: HashSet::default(), comb_writes: HashSet::default(), processes: Vec::new(), + testbench_kernels: None, } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f3f3b2aaee6..76c4d386571 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1125,6 +1125,7 @@ pub fn schedule_symbolic_rtl( rtl_writes, comb_writes: Default::default(), processes: process_slots, + testbench_kernels: None, }, }; diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 576967d4388..a2fc89c0934 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -334,9 +334,61 @@ fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result, +) -> bool { + statements.iter().any(|statement| match statement { + Statement::If(stmt) => { + contains_runtime_event(ir, &stmt.true_side, active) + || contains_runtime_event(ir, &stmt.false_side, active) + } + Statement::IfReset(stmt) => { + contains_runtime_event(ir, &stmt.true_side, active) + || contains_runtime_event(ir, &stmt.false_side, active) + } + Statement::Case(stmt) => { + stmt.arms + .iter() + .any(|arm| contains_runtime_event(ir, &arm.body, active)) + || contains_runtime_event(ir, &stmt.default, active) + } + Statement::For(stmt) => contains_runtime_event(ir, &stmt.body, active), + Statement::FunctionCall(call) => { + active.insert(call.id) + && function_body(&ir.functions, call) + .is_some_and(|body| contains_runtime_event(ir, &body.statements, active)) + } + Statement::SystemFunctionCall(call) => matches!( + call.kind, + SystemFunctionKind::Display(_) + | SystemFunctionKind::Write(_) + | SystemFunctionKind::Assert { .. } + ), + Statement::TbMethodCall(_) + | Statement::Assign(_) + | Statement::Break + | Statement::Unsupported(_) + | Statement::Null => false, + }) +} + fn collect_scratch_needs( ir: &Module, statements: &[Statement], @@ -500,8 +552,18 @@ struct BlockLowering<'a> { /// was last settled, so a statement that reads design state settles /// it first. dirty: bool, + /// Scratch counting the runtime events emitted since the kernel last + /// gave the host a chance to drain them (see + /// [`BlockLowering::yield_for_runtime_event`]). + event_yield: Option, } +/// Bits of the runtime-event yield counter. +const EVENT_YIELD_WIDTH: usize = 16; +/// Runtime events a kernel emits between two yields to the host: well +/// within the runtime event ring, so none is lost before the host drains. +const EVENT_YIELD_EVERY: u64 = 256; + #[allow(clippy::too_many_arguments)] fn lower_block( scheduled: &mut ScheduledRtl, @@ -588,9 +650,17 @@ fn lower_block( targets: Vec::new(), sources: Vec::new(), dirty: false, + event_yield: None, }; + if contains_runtime_event(ir, statements, &mut HashSet::default()) { + lowering.event_yield = Some(lowering.take_scratch("event_yield")?.1); + } lowering.declare_clocks(statements); - lowering.lower_statements(statements)?; + // A block that ends right after a store settles, so a process that runs + // next reads the logic derived from it. + if let Flow::Continue = lowering.lower_statements(statements)? { + lowering.settle_if_dirty()?; + } let BlockLowering { parser, kernel, @@ -688,6 +758,11 @@ fn lower_block( if let Some(error) = failure { return Err(error); } + // The first testbench kernel marks where the design's own processes end. + scheduled + .runtime_schema + .testbench_kernels + .get_or_insert(scheduled.runtime_schema.processes.len()); scheduled.sir.processes.push(unit); scheduled.runtime_schema.processes.push(slots); Ok(()) @@ -1876,7 +1951,11 @@ impl<'a> BlockLowering<'a> { self.dirty = true; self.system_task(&local) } - SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => self.system_task(call), + SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => { + let flow = self.system_task(call)?; + self.yield_for_runtime_event()?; + Ok(flow) + } SystemFunctionKind::Bits(_) | SystemFunctionKind::Size(..) | SystemFunctionKind::Clog2(_) @@ -1967,9 +2046,56 @@ impl<'a> BlockLowering<'a> { } } self.kernel.builder().switch_to_block(join); + self.yield_for_runtime_event()?; Ok(Flow::Continue) } + /// Count a runtime event the kernel just emitted; every + /// [`EVENT_YIELD_EVERY`] events the kernel settles, which returns to the + /// host, so the runtime event ring never wraps within one kernel run. + fn yield_for_runtime_event(&mut self) -> Result<(), ParserError> { + let Some(slot) = self.event_yield else { + return Ok(()); + }; + let count = self.load_scratch(slot, EVENT_YIELD_WIDTH, false); + let one = self.constant(1, EVENT_YIELD_WIDTH); + let limit = self.constant(EVENT_YIELD_EVERY, EVENT_YIELD_WIDTH); + let zero = self.constant(0, EVENT_YIELD_WIDTH); + let builder = self.kernel.builder(); + let next = builder.alloc_bit(EVENT_YIELD_WIDTH, false); + builder.emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + let due = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(due, next, BinaryOp::GeU, limit)); + let yield_block = builder.new_block(); + let keep_block = builder.new_block(); + let after = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: due, + true_block: (yield_block, Vec::new()), + false_block: (keep_block, Vec::new()), + }); + builder.switch_to_block(keep_block); + self.store_scratch(slot, EVENT_YIELD_WIDTH, next); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(yield_block); + self.store_scratch(slot, EVENT_YIELD_WIDTH, zero); + let dirty = self.dirty; + self.kernel + .settle() + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(after); + // Registers do not survive the yield path; the dirty state is the + // one before it, as the other path kept it. + self.parser.clear_register_cache(); + self.dirty = dirty; + Ok(()) + } + /// Inline a function call statement: bind its inputs, run its body, and /// copy its outputs back. fn lower_function_call( diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 28171491498..f64f5a7476e 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -35,7 +35,9 @@ pub trait SimulationExecutor { &mut self, event: ::Event, ) -> Result<(), SimulatorErrorCode>; - fn run_process(&mut self, index: usize) -> Result<(), SimulatorErrorCode> { + /// Run process kernel `index` at simulation time `time` until it + /// suspends or ends. + fn run_process(&mut self, index: usize, _time: u64) -> Result<(), SimulatorErrorCode> { self.backend_mut().run_process(index) } @@ -300,6 +302,10 @@ pub struct SimulationState { tick_budget: Option, /// A process requested the end of the simulation. finished: bool, + /// A wait ended with a release this round: the combinational logic is + /// settled before the processes run, so the released process reads + /// what its release implies. + settle_before_processes: bool, } /// The edges of a transition between sampled values `(nonzero, unknown)`, @@ -424,6 +430,7 @@ impl SimulationState { ticks: 0, tick_budget: None, finished: false, + settle_before_processes: false, } } @@ -820,6 +827,7 @@ impl SimulationState { } self.process_wakeups.pop(); if let Some(release) = self.pending_releases.remove(&process) { + self.settle_before_processes = true; let release = self.processes[process].releases[release].clone(); match release.event { Some(event) => events.push(SimEvent { @@ -871,7 +879,7 @@ impl SimulationState { for process in pass.drain(..) { // A settle resumes the same process at once. loop { - executor.run_process(process)?; + executor.run_process(process, current_time)?; let refs = &self.processes[process]; let status: u8 = executor.backend().get_as(refs.status); match ProcessStatus::from_code(status) { @@ -927,13 +935,18 @@ impl SimulationState { if count == 0 { // Nothing to wait for: the process continues in // the next pass, after its release. + // Nothing to wait for: the release is made and + // the process continues at once, as a zero + // count documents. if let Some(release) = release { let release = refs.releases[release].clone(); executor .backend_mut() .set_wide(release.signal, release.value.into()); + executor.eval_comb()?; } - again.push(process); + any_ran = true; + continue; } else { let id = clock.event.id(); let tick_clock = @@ -1057,6 +1070,9 @@ impl SimulationState { for event in &events_to_process { executor.backend_mut().set(event.signal, event.next_val); } + if std::mem::take(&mut self.settle_before_processes) { + executor.eval_comb()?; + } // Processes run after this time's scheduled values are applied and // see the state settled at the previous time. The event signals they diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index c3682cff0d8..35bea4a1491 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -392,6 +392,8 @@ pub(crate) struct NativeRuntimeSchema { /// Ordered so that the encoded image does not depend on hash order. pub(crate) comb_writes: std::collections::BTreeSet, pub(crate) processes: Vec>, + #[serde(default)] + pub(crate) testbench_kernels: Option, } /// Pointer-free native compiler artifact which can be attached to the @@ -500,6 +502,7 @@ impl NativeProgramImage { rtl_writes: self.runtime_schema.rtl_writes.clone(), comb_writes: self.runtime_schema.comb_writes.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), + testbench_kernels: self.runtime_schema.testbench_kernels, }, testbench: self.testbench.clone(), } @@ -2258,6 +2261,7 @@ fn compile_program( .copied() .collect(), processes: sir.runtime().runtime_schema.processes.clone(), + testbench_kernels: sir.runtime().runtime_schema.testbench_kernels, }, layout: layout.clone(), native_memory_size, diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 2d7bf6a5064..a4383788654 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -728,11 +728,13 @@ fn rebuild_rtl_writes(program: &mut OptimizedSir) { let mut rtl_writes = crate::HashSet::default(); // The kernels of a Veryl testbench drive signals as the testbench, not // as RTL; the processes of an SV design are RTL. - let processes = if program.runtime.testbench.is_some() { - &[][..] - } else { - &program.sir.processes[..] - }; + let design_processes = program + .runtime + .runtime_schema + .testbench_kernels + .unwrap_or(program.sir.processes.len()) + .min(program.sir.processes.len()); + let processes = &program.sir.processes[..design_processes]; for unit in program .sir .eval_comb diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index cb91c6eb083..046daf1be9f 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -92,10 +92,22 @@ impl SimulationExecutor for Simulator { self.apply_ff_at_checked(event) } - fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { - self.backend + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + let result = self + .backend .run_process(index) - .map_err(|e| self.decorate_runtime_error(e)) + .map_err(|e| self.decorate_runtime_error(e)); + // A kernel testbench's kernels yield before the runtime event ring + // could wrap; the events so far leave the ring here. + if self.testbench_random.is_some() { + let ctx = crate::simulator::RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let events = self.collect_sited_runtime_events(ctx); + self.testbench_events.extend(events); + } + result } fn tick_many(&mut self, event: B::Event, count: u64) -> (u64, Result<(), RuntimeErrorCode>) { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 7a54c47e195..ca434bb5266 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -103,6 +103,10 @@ mod host { pub(crate) component_simulation: Option>, /// The random number generators of a running kernel testbench. pub(crate) testbench_random: Option, + /// Runtime events of a running kernel testbench the executor took + /// out of the ring when a kernel yielded, until the runner drains + /// them. + pub(crate) testbench_events: Vec<(Option, RuntimeEvent)>, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, pub(super) comb_observer_snapshots: Vec>, @@ -657,6 +661,7 @@ mod host { components: Default::default(), component_simulation: None, testbench_random: None, + testbench_events: Vec::new(), runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_event_drain_active: Arc::new(AtomicBool::new(false)), comb_observer_snapshots: Vec::new(), diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 872f5a3986c..baefe0ea52b 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -18,9 +18,11 @@ use celox_design::{HostRequest, HostValue}; use num_bigint::BigUint; use num_traits::ToPrimitive as _; -/// Whether the simulator's testbench runs as process kernels. +/// Whether the simulator's testbench runs as process kernels: the schema +/// marks them (a design's own processes alone do not make a kernel +/// testbench). pub(crate) fn enabled(sim: &Simulator) -> bool { - !sim.program.runtime_schema.processes.is_empty() + sim.program.runtime_schema.testbench_kernels.is_some() } /// What a run of the kernels observed. @@ -128,18 +130,29 @@ fn run( apply_component_writes(sim, initial_writes); sim.testbench_random = Some(RandomTable::new(seed)); // A run starts every process at its beginning, whatever an earlier run - // of the same simulator left in the control slots. + // of the same simulator left in the control slots, and every process + // clock low, as the bytecode testbench does: the first `clk.next()` + // then counts a real rising edge. for slots in &sim.program.runtime_schema.processes.clone() { for slot in slots.iter() { let signal = sim.backend.resolve_signal(slot); sim.backend.set_wide(signal, BigUint::ZERO); } + for clock in &slots.clocks { + let signal = sim.backend.resolve_signal(&clock.signal); + sim.backend.set_wide(signal, BigUint::ZERO); + sim.dirty = true; + } } + sim.testbench_events.clear(); // The scheduler samples the clocks it detects edges on from settled // state. if sim.dirty { if let Err(error) = sim.eval_comb_checked() { + // The components were installed above; take them down again. + let _ = sim.components.finish(0); + sim.testbench_random = None; return failed(error.to_string()); } sim.dirty = false; @@ -189,12 +202,15 @@ fn run( } } sim.testbench_random = None; + // A completion a component requested is read before the teardown + // clears the components. + let component_finished = sim.components.finish_requested(); if let Err(message) = sim.components.finish(state.time()) && error.is_none() { error = Some(message); } - let finished = finish_observed || state.is_finished() || sim.components.finish_requested(); + let finished = finish_observed || state.is_finished() || component_finished; KernelRun { assertions, error, @@ -225,7 +241,10 @@ fn drain( fatal: None, finished: false, }; - for (site, event) in sim.collect_sited_runtime_events(ctx) { + // The events the kernels' yields let the executor spill, then the ring. + let mut events = std::mem::take(&mut sim.testbench_events); + events.extend(sim.collect_sited_runtime_events(ctx)); + for (site, event) in events { let location = site.and_then(|site| { sim.program .runtime_schema diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index cd09d58c75f..a8997fb0f9f 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -638,3 +638,86 @@ fn finish_from_design_logic_completes_the_run() { check(Simulator::builder(code, "Top").build_interpreter().unwrap()); check(Simulator::builder(code, "Top").build_cranelift().unwrap()); } + +/// A run starts its process clocks low, as the bytecode testbench did: a +/// clock the host drove high still counts a real first edge. +#[test] +fn a_run_starts_its_process_clocks_low() { + let code = r#" + module Counter(clk: input clock, count: output logic<8>) { + always_ff(clk) { count += 1; } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: logic<8>; + inst dut: Counter(clk, count); + initial { clk.next(1); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_cranelift().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let clk = sim.signal("clk"); + sim.set_wide(clk, 1u8.into()); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); +} + +/// More runtime events than the ring holds, in one uninterrupted block: +/// the kernel yields to the host before the ring wraps. +#[test] +fn many_events_in_one_run_are_not_missed() { + let code = r#"#[test(Top)] module Top { + var x: logic<8>; + initial { + x = 1; + for i in 0..3000 { $assert(x == 1, "x=%d", x); } + for i in 0..1500 { $display("line %d", i); } + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// A fatal assertion with a formatted message fails with that message +/// alone. +#[test] +fn a_fatal_assertion_reports_its_rendered_message_once() { + let code = r#"#[test(Top)] module Top { + var x: logic<8>; + initial { x = 5; $assert(x == 6, "x=%d", x); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_cranelift().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench(&mut sim, &tb), + TestResult::Fail("x=5".to_string()) + ); +} + +/// `clk.next(0)` continues at once: no other block runs in between. +#[test] +fn zero_count_clock_waits_do_not_interleave_other_processes() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var x: u8; + var seen: u8; + initial { x = 8'd1; clk.next(0); x = 8'd2; } + initial { seen = x; $assert(seen == 8'd2, "seen=%d", seen); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +/// A block that ends right after a store settles, so the next block reads +/// the logic derived from it. +#[test] +fn a_block_ending_after_a_store_settles_for_the_next_block() { + let code = r#"#[test(Top)] module Top { + var source: logic<8>; + let derived: logic<8> = source + 8'd1; + initial { source = 8'd41; } + initial { $assert(derived == 8'd42, "derived=%d", derived); $finish(); } + }"#; + check_passes_on_every_backend(code); +} From b55e504a971fb4c7b5a59d07ff9549db9761aa05 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 10 Oct 2026 19:46:02 +0900 Subject: [PATCH 04/72] fix(runtime): take the due processes of settle_at with their releases --- crates/celox-runtime/src/simulation.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index f2761033c4f..190d9328da5 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1023,8 +1023,9 @@ impl SimulationState { if self.finished { return Ok(None); } - let ready = self.take_ready_processes(time); - self.step_round(executor, time, Vec::new(), ready, true)?; + let mut events = Vec::new(); + let ready = self.take_ready_processes(executor, time, &mut events); + self.step_round(executor, time, events, ready, true)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. self.run_remaining_rounds(executor, time, u64::MAX)?; From 8897b7a76883360391a122b41e9d840ae07d8e36 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 08:41:12 +0900 Subject: [PATCH 05/72] fix(veryl): preserve process expression effects and runtime state --- .../src/backend/native/isel/instruction.rs | 25 +- .../src/backend/native/isel/tests/wide.rs | 110 ++++ .../celox-frontend-veryl/src/lowering/ff.rs | 20 + .../src/lowering/process.rs | 484 ++++++++++++++---- .../src/lowering/process/expressions.rs | 446 ++++++++++++++++ crates/celox-frontend-veryl/src/testbench.rs | 3 +- crates/celox-runtime/src/simulation.rs | 55 +- crates/celox-runtime/src/state_file.rs | 19 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 18 +- crates/celox/src/simulator.rs | 9 +- crates/celox/src/simulator/builder.rs | 7 + crates/celox/src/simulator/state_file.rs | 7 + crates/celox/src/testbench/kernels.rs | 6 +- crates/celox/tests/component_method.rs | 44 ++ .../celox/tests/concurrent_initial_runtime.rs | 247 +++++++++ crates/celox/tests/state_file.rs | 43 ++ 17 files changed, 1429 insertions(+), 116 deletions(-) create mode 100644 crates/celox-frontend-veryl/src/lowering/process/expressions.rs diff --git a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs index d8e08a8204e..693805ce832 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs @@ -345,12 +345,25 @@ pub(super) fn lower_instruction( let chunk_vreg = ctx.alloc_vreg(SpillDesc::sim_state( *addr, bit_pos, chunk_bits, false, )); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + chunk_vreg + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: chunk_vreg, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != chunk_vreg { + ctx.emit_and_imm( + block, + chunk_vreg, + raw, + mask_for_width(chunk_bits), + ); + } chunks.push((chunk_vreg, chunk_bits)); bit_pos += chunk_bits; remaining -= chunk_bits; @@ -370,12 +383,20 @@ pub(super) fn lower_instruction( let chunk_byte_off = ctx.mask_byte_offset(addr, m_bit_pos); let chunk_size = ISelContext::op_size_for_width(chunk_bits); let mv = ctx.alloc_vreg(SpillDesc::transient()); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + mv + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: mv, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != mv { + ctx.emit_and_imm(block, mv, raw, mask_for_width(chunk_bits)); + } mchunks.push((mv, chunk_bits)); m_bit_pos += chunk_bits; m_remaining -= chunk_bits; diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 22a998009da..a8a311d2ca7 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -1537,3 +1537,113 @@ fn four_state_sar_uses_sign_fill_past_the_logical_source_words() { } } } + +#[test] +fn widened_zero_compares_equal_to_a_zero_wide_load() { + for four_state in [false, true] { + let a = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId(0), + }; + let o = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId(1), + }; + let address = |a| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, a); + let [loaded, zero, widened, equal, result] = std::array::from_fn(RegisterId); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(loaded, address(a), SIROffset::Static(0), 100), + SIRInstruction::Imm(zero, SIRValue::new(0u8)), + SIRInstruction::Unary(widened, UnaryOp::Ident, zero), + SIRInstruction::Binary(equal, loaded, BinaryOp::Eq, widened), + SIRInstruction::Unary(result, UnaryOp::ToTwoState, equal), + SIRInstruction::Store( + address(o), + SIROffset::Static(0), + 1, + result, + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: [ + (loaded, RegisterType::Logic { width: 100 }), + ( + zero, + RegisterType::Bit { + width: 32, + signed: false, + }, + ), + ( + widened, + RegisterType::Bit { + width: 100, + signed: false, + }, + ), + (equal, RegisterType::Logic { width: 1 }), + ( + result, + RegisterType::Bit { + width: 1, + signed: false, + }, + ), + ] + .into_iter() + .collect(), + }; + unit.verify(); + let mut layout = empty_layout(); + let output_offset = if four_state { 32 } else { 16 }; + let state_size = output_offset + 1; + layout.four_state = four_state; + layout.offsets = [(a, 0), (o, output_offset)].into_iter().collect(); + layout.widths = [(a, 100), (o, 1)].into_iter().collect(); + layout.is_4states = [(a, four_state), (o, false)].into_iter().collect(); + layout.total_size = state_size; + layout.working_base_offset = state_size; + layout.sparse_base_offset = state_size; + layout.merged_total_size = state_size; + layout.triggered_bits_offset = state_size; + layout.scratch_base_offset = state_size; + let mut function = lower_execution_unit(&unit, &layout, four_state); + mir_legalize::legalize(&mut function); + mir_opt::optimize(&mut function); + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + mir_opt::post_regalloc_peephole(&mut function, &allocation.assignment); + function.verify(); + let emitted = emit::emit( + &function, + &allocation.assignment, + allocation.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let mut state = vec![0u8; state_size]; + state[12] = 0xf0; + if four_state { + state[25] = 0xf0; + state[26] = 6; + state[28] = 0xff; + } else { + state[13] = 6; + state[15] = 0xff; + } + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[output_offset] & 1, 1, "four_state={four_state}"); + } +} diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index a94abcdfe1d..25360be4a91 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -439,6 +439,26 @@ pub(crate) enum ControlFlow { } impl<'a> FfParser<'a> { + pub(super) fn process_expression_value(&self, token: TokenRange) -> Option { + self.function_expression_value_stack + .iter() + .rev() + .find_map(|values| values.get(&token).copied()) + } + + pub(super) fn push_process_expression_values( + &mut self, + values: HashMap, + ) { + self.function_expression_value_stack.push(values); + } + + pub(super) fn pop_process_expression_values(&mut self) { + self.function_expression_value_stack + .pop() + .expect("process expression scope"); + } + pub fn new(module: &'a Module, config: BuildConfig) -> Self { let local_working_vars = module .variables diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index a2fc89c0934..ecda34a1222 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -42,6 +42,9 @@ use crate::{ }; use celox_frontend_core::ScheduledRtl; +mod expressions; +use veryl_parser::token_range::TokenRange; + type SourceAddr = AbsoluteAddrBase; type RegionedSourceAddr = RegionedAbsoluteAddrBase; @@ -66,6 +69,8 @@ pub struct BlockStorage { /// that waits keeps its arguments and locals while another block calls /// the function. pub private: HashMap, + /// Values preserved while nested expression calls suspend. + pub expression_values: HashMap, } /// The hidden state of a module's `initial` blocks, in declaration order. @@ -135,6 +140,35 @@ pub(crate) fn declare_storage( (need, id) }) .collect(); + let mut expression_needs = HashMap::default(); + collect_expression_storage( + ir, + statements, + &mut HashSet::default(), + &mut expression_needs, + ); + let mut expression_needs = expression_needs.into_iter().collect::>(); + expression_needs.sort_by_key(|(token, _)| { + ( + token + .beg + .source + .get_path() + .and_then(resource_table::get_path_value) + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_default(), + token.beg.pos, + token.end.pos, + ) + }); + let expression_values = expression_needs + .into_iter() + .enumerate() + .map(|(slot, (token, width))| { + let id = declare(name(&format!("expression@{slot}")), None, width); + (token, (width, id)) + }) + .collect(); let private = templates .iter() .map(|(local, template)| { @@ -150,8 +184,16 @@ pub(crate) fn declare_storage( release: declare(name("release"), None, PROCESS_RELEASE_WIDTH), scratch, private, + expression_values, }); } + for block in &blocks { + for (_, id) in block.expression_values.values() { + let variable = variables.get_mut(id).unwrap(); + variable.metadata.is_4state = true; + variable.metadata.type_kind = PortTypeKind::Logic; + } + } Ok(ModuleProcessStorage { blocks }) } @@ -166,6 +208,14 @@ fn initial_blocks(ir: &Module) -> impl Iterator { }) } +fn constant_truth(expr: &Expression) -> Option { + if expressions::has_call(expr) { + None + } else { + FfParser::get_constant_procedural_truth(expr) + } +} + /// Whether a range with constant bounds has no value. fn constant_empty_range(range: &ForRange) -> bool { let constant = |bound: &ForBound| match bound { @@ -298,8 +348,8 @@ fn loop_shape<'s>( cmp_signed: var_signed && continuation_signed, start_signed, end_signed, - start_wide: !start_signed && bound_width(start) > 64, - end_wide: !end_signed && bound_width(end) > 64, + start_wide: bound_width(start) > if start_signed { 128 } else { 64 }, + end_wide: bound_width(end) > if end_signed { 128 } else { 64 }, }) } @@ -329,6 +379,74 @@ fn function_body( } } +fn collect_expression_storage( + ir: &Module, + statements: &[Statement], + active: &mut HashSet, + values: &mut HashMap, +) { + fn expr( + ir: &Module, + value: &Expression, + active: &mut HashSet, + values: &mut HashMap, + ) { + if expressions::has_call(value) { + values.insert(value.token_range(), expressions::storage_width(value)); + for child in expressions::children(value) { + values.insert(child.token_range(), expressions::storage_width(child)); + } + } + for child in expressions::children(value) { + expr(ir, child, active, values); + } + if let Expression::Term(factor) = value + && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() + && active.insert(call.id) + { + if let Some(body) = function_body(&ir.functions, call) { + collect_expression_storage(ir, &body.statements, active, values); + } + active.remove(&call.id); + } + } + for statement in statements { + let inputs = expressions::statement_inputs(statement); + if inputs.iter().any(|expr| expressions::has_call(expr)) { + for input in &inputs { + values.insert(input.token_range(), expressions::storage_width(input)); + } + } + for value in inputs { + expr(ir, value, active, values); + } + if let Statement::Case(stmt) = statement { + values.insert( + stmt.case_target.token_range(), + expressions::storage_width(&stmt.case_target), + ); + } + if let Statement::FunctionCall(call) = statement + && call.inputs.values().any(expressions::has_call) + { + for input in call.inputs.values() { + values.insert(input.token_range(), expressions::storage_width(input)); + } + } + if let Statement::FunctionCall(call) = statement + && active.insert(call.id) + { + if let Some(body) = function_body(&ir.functions, call) { + collect_expression_storage(ir, &body.statements, active, values); + } + active.remove(&call.id); + } + for body in expressions::statement_bodies(statement) { + collect_expression_storage(ir, body, active, values); + } + } +} + /// The scratch state the statements need, in lowering order. fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result, ParserError> { let mut needs = Vec::new(); @@ -354,39 +472,35 @@ fn contains_runtime_event( statements: &[Statement], active: &mut HashSet, ) -> bool { - statements.iter().any(|statement| match statement { - Statement::If(stmt) => { - contains_runtime_event(ir, &stmt.true_side, active) - || contains_runtime_event(ir, &stmt.false_side, active) - } - Statement::IfReset(stmt) => { - contains_runtime_event(ir, &stmt.true_side, active) - || contains_runtime_event(ir, &stmt.false_side, active) - } - Statement::Case(stmt) => { - stmt.arms - .iter() - .any(|arm| contains_runtime_event(ir, &arm.body, active)) - || contains_runtime_event(ir, &stmt.default, active) - } - Statement::For(stmt) => contains_runtime_event(ir, &stmt.body, active), - Statement::FunctionCall(call) => { - active.insert(call.id) - && function_body(&ir.functions, call) - .is_some_and(|body| contains_runtime_event(ir, &body.statements, active)) - } - Statement::SystemFunctionCall(call) => matches!( - call.kind, - SystemFunctionKind::Display(_) - | SystemFunctionKind::Write(_) - | SystemFunctionKind::Assert { .. } - ), - Statement::TbMethodCall(_) - | Statement::Assign(_) - | Statement::Break - | Statement::Unsupported(_) - | Statement::Null => false, - }) + for statement in statements { + if matches!(statement, Statement::SystemFunctionCall(call) if matches!(call.kind, SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) | SystemFunctionKind::Assert {..})) + { + return true; + } + let mut calls = Vec::new(); + for expr in expressions::statement_inputs(statement) { + expressions::expression_calls(expr, &mut calls); + } + if let Statement::FunctionCall(call) = statement { + calls.push(call); + } + for call in calls { + if active.insert(call.id) { + let emits = function_body(&ir.functions, call) + .is_some_and(|body| contains_runtime_event(ir, &body.statements, active)); + active.remove(&call.id); + if emits { + return true; + } + } + } + for body in expressions::statement_bodies(statement) { + if contains_runtime_event(ir, body, active) { + return true; + } + } + } + false } fn collect_scratch_needs( @@ -402,8 +516,20 @@ fn collect_scratch_needs( // out of the kernel, and a loop over a constant-empty range, take no // scratch, as their slots would otherwise be handed to a later statement. for statement in statements { + let mut calls = Vec::new(); + for expr in expressions::statement_inputs(statement) { + expressions::expression_calls(expr, &mut calls); + } + for call in calls { + if active.insert(call.id) { + if let Some(body) = function_body(&ir.functions, call) { + collect_scratch_needs(ir, &body.statements, active, needs)?; + } + active.remove(&call.id); + } + } match statement { - Statement::If(stmt) => match FfParser::get_constant_procedural_truth(&stmt.cond) { + Statement::If(stmt) => match constant_truth(&stmt.cond) { Some(true) => collect_scratch_needs(ir, &stmt.true_side, active, needs)?, Some(false) => collect_scratch_needs(ir, &stmt.false_side, active, needs)?, None => { @@ -538,7 +664,8 @@ struct BlockLowering<'a> { module_id: celox_design::ModuleId, hierarchical: HashMap, private: HashMap, - scratch: std::vec::IntoIter<(ScratchNeed, SourceVarId)>, + expression_values: HashMap, + scratch: Vec<(ScratchNeed, SourceVarId)>, clocks: Vec<(StrId, ProcessClock)>, releases: Vec>, host_requests: Vec>, @@ -639,7 +766,8 @@ fn lower_block( module_id, hierarchical, private: storage.private.clone(), - scratch: storage.scratch.clone().into_iter(), + expression_values: storage.expression_values.clone(), + scratch: storage.scratch.clone(), clocks: Vec::new(), releases: Vec::new(), host_requests: Vec::new(), @@ -653,7 +781,7 @@ fn lower_block( event_yield: None, }; if contains_runtime_event(ir, statements, &mut HashSet::default()) { - lowering.event_yield = Some(lowering.take_scratch("event_yield")?.1); + lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); } lowering.declare_clocks(statements); // A block that ends right after a store settles, so a process that runs @@ -947,15 +1075,27 @@ impl<'a> BlockLowering<'a> { } } - fn take_scratch(&mut self, purpose: &'static str) -> Result<(usize, SourceVarId), ParserError> { - match self.scratch.next() { - Some((need, id)) if need.purpose == purpose => Ok((need.width, id)), - other => Err(ParserError::internal( - "testbench process lowering", - format!("scratch for {purpose} expected, found {other:?}"), - None, - )), - } + fn take_scratch( + &mut self, + purpose: &'static str, + width: usize, + ) -> Result<(usize, SourceVarId), ParserError> { + // Nested expression calls can consume their storage between the host + // operation's own values. Slots are distinct; select by purpose/type + // rather than requiring planning and evaluation to interleave alike. + let position = self + .scratch + .iter() + .position(|(need, _)| need.purpose == purpose && need.width == width) + .ok_or_else(|| { + ParserError::internal( + "testbench process lowering", + format!("missing scratch for {purpose} at width {width}"), + None, + ) + })?; + let (need, id) = self.scratch.remove(position); + Ok((need.width, id)) } fn error( @@ -1001,6 +1141,18 @@ impl<'a> BlockLowering<'a> { fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) { for statement in statements { + let mut calls = Vec::new(); + for expr in expressions::statement_inputs(statement) { + expressions::expression_calls(expr, &mut calls); + } + for call in calls { + if active.insert(call.id) { + if let Some(body) = function_body(&self.ir.functions, call) { + self.scan_clocks(&body.statements, active); + } + active.remove(&call.id); + } + } match statement { Statement::TbMethodCall(tb) => match &tb.method { TbMethod::ClockNext { period, .. } => { @@ -1019,10 +1171,14 @@ impl<'a> BlockLowering<'a> { } _ => {} }, - Statement::If(stmt) => { - self.scan_clocks(&stmt.true_side, active); - self.scan_clocks(&stmt.false_side, active); - } + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => self.scan_clocks(&stmt.true_side, active), + Some(false) => self.scan_clocks(&stmt.false_side, active), + None => { + self.scan_clocks(&stmt.true_side, active); + self.scan_clocks(&stmt.false_side, active); + } + }, Statement::IfReset(stmt) => { self.scan_clocks(&stmt.true_side, active); self.scan_clocks(&stmt.false_side, active); @@ -1033,7 +1189,9 @@ impl<'a> BlockLowering<'a> { } self.scan_clocks(&stmt.default, active); } - Statement::For(stmt) => self.scan_clocks(&stmt.body, active), + Statement::For(stmt) if !constant_empty_range(&stmt.range) => { + self.scan_clocks(&stmt.body, active) + } Statement::FunctionCall(call) => { if active.insert(call.id) && let Some(body) = function_body(&self.ir.functions, call) @@ -1079,7 +1237,7 @@ impl<'a> BlockLowering<'a> { // ------------------------------------------------------------ helpers - fn expression(&mut self, expr: &Expression) -> Result { + fn raw_expression(&mut self, expr: &Expression) -> Result { let (parser, kernel, targets, sources, convert) = parts!(self); parser.parse_expression( expr, @@ -1184,6 +1342,21 @@ impl<'a> BlockLowering<'a> { destination: &AssignDestination, value: RegisterId, ) -> Result<(), ParserError> { + if let Some(&id) = self.ids.get(&destination.id) + && let Some(info) = self.lookup.module_variables[&self.module_id].get(&id) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } if !self.private.contains_key(&destination.id) { self.dirty = true; } @@ -1236,10 +1409,11 @@ impl<'a> BlockLowering<'a> { fn host_scratch( &mut self, purpose: &'static str, + width: usize, signed: bool, is_string: bool, ) -> Result<(HostValue, SourceVarId), ParserError> { - let (width, id) = self.take_scratch(purpose)?; + let (width, id) = self.take_scratch(purpose, width)?; Ok(( HostValue { signal: SourceAddr { @@ -1294,7 +1468,7 @@ impl<'a> BlockLowering<'a> { Statement::If(stmt) => { // A constant condition keeps the other side out of the // kernel, as the interpreter never ran it. - match FfParser::get_constant_procedural_truth(&stmt.cond) { + match constant_truth(&stmt.cond) { Some(true) => self.lower_statements(&stmt.true_side), Some(false) => self.lower_statements(&stmt.false_side), None => { @@ -1394,6 +1568,8 @@ impl<'a> BlockLowering<'a> { &mut self, stmt: &veryl_analyzer::ir::CaseStatement, ) -> Result { + let value = self.expression(&stmt.case_target)?; + self.save_expression(&stmt.case_target, value)?; self.lower_case_arm(stmt, 0) } @@ -1406,7 +1582,16 @@ impl<'a> BlockLowering<'a> { return self.lower_statements(&stmt.default); }; let condition_expr = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); - let condition = self.condition(&condition_expr)?; + self.settle_if_dirty()?; + let target = self.saved_expression(&stmt.case_target); + self.parser.push_process_expression_values( + [(stmt.case_target.token_range(), target)] + .into_iter() + .collect(), + ); + let condition = self.condition(&condition_expr); + self.parser.pop_process_expression_values(); + let condition = condition?; let builder = self.kernel.builder(); let then_block = builder.new_block(); let else_block = builder.new_block(); @@ -1506,15 +1691,29 @@ impl<'a> BlockLowering<'a> { } else { assign }; + let prepared = if expressions::has_call(&assign.expr) { + Some(self.expression(&assign.expr)?) + } else { + None + }; + if let Some(value) = prepared { + self.parser.push_process_expression_values( + [(assign.expr.token_range(), value)].into_iter().collect(), + ); + } let (parser, kernel, targets, sources, convert) = parts!(self); - parser.parse_assign_statement( + let result = parser.parse_assign_statement( assign, targets, &Domain::Process, &convert, sources, kernel.builder(), - ) + ); + if prepared.is_some() { + self.parser.pop_process_expression_values(); + } + result } /// A `for` loop whose counter and bounds live in state, so its body @@ -1532,17 +1731,18 @@ impl<'a> BlockLowering<'a> { cmp_signed, .. } = shape; - let (_, start_slot) = self.take_scratch("for_start")?; - let (_, end_slot) = self.take_scratch("for_end")?; + let (_, start_slot) = self.take_scratch("for_start", width)?; + let (_, end_slot) = self.take_scratch("for_end", width)?; let single_slot = if shape.wide_capable() { - Some(self.take_scratch("for_single")?.1) + Some(self.take_scratch("for_single", 1)?.1) } else { None }; let start_reg = self.for_bound(shape.start, width, cmp_signed)?; - let end_reg = self.for_bound(shape.end, width, cmp_signed)?; self.store_scratch(start_slot, width, start_reg); + let end_reg = self.for_bound(shape.end, width, cmp_signed)?; self.store_scratch(end_slot, width, end_reg); + let start_reg = self.load_scratch(start_slot, width, cmp_signed); let var = self.destination(stmt.var_id, stmt.token); let stall_message = format!( "non-progressing stepped for loop (loop variable `{}`)", @@ -1560,10 +1760,21 @@ impl<'a> BlockLowering<'a> { // one value, nothing when it is empty, and fails otherwise. if let Some(single_slot) = single_slot { let mut wide = None; - for (reg, is_wide) in [(start_reg, shape.start_wide), (end_reg, shape.end_wide)] { + for (reg, is_wide, signed_bound) in [ + (start_reg, shape.start_wide, shape.start_signed), + (end_reg, shape.end_wide, shape.end_signed), + ] { if !is_wide { continue; } + let signed_high = if signed_bound { + let low = self + .parser + .cast_reg_width_ext(self.kernel.builder(), reg, 128, true); + Some(self.extend_for_compare(low, width, true)) + } else { + None + }; let builder = self.kernel.builder(); let shift = builder.alloc_bit(width, false); builder.emit(SIRInstruction::Imm(shift, SIRValue::new(64u64))); @@ -1572,7 +1783,12 @@ impl<'a> BlockLowering<'a> { let zero = builder.alloc_bit(width, cmp_signed); builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); let nonzero = builder.alloc_bit(1, false); - builder.emit(SIRInstruction::Binary(nonzero, high, BinaryOp::Ne, zero)); + builder.emit(SIRInstruction::Binary( + nonzero, + if signed_bound { reg } else { high }, + BinaryOp::Ne, + signed_high.unwrap_or(zero), + )); wide = Some(match wide { None => nonzero, Some(previous) => { @@ -1852,6 +2068,7 @@ impl<'a> BlockLowering<'a> { self.kernel.builder().seal_block(SIRTerminator::Error(code)); self.kernel.builder().switch_to_block(progress); self.store(&var, next)?; + self.settle_if_dirty()?; self.parser.clear_register_cache(); match single_slot { Some(single_slot) => { @@ -1898,8 +2115,18 @@ impl<'a> BlockLowering<'a> { width: usize, signed: bool, ) -> Result { + let prepared = match bound { + ForBound::Expression(expr) if expressions::has_call(expr) => { + Some((expr.token_range(), self.expression(expr)?)) + } + _ => None, + }; + if let Some((token, value)) = prepared { + self.parser + .push_process_expression_values([(token, value)].into_iter().collect()); + } let (parser, kernel, targets, sources, convert) = parts!(self); - parser.parse_for_bound( + let result = parser.parse_for_bound( bound, width, width, @@ -1909,7 +2136,11 @@ impl<'a> BlockLowering<'a> { &convert, sources, kernel.builder(), - ) + ); + if prepared.is_some() { + self.parser.pop_process_expression_values(); + } + result } fn lower_system_function(&mut self, call: &SystemFunctionCall) -> Result { @@ -1966,15 +2197,19 @@ impl<'a> BlockLowering<'a> { } fn system_task(&mut self, call: &SystemFunctionCall) -> Result { + let bindings = self.expression_bindings(&expressions::system_inputs(&call.kind))?; + self.parser.push_process_expression_values(bindings); let (parser, kernel, targets, sources, convert) = parts!(self); - parser.parse_system_task_statement( + let result = parser.parse_system_task_statement( call, targets, &Domain::Process, &convert, sources, kernel.builder(), - )?; + ); + self.parser.pop_process_expression_values(); + result?; Ok(Flow::Continue) } @@ -1985,7 +2220,22 @@ impl<'a> BlockLowering<'a> { cond: &SystemFunctionInput, args: &[SystemFunctionInput], ) -> Result { - let condition = self.condition(&cond.0)?; + let mut condition = self.condition(&cond.0)?; + let argument_calls = args.iter().any(|arg| expressions::has_call(&arg.0)); + let freeze_condition = argument_calls || expressions::has_call(&cond.0); + if freeze_condition { + self.save_expression(&cond.0, condition)?; + } + self.settle_if_dirty()?; + let inputs = args.iter().map(|arg| &arg.0).collect::>(); + let bindings = self.expression_bindings(&inputs)?; + if freeze_condition { + let value = self.saved_expression(&cond.0); + condition = self + .parser + .lower_procedural_condition(value, self.kernel.builder()); + } + self.parser.push_process_expression_values(bindings); let location = event_location(&call.comptime.token); let pass_site = self .parser @@ -2045,6 +2295,7 @@ impl<'a> BlockLowering<'a> { .seal_block(SIRTerminator::Jump(join, Vec::new())); } } + self.parser.pop_process_expression_values(); self.kernel.builder().switch_to_block(join); self.yield_for_runtime_event()?; Ok(Flow::Continue) @@ -2109,6 +2360,28 @@ impl<'a> BlockLowering<'a> { Some(&call.comptime.token), )); }; + let paths = self.ir.functions[&call.id] + .args + .iter() + .flat_map(|arg| arg.members.iter().map(|(path, _, _)| path.clone())) + .collect::>(); + let inputs = paths + .iter() + .filter_map(|path| { + call.inputs + .iter() + .find_map(|(input, expr)| (input == path).then_some((path, expr))) + }) + .collect::>(); + let freeze = inputs.iter().any(|(_, expr)| expressions::has_call(expr)); + let mut values = Vec::new(); + for (path, expr) in &inputs { + let value = self.expression(expr)?; + if freeze { + self.save_expression(expr, value)?; + } + values.push((*path, *expr, value)); + } if !self.active_functions.insert(call.id) { return Err(self.error( "function call in an initial block", @@ -2116,9 +2389,13 @@ impl<'a> BlockLowering<'a> { Some(&call.comptime.token), )); } - for (path, expr) in &call.inputs { + for (path, expr, value) in values { if let Some(&formal) = body.arg_map.get(path) { - let value = self.expression(expr)?; + let value = if freeze { + self.saved_expression(expr) + } else { + value + }; let destination = self.destination(formal, call.comptime.token); self.store(&destination, value)?; } @@ -2172,12 +2449,6 @@ impl<'a> BlockLowering<'a> { PortTypeKind::ResetAsyncHigh | PortTypeKind::ResetSyncHigh => (1, 0), _ => (0, 1), }; - let value = self.constant(assert_value, 1); - let destination = self.destination( - reset, - tb.ret.as_ref().map_or(self.ir.token, |ret| ret.token), - ); - self.store(&destination, value)?; let duration = match duration { Some(expr) => { let value = self.expression(expr)?; @@ -2196,11 +2467,20 @@ impl<'a> BlockLowering<'a> { } None => self.constant(3, PROCESS_DELAY_WIDTH), }; - let release = match self - .releases - .iter() - .position(|release| release.signal == reset_source) - { + let value = self.constant(assert_value, 1); + let destination = self.destination( + reset, + tb.ret.as_ref().map_or(self.ir.token, |ret| ret.token), + ); + self.store(&destination, value)?; + let clock_var = self.instance_var(*clock)?; + let clock_source = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&clock_var], + }; + let release = match self.releases.iter().position(|release| { + release.signal == reset_source && release.clock == Some(clock_source) + }) { Some(index) => index as u32, None => { let clock_var = self.instance_var(*clock)?; @@ -2228,7 +2508,7 @@ impl<'a> BlockLowering<'a> { TbMethod::RandomSeed { value } => { let seed = self.expression(value)?; let seed = self.unsigned_bits(seed, 64); - let (host_value, slot) = self.host_scratch("random_seed", false, false)?; + let (host_value, slot) = self.host_scratch("random_seed", 64, false, false)?; self.store_scratch(slot, 64, seed); self.host_request(HostRequest::RandomSeed { handle: self.resource_name(tb.inst), @@ -2237,7 +2517,8 @@ impl<'a> BlockLowering<'a> { Ok(Flow::Continue) } TbMethod::RandomGet { width, signed } => { - let (result, slot) = self.host_scratch("random_value", *signed, false)?; + let (result, slot) = + self.host_scratch("random_value", (*width as usize).max(1), *signed, false)?; let result_width = result.width; self.host_request(HostRequest::RandomGet { handle: self.resource_name(tb.inst), @@ -2253,16 +2534,26 @@ impl<'a> BlockLowering<'a> { TbMethod::RandomGetRange { min, max, - width: _, + width, signed, } => { + let freeze = expressions::has_call(min) || expressions::has_call(max); let min_reg = self.expression(min)?; - let min_reg = self.unsigned_bits(min_reg, 64); + if freeze { + self.save_expression(min, min_reg)?; + } let max_reg = self.expression(max)?; + let min_reg = if freeze { + self.saved_expression(min) + } else { + min_reg + }; + let min_reg = self.unsigned_bits(min_reg, 64); let max_reg = self.unsigned_bits(max_reg, 64); - let (min_value, min_slot) = self.host_scratch("random_min", *signed, false)?; - let (max_value, max_slot) = self.host_scratch("random_max", *signed, false)?; - let (result, slot) = self.host_scratch("random_value", *signed, false)?; + let (min_value, min_slot) = self.host_scratch("random_min", 64, *signed, false)?; + let (max_value, max_slot) = self.host_scratch("random_max", 64, *signed, false)?; + let (result, slot) = + self.host_scratch("random_value", (*width as usize).max(1), *signed, false)?; let result_width = result.width; self.store_scratch(min_slot, 64, min_reg); self.store_scratch(max_slot, 64, max_reg); @@ -2279,7 +2570,7 @@ impl<'a> BlockLowering<'a> { Ok(Flow::Continue) } TbMethod::RandomGetSeed => { - let (result, slot) = self.host_scratch("random_seed", false, false)?; + let (result, slot) = self.host_scratch("random_seed", 64, false, false)?; self.host_request(HostRequest::RandomGetSeed { handle: self.resource_name(tb.inst), result, @@ -2295,7 +2586,8 @@ impl<'a> BlockLowering<'a> { for arg in args { let is_string = arg.0.comptime().r#type.is_string(); let signed = expression_signed(&arg.0); - let (value, slot) = self.host_scratch("component_arg", signed, is_string)?; + let (value, slot) = + self.host_scratch("component_arg", argument_width(arg), signed, is_string)?; let width = value.width; let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { let builder = self.kernel.builder(); @@ -2314,8 +2606,12 @@ impl<'a> BlockLowering<'a> { } let result = match tb.ret.as_deref() { Some(_) => { - let (value, slot) = - self.host_scratch("component_result", tb.ret_signed, false)?; + let (value, slot) = self.host_scratch( + "component_result", + tb.ret_width.map_or(64, |width| width as usize).max(1), + tb.ret_signed, + false, + )?; Some((value, slot)) } None => None, diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs new file mode 100644 index 00000000000..fc644dfbf75 --- /dev/null +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -0,0 +1,446 @@ +//! Expressions a process evaluates, in their source order. +use super::*; +use veryl_analyzer::ir::{ArrayLiteralItem, CasePattern, Factor}; + +pub(super) fn system_inputs(kind: &SystemFunctionKind) -> Vec<&Expression> { + match kind { + SystemFunctionKind::Bits(input) + | SystemFunctionKind::Size(input, _) + | SystemFunctionKind::Clog2(input) + | SystemFunctionKind::Onehot(input) + | SystemFunctionKind::Signed(input) + | SystemFunctionKind::Unsigned(input) + | SystemFunctionKind::Readmemh(input, _) => vec![&input.0], + SystemFunctionKind::Display(inputs) | SystemFunctionKind::Write(inputs) => { + inputs.iter().map(|input| &input.0).collect() + } + SystemFunctionKind::Assert { cond, args, .. } => std::iter::once(&cond.0) + .chain(args.iter().map(|input| &input.0)) + .collect(), + SystemFunctionKind::Finish => Vec::new(), + } +} +fn selection<'s>(index: &'s VarIndex, select: &'s VarSelect) -> Vec<&'s Expression> { + index + .0 + .iter() + .chain(select.0.iter()) + .chain(select.1.iter().map(|(_, expr)| expr)) + .collect() +} +pub(super) fn children(expr: &Expression) -> Vec<&Expression> { + match expr { + Expression::Term(factor) => match factor.as_ref() { + Factor::Variable(_, index, select, _) => selection(index, select), + Factor::HierVariable(reference) => selection(&reference.index, &reference.select), + Factor::FunctionCall(call) => call.inputs.values().collect(), + Factor::SystemFunctionCall(call) + if !matches!( + call.kind, + SystemFunctionKind::Bits(_) | SystemFunctionKind::Size(..) + ) => + { + system_inputs(&call.kind) + } + _ => Vec::new(), + }, + Expression::Unary(_, inner, _) => vec![inner], + Expression::Binary(lhs, _, rhs, _) => vec![lhs, rhs], + Expression::Ternary(cond, yes, no, _) => vec![cond, yes, no], + Expression::Concatenation(parts, _) => parts + .iter() + .flat_map(|(value, repeat)| std::iter::once(value).chain(repeat.iter())) + .collect(), + Expression::ArrayLiteral(items, _) => items + .iter() + .flat_map(|item| match item { + ArrayLiteralItem::Value(value, repeat) => std::iter::once(value.as_ref()) + .chain(repeat.iter().map(|expr| expr.as_ref())) + .collect::>(), + ArrayLiteralItem::Defaul(value) => vec![value.as_ref()], + }) + .collect(), + Expression::StructConstructor(_, fields, _) => { + fields.iter().map(|(_, expr)| expr).collect() + } + } +} +pub(super) fn has_call(expr: &Expression) -> bool { + matches!(expr, Expression::Term(factor) if matches!(factor.as_ref(),Factor::FunctionCall(_))) + || children(expr).into_iter().any(has_call) +} +pub(super) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { + match statement { + Statement::Assign(assign) => std::iter::once(&assign.expr) + .chain( + assign + .dst + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)), + ) + .collect(), + Statement::If(stmt) => vec![&stmt.cond], + Statement::Case(stmt) => std::iter::once(stmt.case_target.as_ref()) + .chain(stmt.arms.iter().flat_map(|arm| { + arm.patterns.iter().flat_map(|pattern| match pattern { + CasePattern::Eq(expr) => vec![expr.as_ref()], + CasePattern::Range { lo, hi, .. } => vec![lo.as_ref(), hi.as_ref()], + }) + })) + .collect(), + Statement::For(stmt) => { + let (start, end) = match &stmt.range { + ForRange::Forward { start, end, .. } + | ForRange::Reverse { start, end, .. } + | ForRange::Stepped { start, end, .. } => (start, end), + }; + [start, end] + .into_iter() + .filter_map(|bound| { + if let ForBound::Expression(expr) = bound { + Some(expr.as_ref()) + } else { + None + } + }) + .collect() + } + Statement::FunctionCall(call) => call.inputs.values().collect(), + Statement::SystemFunctionCall(call) => system_inputs(&call.kind), + Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::ClockNext { count, .. } => count.iter().collect(), + TbMethod::ResetAssert { duration, .. } => duration.iter().collect(), + TbMethod::RandomSeed { value, .. } => vec![value], + TbMethod::RandomGetRange { min, max, .. } => vec![min, max], + TbMethod::Component { args, .. } => args.iter().map(|arg| &arg.0).collect(), + _ => Vec::new(), + }, + _ => Vec::new(), + } +} +pub(super) fn statement_bodies(statement: &Statement) -> Vec<&[Statement]> { + match statement { + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => vec![&stmt.true_side], + Some(false) => vec![&stmt.false_side], + None => vec![&stmt.true_side, &stmt.false_side], + }, + Statement::IfReset(stmt) => vec![&stmt.true_side, &stmt.false_side], + Statement::Case(stmt) => stmt + .arms + .iter() + .map(|arm| arm.body.as_slice()) + .chain(std::iter::once(stmt.default.as_slice())) + .collect(), + Statement::For(stmt) if !constant_empty_range(&stmt.range) => vec![&stmt.body], + _ => Vec::new(), + } +} +pub(super) fn expression_calls<'s>( + expr: &'s Expression, + calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, +) { + for child in children(expr) { + expression_calls(child, calls); + } + if let Expression::Term(factor) = expr + && let Factor::FunctionCall(call) = factor.as_ref() + { + calls.push(call); + } +} +pub(super) fn storage_width(expr: &Expression) -> usize { + expr.comptime() + .expr_context + .width + .max(crate::context_width::get_expr_width(expr).unwrap_or(0)) + .max(expr.comptime().r#type.total_width().unwrap_or(64)) + .max( + expr.comptime() + .get_value() + .ok() + .map_or(0, |value| value.width()), + ) + .max(1) +} + +impl BlockLowering<'_> { + pub(super) fn save_expression( + &mut self, + expr: &Expression, + value: RegisterId, + ) -> Result<(), ParserError> { + let (width, id) = self + .expression_values + .get(&expr.token_range()) + .copied() + .ok_or_else(|| { + self.error( + "process expression storage", + format!("missing value for {expr}"), + Some(&expr.token_range()), + ) + })?; + let value = self.parser.cast_reg_width_ext( + self.kernel.builder(), + value, + width, + expression_signed(expr), + ); + self.store_scratch(id, width, value); + Ok(()) + } + pub(super) fn saved_expression(&mut self, expr: &Expression) -> RegisterId { + let (width, id) = self.expression_values[&expr.token_range()]; + let builder = self.kernel.builder(); + let value = if expr.comptime().r#type.is_2state() { + builder.alloc_bit(width, expression_signed(expr)) + } else { + builder.alloc_logic(width) + }; + builder.emit(SIRInstruction::Load( + value, + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: id, + }, + SIROffset::Static(0), + width, + )); + value + } + fn parse_with_values( + &mut self, + expr: &Expression, + values: HashMap, + ) -> Result { + self.parser.push_process_expression_values(values); + let result = self.raw_expression(expr); + self.parser.pop_process_expression_values(); + result + } + fn has_unbound_calls(&self, expr: &Expression) -> bool { + self.parser + .process_expression_value(expr.token_range()) + .is_none() + && (matches!(expr,Expression::Term(factor) if matches!(factor.as_ref(),Factor::FunctionCall(_))) + || children(expr) + .into_iter() + .any(|child| self.has_unbound_calls(child))) + } + + pub(super) fn expression_bindings( + &mut self, + inputs: &[&Expression], + ) -> Result, ParserError> { + if !inputs.iter().any(|expr| has_call(expr)) { + return Ok(HashMap::default()); + } + let inputs = inputs + .iter() + .copied() + .filter(|expr| has_call(expr) || FfParser::static_string_expr(expr).is_none()) + .collect::>(); + for expr in &inputs { + let value = self.expression(expr)?; + self.save_expression(expr, value)?; + } + Ok(inputs + .into_iter() + .map(|expr| (expr.token_range(), self.saved_expression(expr))) + .collect()) + } + + pub(super) fn expression(&mut self, expr: &Expression) -> Result { + self.settle_if_dirty()?; + if let Some(value) = self.parser.process_expression_value(expr.token_range()) { + return Ok(value); + } + if !self.has_unbound_calls(expr) { + return self.raw_expression(expr); + } + if let Expression::Term(factor) = expr + && let Factor::FunctionCall(call) = factor.as_ref() + { + let body = function_body(&self.ir.functions, call).ok_or_else(|| { + self.error( + "process function expression", + format!("{call}"), + Some(&call.comptime.token), + ) + })?; + if let Flow::Ended = self.lower_function_call(call)? { + // Keep the syntactic continuation unreachable. The Finish return + // already stops this kernel and the other ready processes. + let unreachable = self.kernel.builder().new_block(); + self.kernel.builder().switch_to_block(unreachable); + return Ok(self.constant(0, storage_width(expr))); + } + self.parser.clear_register_cache(); + return self.load_var(body.ret.ok_or_else(|| { + self.error( + "process function expression", + "function has no result", + Some(&call.comptime.token), + ) + })?); + } + if let Expression::Binary(lhs, op, rhs, _) = expr + && matches!(op, Op::LogicAnd | Op::LogicOr) + { + return self.logical_expression(expr, lhs, rhs, *op == Op::LogicAnd); + } + if let Expression::Ternary(cond, yes, no, _) = expr { + return self.conditional_expression(expr, cond, yes, no); + } + let inputs = match expr { + Expression::Binary(lhs, Op::As, _, _) => vec![lhs.as_ref()], + _ => children(expr), + }; + for child in &inputs { + let value = self.expression(child)?; + self.save_expression(child, value)?; + } + let values = inputs + .into_iter() + .map(|child| (child.token_range(), self.saved_expression(child))) + .collect(); + self.parse_with_values(expr, values) + } + fn logical_expression( + &mut self, + expr: &Expression, + lhs: &Expression, + rhs: &Expression, + is_and: bool, + ) -> Result { + let left = self.expression(lhs)?; + self.save_expression(lhs, left)?; + let builder = self.kernel.builder(); + let not = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(not, UnaryOp::LogicNot, left)); + let dominant = if is_and { + not + } else { + let truth = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(truth, UnaryOp::LogicNot, not)); + truth + }; + let shortcut = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary( + shortcut, + UnaryOp::ToTwoState, + dominant, + )); + let short = builder.new_block(); + let full = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: shortcut, + true_block: (short, Vec::new()), + false_block: (full, Vec::new()), + }); + let dirty_before = self.dirty; + self.kernel.builder().switch_to_block(short); + let value = self.constant(u64::from(!is_and), 1); + self.save_expression(expr, value)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(full); + let right = self.expression(rhs)?; + let left = self.saved_expression(lhs); + let builder = self.kernel.builder(); + let value = builder.alloc_logic(1); + builder.emit(SIRInstruction::Binary( + value, + left, + if is_and { + BinaryOp::LogicAnd + } else { + BinaryOp::LogicOr + }, + right, + )); + self.save_expression(expr, value)?; + self.dirty |= dirty_before; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(join); + self.parser.clear_register_cache(); + Ok(self.saved_expression(expr)) + } + fn conditional_expression( + &mut self, + expr: &Expression, + cond: &Expression, + yes: &Expression, + no: &Expression, + ) -> Result { + let value = self.expression(cond)?; + self.save_expression(cond, value)?; + let truth = self + .parser + .lower_procedural_condition(value, self.kernel.builder()); + let builder = self.kernel.builder(); + let yes_block = builder.new_block(); + let decide = builder.new_block(); + let no_block = builder.new_block(); + let unknown = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: truth, + true_block: (yes_block, Vec::new()), + false_block: (decide, Vec::new()), + }); + let dirty_before = self.dirty; + self.kernel.builder().switch_to_block(yes_block); + let result = self.expression(yes)?; + self.save_expression(expr, result)?; + let yes_dirty = self.dirty; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(decide); + self.dirty = dirty_before; + let condition = self.saved_expression(cond); + let builder = self.kernel.builder(); + let not = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(not, UnaryOp::LogicNot, condition)); + let false_known = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(false_known, UnaryOp::ToTwoState, not)); + builder.seal_block(SIRTerminator::Branch { + cond: false_known, + true_block: (no_block, Vec::new()), + false_block: (unknown, Vec::new()), + }); + self.kernel.builder().switch_to_block(no_block); + let result = self.expression(no)?; + self.save_expression(expr, result)?; + let no_dirty = self.dirty; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(unknown); + self.dirty = dirty_before; + for child in [yes, no] { + let value = self.expression(child)?; + self.save_expression(child, value)?; + } + let values = [cond, yes, no] + .into_iter() + .map(|child| (child.token_range(), self.saved_expression(child))) + .collect(); + let result = self.parse_with_values(expr, values)?; + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(join); + self.dirty |= yes_dirty || no_dirty; + self.parser.clear_register_cache(); + Ok(self.saved_expression(expr)) + } +} diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 2e550c48140..6eba6c334e8 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -3560,6 +3560,7 @@ pub fn compile_semantic_testbench( runtime_event_site_count: usize, random_seed: Option, ) -> Result>, ParserError> { + let kernels = source.kernels; let sources: Vec<_> = source .sources() .filter(|source| source.initial_statements.is_some()) @@ -3594,7 +3595,7 @@ pub fn compile_semantic_testbench( let mut site_end = runtime_event_site_count.saturating_sub(total_sites); let mut processes = Vec::new(); for source in sources { - if source.kernels { + if kernels { break; } let initial_stmts = source.initial_statements.as_ref().unwrap(); diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 97ce56ecade..83c540a8d9b 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -553,7 +553,8 @@ impl SimulationState { .tick_clocks .iter() .filter(|(id, clock)| { - !events_to_process.is_empty() && !self.tick_budget_spent() + !events_to_process.is_empty() + && !self.tick_budget_spent() && clock.next_edge == current_time && self.clock_has_waiters(**id) && executor.backend().get_as::(clock.signal) == 0 @@ -879,7 +880,9 @@ impl SimulationState { where E: SimulationExecutor, { - let mut ready = std::mem::take(&mut self.inactive).into_iter().collect::>(); + let mut ready = std::mem::take(&mut self.inactive) + .into_iter() + .collect::>(); while let Some(&Reverse((wakeup, process))) = self.process_wakeups.peek() { if wakeup != time { break; @@ -908,6 +911,31 @@ impl SimulationState { ready } + fn process_counter_values(&self, backend: &B) -> Vec<(u32, u32)> { + self.process_event_counters + .iter() + .map(|(_, rises, falls)| (backend.get_as(*rises), backend.get_as(*falls))) + .collect() + } + + fn process_counter_edges(&self, backend: &B, before: &[(u32, u32)]) -> BitSet { + let mut edges = BitSet::with_capacity(backend.num_events()); + for ((id, rises, falls), (old_rises, old_falls)) in + self.process_event_counters.iter().zip(before) + { + let changed = match self.domain_kinds[*id] { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + backend.get_as::(*falls) != *old_falls + } + _ => backend.get_as::(*rises) != *old_rises, + }; + if changed { + edges.insert(*id); + } + } + edges + } + /// Run `ready` processes, and the processes waiting for an event or a /// condition, in declaration order until each suspends or ends. A /// process another one wakes runs in a further pass of the same round, @@ -981,7 +1009,10 @@ impl SimulationState { } })?; self.waiting.remove(&process); - if delay == 0 && ProcessStatus::from_code(status) == Some(ProcessStatus::InactiveDelay) { + if delay == 0 + && ProcessStatus::from_code(status) + == Some(ProcessStatus::InactiveDelay) + { self.inactive.insert(process); } else { self.process_wakeups.push(Reverse((time, process))); @@ -1177,6 +1208,7 @@ impl SimulationState { // sampled value before, so transitions from and into x or z count // as IEEE 1800-2023 Table 9-2 says. executor.backend_mut().clear_triggered_bits(); + let counter_values = self.process_counter_values(executor.backend()); let mut process_driven = Vec::new(); if !ready_processes.is_empty() || !self.waiting.is_empty() { let before: Vec<(bool, bool)> = self @@ -1205,7 +1237,8 @@ impl SimulationState { let mut discovered_in_this_step = BitSet::with_capacity(num_events); // Counter-recorded kernel edges survive later blocking stores that // restored the signal before the kernel returned. - let mut scheduled_trigger_ids = executor.backend().get_triggered_bits(); + let mut scheduled_trigger_ids = + self.process_counter_edges(executor.backend(), &counter_values); // An external drive may already have been combinationally evaluated // by a testbench read. Compare against our saved baseline even if that // evaluation's transient trigger bits have since been cleared. @@ -1315,6 +1348,7 @@ impl SimulationState { executor.backend_mut().clear_triggered_bits(); // Inactive-region (#0) continuations run after the active // FF evaluations and before the pending NBA publications. + let inactive_counter_values = self.process_counter_values(executor.backend()); let mut inactive_ran = false; loop { let ready = std::mem::take(&mut self.inactive) @@ -1326,7 +1360,8 @@ impl SimulationState { inactive_ran |= self.run_processes(executor, current_time, ready)?; } if inactive_ran { - let driven = executor.backend().get_triggered_bits(); + let driven = + self.process_counter_edges(executor.backend(), &inactive_counter_values); executor.eval_comb()?; if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); @@ -1588,6 +1623,7 @@ pub struct ScheduleParts { pub periodic: Vec<(SimEvent, u64)>, /// Events whose signal was high when edge detection last sampled it. pub high_events: Vec, + pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, /// Processes waiting for an event or a condition, in ascending order. @@ -1638,6 +1674,11 @@ impl SimulationState { }) .collect(), high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + unknown_events: self + .unknown_clock_values + .iter() + .map(|id| events[id]) + .collect(), process_wakeups: { let mut wakeups = self .process_wakeups @@ -1695,8 +1736,10 @@ impl SimulationState { .map(|(event, count)| (PeriodicEventKey::from_event(&event), count as usize)) .collect(); self.last_clock_values.make_empty(); - // A state file holds known values only. self.unknown_clock_values.make_empty(); + for event in parts.unknown_events { + self.unknown_clock_values.insert(event.id()); + } for event in parts.high_events { self.last_clock_values.insert(event.id()); } diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index af5e4737441..d04d8922e64 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -26,7 +26,7 @@ use std::io::{self, Read, Write}; const MAGIC: &[u8; 8] = b"CXSTATE\0"; -const VERSION: u16 = 1; +const VERSION: u16 = 2; const FLAG_FOUR_STATE: u16 = 1 << 0; const FLAG_SCHEDULE: u16 = 1 << 1; @@ -77,6 +77,8 @@ pub struct ScheduleRecord { pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. pub high_events: Vec, + /// Events whose baseline contains X/Z bits. + pub unknown_events: Vec, } /// Contents of a state file. @@ -168,6 +170,10 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } + put_len(w, schedule.unknown_events.len())?; + for event in &schedule.unknown_events { + put_str(w, event)?; + } } Ok(()) } @@ -180,7 +186,7 @@ impl StateFile { return Err(StateFileError::BadMagic); } let version = get_u16(r)?; - if version != VERSION { + if !(1..=VERSION).contains(&version) { return Err(StateFileError::UnsupportedVersion(version)); } let flags = get_u16(r)?; @@ -233,7 +239,15 @@ impl StateFile { let high_events = (0..get_u32(r)?) .map(|_| get_str(r)) .collect::>()?; + let unknown_events = if version >= 2 { + (0..get_u32(r)?) + .map(|_| get_str(r)) + .collect::>()? + } else { + Vec::new() + }; Some(ScheduleRecord { + unknown_events, time, clocks, events, @@ -440,6 +454,7 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], + unknown_events: vec!["clk".into()], }), } } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 460d48c31b1..f68a8012e79 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 12; +const CONTAINER_VERSION: u16 = 13; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 92fb2fcddee..8fa059bf855 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -168,14 +168,26 @@ impl SimulationExecutor for Simulator { if !self.program.runtime_schema.processes.is_empty() { for reset_event in self.components.reset_event_ids() { let address = self.backend.id_to_addr_slice()[reset_event]; - let Some(release) = self + let releases = self .program .runtime_schema .processes .iter() .flat_map(|slots| &slots.releases) - .find(|release| release.signal == address) - else { + .filter(|release| release.signal == address); + // Prefer the firing domain; a single-domain component can + // also inherit a held reset on its derived clock. + let release = releases + .clone() + .find(|release| { + release.clock.is_some_and(|clock| { + self.backend + .resolve_event_opt(&clock) + .is_some_and(|clock| clock.id() == event.id()) + }) + }) + .or_else(|| releases.into_iter().next()); + let Some(release) = release else { continue; }; let signal = self.backend.resolve_signal(&address); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index f1ecb2f602e..8e51a3f85f0 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -847,9 +847,9 @@ mod host { self.collect_formatted_runtime_events(ctx) } - /// The runtime events with the site each came from, settling the - /// combinational observers first as - /// [`Self::drain_runtime_events_deferred_with_context`] does. + /// Collect already-published events with their sites. Scheduler callers + /// settle explicitly; collecting after an execution error must not retry + /// the failed combinational evaluation. pub(crate) fn collect_sited_runtime_events( &mut self, ctx: RuntimeFormatContext<'_>, @@ -858,9 +858,6 @@ mod host { !self.runtime_event_drain_active.load(Ordering::Acquire), "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", ); - if !self.program.runtime_schema.comb_observers.is_empty() && self.dirty { - self.eval_comb_for_runtime_event_drain().unwrap(); - } if self.runtime_event_read_seq.load(Ordering::Acquire) == self.runtime_event_write_seq() { return Vec::new(); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index a9667da17e6..8e7af6a768f 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -351,6 +351,13 @@ fn analyze( // Shared context for pass2 let mut context = Context::default(); + // The analyzer's constant evaluator does not retain testbench runtime + // effects. Keep calls in kernel testbench IR; SIR lowering can still fold + // their values after executing the process effects. + context.disalbe_const_opt = testbench_kernels + && symbol_table::get_all().iter().any( + |symbol| matches!(&symbol.kind, SymbolKind::Module(module) if module.test.is_some()), + ); let mut ir = Ir::default(); diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index d72a2c6b10c..c604160502c 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -373,6 +373,7 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), + unknown_events: parts.unknown_events.into_iter().map(event_path).collect(), } } @@ -403,6 +404,7 @@ impl Simulator { .iter() .map(|(name, _)| name) .chain(&record.high_events) + .chain(&record.unknown_events) .chain(scheduled.clone().map(|event| &event.event)) .filter(|name| !events.contains_key(*name)) .chain( @@ -440,6 +442,11 @@ impl Simulator { .map(|(event, count)| (resolve(event), *count)) .collect(), high_events: record.high_events.iter().map(|name| events[name]).collect(), + unknown_events: record + .unknown_events + .iter() + .map(|name| events[name]) + .collect(), // State files are rejected for designs with processes. process_wakeups: Vec::new(), waiting_processes: Vec::new(), diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index baefe0ea52b..4f511460309 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -125,6 +125,7 @@ fn run( if let Some(writer) = sim.vcd_writer.as_mut() && let Err(error) = writer.add_external_signals(&sim.components.trace_descriptors()) { + let _ = sim.components.finish(0); return failed(format!("component VCD registration failed: {error}")); } apply_component_writes(sim, initial_writes); @@ -261,7 +262,10 @@ fn drain( match event { RuntimeEvent::AssertPass { message } => assertions.push(AssertionResult { passed: true, - message: Some(message), + message: site + .and_then(|id| sim.program.runtime_schema.runtime_event_sites.get(id)) + .and_then(|site| site.template.as_ref()) + .map(|_| message), location, }), RuntimeEvent::AssertContinue { message } => assertions.push(AssertionResult { diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 2d144cb851f..2ffca4b207f 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -3053,3 +3053,47 @@ fn concurrent_reset_only_replaces_its_own_component_clock_domain() { TestResult::Pass ); } + +static VCD_FINISH_CALLS: AtomicUsize = AtomicUsize::new(0); +unsafe extern "C" fn finish_vcd_registration(_: *mut c_void, _: *mut sys::VrlCtx) -> i32 { + VCD_FINISH_CALLS.fetch_add(1, Ordering::Relaxed); + 0 +} +static VCD_CLEANUP_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + on_finish: finish_vcd_registration, + ..CLOCK_COMPONENT +}; + +#[test] +fn failed_component_vcd_registration_calls_finish_on_each_run() { + celox::register_static_component("celox_vcd_cleanup", &VCD_CLEANUP_COMPONENT); + VCD_FINISH_CALLS.store(0, Ordering::Relaxed); + let (directory, metadata) = component_metadata(); + let manifest = directory.path().join("component/veryl.manifest.json"); + let mut json: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest).unwrap()).unwrap(); + json["types"]["celox_vcd_cleanup"] = json["types"]["celox_clocked"].clone(); + std::fs::write(&manifest, serde_json::to_vec(&json).unwrap()).unwrap(); + let code = r#"#[test(t)] module t { + inst clk: $tb::clock_gen; + var d: logic<8>; var q: logic<8>; + inst component: $comp::celox_vcd_cleanup #(STEP: 0)(clk,d,q); + initial {clk.next();$finish();} + }"#; + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .vcd(directory.path().join("cleanup.vcd")) + .build() + .unwrap(); + // A written header cannot accept newly initialized component signals. + sim.dump(0); + let tb = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for expected in 1..=2 { + let result = celox::testbench::run_compiled_testbench(&mut sim, &tb); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("component VCD registration failed")), + "{result:?}" + ); + assert_eq!(VCD_FINISH_CALLS.load(Ordering::Relaxed), expected); + } +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index a8997fb0f9f..ec2ae2ca035 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -453,6 +453,7 @@ fn tick_limit_drains_falling_edges_and_reset_release_without_resuming_processes( check(Simulator::builder(code, "Top").build_interpreter().unwrap()); check(Simulator::builder(code, "Top").build_cranelift().unwrap()); check(Simulator::builder(code, "Top").build_wasm().unwrap()); + check(Simulator::builder(code, "Top").build_tiered().unwrap()); #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulator::builder(code, "Top").build_native().unwrap()); } @@ -721,3 +722,249 @@ fn a_block_ending_after_a_store_settles_for_the_next_block() { }"#; check_passes_on_every_backend(code); } + +#[test] +fn expression_helper_finish_stops_continuations_and_other_processes() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function stop() -> u32 { $finish(); return 7; } + initial { value = stop(); for i in 0..10000 { $assert(1'd0, "continued after finish"); } } + initial { $assert(1'd0, "other process ran after finish"); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_helper_output_stores_settle_derived_reads() { + let code = r#"#[test(Top)] module Top { + var source: logic<8>; + let derived: logic<8> = source + 8'd1; + function update(value: output logic<8>) -> logic { value = 8'd41; return 1'd1; } + initial { if update(source) { $assert(derived == 8'd42); } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn effectful_case_target_is_evaluated_once() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function next() -> u32 { calls += 1; return calls; } + initial { case next() { 0: $assert(1'd0); 1: $assert(calls == 1); default: $assert(1'd0); } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn loop_backedges_settle_the_previous_iteration_store() { + let code = r#"#[test(Top)] module Top { + var source: u32; + let derived: u32 = source + 1; + initial { for i in 0..3 { $assert(derived == i + 1); source += 1; } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_values_survive_nested_helper_clock_waits() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var value: u32; + function later(value: input u32) -> u32 { clk.next(); return value; } + initial { value = later(2) + later(5); $assert(value == 7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn effectful_expression_helpers_preserve_short_circuit_and_branch_selection() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + var value: logic; + function next() -> logic { calls += 1; return 1'd1; } + initial { + value = 1'd0 && next(); $assert(value == 1'd0); + value = 1'd1 || next(); $assert(value == 1'd1); + value = if 1'd1 ? next() : next(); + $assert(calls == 1); $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_helpers_publish_passing_assertions_and_yield_before_ring_wrap() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function emit_event() -> u32 { $write(""); $assert(1'd1); return 1; } + initial { for i in 0..1500 { value = emit_event(); } $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!(detailed.assertions.len(), 1500); + assert!( + detailed + .assertions + .iter() + .all(|assertion| assertion.passed && assertion.message.is_none()) + ); + check_passes_on_every_backend(code); +} + +#[test] +fn fatal_combinational_step_returns_failure_without_event_drain_panic() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: u32; + always_ff(clk) { count += 1; } + always_comb { $assert(count <: 2, "comb failed"); } + initial { clk.next(10); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(!detailed.passed); + assert!( + detailed + .error + .as_deref() + .is_some_and(|error| error.contains("comb failed")), + "{detailed:?}" + ); +} + +#[test] +fn dynamic_signed_wide_singleton_uses_the_wide_loop_path() { + let code = r#"#[test(Top)] module Top { + var bound: signed logic<192>; + var count: u32; + initial { bound = -(192'd1 << 150); for i in bound..=bound { count += 1; } $assert(count == 1); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn unreachable_clock_waits_leave_a_host_driven_clock_unchanged() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + initial { if 1'd0 { clk.next(); } for i in 3..3 { clk.next(); } $assert(clk == 1'd1); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); +} + +#[test] +fn reset_duration_reads_the_value_before_assertion() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 2); + inst rst: $tb::reset_gen(clk); + initial { rst.assert(1); rst.assert((rst as u32) + 1); $assert(1'd1, "time=%t"); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!(detailed.assertions[0].message.as_deref(), Some("time=6")); + check_passes_on_every_backend(code); +} + +#[test] +fn statement_call_arguments_preserve_order_and_each_nested_result() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function probe(value: input u32) -> u32 { calls = calls * 10 + value; return value; } + function accept(first: input u32, second: input u32) { $assert(first == 1 && second == 2); } + initial { accept(probe(1), probe(2)); $assert(calls == 12); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn selected_method_and_function_outputs_validate_destination_bounds() { + for operation in ["words[2] = random.get();", "fill(words[2]);"] { + let code = format!( + r#"#[test(Top)] module Top {{ + var random: $tb::random::; + var words: u8[2]; + function fill(value: output u8) {{ value=7; }} + initial {{ {operation} $finish(); }} + }}"# + ); + let error = Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap_err() + .to_string(); + assert!( + error.contains("testbench selected destination") || error.contains("invalid select"), + "{error}" + ); + } +} + +#[test] +fn display_and_assertion_arguments_use_process_helper_effects() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function probe(value: input u32) -> u32 { calls += 1; $assert(1'd1); return value; } + initial { $write("%d",probe(1)); $assert(1'd1,"value=%d",probe(2)); $assert(calls == 2); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!(detailed.assertions.len(), 4); + assert_eq!(detailed.assertions[2].message.as_deref(), Some("value=2")); + check_passes_on_every_backend(code); +} + +#[test] +fn loop_and_random_bounds_survive_a_suspending_expression_call() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var random: $tb::random::; + var count: u32; + var value: u8; + function bound(value: input u32) -> u32 { var sample:u8; sample=random.get(); clk.next(); return value + (sample & 0); } + initial { for i in bound(0)..3 { count += 1; } value=random.get_range(7,bound(7)); $assert(count == 3 && value == 7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn unknown_conditional_helpers_preserve_value_masks_and_both_effects() { + let code = r#"#[test(Top)] module Top(value: output logic<8>, calls: output u32) { + var selector: logic; + function one() -> logic<8> {calls += 1;return 8'haa;} + function two() -> logic<8> {calls += 1;return 8'haf;} + initial {selector=1'bx;value=if selector ? one() : two();$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!( + sim.get_four_state(sim.signal("value")), + (0xafu8.into(), 5u8.into()) + ); + } + macro_rules! backend { + ($build:ident) => { + check( + Simulator::builder(code, "Top") + .four_state(true) + .$build() + .unwrap(), + ) + }; + } + backend!(build_interpreter); + backend!(build_cranelift); + backend!(build_wasm); + backend!(build_tiered); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + backend!(build_native); +} diff --git a/crates/celox/tests/state_file.rs b/crates/celox/tests/state_file.rs index 5ce804503bb..406253d055c 100644 --- a/crates/celox/tests/state_file.rs +++ b/crates/celox/tests/state_file.rs @@ -519,3 +519,46 @@ fn a_failed_load_changes_nothing() { assert_eq!(target.time(), 10); assert_eq!(target.get(b), 3u8.into()); } + +#[test] +fn timed_state_files_preserve_unknown_edge_detection_baselines() { + let code = r#"module Top(clk: input clock, q: output logic<8>) { + always_ff(clk) { q += 1; } + }"#; + for (clock_type, payload, next) in [ + (celox::ClockType::PosEdge, 1u8, 1u8), + (celox::ClockType::NegEdge, 0u8, 0u8), + ] { + let builder = || { + celox::Simulation::builder(code, "Top") + .four_state(true) + .clock_type(clock_type) + .build() + .unwrap() + }; + let mut source = builder(); + let clk = source.signal("clk"); + let q = source.signal("q"); + source + .modify(|io| { + io.set(q, 0u8); + io.set(clk, 0u8); + }) + .unwrap(); + source.settle().unwrap(); + source + .modify(|io| io.set_four_state(clk, payload.into(), 1u8.into())) + .unwrap(); + source.settle().unwrap(); + let expected = source.get(q) + 1u8; + let file = through_bytes(&source.save_state().unwrap()); + assert_eq!(file.schedule.as_ref().unwrap().unknown_events, ["clk"]); + let mut restored = builder(); + restored.load_state(&file).unwrap(); + let clk = restored.signal("clk"); + let q = restored.signal("q"); + restored.modify(|io| io.set(clk, next)).unwrap(); + restored.settle().unwrap(); + assert_eq!(restored.get(q), expected, "{clock_type:?}"); + } +} From 047fbcef45a46c9b9264dc36a791ae9b57e11b7f Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 08:56:37 +0900 Subject: [PATCH 06/72] fix(veryl): adapt external projection to process storage --- crates/celox-frontend-veryl/src/artifact.rs | 2 +- crates/celox-runtime/src/simulation.rs | 5 +++-- crates/celox-runtime/src/state_file.rs | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 57e07dd62f1..8918f9e78e8 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -78,7 +78,7 @@ pub fn external_signatures( let mut port_ids = module.ports.values().copied().collect::>(); port_ids.sort(); let port_order = port_ids.iter().map(|id| ids[id]).collect(); - let (sim_module, _) = + let (sim_module, _, _) = project_module_with_ids(&empty, module, config, ids, &HashMap::default())?; let id = celox_design::ModuleId(external.modules.len()); external.roots.insert(sim_module.name.clone(), id); diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 9bb53650395..582f914fabe 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1350,7 +1350,7 @@ impl SimulationState { // FF evaluations and before the pending NBA publications. // Drain active evaluations before promoting another inactive // batch, including evaluations a combinational settle woke. - let inactive_counter_values=self.process_counter_values(executor.backend()); + let inactive_counter_values = self.process_counter_values(executor.backend()); let active_ran = self.run_processes(executor, current_time, Vec::new())?; let progressed = if active_ran { true @@ -1364,7 +1364,8 @@ impl SimulationState { self.run_processes(executor, current_time, ready)? }; if progressed { - let driven=self.process_counter_edges(executor.backend(),&inactive_counter_values); + let driven = + self.process_counter_edges(executor.backend(), &inactive_counter_values); executor.eval_comb()?; if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index d04d8922e64..4c31ba9a53f 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -19,6 +19,7 @@ //! event count u32, then per event: scheduled event //! periodic count u32, then per marker: scheduled event | count u64 //! high count u32, then per event: event str +//! unknown count u32, then per event: event str (version 2 and later) //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 //! ``` From 2df766db29239693d3df801067827ab089c4ece7 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 09:08:33 +0900 Subject: [PATCH 07/72] fix(native): advance container schema for kernel host state --- crates/celox/src/backend/native/backend.rs | 12 ++++++++++++ crates/celox/src/backend/native/image_file.rs | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index e9b3cfef4f7..33d4abad0ae 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -567,6 +567,18 @@ impl NativeProgramImage { return Err("process kernels and their control slots disagree".into()); } for process in &self.runtime_schema.processes { + if !self + .design + .state_objects + .get(&process.release) + .is_some_and(|metadata| { + metadata.width == celox_design::PROCESS_RELEASE_WIDTH + && !metadata.is_4state + && metadata.array_dims.is_empty() + }) + { + return Err("a process release control slot has an invalid state object".into()); + } if !self .design .state_objects diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index e1ee091a943..79a67ec75fa 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 13; +const CONTAINER_VERSION: u16 = 14; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; From fa5813a0fef02264b1e8a2b7716524206901f715 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 10:11:45 +0900 Subject: [PATCH 08/72] fix(veryl): settle break edges and preserve reachable call order --- .../src/lowering/process.rs | 10 ++++- .../src/lowering/process/expressions.rs | 26 ++++++++++- .../celox/tests/concurrent_initial_runtime.rs | 45 +++++++++++++++++++ 3 files changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index ecda34a1222..4ae212bc681 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1498,6 +1498,7 @@ impl<'a> BlockLowering<'a> { None, )); }; + self.settle_if_dirty()?; self.kernel .builder() .seal_block(SIRTerminator::Jump(exit, Vec::new())); @@ -2405,7 +2406,14 @@ impl<'a> BlockLowering<'a> { if let Flow::Ended = flow { return Ok(Flow::Ended); } - for (path, destinations) in &call.outputs { + for path in &paths { + let Some(destinations) = call + .outputs + .iter() + .find_map(|(output, destinations)| (output == path).then_some(destinations)) + else { + continue; + }; if let Some(&formal) = body.arg_map.get(path) { for destination in destinations { let value = self.load_var(formal)?; diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index fc644dfbf75..b17bdf47f82 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -140,7 +140,21 @@ pub(super) fn expression_calls<'s>( expr: &'s Expression, calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, ) { - for child in children(expr) { + let inputs = match expr { + Expression::Binary(lhs, Op::LogicAnd, _, _) if constant_truth(lhs) == Some(false) => { + vec![lhs.as_ref()] + } + Expression::Binary(lhs, Op::LogicOr, _, _) if constant_truth(lhs) == Some(true) => { + vec![lhs.as_ref()] + } + Expression::Ternary(cond, yes, no, _) => match constant_truth(cond) { + Some(true) => vec![cond.as_ref(), yes.as_ref()], + Some(false) => vec![cond.as_ref(), no.as_ref()], + None => children(expr), + }, + _ => children(expr), + }; + for child in inputs { expression_calls(child, calls); } if let Expression::Term(factor) = expr @@ -289,6 +303,11 @@ impl BlockLowering<'_> { if let Expression::Binary(lhs, op, rhs, _) = expr && matches!(op, Op::LogicAnd | Op::LogicOr) { + if let Some(truth) = constant_truth(lhs) + && ((*op == Op::LogicAnd && !truth) || (*op == Op::LogicOr && truth)) + { + return Ok(self.constant(u64::from(truth), 1)); + } return self.logical_expression(expr, lhs, rhs, *op == Op::LogicAnd); } if let Expression::Ternary(cond, yes, no, _) = expr { @@ -379,6 +398,11 @@ impl BlockLowering<'_> { yes: &Expression, no: &Expression, ) -> Result { + if let Some(truth) = constant_truth(cond) { + let value = self.expression(if truth { yes } else { no })?; + self.save_expression(expr, value)?; + return Ok(self.saved_expression(expr)); + } let value = self.expression(cond)?; self.save_expression(cond, value)?; let truth = self diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index ec2ae2ca035..02c7ba6116b 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -968,3 +968,48 @@ fn unknown_conditional_helpers_preserve_value_masks_and_both_effects() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] backend!(build_native); } + +#[test] +fn statically_skipped_expression_helpers_do_not_install_clocks() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var value: logic; + function wait_on_clk() -> logic { clk.next(); return 1'd1; } + initial { + value = 1'd0 && wait_on_clk(); + value = 1'd1 || wait_on_clk(); + value = if 1'd0 ? wait_on_clk() : 1'd1; + value = if 1'd1 ? 1'd1 : wait_on_clk(); + $assert(clk == 1'd1); $finish(); + } + }"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); +} + +#[test] +fn dirty_break_edges_settle_before_loop_successors() { + let code = r#"#[test(Top)] module Top { + var source: u32; var derived: u32; + assign derived = source + 1; + initial { for i in 0..4 { source = 41; break; } $assert(derived == 42); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn overlapping_function_outputs_copy_in_declaration_order() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function update(a: output u32, b: output u32) { a = 1; b = 2; } + initial { update(value, value); $assert(value == 2); $finish(); } + }"#; + check_passes_on_every_backend(code); +} From 6484abd0617ecc5b94223748316856c9dd07b6e8 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 10:51:31 +0900 Subject: [PATCH 09/72] fix(native): version combined kernel and clock-phase metadata --- crates/celox/src/backend/native/image_file.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 79a67ec75fa..6261830aac2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 14; +const CONTAINER_VERSION: u16 = 15; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; From 746805919454b7230b16d7d8b8d0e590ab1cf3f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:21:36 +0900 Subject: [PATCH 10/72] fix(runtime): preserve grouped tick budgets after clock validation --- crates/celox-runtime/src/simulation.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 051b9e00f71..3300017ca78 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -548,11 +548,13 @@ impl SimulationState { if current_time > limit { return Ok(None); } - for (id, clock) in &self.tick_clocks { - if clock.next_edge == current_time && self.clock_has_waiters(*id) { - current_time - .checked_add(clock.period) - .ok_or_else(|| clock_overflow(*id))?; + if !self.tick_budget_spent() { + for (id, clock) in &self.tick_clocks { + if clock.next_edge == current_time && self.clock_has_waiters(*id) { + current_time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(*id))?; + } } } let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { @@ -719,6 +721,10 @@ impl SimulationState { if rising.is_empty() { return Ok(()); } + for id in &rising { + time.checked_add(self.tick_clocks[id].period) + .ok_or_else(|| clock_overflow(*id))?; + } self.ticks += 1; if let Some(budget) = &mut self.tick_budget { *budget -= 1; @@ -728,7 +734,6 @@ impl SimulationState { let next_edge = time .checked_add(clock.period) .ok_or_else(|| clock_overflow(id))?; - self.ticks += 1; clock.next_edge = next_edge; clock.falling_edge = Some(next_edge - clock.period / 2); let resume_at = clock.next_edge; From e258baaa36e94259b3d87559082f6a969c1ff902 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:46:41 +0900 Subject: [PATCH 11/72] fix(veryl): retain kernel edges and honor termination during settles --- .../src/lowering/process.rs | 224 ++++++++++++++++-- crates/celox-runtime/src/simulation.rs | 17 ++ crates/celox/src/simulation.rs | 14 ++ .../celox/tests/concurrent_initial_runtime.rs | 92 +++++++ 4 files changed, 323 insertions(+), 24 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 4ae212bc681..11af0929d13 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -64,6 +64,7 @@ pub struct BlockStorage { pub delay: SourceVarId, pub clock: SourceVarId, pub release: SourceVarId, + pub event_counters: Vec<(VarId, SourceVarId, SourceVarId)>, pub scratch: Vec<(ScratchNeed, SourceVarId)>, /// The block's own copy of each function-local variable, so a call /// that waits keeps its arguments and locals while another block calls @@ -97,6 +98,22 @@ pub(crate) fn declare_storage( .iter() .map(|&local| (local, variables[&ids[&local]].clone())) .collect::>(); + let mut event_variables = ir + .variables + .keys() + .filter(|id| { + ir.variables[id].affiliation != Affiliation::Function + && matches!( + variables[&ids[id]].metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + | celox_design::DomainKind::ResetAsyncHigh + | celox_design::DomainKind::ResetAsyncLow + ) + }) + .copied() + .collect::>(); + event_variables.sort_unstable(); let mut next = variables.len() as u32; let mut declare = |path: Vec, template: Option<&SymbolicVariable>, width: usize| { let id = SourceVarId(next); @@ -182,6 +199,24 @@ pub(crate) fn declare_storage( delay: declare(name("delay"), None, PROCESS_DELAY_WIDTH), clock: declare(name("clock"), None, PROCESS_CLOCK_WIDTH), release: declare(name("release"), None, PROCESS_RELEASE_WIDTH), + event_counters: event_variables + .iter() + .map(|&var| { + ( + var, + declare( + name(&format!("event_rises@{}", ids[&var].0)), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + ), + declare( + name(&format!("event_falls@{}", ids[&var].0)), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + ), + ) + }) + .collect(), scratch, private, expression_values, @@ -683,6 +718,7 @@ struct BlockLowering<'a> { /// gave the host a chance to drain them (see /// [`BlockLowering::yield_for_runtime_event`]). event_yield: Option, + event_counters: HashMap, } /// Bits of the runtime-event yield counter. @@ -779,6 +815,11 @@ fn lower_block( sources: Vec::new(), dirty: false, event_yield: None, + event_counters: storage + .event_counters + .iter() + .map(|(var, rises, falls)| (*var, (*rises, *falls))) + .collect(), }; if contains_runtime_event(ir, statements, &mut HashSet::default()) { lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); @@ -891,6 +932,28 @@ fn lower_block( .runtime_schema .testbench_kernels .get_or_insert(scheduled.runtime_schema.processes.len()); + for (var, rises, falls) in &storage.event_counters { + let signal = to_state(&SourceAddr { + instance_id: instance, + var_id: ids[var], + })?; + let signal = scheduled.design.events.canonical(signal); + if scheduled.design.events.ordered_events.contains(&signal) { + let counters = celox_design::ProcessEventCounters { + signal, + rises: to_state(&stable(*rises).into_absolute())?, + falls: to_state(&stable(*falls).into_absolute())?, + }; + scheduled + .runtime_schema + .testbench_read_roots + .extend([counters.rises, counters.falls]); + scheduled + .runtime_schema + .process_event_counters + .push(counters); + } + } scheduled.sir.processes.push(unit); scheduled.runtime_schema.processes.push(slots); Ok(()) @@ -1139,7 +1202,7 @@ impl<'a> BlockLowering<'a> { self.scan_clocks(statements, &mut active); } - fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) { + fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) -> bool { for statement in statements { let mut calls = Vec::new(); for expr in expressions::statement_inputs(statement) { @@ -1148,9 +1211,14 @@ impl<'a> BlockLowering<'a> { for call in calls { if active.insert(call.id) { if let Some(body) = function_body(&self.ir.functions, call) { - self.scan_clocks(&body.statements, active); + let continues = self.scan_clocks(&body.statements, active); + active.remove(&call.id); + if !continues { + return false; + } + } else { + active.remove(&call.id); } - active.remove(&call.id); } } match statement { @@ -1171,38 +1239,57 @@ impl<'a> BlockLowering<'a> { } _ => {} }, - Statement::If(stmt) => match constant_truth(&stmt.cond) { - Some(true) => self.scan_clocks(&stmt.true_side, active), - Some(false) => self.scan_clocks(&stmt.false_side, active), - None => { - self.scan_clocks(&stmt.true_side, active); - self.scan_clocks(&stmt.false_side, active); + Statement::If(stmt) => { + let continues = match constant_truth(&stmt.cond) { + Some(true) => self.scan_clocks(&stmt.true_side, active), + Some(false) => self.scan_clocks(&stmt.false_side, active), + None => { + let a = self.scan_clocks(&stmt.true_side, active); + let b = self.scan_clocks(&stmt.false_side, active); + a || b + } + }; + if !continues { + return false; } - }, + } Statement::IfReset(stmt) => { self.scan_clocks(&stmt.true_side, active); self.scan_clocks(&stmt.false_side, active); } Statement::Case(stmt) => { + let mut continues = self.scan_clocks(&stmt.default, active); for arm in &stmt.arms { - self.scan_clocks(&arm.body, active); + continues |= self.scan_clocks(&arm.body, active); + } + if !continues { + return false; } - self.scan_clocks(&stmt.default, active); } Statement::For(stmt) if !constant_empty_range(&stmt.range) => { - self.scan_clocks(&stmt.body, active) + self.scan_clocks(&stmt.body, active); } Statement::FunctionCall(call) => { if active.insert(call.id) && let Some(body) = function_body(&self.ir.functions, call) { - self.scan_clocks(&body.statements, active); + let continues = self.scan_clocks(&body.statements, active); active.remove(&call.id); + if !continues { + return false; + } } } + Statement::SystemFunctionCall(call) + if matches!(call.kind, SystemFunctionKind::Finish) => + { + return false; + } + Statement::Break => return false, _ => {} } } + true } fn declare_clock(&mut self, inst: StrId, period: u64) { @@ -1360,16 +1447,105 @@ impl<'a> BlockLowering<'a> { if !self.private.contains_key(&destination.id) { self.dirty = true; } - let (parser, kernel, targets, sources, convert) = parts!(self); - parser.push_value(value); - parser.op_store( - destination, - targets, - &Domain::Process, - &convert, - sources, - kernel.builder(), - ) + let counters = self.event_counters.get(&destination.id).copied(); + let before = if counters.is_some() { + self.parser.clear_register_cache(); + Some(self.load_var(destination.id)?) + } else { + None + }; + { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.push_value(value); + parser.op_store( + destination, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + } + if let (Some((rises, falls)), Some(before)) = (counters, before) { + self.parser.clear_register_cache(); + let after = self.load_var(destination.id)?; + self.record_event_edges(before, after, rises, falls); + } + Ok(()) + } + + fn record_event_edges( + &mut self, + before: RegisterId, + after: RegisterId, + rises: SourceVarId, + falls: SourceVarId, + ) { + let builder = self.kernel.builder(); + let logic = matches!(builder.register(&before), RegisterType::Logic { .. }); + let mut known = Vec::new(); + for value in [0u8, 1] { + let reg = if logic { + builder.alloc_logic(1) + } else { + builder.alloc_bit(1, false) + }; + builder.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + known.push(reg); + } + let mut eq = Vec::new(); + for value in [before, after] { + for constant in &known { + let reg = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + reg, + value, + BinaryOp::EqCase, + *constant, + )); + eq.push(reg); + } + } + for (counter, a, b, c, d) in [ + (rises, eq[0], eq[2], eq[1], eq[3]), + (falls, eq[1], eq[3], eq[0], eq[2]), + ] { + let not_b = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(not_b, UnaryOp::BitNot, b)); + let first = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(first, a, BinaryOp::And, not_b)); + let not_c = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(not_c, UnaryOp::BitNot, c)); + let second = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(second, not_c, BinaryOp::And, d)); + let edge = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(edge, first, BinaryOp::Or, second)); + let width = celox_design::PROCESS_EVENT_COUNTER_WIDTH; + let delta = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(delta, UnaryOp::Ident, edge)); + let address = RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: counter, + }; + let old = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Load( + old, + address, + SIROffset::Static(0), + width, + )); + let next = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Binary(next, old, BinaryOp::Add, delta)); + builder.emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + width, + next, + Vec::new(), + Vec::new(), + )); + } } /// Settle the combinational logic before a read of design state that diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 3300017ca78..6195a4af2d8 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -41,6 +41,11 @@ pub trait SimulationExecutor { self.backend_mut().run_process(index) } + /// Whether an internal settle or process execution emitted a finish event. + fn finish_requested(&mut self, _time: u64) -> bool { + false + } + /// Run up to `count` rising edges of `event` as fused ticks: each one /// evaluates the combinational logic and then the sequential domain, /// without toggling the clock signal. Returns how many completed before @@ -1003,6 +1008,10 @@ impl SimulationState { where E: SimulationExecutor, { + if self.finished || executor.finish_requested(current_time) { + self.finished = true; + return Ok(false); + } let mut progressed = false; let mut pass = ready; loop { @@ -1027,6 +1036,10 @@ impl SimulationState { }) .collect::>(); executor.run_process(process, current_time)?; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } for ((id, rises, falls), (old_rises, old_falls)) in self.process_event_counters.iter().zip(before) { @@ -1046,6 +1059,10 @@ impl SimulationState { match ProcessStatus::from_code(status) { Some(ProcessStatus::Settle) => { executor.eval_comb()?; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } any_ran = true; continue; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2ca0b37f2d3..5159121642d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -110,6 +110,20 @@ impl SimulationExecutor for Simulator { result } + fn finish_requested(&mut self, time: u64) -> bool { + if self.testbench_random.is_some() { + let ctx = crate::simulator::RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let events = self.collect_sited_runtime_events(ctx); + self.testbench_events.extend(events); + } + self.testbench_events + .iter() + .any(|(_, event)| matches!(event, crate::RuntimeEvent::Finish)) + } + fn tick_many(&mut self, event: B::Event, count: u64) -> (u64, Result<(), RuntimeErrorCode>) { if count == 0 { return (0, Ok(())); diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 02c7ba6116b..cd5ca80c10d 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1013,3 +1013,95 @@ fn overlapping_function_outputs_copy_in_declaration_order() { }"#; check_passes_on_every_backend(code); } + +#[test] +fn finished_paths_do_not_initialize_unreachable_clocks() { + for tail in [ + "$finish(); clk.next();", + "if 1'd1 { $finish(); } clk.next();", + ] { + let code = + format!("#[test(Top)] module Top {{ inst clk: $tb::clock_gen; initial {{ {tail} }} }}"); + let mut sim = Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); + } +} + +#[test] +fn design_finish_during_settle_stops_kernel_continuations() { + let code = r#"#[test(Top)] module Top { + var go: logic; + var after: logic; + always_comb { if go { $finish(); } } + initial { go=1; after=1; $assert(1'd0, "continued after finish"); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("after")), 0u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn overlapping_clock_outputs_retain_the_intermediate_rising_edge() { + let code = r#"#[test(Top)] module Top { + var clk: clock; + var q: logic; + function update(a: output clock, b: output clock) { a=1; b=0; } + always_ff (clk) { q=1; } + initial { clk=0; update(clk, clk); $assert(clk == 0); $finish(); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + } + for four_state in [false, true] { + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_native() + .unwrap(), + ); + } +} From da31c75313ab0eac7d49cd985d1bfd3ddd7946fb Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 11:54:00 +0900 Subject: [PATCH 12/72] style(runtime): format merged clock scheduling calls --- crates/celox-runtime/src/simulation.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 1d27cf4d76b..40598db2431 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -593,7 +593,14 @@ impl SimulationState { next_val: 1, }); } - self.step_round(executor, current_time, events_to_process, generated_events, ready, true)?; + self.step_round( + executor, + current_time, + events_to_process, + generated_events, + ready, + true, + )?; self.credit_rising_edges(current_time, rising)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); @@ -656,7 +663,8 @@ impl SimulationState { } break; } - if !self.step_round(executor, current_time, events, Vec::new(), ready, false)? && !fired { + if !self.step_round(executor, current_time, events, Vec::new(), ready, false)? && !fired + { break; } } @@ -1424,7 +1432,8 @@ impl SimulationState { "FF trigger discovered without a corresponding execution unit" ); } - ff_body_edges.union_with(&self.process_counter_edges(executor.backend(), &before)); + ff_body_edges + .union_with(&self.process_counter_edges(executor.backend(), &before)); } // Working-region writes become visible only when this NBA From eb3c399087f6fb37d2c2d4c3210c8f9d40f8e93a Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 13:49:41 +0900 Subject: [PATCH 13/72] fix(veryl): retain reachable clocks and honor init finish --- .../src/lowering/process.rs | 8 +++- .../src/lowering/process/expressions.rs | 37 +++++++++++++++++++ crates/celox/src/testbench/kernels.rs | 2 +- crates/celox/tests/component_method.rs | 2 + .../celox/tests/concurrent_initial_runtime.rs | 16 ++++++++ 5 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 11af0929d13..dbea35bbc9f 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1205,15 +1205,21 @@ impl<'a> BlockLowering<'a> { fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) -> bool { for statement in statements { let mut calls = Vec::new(); + let mut unconditional = Vec::new(); for expr in expressions::statement_inputs(statement) { expressions::expression_calls(expr, &mut calls); + expressions::unconditional_expression_calls(expr, &mut unconditional); } for call in calls { if active.insert(call.id) { if let Some(body) = function_body(&self.ir.functions, call) { let continues = self.scan_clocks(&body.statements, active); active.remove(&call.id); - if !continues { + if !continues + && unconditional + .iter() + .any(|required| std::ptr::eq(*required, call)) + { return false; } } else { diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index b17bdf47f82..fdfa7712334 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -136,6 +136,43 @@ pub(super) fn statement_bodies(statement: &Statement) -> Vec<&[Statement]> { _ => Vec::new(), } } +/// Calls that every evaluation of this expression must reach. +pub(super) fn unconditional_expression_calls<'s>( + expr: &'s Expression, + calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, +) { + let inputs = match expr { + Expression::Binary(lhs, Op::LogicAnd, rhs, _) => { + if constant_truth(lhs) == Some(true) { + vec![lhs.as_ref(), rhs.as_ref()] + } else { + vec![lhs.as_ref()] + } + } + Expression::Binary(lhs, Op::LogicOr, rhs, _) => { + if constant_truth(lhs) == Some(false) { + vec![lhs.as_ref(), rhs.as_ref()] + } else { + vec![lhs.as_ref()] + } + } + Expression::Ternary(cond, yes, no, _) => match constant_truth(cond) { + Some(true) => vec![cond.as_ref(), yes.as_ref()], + Some(false) => vec![cond.as_ref(), no.as_ref()], + None => vec![cond.as_ref()], + }, + _ => children(expr), + }; + for child in inputs { + unconditional_expression_calls(child, calls); + } + if let Expression::Term(factor) = expr + && let Factor::FunctionCall(call) = factor.as_ref() + { + calls.push(call); + } +} + pub(super) fn expression_calls<'s>( expr: &'s Expression, calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 4f511460309..d2560a531c7 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -149,7 +149,7 @@ fn run( // The scheduler samples the clocks it detects edges on from settled // state. - if sim.dirty { + if sim.dirty && !sim.components.finish_requested() { if let Err(error) = sim.eval_comb_checked() { // The components were installed above; take them down again. let _ = sim.components.finish(0); diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 2ffca4b207f..1280c857832 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -2061,7 +2061,9 @@ fn component_finish_request_during_init_skips_testbench_execution() { module t { inst clk: $tb::clock_gen; inst component: $comp::celox_init_finisher (clk); + always_comb { $assert(0, "on_init finish must skip initial settling"); } initial { + clk.next(); $assert(0, "on_init finish must skip this statement"); } } diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index cd5ca80c10d..c8a65db1b80 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1105,3 +1105,19 @@ fn overlapping_clock_outputs_retain_the_intermediate_rising_edge() { ); } } + +#[test] +fn conditional_finish_calls_preserve_reachable_clocks() { + for expression in ["if flag ? stop() : 0", "flag && stop()", "!flag || stop()"] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk: $tb::clock_gen; + var flag: logic; + var value: logic; + function stop() -> logic {{ $finish(); return 1; }} + initial {{ flag=0; value={expression}; clk.next(); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + } +} From c2696a2fa5426c8e3cbfce980a9f3eeb2795ff1c Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 14:17:09 +0900 Subject: [PATCH 14/72] fix(testbench): batch reset assertion with its first clock edge --- crates/celox-runtime/src/simulation.rs | 51 +++++++++++++++++-- .../celox/tests/concurrent_initial_runtime.rs | 30 +++++++++++ 2 files changed, 76 insertions(+), 5 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 429104cec8c..6af251f6aa1 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -282,6 +282,7 @@ pub struct SimulationState { scheduled_clock_drives: BitSet, scheduled_clock_time: u64, round_evaluated: bool, + round_new_rising: BitSet, periodic_events: FxHashMap, last_clock_values: BitSet, /// Events whose signal was x or z when edge detection last sampled it: @@ -452,6 +453,7 @@ impl SimulationState { scheduled_clock_drives: BitSet::new(), scheduled_clock_time: 0, round_evaluated: false, + round_new_rising: BitSet::new(), } } @@ -696,8 +698,10 @@ impl SimulationState { } break; } - if !self.step_round(executor, current_time, events, Vec::new(), ready, false)? && !fired - { + let result = self.step_round(executor, current_time, events, Vec::new(), ready, false); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(current_time, Vec::new(), &[], result)?; + if !progressed && !fired { break; } } @@ -761,6 +765,10 @@ impl SimulationState { falling: &[usize], result: Result, ) -> Result<(), SimulatorErrorCode> { + let rising: BTreeSet<_> = rising + .into_iter() + .chain(self.round_new_rising.iter()) + .collect(); let committed = rising .into_iter() .filter(|id| { @@ -996,7 +1004,10 @@ impl SimulationState { return Ok(false); } let time = self.scheduler.time; - if !self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false)? { + let result = self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(time, Vec::new(), &[], result)?; + if !progressed { return Ok(false); } self.run_remaining_rounds(executor, time, limit)?; @@ -1294,7 +1305,8 @@ impl SimulationState { } let mut events = Vec::new(); let ready = self.take_ready_processes(executor, time, &mut events); - self.step_round(executor, time, events, Vec::new(), ready, true)?; + let result = self.step_round(executor, time, events, Vec::new(), ready, true); + self.finish_clock_round(time, Vec::new(), &[], result)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. self.run_remaining_rounds(executor, time, time)?; @@ -1311,7 +1323,7 @@ impl SimulationState { executor: &mut E, current_time: u64, mut events_to_process: Vec>, - generated_events: Vec>, + mut generated_events: Vec>, ready_processes: Vec, settle_idle: bool, ) -> Result @@ -1322,6 +1334,7 @@ impl SimulationState { self.round_published_domains.make_empty(); self.round_triggered_domains.make_empty(); self.round_evaluated = false; + self.round_new_rising.make_empty(); // Keep periodic provenance private so the public SimEvent shape stays // stable. Consume matching sidecar counts before fallible work so an @@ -1391,6 +1404,34 @@ impl SimulationState { } } + // A newly asserted reset and the first edge of its clock wait + // belong to one batch, including consecutive reset helpers. + let reset_edge_due = self.clock_waits.values().any(|wait| { + wait.release.is_some() && self.tick_clocks[&wait.clock].next_edge == current_time + }); + if !self.tick_budget_spent() && reset_edge_due { + for (id, clock) in &self.tick_clocks { + if clock.next_edge == current_time + && self.clock_has_waiters(*id) + && executor.backend().get_as::(clock.signal) == 0 + && !generated_events + .iter() + .any(|event| event.event_ref.id() == *id) + { + current_time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(*id))?; + generated_events.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + }); + self.round_new_rising.insert(*id); + } + } + } + // A completed clock wait resumes before the following generated // rising edge. Apply that edge after the ready processes, then join // it to scheduled triggers so coincident FF domains share one batch. diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index c8a65db1b80..7798221814c 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1121,3 +1121,33 @@ fn conditional_finish_calls_preserve_reachable_clocks() { check_passes_on_every_backend(&code); } } + +#[test] +fn consecutive_reset_helpers_share_the_first_clock_edge() { + for body in [ + "for i in 1..=3 { rst.assert(i); }", + "reset_for(2); reset_for(4);", + ] { + let code = format!( + r#"module Counter(clk: input clock, rst: input reset, q: output u32) {{ + always_ff {{ if_reset {{ q+=1; }} else {{ q+=1; }} }} + }} + #[test(Top)] module Top {{ + inst clk: $tb::clock_gen; inst rst: $tb::reset_gen(clk); var q:u32; + inst dut: Counter(clk,rst,q); + function reset_for(n: input u32) {{ rst.assert(n); }} + initial {{ {body} $assert(q==6,"ticks=%d",q); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + let mut fallback = Simulator::builder(&code, "Top") + .testbench_kernels(false) + .build_interpreter() + .unwrap(); + let tb = compile_initial_testbench(&fallback).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut fallback, &tb), + TestResult::Pass + ); + } +} From 956169486556cda8ce21a6cc86c655b58beb1d70 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 15:23:23 +0900 Subject: [PATCH 15/72] fix(testbench): settle host effects and preserve empty component strings --- .../src/lowering/process.rs | 12 ++++- crates/celox-runtime/src/simulation.rs | 10 +++- crates/celox/src/component.rs | 3 ++ crates/celox/src/testbench/kernels.rs | 8 +++- crates/celox/tests/component_method.rs | 47 +++++++++++++++++++ .../celox/tests/concurrent_initial_runtime.rs | 46 ++++++++++++++++++ 6 files changed, 121 insertions(+), 5 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index dbea35bbc9f..4ec9d3cf1a9 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1611,6 +1611,8 @@ impl<'a> BlockLowering<'a> { } fn host_request(&mut self, request: HostRequest) -> Result<(), ParserError> { + // Random requests do not settle the design themselves. + self.settle_if_dirty()?; self.host_requests.push(request); let index = self.kernel.add_host_request(); debug_assert_eq!(index as usize + 1, self.host_requests.len()); @@ -1925,7 +1927,10 @@ impl<'a> BlockLowering<'a> { self.store_scratch(start_slot, width, start_reg); let end_reg = self.for_bound(shape.end, width, cmp_signed)?; self.store_scratch(end_slot, width, end_reg); + // Bounds can write design state even when the range is empty. + self.settle_if_dirty()?; let start_reg = self.load_scratch(start_slot, width, cmp_signed); + let end_reg = self.load_scratch(end_slot, width, cmp_signed); let var = self.destination(stmt.var_id, stmt.token); let stall_message = format!( "non-progressing stepped for loop (loop variable `{}`)", @@ -2776,9 +2781,14 @@ impl<'a> BlockLowering<'a> { for arg in args { let is_string = arg.0.comptime().r#type.is_string(); let signed = expression_signed(&arg.0); - let (value, slot) = + let (mut value, slot) = self.host_scratch("component_arg", argument_width(arg), signed, is_string)?; let width = value.width; + if is_string + && FfParser::static_string_expr(&arg.0).is_some_and(|text| text.is_empty()) + { + value.width = 0; // logical byte length; physical scratch still has one bit + } let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { let builder = self.kernel.builder(); let reg = builder.alloc_bit(width, false); diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 6af251f6aa1..8cf28613733 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -691,7 +691,11 @@ impl SimulationState { } let mut events = Vec::new(); let ready = self.take_ready_processes(executor, current_time, &mut events); - if ready.is_empty() && self.waiting.is_empty() && events.is_empty() { + if ready.is_empty() + && self.waiting.is_empty() + && events.is_empty() + && !self.settle_before_processes + { if fired { // The edges may have released waits that resume now. continue; @@ -1368,7 +1372,9 @@ impl SimulationState { for event in &events_to_process { executor.backend_mut().set(event.signal, event.next_val); } - if std::mem::take(&mut self.settle_before_processes) { + if std::mem::take(&mut self.settle_before_processes) + && (!ready_processes.is_empty() || !self.waiting.is_empty()) + { executor.eval_comb()?; } diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 16d33713108..8419d96dc8a 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -908,6 +908,9 @@ pub(crate) fn host_value_from_bits( is_string: bool, ) -> HostValue { if is_string { + if width == 0 { + return HostValue::Str(String::new()); + } let byte_len = width.div_ceil(8); let mut bytes = value.to_bytes_be(); if bytes.len() < byte_len { diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index d2560a531c7..966e762237a 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -344,8 +344,12 @@ pub(crate) fn serve_host_request( declared_width, strict, } => { - // The component reads settled design state. - sim.eval_comb_checked().map_err(|error| error.to_string())?; + // Effectful arguments have a lowering barrier. A clean call + // must not replay combinational displays/assertions. + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } let host_args = args .iter() .map(|arg| { diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 1280c857832..3d1b99b1651 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -84,6 +84,9 @@ unsafe extern "C" fn call_method( if unsafe { args[0].str_.as_str() } == "hello" { state.value = 7; 0 + } else if unsafe { args[0].str_.as_str() }.is_empty() { + state.value = 9; + 0 } else { 1 } @@ -3099,3 +3102,47 @@ fn failed_component_vcd_registration_calls_finish_on_each_run() { assert_eq!(VCD_FINISH_CALLS.load(Ordering::Relaxed), expected); } } + +#[test] +fn empty_component_string_arguments_preserve_bytecode_behavior() { + register_component(); + for kernels in [false, true] { + let (_dir, metadata) = component_metadata(); + let code = r#"#[test(t)] module t { var c:$comp::celox_counter; + initial { c.set_str(""); var value:u8; value=c.get(); $assert(value==9); $finish(); } + }"#; + assert_eq!( + Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(kernels) + .run_test() + .unwrap(), + TestResult::Pass + ); + } +} + +#[test] +fn clean_component_calls_do_not_replay_comb_assertions() { + register_component(); + let count = |calls: &str| { + let (_dir, metadata) = component_metadata(); + let code = format!( + r#"#[test(t)] module t {{ var c:$comp::celox_counter; + always_comb {{ $assert(1,"comb"); }} + initial {{ {calls} $finish(); }} + }}"# + ); + let result = Simulator::builder(&code, "t") + .with_metadata(metadata) + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some("comb")) + .count() + }; + assert_eq!(count("c.get(); c.get();"), count("")); +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 7798221814c..bf3c9eaafec 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1151,3 +1151,49 @@ fn consecutive_reset_helpers_share_the_first_clock_edge() { ); } } + +#[test] +fn empty_dynamic_loop_bounds_settle_their_effects() { + let code = r#"#[test(Top)] module Top { + var source:u32; let derived:u32=source+1; var limit:u32; + function bound(value:output u32)->u32 { value=7; return 1; } + initial { limit=0; for i in bound(source)..limit { source=9; } $assert(derived==8); $finish(); } + }"#; + check_passes_on_every_backend(code); +} +#[test] +fn random_arguments_settle_their_effects() { + for op in [ + "random.seed(bound(source));", + "value=random.get_range(bound(source),bound(source));", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + var random:$tb::random::; var source:u32; let derived:u32=source+1; var value:u32; + function bound(value:output u32)->u32 {{ value=7; return 3; }} + initial {{ {op} $assert(derived==8); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + } +} +#[test] +fn tick_limit_settles_reset_releases_without_domains() { + let code = r#"#[test(Top)] module Top { + inst clk:$tb::clock_gen; inst rst:$tb::reset_gen(clk); let released:logic=rst; + initial { rst.assert(1); $finish(); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, 1); + assert_eq!(result.result, TestResult::Pass); + assert_eq!(result.ticks, 1); + assert_eq!(sim.get(sim.signal("rst")), sim.get(sim.signal("released"))); + assert_eq!(sim.get(sim.signal("released")), 1u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} From be46828fe4236e2407d40f1ae84c2e859cd263f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 16:20:21 +0900 Subject: [PATCH 16/72] fix(testbench): preserve kernel yields and completion contracts --- crates/celox-design/src/lib.rs | 4 ++ crates/celox-frontend-core/src/process.rs | 5 ++ .../src/lowering/process.rs | 31 +++++---- crates/celox-runtime/src/simulation.rs | 11 ++++ crates/celox/src/simulator/builder.rs | 3 + crates/celox/src/testbench/kernels.rs | 26 ++++++-- crates/celox/tests/component_method.rs | 38 ++++++++++- .../celox/tests/concurrent_initial_runtime.rs | 66 +++++++++++++++++++ 8 files changed, 160 insertions(+), 24 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 58db088381a..9998e41524b 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -261,6 +261,8 @@ pub enum ProcessStatus { /// the runtime settles the combinational logic and resumes the process /// at once, before any other process runs. Settle, + /// Return control to drain events without evaluating combinational logic. + Yield, } impl ProcessStatus { @@ -277,6 +279,7 @@ impl ProcessStatus { Self::WaitClock => 6, Self::Host => 7, Self::Settle => 8, + Self::Yield => 10, } } @@ -291,6 +294,7 @@ impl ProcessStatus { 6 => Some(Self::WaitClock), 7 => Some(Self::Host), 8 => Some(Self::Settle), + 10 => Some(Self::Yield), _ => None, } } diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index a8bc2b09ad1..5dfe98642c9 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -228,6 +228,11 @@ impl ProcessKernelBuilder { /// Have the runtime settle the combinational logic, then continue at /// once. A process stores to design state directly, so a read of a /// combinational result after such a store needs this first. + /// Drain host events and resume without reevaluating clean logic. + pub fn yield_events(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Yield) + } + pub fn settle(&mut self) -> Result<(), ProcessKernelError> { self.suspend(ProcessStatus::Settle) } diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 4ec9d3cf1a9..13da6857845 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1646,7 +1646,11 @@ impl<'a> BlockLowering<'a> { match statement { Statement::Assign(assign) => { self.lower_assign(assign)?; - self.dirty = true; + self.dirty |= assign.hier_dst.is_some() + || assign + .dst + .iter() + .any(|destination| !self.private.contains_key(&destination.id)); Ok(Flow::Continue) } Statement::If(stmt) => { @@ -1876,16 +1880,9 @@ impl<'a> BlockLowering<'a> { } else { assign }; - let prepared = if expressions::has_call(&assign.expr) { - Some(self.expression(&assign.expr)?) - } else { - None - }; - if let Some(value) = prepared { - self.parser.push_process_expression_values( - [(assign.expr.token_range(), value)].into_iter().collect(), - ); - } + let statement = Statement::Assign(assign.clone()); + let bindings = self.expression_bindings(&expressions::statement_inputs(&statement))?; + self.parser.push_process_expression_values(bindings); let (parser, kernel, targets, sources, convert) = parts!(self); let result = parser.parse_assign_statement( assign, @@ -1895,9 +1892,7 @@ impl<'a> BlockLowering<'a> { sources, kernel.builder(), ); - if prepared.is_some() { - self.parser.pop_process_expression_values(); - } + self.parser.pop_process_expression_values(); result } @@ -2521,8 +2516,12 @@ impl<'a> BlockLowering<'a> { self.kernel.builder().switch_to_block(yield_block); self.store_scratch(slot, EVENT_YIELD_WIDTH, zero); let dirty = self.dirty; - self.kernel - .settle() + let yielded = if dirty { + self.kernel.settle() + } else { + self.kernel.yield_events() + }; + yielded .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; self.kernel .builder() diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index d0d09a295f5..2fa0734eeaa 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1157,6 +1157,11 @@ impl SimulationState { let refs = &self.processes[process]; let status: u8 = executor.backend().get_as(refs.status); match ProcessStatus::from_code(status) { + Some(ProcessStatus::Yield) => { + self.waiting.remove(&process); + any_ran = true; + continue; + } Some(ProcessStatus::Settle) => { executor.eval_comb()?; if executor.finish_requested(current_time) { @@ -1284,6 +1289,12 @@ impl SimulationState { } } + /// Whether all processes at or beyond the testbench boundary are done. + pub fn processes_done_from(&self, first: usize) -> bool { + first <= self.processes.len() + && self.done.range(first..).count() == self.processes.len() - first + } + /// Whether a process requested the end of the simulation. pub fn is_finished(&self) -> bool { self.finished diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index d457187f402..9b9e38ec89d 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2834,6 +2834,9 @@ mod host { let sim_res = program_res.and_then(|(program, warnings)| { let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); + if !laid_out.runtime().runtime_schema.processes.is_empty() { + self.options.emit_triggers = true; + } if self.vcd_path.is_some() { laid_out.enable_vcd_tracking(); } diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 966e762237a..810b9fc4b36 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -188,7 +188,16 @@ fn run( finished = true; } match stepped { - Ok(Some(_)) => {} + Ok(Some(_)) => { + if sim + .program + .runtime_schema + .testbench_kernels + .is_some_and(|first| state.processes_done_from(first)) + { + finished = true; + } + } Ok(None) => finished = true, Err(code) => { if error.is_none() { @@ -367,13 +376,11 @@ pub(crate) fn serve_host_request( if sim.components.finish_requested() { return Ok(false); } - // The outputs the method wrote feed the design: the process - // resumes at once and reads the logic derived from them. - if sim.dirty { - sim.eval_comb_checked().map_err(|error| error.to_string())?; - sim.dirty = false; - } let Some(result) = result else { + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } return Ok(true); }; let Some((value, width)) = crate::component::host_bits(&returned) else { @@ -395,6 +402,11 @@ pub(crate) fn serve_host_request( } let value = resize_component_return(value, width as usize, result.signed, result.width); write(sim, &result, value); + // Invalid return contracts must not expose derived output effects. + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } } } Ok(true) diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 3d1b99b1651..fd347b6cd9b 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -307,7 +307,7 @@ unsafe extern "C" fn clock_call_method( name: sys::VrlStr, args: *const sys::VrlValue, nargs: usize, - _ret: *mut sys::VrlValue, + ret: *mut sys::VrlValue, ) -> i32 { let state = unsafe { &mut *state.cast::() }; let api = unsafe { &*state.api }; @@ -361,6 +361,12 @@ unsafe extern "C" fn clock_call_method( unsafe { (api.write_output)(ctx, state.output, &value, std::ptr::null()) }; 0 } + "drive_lying" if args.is_empty() => { + let value = 1; + unsafe { (api.write_output)(ctx, state.output, &value, std::ptr::null()) }; + unsafe { write_return(ret, 1, 16) }; + 0 + } "check_clocks" if args.len() == 1 && argument(0) == Some(state.clocks) => 0, "stop" if args.is_empty() => { unsafe { (api.finish)(ctx) }; @@ -3146,3 +3152,33 @@ fn clean_component_calls_do_not_replay_comb_assertions() { }; assert_eq!(count("c.get(); c.get();"), count("")); } + +#[test] +fn invalid_component_returns_precede_output_assertions() { + register_component(); + for kernels in [false, true] { + let (dir, _) = component_metadata(); + let path = dir.path().join("component/veryl.manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + manifest["types"]["celox_clocked"]["methods"] = + serde_json::json!([{"name":"drive_lying","args":[],"ret":"value","ret_width":8}]); + std::fs::write(path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + let metadata = veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + let code = r#"#[test(t)] module t { + inst clk:$tb::clock_gen;var d:u8;var q:u8;var value:u8; + inst c:$comp::celox_clocked #(STEP:0)(clk:clk,d,q); + always_comb { $assert(q!=1,"output assertion"); } + initial { value=c.drive_lying();$finish(); } + }"#; + let result = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(kernels) + .run_test() + .unwrap(); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("declares a 8-bit return value but returned 16 bits")), + "{result:?}" + ); + } +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index bf3c9eaafec..fb04a30d6c3 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1197,3 +1197,69 @@ fn tick_limit_settles_reset_releases_without_domains() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulator::builder(code, "Top").build_native().unwrap()); } + +#[test] +fn assignment_selection_helpers_use_process_semantics() { + let code = r#"#[test(Top)] module Top { inst clk:$tb::clock_gen; var words:u8[2]; + function index()->u32 { clk.next(); $assert(1,"selected"); return 1; } + initial { words[index()]=7; $assert(words[1]==7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} +#[cfg(feature = "systemverilog")] +#[test] +fn testbench_fallthrough_ignores_background_design_processes() { + let veryl = + "#[test(Top)] module Top { var x:logic; inst dut:$sv::Worker(x); initial { $assert(1); } }"; + let sv = "module Worker(output logic x);initial forever #1 x=~x;endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("worker.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); +} +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn traced_builds_preserve_kernel_clock_pulses() { + let code = r#"#[test(Top)] module Top {var clk:clock;var q:logic; + function pulse(a:output clock,b:output clock) {a=1;b=0;} always_ff(clk){q=1;} + initial{clk=0;pulse(clk,clk);$finish();} }"#; + let mut sim = Simulator::builder(code, "Top") + .build_with_trace() + .res + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); +} + +#[test] +fn private_assignments_and_event_yields_do_not_replay_clean_comb_logic() { + let count = |body: &str| { + let code = format!( + r#"#[test(Top)] module Top {{ + always_comb {{ $assert(1,"comb"); }} + function helper()->u32 {{var tmp:u32;tmp=1;return tmp;}} + initial {{ {body} $finish(); }} + }}"# + ); + let result = Simulator::builder(&code, "Top") + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some("comb")) + .count() + }; + assert_eq!(count("helper();"), count("")); + assert_eq!(count(&"$assert(1);".repeat(600)), count("")); +} From d8d33cd5f4ef1e8bbc13a1417afcc977358d73fe Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 16:42:37 +0900 Subject: [PATCH 17/72] fix(testbench): resume selected copybacks and restore clock budgets --- .../src/lowering/process.rs | 75 +++++++++++++++---- .../src/lowering/process/expressions.rs | 44 ++++++++--- crates/celox-runtime/src/simulation.rs | 4 + crates/celox/src/backend/native/image_file.rs | 3 +- crates/celox/src/simulation.rs | 23 ++++++ crates/celox/tests/component_method.rs | 16 ++++ .../celox/tests/concurrent_initial_runtime.rs | 32 ++++++++ 7 files changed, 171 insertions(+), 26 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 13da6857845..91838c91d71 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -297,6 +297,24 @@ fn constant_empty_range(range: &ForRange) -> bool { } } +fn constant_nonempty_range(range: &ForRange) -> bool { + let (start, end) = match range { + ForRange::Forward { start, end, .. } + | ForRange::Reverse { start, end, .. } + | ForRange::Stepped { start, end, .. } => (start, end), + }; + matches!((start, end), (ForBound::Const(..), ForBound::Const(..))) + && !constant_empty_range(range) +} +fn contains_loop_break(statements: &[Statement]) -> bool { + statements.iter().any(|stmt| { + matches!(stmt, Statement::Break) + || expressions::statement_bodies(stmt) + .iter() + .any(|body| contains_loop_break(body)) + }) +} + /// How a `for` loop compares and steps, following the testbench /// interpreter: the counter is kept at its own width, bounds compare in /// the counter's signedness only when the bound is signed too, and a @@ -1273,7 +1291,13 @@ impl<'a> BlockLowering<'a> { } } Statement::For(stmt) if !constant_empty_range(&stmt.range) => { - self.scan_clocks(&stmt.body, active); + let continues = self.scan_clocks(&stmt.body, active); + if !continues + && constant_nonempty_range(&stmt.range) + && !contains_loop_break(&stmt.body) + { + return false; + } } Statement::FunctionCall(call) => { if active.insert(call.id) @@ -1430,6 +1454,19 @@ impl<'a> BlockLowering<'a> { } } + fn copy_back( + &mut self, + destination: &AssignDestination, + load: impl FnOnce(&mut Self) -> Result, + ) -> Result<(), ParserError> { + let inputs = expressions::selection(&destination.index, &destination.select); + let bindings = self.expression_bindings(&inputs)?; + self.parser.push_process_expression_values(bindings); + let result = load(self).and_then(|value| self.store(destination, value)); + self.parser.pop_process_expression_values(); + result + } + fn store( &mut self, destination: &AssignDestination, @@ -2183,7 +2220,8 @@ impl<'a> BlockLowering<'a> { self.parser.loop_exit_blocks_mut().push(exit); let flow = self.lower_statements(&stmt.body); self.parser.loop_exit_blocks_mut().pop(); - if let Flow::Continue = flow? { + let body_flow = flow?; + if let Flow::Continue = body_flow { self.kernel .builder() .seal_block(SIRTerminator::Jump(latch, Vec::new())); @@ -2270,7 +2308,16 @@ impl<'a> BlockLowering<'a> { } self.kernel.builder().switch_to_block(exit); self.parser.clear_register_cache(); - Ok(Flow::Continue) + if matches!(body_flow, Flow::Ended) + && constant_nonempty_range(&stmt.range) + && !contains_loop_break(&stmt.body) + { + // The exit is unreachable for this known nonempty terminating body. + self.kernel.finish(); + Ok(Flow::Ended) + } else { + Ok(Flow::Continue) + } } /// `value` at `width` bits, sign-extended when `signed`. @@ -2602,8 +2649,7 @@ impl<'a> BlockLowering<'a> { }; if let Some(&formal) = body.arg_map.get(path) { for destination in destinations { - let value = self.load_var(formal)?; - self.store(destination, value)?; + self.copy_back(destination, |this| this.load_var(formal))?; } } } @@ -2719,9 +2765,9 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - let value = self.load_scratch(slot, result_width, *signed); - let _ = width; - self.store(ret, value)?; + self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, result_width, *signed)) + })?; } Ok(Flow::Continue) } @@ -2758,8 +2804,9 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - let value = self.load_scratch(slot, result_width, *signed); - self.store(ret, value)?; + self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, result_width, *signed)) + })?; } Ok(Flow::Continue) } @@ -2770,8 +2817,7 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - let value = self.load_scratch(slot, 64, false); - self.store(ret, value)?; + self.copy_back(ret, |this| Ok(this.load_scratch(slot, 64, false)))?; } Ok(Flow::Continue) } @@ -2824,8 +2870,9 @@ impl<'a> BlockLowering<'a> { strict: tb.ret_strict, })?; if let (Some(ret), Some((value, slot))) = (tb.ret.as_deref(), result) { - let reg = self.load_scratch(slot, value.width, tb.ret_signed); - self.store(ret, reg)?; + self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, value.width, tb.ret_signed)) + })?; } Ok(Flow::Continue) } diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index fdfa7712334..233e7160a7a 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -20,7 +20,7 @@ pub(super) fn system_inputs(kind: &SystemFunctionKind) -> Vec<&Expression> { SystemFunctionKind::Finish => Vec::new(), } } -fn selection<'s>(index: &'s VarIndex, select: &'s VarSelect) -> Vec<&'s Expression> { +pub(super) fn selection<'s>(index: &'s VarIndex, select: &'s VarSelect) -> Vec<&'s Expression> { index .0 .iter() @@ -33,7 +33,15 @@ pub(super) fn children(expr: &Expression) -> Vec<&Expression> { Expression::Term(factor) => match factor.as_ref() { Factor::Variable(_, index, select, _) => selection(index, select), Factor::HierVariable(reference) => selection(&reference.index, &reference.select), - Factor::FunctionCall(call) => call.inputs.values().collect(), + Factor::FunctionCall(call) => call + .inputs + .values() + .chain(call.outputs.values().flat_map(|destinations| { + destinations + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)) + })) + .collect(), Factor::SystemFunctionCall(call) if !matches!( call.kind, @@ -105,16 +113,30 @@ pub(super) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { }) .collect() } - Statement::FunctionCall(call) => call.inputs.values().collect(), + Statement::FunctionCall(call) => call + .inputs + .values() + .chain(call.outputs.values().flat_map(|destinations| { + destinations + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)) + })) + .collect(), Statement::SystemFunctionCall(call) => system_inputs(&call.kind), - Statement::TbMethodCall(tb) => match &tb.method { - TbMethod::ClockNext { count, .. } => count.iter().collect(), - TbMethod::ResetAssert { duration, .. } => duration.iter().collect(), - TbMethod::RandomSeed { value, .. } => vec![value], - TbMethod::RandomGetRange { min, max, .. } => vec![min, max], - TbMethod::Component { args, .. } => args.iter().map(|arg| &arg.0).collect(), - _ => Vec::new(), - }, + Statement::TbMethodCall(tb) => { + let mut inputs: Vec<&Expression> = match &tb.method { + TbMethod::ClockNext { count, .. } => count.iter().collect(), + TbMethod::ResetAssert { duration, .. } => duration.iter().collect(), + TbMethod::RandomSeed { value, .. } => vec![value], + TbMethod::RandomGetRange { min, max, .. } => vec![min, max], + TbMethod::Component { args, .. } => args.iter().map(|arg| &arg.0).collect(), + _ => Vec::new(), + }; + if let Some(ret) = tb.ret.as_deref() { + inputs.extend(selection(&ret.index, &ret.select)); + } + inputs + } _ => Vec::new(), } } diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 40a11c9d7d1..5115b744332 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1909,6 +1909,7 @@ impl SimulationState { done: self.done.clone(), pending_releases: self.pending_releases.clone(), ticks: self.ticks, + tick_budget: self.tick_budget, inactive: self.inactive.clone(), scheduled_clock_drives: self.scheduled_clock_drives.clone(), scheduled_clock_time: self.scheduled_clock_time, @@ -1967,6 +1968,7 @@ impl SimulationState { self.done.clone_from(&snapshot.done); self.pending_releases.clone_from(&snapshot.pending_releases); self.ticks = snapshot.ticks; + self.tick_budget = snapshot.tick_budget; self.inactive.clone_from(&snapshot.inactive); self.scheduled_clock_drives .clone_from(&snapshot.scheduled_clock_drives); @@ -2168,6 +2170,7 @@ pub struct SimulationSnapshot { done: BTreeSet, pending_releases: BTreeMap, ticks: u64, + tick_budget: Option, inactive: BTreeSet, scheduled_clock_drives: BitSet, scheduled_clock_time: u64, @@ -2190,6 +2193,7 @@ impl Clone for SimulationSnapshot { done: self.done.clone(), pending_releases: self.pending_releases.clone(), ticks: self.ticks, + tick_budget: self.tick_budget, inactive: self.inactive.clone(), scheduled_clock_drives: self.scheduled_clock_drives.clone(), scheduled_clock_time: self.scheduled_clock_time, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 94ab446af5b..09a5bea0070 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 18; +// Version 19 adds the drain-only kernel status to the runtime protocol. +const CONTAINER_VERSION: u16 = 19; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 05efe5b182b..9429adef2c5 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -150,6 +150,8 @@ impl SimulationExecutor for Simulator { self.vcd_writer.is_none() && !self.components.has_scheduled_components() && self.program.runtime_schema.comb_observers.is_empty() + // Design events must return to the scheduler to drain the ring. + && self.program.runtime_schema.runtime_event_sites.iter().all(|site|site.location.is_some()) && !self.program.runtime_schema.clock_phase_sensitive_comb } @@ -2060,3 +2062,24 @@ mod rtl_finish_backend_tests { } } } + +#[cfg(test)] +mod tick_budget_snapshot_tests { + use super::*; + #[test] + fn restoring_a_checkpoint_restores_the_remaining_tick_budget() { + let code = + "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{clk.next(3);$finish();}}"; + let mut sim = Simulation::new(Simulator::builder(code, "Top").build_interpreter().unwrap()); + sim.state.set_tick_budget(Some(1)); + let saved = sim.checkpoint().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + assert!(sim.state.tick_budget_spent()); + sim.restore(&saved).unwrap(); + assert!(!sim.state.tick_budget_spent()); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + assert!(sim.state.tick_budget_spent()); + } +} diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index fd347b6cd9b..d22f68f43b4 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -3182,3 +3182,19 @@ fn invalid_component_returns_precede_output_assertions() { ); } } + +#[test] +fn component_return_selection_helpers_resume() { + register_component(); + let (_dir, metadata) = component_metadata(); + let code = r#"#[test(t)]module t{inst clk:$tb::clock_gen;var c:$comp::celox_counter;var words:u8[2]; + function index()->u32{clk.next();$assert(1,"index");return 1;} + initial{c.set(7);words[index()]=c.get();$assert(words[1]==7);$finish();}}"#; + assert_eq!( + Simulator::builder(code, "t") + .with_metadata(metadata) + .run_test() + .unwrap(), + TestResult::Pass + ); +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index fb04a30d6c3..597177aa412 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1263,3 +1263,35 @@ fn private_assignments_and_event_yields_do_not_replay_clean_comb_logic() { assert_eq!(count("helper();"), count("")); assert_eq!(count(&"$assert(1);".repeat(600)), count("")); } + +#[test] +fn copyback_selection_helpers_resume_for_random_and_function_outputs() { + for action in [ + "words[index()]=random.get_range(7,7);", + "give(words[index()]);", + ] { + let code = format!( + r#"#[test(Top)]module Top{{inst clk:$tb::clock_gen;var random:$tb::random::;var words:u8[2]; + function index()->u32{{clk.next();$assert(1,"index");return 1;}} + function give(value:output u8){{value=7;}} + initial{{{action}$assert(words[1]==7);$finish();}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} +#[test] +fn guaranteed_finish_loops_do_not_register_unreachable_clocks() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{$finish();}clk.next();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); +} +#[test] +fn long_clock_waits_drain_design_runtime_events() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:u32;always_ff(clk){$display("edge");q+=1;}initial{clk.next(1500);$assert(q==1500);$finish();}}"#; + check_passes_on_every_backend(code); +} From 00f53fa8b81f8bee7a1d862cd83cfd978c37903c Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 17:42:01 +0900 Subject: [PATCH 18/72] test(runtime): retain mixed process roots at O2 --- crates/celox/src/testbench_compile.rs | 28 +++++++++++++++++++ .../celox/tests/concurrent_initial_runtime.rs | 24 ++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index 281254b4e98..6fba4e50b0a 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -31,3 +31,31 @@ pub(crate) fn compile_semantic_testbench( random_seed, ) } + +#[cfg(all(test, feature = "systemverilog"))] +mod process_root_tests { + use crate::{OptLevel, Simulation, Simulator}; + #[test] + fn semantic_testbench_projection_preserves_process_counter_roots() { + let veryl = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:logic;inst dut:$sv::Pulse(q);initial{clk.next(2);$assert(q==1);$finish();}}"#; + let sv = "module Pulse(output bit q);bit clk;always @(posedge clk)q<=1;initial begin #1;clk=1;clk=0;end endmodule"; + let sim = Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("pulse.sv"))], + "Top", + ) + .testbench_kernels(false) + .opt_level(OptLevel::O2) + .build_interpreter() + .unwrap(); + let schema = &sim.program.runtime_schema; + assert!(!schema.process_event_counters.is_empty()); + for counters in &schema.process_event_counters { + assert!(schema.testbench_read_roots.contains(&counters.rises)); + assert!(schema.testbench_read_roots.contains(&counters.falls)); + } + let mut sim = Simulation::new(sim); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 597177aa412..7bd43120cd4 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1295,3 +1295,27 @@ fn long_clock_waits_drain_design_runtime_events() { let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:u32;always_ff(clk){$display("edge");q+=1;}initial{clk.next(1500);$assert(q==1500);$finish();}}"#; check_passes_on_every_backend(code); } + +#[cfg(feature = "systemverilog")] +#[test] +fn optimized_mixed_testbenches_preserve_sv_process_pulses() { + let veryl = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:logic;inst dut:$sv::Pulse(q);initial{clk.next(2);$assert(q==1);$finish();}}"#; + let sv = "module Pulse(output bit q);bit clk;always @(posedge clk)q<=1;initial begin #1;clk=1;clk=0;end endmodule"; + let builder = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("pulse.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O2) + }; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + } + check(builder().build_interpreter().unwrap()); + check(builder().build_cranelift().unwrap()); + check(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap()); +} From 413fba1a494af49b16a8a62002c34d3e5d7e58c7 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 17:45:35 +0900 Subject: [PATCH 19/72] fix(testbench): retain executed clock effects at kernel finish --- crates/celox/src/simulation.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3d589d1d50e..dc5091f40fb 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -146,6 +146,15 @@ impl SimulationExecutor for Simulator { ) } + fn finish_stops_round(&self, process: usize) -> bool { + // Veryl testbench stores already executed before finish retain their + // clock/reset effects. SV and SDK finish stop the current time slot. + self.program + .runtime_schema + .testbench_kernels + .is_none_or(|first| process < first) + } + fn fused_ticks_allowed(&self) -> bool { self.vcd_writer.is_none() && !self.components.has_scheduled_components() From c731686de73d1e18ad73b9010526341eb8c3cf39 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 17:54:29 +0900 Subject: [PATCH 20/72] fix(testbench): select static case arms and distinguish function bodies --- .../src/lowering/process.rs | 83 ++++++++++++------- .../src/lowering/process/expressions.rs | 3 + .../celox/tests/concurrent_initial_runtime.rs | 18 ++++ 3 files changed, 74 insertions(+), 30 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 91838c91d71..e0fc5a30bb7 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -251,6 +251,21 @@ fn constant_truth(expr: &Expression) -> Option { } } +type FunctionKey = (VarId, Option>); +fn function_key(call: &veryl_analyzer::ir::FunctionCall) -> FunctionKey { + (call.id, call.index.clone()) +} +fn selected_case_body(stmt: &veryl_analyzer::ir::CaseStatement) -> Option<&[Statement]> { + for arm in &stmt.arms { + match constant_truth(&case_arm_condition_expr(&stmt.case_target, &arm.patterns)) { + Some(true) => return Some(&arm.body), + Some(false) => {} + None => return None, + } + } + Some(&stmt.default) +} + /// Whether a range with constant bounds has no value. fn constant_empty_range(range: &ForRange) -> bool { let constant = |bound: &ForBound| match bound { @@ -435,13 +450,13 @@ fn function_body( fn collect_expression_storage( ir: &Module, statements: &[Statement], - active: &mut HashSet, + active: &mut HashSet, values: &mut HashMap, ) { fn expr( ir: &Module, value: &Expression, - active: &mut HashSet, + active: &mut HashSet, values: &mut HashMap, ) { if expressions::has_call(value) { @@ -455,12 +470,12 @@ fn collect_expression_storage( } if let Expression::Term(factor) = value && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() - && active.insert(call.id) + && active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { collect_expression_storage(ir, &body.statements, active, values); } - active.remove(&call.id); + active.remove(&function_key(call)); } } for statement in statements { @@ -487,12 +502,12 @@ fn collect_expression_storage( } } if let Statement::FunctionCall(call) = statement - && active.insert(call.id) + && active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { collect_expression_storage(ir, &body.statements, active, values); } - active.remove(&call.id); + active.remove(&function_key(call)); } for body in expressions::statement_bodies(statement) { collect_expression_storage(ir, body, active, values); @@ -523,7 +538,7 @@ fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result, + active: &mut HashSet, ) -> bool { for statement in statements { if matches!(statement, Statement::SystemFunctionCall(call) if matches!(call.kind, SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) | SystemFunctionKind::Assert {..})) @@ -538,10 +553,10 @@ fn contains_runtime_event( calls.push(call); } for call in calls { - if active.insert(call.id) { + if active.insert(function_key(call)) { let emits = function_body(&ir.functions, call) .is_some_and(|body| contains_runtime_event(ir, &body.statements, active)); - active.remove(&call.id); + active.remove(&function_key(call)); if emits { return true; } @@ -559,7 +574,7 @@ fn contains_runtime_event( fn collect_scratch_needs( ir: &Module, statements: &[Statement], - active: &mut HashSet, + active: &mut HashSet, needs: &mut Vec, ) -> Result<(), ParserError> { let need = |needs: &mut Vec, purpose: &'static str, width: usize| { @@ -574,11 +589,11 @@ fn collect_scratch_needs( expressions::expression_calls(expr, &mut calls); } for call in calls { - if active.insert(call.id) { + if active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { collect_scratch_needs(ir, &body.statements, active, needs)?; } - active.remove(&call.id); + active.remove(&function_key(call)); } } match statement { @@ -594,11 +609,10 @@ fn collect_scratch_needs( collect_scratch_needs(ir, &stmt.true_side, active, needs)?; collect_scratch_needs(ir, &stmt.false_side, active, needs)?; } - Statement::Case(stmt) => { - for arm in &stmt.arms { - collect_scratch_needs(ir, &arm.body, active, needs)?; + Statement::Case(_) => { + for body in expressions::statement_bodies(statement) { + collect_scratch_needs(ir, body, active, needs)?; } - collect_scratch_needs(ir, &stmt.default, active, needs)?; } Statement::For(stmt) => { if constant_empty_range(&stmt.range) { @@ -613,11 +627,11 @@ fn collect_scratch_needs( collect_scratch_needs(ir, &stmt.body, active, needs)?; } Statement::FunctionCall(call) => { - if active.insert(call.id) + if active.insert(function_key(call)) && let Some(body) = function_body(&ir.functions, call) { collect_scratch_needs(ir, &body.statements, active, needs)?; - active.remove(&call.id); + active.remove(&function_key(call)); } } Statement::TbMethodCall(tb) => match &tb.method { @@ -724,7 +738,7 @@ struct BlockLowering<'a> { host_requests: Vec>, clock_periods: &'a HashMap, resource_prefix: String, - active_functions: HashSet, + active_functions: HashSet, site_base: u32, targets: Vec>, sources: Vec>, @@ -1037,7 +1051,7 @@ fn resolve_hierarchical( fn collect_hierarchical_references( statements: &[Statement], functions: &HashMap, - active: &mut HashSet, + active: &mut HashSet, out: &mut Vec, ) { let mut reads = Vec::new(); @@ -1086,11 +1100,11 @@ fn collect_hierarchical_references( collect_hierarchical_references(&stmt.body, functions, active, out); } Statement::FunctionCall(call) => { - if active.insert(call.id) + if active.insert(function_key(call)) && let Some(body) = function_body(functions, call) { collect_hierarchical_references(&body.statements, functions, active, out); - active.remove(&call.id); + active.remove(&function_key(call)); } } Statement::TbMethodCall(_) @@ -1220,7 +1234,7 @@ impl<'a> BlockLowering<'a> { self.scan_clocks(statements, &mut active); } - fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) -> bool { + fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) -> bool { for statement in statements { let mut calls = Vec::new(); let mut unconditional = Vec::new(); @@ -1229,10 +1243,10 @@ impl<'a> BlockLowering<'a> { expressions::unconditional_expression_calls(expr, &mut unconditional); } for call in calls { - if active.insert(call.id) { + if active.insert(function_key(call)) { if let Some(body) = function_body(&self.ir.functions, call) { let continues = self.scan_clocks(&body.statements, active); - active.remove(&call.id); + active.remove(&function_key(call)); if !continues && unconditional .iter() @@ -1241,7 +1255,7 @@ impl<'a> BlockLowering<'a> { return false; } } else { - active.remove(&call.id); + active.remove(&function_key(call)); } } } @@ -1282,6 +1296,12 @@ impl<'a> BlockLowering<'a> { self.scan_clocks(&stmt.false_side, active); } Statement::Case(stmt) => { + if let Some(body) = selected_case_body(stmt) { + if !self.scan_clocks(body, active) { + return false; + } + continue; + } let mut continues = self.scan_clocks(&stmt.default, active); for arm in &stmt.arms { continues |= self.scan_clocks(&arm.body, active); @@ -1300,11 +1320,11 @@ impl<'a> BlockLowering<'a> { } } Statement::FunctionCall(call) => { - if active.insert(call.id) + if active.insert(function_key(call)) && let Some(body) = function_body(&self.ir.functions, call) { let continues = self.scan_clocks(&body.statements, active); - active.remove(&call.id); + active.remove(&function_key(call)); if !continues { return false; } @@ -1796,6 +1816,9 @@ impl<'a> BlockLowering<'a> { ) -> Result { let value = self.expression(&stmt.case_target)?; self.save_expression(&stmt.case_target, value)?; + if let Some(body) = selected_case_body(stmt) { + return self.lower_statements(body); + } self.lower_case_arm(stmt, 0) } @@ -2616,7 +2639,7 @@ impl<'a> BlockLowering<'a> { } values.push((*path, *expr, value)); } - if !self.active_functions.insert(call.id) { + if !self.active_functions.insert(function_key(call)) { return Err(self.error( "function call in an initial block", "recursive call", @@ -2635,7 +2658,7 @@ impl<'a> BlockLowering<'a> { } } let flow = self.lower_statements(&body.statements)?; - self.active_functions.remove(&call.id); + self.active_functions.remove(&function_key(call)); if let Flow::Ended = flow { return Ok(Flow::Ended); } diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index 233e7160a7a..cb3b2eb66dd 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -148,6 +148,9 @@ pub(super) fn statement_bodies(statement: &Statement) -> Vec<&[Statement]> { None => vec![&stmt.true_side, &stmt.false_side], }, Statement::IfReset(stmt) => vec![&stmt.true_side, &stmt.false_side], + Statement::Case(stmt) if selected_case_body(stmt).is_some() => { + vec![selected_case_body(stmt).unwrap()] + } Statement::Case(stmt) => stmt .arms .iter() diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 7bd43120cd4..eb361bd2007 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1319,3 +1319,21 @@ fn optimized_mixed_testbenches_preserve_sv_process_pulses() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(builder().build_native().unwrap()); } + +#[test] +fn unselected_constant_case_arms_leave_host_clocks_unchanged() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{case 1 {1:{$assert(1);},2:{clk.next();},default:{$assert(0);}}$finish();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); +} +#[test] +fn function_specializations_can_call_other_specializations() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen; + function helper::()->u32 {if N==0 {return helper::<1>();}else{clk.next();$assert(1);return 7;}} + initial{$assert(helper::<0>()==7);$finish();}}"#; + check_passes_on_every_backend(code); +} From 8a51c651ed9d232f3442d14a15e7d7d04c6a63e6 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 18:23:32 +0900 Subject: [PATCH 21/72] fix(testbench): prune self-determined constant case branches --- .../src/lowering/process.rs | 43 +++++++++++++++++-- .../celox/tests/concurrent_initial_runtime.rs | 9 +--- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index e0fc5a30bb7..626511b0af5 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -256,11 +256,46 @@ fn function_key(call: &veryl_analyzer::ir::FunctionCall) -> FunctionKey { (call.id, call.index.clone()) } fn selected_case_body(stmt: &veryl_analyzer::ir::CaseStatement) -> Option<&[Statement]> { + // Arithmetic targets need each label's comparison width. Prune only + // self-determined known nonnegative terms whose value fits in u64. + let value = |expr: &Expression| { + if !matches!(expr, Expression::Term(_)) + || expressions::has_call(expr) + || !expr.comptime().is_const + { + return None; + } + let value = expr.comptime().get_value().ok()?; + let width = value.width(); + if value.is_xz() || width == 0 || width > 64 { + return None; + } + let bits = value.payload_u64(); + if value.signed() && bits & (1u64 << (width - 1)) != 0 { + return None; + } + Some(bits) + }; + let target = value(&stmt.case_target)?; for arm in &stmt.arms { - match constant_truth(&case_arm_condition_expr(&stmt.case_target, &arm.patterns)) { - Some(true) => return Some(&arm.body), - Some(false) => {} - None => return None, + let mut selected = false; + for pattern in &arm.patterns { + selected |= match pattern { + veryl_analyzer::ir::CasePattern::Eq(pattern) => target == value(pattern)?, + veryl_analyzer::ir::CasePattern::Range { lo, hi, inclusive } => { + let lo = value(lo)?; + let hi = value(hi)?; + lo <= target + && if *inclusive { + target <= hi + } else { + target < hi + } + } + }; + } + if selected { + return Some(&arm.body); } } Some(&stmt.default) diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index eb361bd2007..8eacd0c7dab 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1322,7 +1322,7 @@ fn optimized_mixed_testbenches_preserve_sv_process_pulses() { #[test] fn unselected_constant_case_arms_leave_host_clocks_unchanged() { - let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{case 1 {1:{$assert(1);},2:{clk.next();},default:{$assert(0);}}$finish();}}"#; + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{case 1 {1:{$assert(1);}2:{clk.next();}default:{$assert(0);}}$finish();}}"#; let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); let clk = sim.signal("clk"); sim.set(clk, 1u8); @@ -1330,10 +1330,3 @@ fn unselected_constant_case_arms_leave_host_clocks_unchanged() { assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); assert_eq!(sim.get(clk), 1u8.into()); } -#[test] -fn function_specializations_can_call_other_specializations() { - let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen; - function helper::()->u32 {if N==0 {return helper::<1>();}else{clk.next();$assert(1);return 7;}} - initial{$assert(helper::<0>()==7);$finish();}}"#; - check_passes_on_every_backend(code); -} From a4579de0d77a6d218767db1323dd97fdf3fa5823 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 18:41:28 +0900 Subject: [PATCH 22/72] fix(runtime): preserve executed SDK clock changes at finish --- crates/celox-frontend-sv/src/lowering/ff.rs | 12 +++++------- crates/celox-runtime/src/simulation.rs | 10 +++------- crates/celox/src/simulation.rs | 9 --------- .../celox/tests/frontends/systemverilog/processes.rs | 1 + .../frontends/systemverilog/system_functions.rs | 9 ++++++--- 5 files changed, 15 insertions(+), 26 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ef04f439188..04150ea2ecf 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2133,12 +2133,6 @@ impl<'p, 'a> Ff<'p, 'a> { } let kind = system_task_kind(name).ok_or_else(|| unsupported(format!("system task `{name}`")))?; - // A process ends the simulation itself; the rest of its body does not - // run. - if matches!(kind, SystemTaskKind::Finish) && self.kernel.is_some() { - self.with_kernel(ProcessKernelBuilder::finish); - return Ok(false); - } let (template, values) = system_task_template(&kind, args); let mut regs = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); @@ -2193,7 +2187,11 @@ impl<'p, 'a> Ff<'p, 'a> { args: regs, }); if matches!(kind, SystemTaskKind::Finish) { - self.b.seal_block(SIRTerminator::Return); + if self.kernel.is_some() { + self.with_kernel(ProcessKernelBuilder::finish); + } else { + self.b.seal_block(SIRTerminator::Return); + } return Ok(false); } if matches!(kind, SystemTaskKind::Fatal) { diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 1bf491ccbe1..ffb4aad0ccf 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -19,11 +19,6 @@ use crate::{ /// decoration and waveform capture outside the backend-independent scheduler. pub trait SimulationExecutor { type Backend: SimBackend; - /// Whether a process finish stops already queued domains in this round. - fn finish_stops_round(&self, _process: usize) -> bool { - true - } - fn backend(&self) -> &Self::Backend; fn backend_mut(&mut self) -> &mut Self::Backend; fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode>; @@ -459,7 +454,7 @@ impl SimulationState { scheduled_clock_time: 0, round_evaluated: false, round_new_rising: BitSet::new(), - finish_round: true, + finish_round: false, } } @@ -1134,6 +1129,7 @@ impl SimulationState { .collect::>(); executor.run_process(process, current_time)?; if executor.finish_requested(current_time) { + self.finish_round = true; self.finished = true; return Ok(true); } @@ -1195,7 +1191,7 @@ impl SimulationState { any_ran = true; } Some(ProcessStatus::Finish) => { - self.finish_round = executor.finish_stops_round(process); + self.finish_round = executor.finish_requested(current_time); self.waiting.remove(&process); self.done.insert(process); self.finished = true; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index afed2a95c6a..c693d10eeee 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -146,15 +146,6 @@ impl SimulationExecutor for Simulator { ) } - fn finish_stops_round(&self, process: usize) -> bool { - // Veryl testbench stores already executed before finish retain their - // clock/reset effects. SV and SDK finish stop the current time slot. - self.program - .runtime_schema - .testbench_kernels - .is_none_or(|first| process < first) - } - fn fused_ticks_allowed(&self) -> bool { self.vcd_writer.is_none() && !self.components.has_scheduled_components() diff --git a/crates/celox/tests/frontends/systemverilog/processes.rs b/crates/celox/tests/frontends/systemverilog/processes.rs index 8a3a5eb3561..c0901b02ee9 100644 --- a/crates/celox/tests/frontends/systemverilog/processes.rs +++ b/crates/celox/tests/frontends/systemverilog/processes.rs @@ -41,6 +41,7 @@ fn displays(sim: &mut Simulation) -> Vec<(u64, String)> { match event { RuntimeEvent::Display { message } => lines.push((time, message)), RuntimeEvent::Write { message } => lines.push((time, message)), + RuntimeEvent::Finish => {} other => panic!("unexpected runtime event {other:?}"), } } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 53feda03742..e14f0b8fe15 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -907,9 +907,12 @@ fn finish_in_an_initial_block_ends_the_simulation() { assert!(sim.is_finished()); assert_eq!( sim.drain_runtime_events(), - vec![celox::RuntimeEvent::Display { - message: "before".to_string(), - }], + vec![ + celox::RuntimeEvent::Display { + message: "before".to_string(), + }, + celox::RuntimeEvent::Finish + ], ); } From 6da8e13ee16a73a2b8cc6897bb6a05d252d4dacd Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 12 Oct 2026 19:09:58 +0900 Subject: [PATCH 23/72] fix(runtime): compare unknown baselines when checking unsettled edges --- crates/celox-runtime/src/simulation.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 11fa1645e17..0cb313ab113 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -977,8 +977,11 @@ impl SimulationState { *id != usize::MAX && self.edge_triggers( *id, - self.last_clock_values.contains(*id), - backend.get_as::(*signal) != 0, + ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ), + sample_event_signal(backend, *signal), ) }) } From 4fab7a8d9c75759c4fc981e9ecaf94ae826d0af4 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:03:55 +0900 Subject: [PATCH 24/72] style: format stacked merge resolutions --- crates/celox-runtime/src/simulation.rs | 29 ++- .../celox-test-suite/src/frontend/timed_ff.rs | 43 +++-- crates/celox-test-suite/src/script/sv.rs | 23 ++- crates/celox/src/simulation.rs | 171 +++++++++++------- .../frontends/systemverilog/processes.rs | 12 +- .../systemverilog/system_functions.rs | 4 +- crates/celox/tests/native_testbench.rs | 11 +- 7 files changed, 198 insertions(+), 95 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index cdb488518cc..93e45aae960 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -380,10 +380,18 @@ impl SimulationState { let Some((signal, _, _)) = self.topo_signals.get(self.signal_index_by_id[id]) else { return true; }; - let was = (self.last_clock_values.contains(id), self.unknown_clock_values.contains(id)); + let was = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); let is = sample_event_signal(backend, *signal); match self.domain_kinds[id] { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh | DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => self.edge_triggers(id, was, is), + Some( + DomainKind::ClockPosedge + | DomainKind::ResetAsyncHigh + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncLow, + ) => self.edge_triggers(id, was, is), _ => was != is, } } @@ -1473,7 +1481,10 @@ impl SimulationState { }); if !self.finished && !self.tick_budget_spent() - && (reset_edge_due || !events_to_process.is_empty() || !process_driven.is_empty() || !generated_events.is_empty()) + && (reset_edge_due + || !events_to_process.is_empty() + || !process_driven.is_empty() + || !generated_events.is_empty()) { for (id, clock) in &self.tick_clocks { if clock.next_edge == current_time @@ -2158,7 +2169,11 @@ impl SimulationState { done_processes: self.done.iter().copied().collect(), ticks: self.ticks, scheduled_clock_time: self.scheduled_clock_time, - scheduled_clock_drives: self.scheduled_clock_drives.iter().map(|id| events[id]).collect(), + scheduled_clock_drives: self + .scheduled_clock_drives + .iter() + .map(|id| events[id]) + .collect(), inactive_processes: self.inactive.iter().copied().collect(), finished: self.finished, } @@ -2230,7 +2245,11 @@ impl SimulationState { self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; self.scheduled_clock_time = parts.scheduled_clock_time; - self.scheduled_clock_drives = parts.scheduled_clock_drives.into_iter().map(|event| event.id()).collect(); + self.scheduled_clock_drives = parts + .scheduled_clock_drives + .into_iter() + .map(|event| event.id()) + .collect(); self.inactive = parts.inactive_processes.into_iter().collect(); self.finished = parts.finished; } diff --git a/crates/celox-test-suite/src/frontend/timed_ff.rs b/crates/celox-test-suite/src/frontend/timed_ff.rs index 82392045325..957fa806b8d 100644 --- a/crates/celox-test-suite/src/frontend/timed_ff.rs +++ b/crates/celox-test-suite/src/frontend/timed_ff.rs @@ -193,7 +193,9 @@ fn single_generate_body(source: &str, start: usize) -> bool { control_end.is_some_and(|end| { let mut at = trivia(source, end); while source[at..].starts_with("(*") { - let Some(end) = parens(source, at) else { return false; }; + let Some(end) = parens(source, at) else { + return false; + }; at = trivia(source, end); } at == start @@ -411,7 +413,9 @@ fn lexical_scope_at(source: &str, at: usize) -> Vec { fn callable_key(source: &str, at: usize, name: &str) -> (String, Vec, String) { let container = container_at(source, at); let mut scope = lexical_scope_at(source, at); - if !container.is_empty() && !scope.is_empty() { scope.remove(0); } + if !container.is_empty() && !scope.is_empty() { + scope.remove(0); + } (container, scope, name.to_owned()) } @@ -478,7 +482,10 @@ impl TaskTiming { let prefix = source[..at].trim_end(); if let Some(prefix) = prefix.strip_suffix("::") { let package = sv_words(prefix).last()?.2; - return self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())).copied(); + return self + .tasks + .get(&(package.to_owned(), Vec::new(), name.to_owned())) + .copied(); } if let Some(prefix) = prefix.strip_suffix('.') { let instance = sv_words(prefix).last()?.2; @@ -486,7 +493,10 @@ impl TaskTiming { let words = sv_words(&source[..at]); for pair in words.windows(2) { if pair[1].2 == instance && container_at(source, pair[0].0) == scope { - if let Some(value) = self.tasks.get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) { + if let Some(value) = + self.tasks + .get(&(pair[0].2.to_owned(), Vec::new(), name.to_owned())) + { return Some(*value); } } @@ -497,8 +507,12 @@ impl TaskTiming { let scope = container_at(source, at); let mut key = callable_key(source, at, name); loop { - if let Some(value) = self.tasks.get(&key) { return Some(*value); } - if key.1.pop().is_none() { break; } + if let Some(value) = self.tasks.get(&key) { + return Some(*value); + } + if key.1.pop().is_none() { + break; + } } let call_scope = lexical_scope_at(source, at); let mut imports: BTreeMap, Option)> = BTreeMap::new(); @@ -524,7 +538,10 @@ impl TaskTiming { }; let selected = words.get(1).map(|word| word.2); if selected == Some(name) || (selected.is_none() && item.contains('*')) { - if let Some(value) = self.tasks.get(&(package.to_owned(), Vec::new(), name.to_owned())) { + if let Some(value) = + self.tasks + .get(&(package.to_owned(), Vec::new(), name.to_owned())) + { if selected == Some(name) { *explicit = Some(*value); } else { @@ -538,18 +555,18 @@ impl TaskTiming { .into_values() .rev() .find_map(|(explicit, wildcard)| explicit.or(wildcard)) - .or_else(|| self.tasks.get(&(String::new(), Vec::new(), name.to_owned())).copied()) + .or_else(|| { + self.tasks + .get(&(String::new(), Vec::new(), name.to_owned())) + .copied() + }) } fn has_timed_call(&self, source: &str, start: usize, end: usize) -> bool { sv_words(&source[start..end]) .iter() .any(|(at, word_end, name)| { - if !self - .tasks - .keys() - .any(|key| key.2 == *name) - { + if !self.tasks.keys().any(|key| key.2 == *name) { return false; } let tail = after_trivia(&source[start + word_end..end]); diff --git a/crates/celox-test-suite/src/script/sv.rs b/crates/celox-test-suite/src/script/sv.rs index bd6301616e0..2a4e4b4b054 100644 --- a/crates/celox-test-suite/src/script/sv.rs +++ b/crates/celox-test-suite/src/script/sv.rs @@ -160,9 +160,12 @@ fn design_output(text: &[u8], sources: &[String]) -> Vec { let mut output = Vec::new(); for chunk in text.split_inclusive(|byte| *byte == b'\n') { let line = chunk.strip_suffix(b"\n").unwrap_or(chunk); - let notice = std::str::from_utf8(line).ok() + let notice = std::str::from_utf8(line) + .ok() .is_some_and(|line| is_source_finish_notice(line, sources)); - if !notice { output.extend_from_slice(chunk); } + if !notice { + output.extend_from_slice(chunk); + } } output } @@ -1156,7 +1159,10 @@ mod tests { #[test] fn finish_notices_are_not_design_output() { let sources = vec!["timed_control.sv".to_string()]; - for log in [b"done\ntimed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), b"done\n- timed_control.sv:3: Verilog $finish\n"] { + for log in [ + b"done\ntimed_control.sv:3: $finish called at 5 (1ns)\n".as_slice(), + b"done\n- timed_control.sv:3: Verilog $finish\n", + ] { assert_eq!(design_output(log, &sources), b"done\n"); } let printed = b"\x80\xffsource_0.sv:3: $finish called at 5 (1ns)\n"; @@ -1259,11 +1265,18 @@ mod tests { #[test] fn checks_non_utf8_output_without_replacement() { assert_eq!( - check_output(b"\x80\xff\0\n@suite output 80ff00 here\n\n@suite end\n", &[]), + check_output( + b"\x80\xff\0\n@suite output 80ff00 here\n\n@suite end\n", + &[] + ), Ok(()) ); assert!( - check_output(b"\xef\xbf\xbd\xff\0\n@suite output 80ff00 here\n\n@suite end\n", &[]).is_err() + check_output( + b"\xef\xbf\xbd\xff\0\n@suite output 80ff00 here\n\n@suite end\n", + &[] + ) + .is_err() ); let text = testbench( &case("(tick clk) (expect_output (bytes 128 255 0))"), diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2b5a8ce639b..abed0c3919f 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -611,7 +611,11 @@ impl Simulation { { self.settle_host_writes()?; let mut drained = false; - while self.state.next_event_time().is_some_and(|next| next <= time) { + while self + .state + .next_event_time() + .is_some_and(|next| next <= time) + { self.state.step(&mut self.simulator)?; drained = true; } @@ -2220,28 +2224,37 @@ mod clock_provenance_checkpoint_tests { assert_eq!(sim.ticks(), 0); } fn check_transfer(mut from: Simulation, mut to: Simulation) { - from.schedule("clk",0,1).unwrap(); + from.schedule("clk", 0, 1).unwrap(); from.step().unwrap(); let design = from.simulator.checkpoint().unwrap(); let mut parts = from.state.export_schedule(&from.simulator.backend); - parts.process_wakeups = vec![(0,0)]; + parts.process_wakeups = vec![(0, 0)]; to.simulator.restore(&design).unwrap(); to.state.import_schedule(parts); let error = to.step().unwrap_err().to_string(); - assert!(error.contains("already driven by schedule"),"{error}"); - assert_eq!(to.ticks(),0); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(to.ticks(), 0); } #[test] fn exported_schedule_retains_consumed_clock_drives() { - let build=|| Simulation::from_frontend(design()).build_interpreter().unwrap(); - check_transfer(build(),build()); - let build=|| Simulation::from_frontend(design()).build_cranelift().unwrap(); - check_transfer(build(),build()); - let build=|| Simulation::from_frontend(design()).build_wasm().unwrap(); - check_transfer(build(),build()); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] { - let build=|| Simulation::from_frontend(design()).build_native().unwrap(); - check_transfer(build(),build()); + let build = || { + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap() + }; + check_transfer(build(), build()); + let build = || { + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap() + }; + check_transfer(build(), build()); + let build = || Simulation::from_frontend(design()).build_wasm().unwrap(); + check_transfer(build(), build()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + let build = || Simulation::from_frontend(design()).build_native().unwrap(); + check_transfer(build(), build()); } } #[test] @@ -2541,11 +2554,9 @@ mod idle_settle_tests { let a = sim.signal("a"); sim.set_wide(a, 1u8.into()); sim.run_until(0).unwrap(); - assert!( - sim.drain_runtime_events() - .iter() - .any(|e| matches!(e,crate::RuntimeEvent::Display { message } if message.as_slice()==b"x")) - ); + assert!(sim.drain_runtime_events().iter().any( + |e| matches!(e,crate::RuntimeEvent::Display { message } if message.as_slice()==b"x") + )); sim.settle().unwrap(); sim.settle().unwrap(); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); @@ -2667,65 +2678,93 @@ mod direct_finish_tests { #[cfg(test)] mod pending_generated_clock_tests { use super::*; - use crate::frontend_sdk::{Constant,Edge,ModuleBuilder,Statement,UnaryOp,ValueType}; - fn design()->crate::frontend_sdk::FrontendArtifact { - let mut m=ModuleBuilder::new("Top").unwrap(); - let bit=ValueType::bits(1).unwrap(); - let a=m.internal("a",bit).unwrap();let b=m.internal("b",bit).unwrap(); - let qa=m.output("qa",bit).unwrap();let qb=m.output("qb",bit).unwrap(); - let old=m.read(qb).unwrap();let next=m.unary(UnaryOp::BitNot,old,bit).unwrap(); - let qa_target=m.whole(qa).unwrap();let qb_target=m.whole(qb).unwrap(); - m.register(qa_target,old,a,Edge::Posedge,None,None).unwrap(); - m.register(qb_target,next,b,Edge::Posedge,None,None).unwrap(); - m.clock_period(a,4).unwrap();m.clock_period(b,4).unwrap(); - let two=m.constant(Constant::two_state(2u8,64).unwrap()); - let one=m.constant(Constant::two_state(1u8,64).unwrap()); - let four=m.constant(Constant::two_state(4u8,64).unwrap()); - m.process(vec![Statement::ClockCycles{clock:b,count:two}]).unwrap(); - m.process(vec![Statement::Delay{amount:four},Statement::ClockCycles{clock:a,count:one}]).unwrap(); + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let a = m.internal("a", bit).unwrap(); + let b = m.internal("b", bit).unwrap(); + let qa = m.output("qa", bit).unwrap(); + let qb = m.output("qb", bit).unwrap(); + let old = m.read(qb).unwrap(); + let next = m.unary(UnaryOp::BitNot, old, bit).unwrap(); + let qa_target = m.whole(qa).unwrap(); + let qb_target = m.whole(qb).unwrap(); + m.register(qa_target, old, a, Edge::Posedge, None, None) + .unwrap(); + m.register(qb_target, next, b, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(a, 4).unwrap(); + m.clock_period(b, 4).unwrap(); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let four = m.constant(Constant::two_state(4u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: b, + count: two, + }]) + .unwrap(); + m.process(vec![ + Statement::Delay { amount: four }, + Statement::ClockCycles { + clock: a, + count: one, + }, + ]) + .unwrap(); m.finish() } - fn check(mut sim:Simulation) { + fn check(mut sim: Simulation) { sim.run_until(3).unwrap(); - assert_eq!(sim.get(sim.signal("qb")),1u8.into()); + assert_eq!(sim.get(sim.signal("qb")), 1u8.into()); // A failed round can leave this generated drive high without publishing its FF batch. - sim.simulator.backend.set(sim.signal("b"),1u8); + sim.simulator.backend.set(sim.signal("b"), 1u8); sim.step().unwrap(); - assert_eq!(sim.get(sim.signal("qa")),1u8.into()); - assert_eq!(sim.get(sim.signal("qb")),0u8.into()); - assert_eq!(sim.ticks(),2); + assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); + assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); + assert_eq!(sim.ticks(), 2); } #[test] fn pending_rises_share_pre_edge_state_with_new_clocks() { - check(Simulation::from_frontend(design()).build_interpreter().unwrap()); - check(Simulation::from_frontend(design()).build_cranelift().unwrap()); + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); check(Simulation::from_frontend(design()).build_wasm().unwrap()); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulation::from_frontend(design()).build_native().unwrap()); } } -#[cfg(all(test, feature="systemverilog"))] +#[cfg(all(test, feature = "systemverilog"))] mod current_time_settle_tests { - use super::*; - #[test] - fn settle_consumes_current_time_clock_events() { - fn check(mut sim:Simulation) { - sim.run_until(0).unwrap(); - sim.schedule("clk",0,1).unwrap(); - sim.settle().unwrap(); - assert_eq!(sim.get(sim.signal("q")),1u8.into()); - assert_eq!(sim.time(),0); - assert_eq!(sim.next_event_time(),None); - sim.settle().unwrap(); - assert_eq!(sim.get(sim.signal("q")),1u8.into()); - } - let source="module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; - let builder=||Simulator::from_sv_sources(vec![(source,std::path::Path::new("settle.sv"))],"Top"); - check(Simulation::new(builder().build_interpreter().unwrap())); - check(Simulation::new(builder().build_cranelift().unwrap())); - check(Simulation::new(builder().build_wasm().unwrap())); - #[cfg(any(target_arch="x86_64",target_arch="aarch64"))] - check(Simulation::new(builder().build_native().unwrap())); - } + use super::*; + #[test] + fn settle_consumes_current_time_clock_events() { + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.next_event_time(), None); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let source = + "module Top(input bit clk,output bit[7:0]q);always @(posedge clk)q<=q+1;endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("settle.sv"))], "Top"); + check(Simulation::new(builder().build_interpreter().unwrap())); + check(Simulation::new(builder().build_cranelift().unwrap())); + check(Simulation::new(builder().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(builder().build_native().unwrap())); + } } diff --git a/crates/celox/tests/frontends/systemverilog/processes.rs b/crates/celox/tests/frontends/systemverilog/processes.rs index 96d9dbc0622..ecb45f72828 100644 --- a/crates/celox/tests/frontends/systemverilog/processes.rs +++ b/crates/celox/tests/frontends/systemverilog/processes.rs @@ -39,8 +39,12 @@ fn displays(sim: &mut Simulation) -> Vec<(u64, String)> { while let Some(time) = sim.step().unwrap() { for event in sim.drain_runtime_events() { match event { - RuntimeEvent::Display { message } => lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))), - RuntimeEvent::Write { message } => lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))), + RuntimeEvent::Display { message } => { + lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))) + } + RuntimeEvent::Write { message } => { + lines.push((time, String::from_utf8(message).expect("UTF-8 test output"))) + } RuntimeEvent::Finish => {} other => panic!("unexpected runtime event {other:?}"), } @@ -794,7 +798,9 @@ fn events_between_cascaded_register_updates_wake_waiters() { .drain_runtime_events() .into_iter() .filter_map(|event| match event { - RuntimeEvent::Display { message } => Some(String::from_utf8(message).expect("UTF-8 test output")), + RuntimeEvent::Display { message } => { + Some(String::from_utf8(message).expect("UTF-8 test output")) + } _ => None, }) .collect(); diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 7d32ff73206..1b62c423507 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1147,7 +1147,9 @@ fn finish_in_an_initial_block_ends_the_simulation() { assert_eq!( sim.drain_runtime_events(), vec![ - celox::RuntimeEvent::Display { message: b"before".to_vec() }, + celox::RuntimeEvent::Display { + message: b"before".to_vec() + }, celox::RuntimeEvent::Finish, ], ); diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 402f19ada4a..3bdb52a9ee2 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2700,7 +2700,11 @@ fn test_ff_runtime_events_drain_with_per_tick_time() { .collect::>(), // `%t` is the scheduler time: the default clock has period 2, and // its first edge is at time 0. - vec![Some(b"ff time=0".as_slice()), Some(b"ff time=2".as_slice()), Some(b"ff time=4".as_slice())], + vec![ + Some(b"ff time=0".as_slice()), + Some(b"ff time=2".as_slice()), + Some(b"ff time=4".as_slice()) + ], ); } @@ -2722,7 +2726,10 @@ fn test_assert_format_args_render_current_time_for_percent_t() { assert_eq!(detailed.assertions.len(), 1); // Three edges of the default clock (period 2) end at time 4; the // process resumes one period later. - assert_eq!(detailed.assertions[0].message.as_deref(), Some(b"time=6".as_slice())); + assert_eq!( + detailed.assertions[0].message.as_deref(), + Some(b"time=6".as_slice()) + ); } #[test] From 48c3a7d82480cec54e4349a4c360f9a8ddbfd306 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:12:22 +0900 Subject: [PATCH 25/72] fix(veryl): retain byte assertion payloads in process kernels --- crates/celox/src/simulator.rs | 4 ++-- crates/celox/src/testbench/kernels.rs | 7 ++++--- crates/celox/tests/component_method.rs | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 48395fe147d..dbe87862710 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -152,7 +152,7 @@ mod host { Finish, /// An assertion of a testbench process held. AssertPass { - message: String, + message: Vec, }, Missed { count: u64, @@ -364,7 +364,7 @@ mod host { } RuntimeEventKind::AssertPass => { if args.is_empty() { - return "assertion passed".to_string(); + return b"assertion passed".to_vec(); } 'x' } diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 810b9fc4b36..b025f10fd13 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -48,7 +48,8 @@ pub(crate) fn run_limited( .map(|assertion| { assertion .message - .clone() + .as_deref() + .map(super::message_diagnostic) .unwrap_or_else(|| "assertion failed".to_string()) }) .collect::>(); @@ -284,7 +285,7 @@ fn drain( }), RuntimeEvent::AssertFatal { message } => { if drained.fatal.is_none() { - drained.fatal = Some(message.clone()); + drained.fatal = Some(super::message_diagnostic(&message)); } assertions.push(AssertionResult { passed: false, @@ -294,7 +295,7 @@ fn drain( } RuntimeEvent::Missed { count } => assertions.push(AssertionResult { passed: false, - message: Some(format!("missed {count} runtime events")), + message: Some(format!("missed {count} runtime events").into_bytes()), location: None, }), RuntimeEvent::Display { message } => forward_display(&message, true), diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index d22f68f43b4..aeffc9c775f 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -3147,7 +3147,7 @@ fn clean_component_calls_do_not_replay_comb_assertions() { result .assertions .iter() - .filter(|a| a.message.as_deref() == Some("comb")) + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) .count() }; assert_eq!(count("c.get(); c.get();"), count("")); From 5443bbe860787a8762399d274d9d55efba2cdd33 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 03:14:37 +0900 Subject: [PATCH 26/72] fix(tests): compare concurrent kernel assertion bytes --- crates/celox/tests/concurrent_initial_runtime.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index bdd3dc4b270..72dc95b35eb 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -871,7 +871,10 @@ fn reset_duration_reads_the_value_before_assertion() { }"#; let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); assert!(detailed.passed, "{detailed:?}"); - assert_eq!(detailed.assertions[0].message.as_deref(), Some("time=6")); + assert_eq!( + detailed.assertions[0].message.as_deref(), + Some(b"time=6".as_slice()) + ); check_passes_on_every_backend(code); } @@ -918,7 +921,10 @@ fn display_and_assertion_arguments_use_process_helper_effects() { let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); assert!(detailed.passed, "{detailed:?}"); assert_eq!(detailed.assertions.len(), 4); - assert_eq!(detailed.assertions[2].message.as_deref(), Some("value=2")); + assert_eq!( + detailed.assertions[2].message.as_deref(), + Some(b"value=2".as_slice()) + ); check_passes_on_every_backend(code); } @@ -1261,7 +1267,7 @@ fn private_assignments_and_event_yields_do_not_replay_clean_comb_logic() { result .assertions .iter() - .filter(|a| a.message.as_deref() == Some("comb")) + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) .count() }; assert_eq!(count("helper();"), count("")); From 97c3e66d7fab6f64df27e730399cb6740e7957af Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 04:01:00 +0900 Subject: [PATCH 27/72] docs(runtime): clarify coincident clock tick accounting --- crates/celox/src/simulation.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index c8063319d04..53feba0f12e 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -706,8 +706,8 @@ impl Simulation { self.state.time() } - /// Rising edges of the clocks processes wait on that the simulation has - /// run so far. + /// Completed process-clock rounds. Coincident rising edges count as + /// one tick against the shared testbench budget. pub fn ticks(&self) -> u64 { self.state.ticks() } @@ -2722,8 +2722,8 @@ mod pending_generated_clock_tests { sim.step().unwrap(); assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); - // B rose once at time zero; both A and B rise at time four. - assert_eq!(sim.ticks(), 3); + // Coincident rising edges count as one completed clock round. + assert_eq!(sim.ticks(), 2); } #[test] fn pending_rises_share_pre_edge_state_with_new_clocks() { From fb246e3c9e8f36f1708d32b562dcbba9faa4af1c Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 05:13:21 +0900 Subject: [PATCH 28/72] fix(runtime): adapt queued event probes to generic kernel slots --- crates/celox-frontend-core/src/process.rs | 4 ++-- crates/celox-runtime/src/simulation.rs | 4 ---- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 5431d716bbf..20fbb563a8d 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -288,7 +288,7 @@ impl ProcessKernelBuilder { let request = self.builder.alloc_bit(PROCESS_DELAY_WIDTH, false); self.builder.emit(SIRInstruction::Load( request, - stable(self.slots.delay.clone()), + self.delay.clone(), SIROffset::Static(0), PROCESS_DELAY_WIDTH, )); @@ -307,7 +307,7 @@ impl ProcessKernelBuilder { let status = self.builder.alloc_bit(PROCESS_STATUS_WIDTH, false); self.builder.emit(SIRInstruction::Load( status, - stable(self.slots.status.clone()), + self.status.clone(), SIROffset::Static(0), PROCESS_STATUS_WIDTH, )); diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index abdb1d1f9d0..d31f6daf426 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -2249,10 +2249,6 @@ impl SimulationState { .map(|(event, count)| (PeriodicEventKey::from_event(&event), count as usize)) .collect(); self.last_clock_values.make_empty(); - self.unknown_clock_values.make_empty(); - for event in parts.unknown_events { - self.unknown_clock_values.insert(event.id()); - } for event in parts.high_events { self.last_clock_values.insert(event.id()); } From a1e2525a6d0aa1e0e746b4f006ae4da4c64539c0 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 05:51:42 +0900 Subject: [PATCH 29/72] fix(runtime): preserve budget-blocked resumptions and verify fatal settle stops --- crates/celox-runtime/src/simulation.rs | 20 ++++++ crates/celox/src/simulation.rs | 71 +++++++++++++++++++ crates/celox/src/simulator/state_file.rs | 2 + .../celox/tests/concurrent_initial_runtime.rs | 33 ++++++++- 4 files changed, 125 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index d31f6daf426..9bee11a4fda 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -296,6 +296,7 @@ pub struct SimulationState { process_event_counters: Vec<(usize, SignalRef, SignalRef)>, active_ff_domains: BitSet, process_wakeups: BinaryHeap, + budget_blocked_processes: BTreeSet, /// Processes suspended at an event or level wait, which their kernels /// re-check whenever the state may have changed. waiting: BTreeSet, @@ -459,6 +460,7 @@ impl SimulationState { process_wakeups: (0..processes.len()) .map(|process| Reverse((0, process))) .collect(), + budget_blocked_processes: BTreeSet::new(), processes, process_event_counters: Vec::new(), active_ff_domains: BitSet::new(), @@ -492,6 +494,12 @@ impl SimulationState { /// run; `None` lifts the limit. pub fn set_tick_budget(&mut self, budget: Option) { self.tick_budget = budget; + if !self.tick_budget_spent() { + for process in std::mem::take(&mut self.budget_blocked_processes) { + self.process_wakeups + .push(Reverse((self.scheduler.time, process))); + } + } } /// Whether the tick budget is spent. @@ -1119,6 +1127,7 @@ impl SimulationState { } } if self.tick_budget_spent() { + self.budget_blocked_processes.insert(process); continue; } ready.push(process); @@ -2039,6 +2048,7 @@ impl SimulationState { last_clock_values: self.last_clock_values.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + budget_blocked_processes: self.budget_blocked_processes.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), @@ -2098,6 +2108,8 @@ impl SimulationState { self.unknown_clock_values .clone_from(&snapshot.unknown_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); + self.budget_blocked_processes + .clone_from(&snapshot.budget_blocked_processes); self.waiting.clone_from(&snapshot.waiting); self.tick_clocks = tick_clocks; self.clock_waits.clone_from(&snapshot.clock_waits); @@ -2130,6 +2142,7 @@ pub struct ScheduleParts { pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, + pub budget_blocked_processes: Vec, /// Processes waiting for an event or a condition, in ascending order. pub waiting_processes: Vec, /// Process clocks that have been waited on. @@ -2143,6 +2156,7 @@ pub struct ScheduleParts { pub done_processes: Vec, /// Rising edges of process clocks so far. pub ticks: u64, + pub tick_budget: Option, /// Timestamp and one-shot clock drives already consumed at that time. pub scheduled_clock_time: u64, pub scheduled_clock_drives: Vec, @@ -2195,6 +2209,7 @@ impl SimulationState { wakeups.sort_unstable(); wakeups }, + budget_blocked_processes: self.budget_blocked_processes.iter().copied().collect(), waiting_processes: self.waiting.iter().copied().collect(), process_clocks: self .tick_clocks @@ -2219,6 +2234,7 @@ impl SimulationState { .collect(), done_processes: self.done.iter().copied().collect(), ticks: self.ticks, + tick_budget: self.tick_budget, scheduled_clock_time: self.scheduled_clock_time, scheduled_clock_drives: self .scheduled_clock_drives @@ -2261,6 +2277,7 @@ impl SimulationState { .into_iter() .map(|(process, time)| Reverse((time, process))) .collect(); + self.budget_blocked_processes = parts.budget_blocked_processes.into_iter().collect(); self.waiting = parts.waiting_processes.into_iter().collect(); self.tick_clocks = parts .process_clocks @@ -2295,6 +2312,7 @@ impl SimulationState { self.pending_releases = parts.pending_releases.into_iter().collect(); self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; + self.tick_budget = parts.tick_budget; self.scheduled_clock_time = parts.scheduled_clock_time; self.scheduled_clock_drives = parts .scheduled_clock_drives @@ -2315,6 +2333,7 @@ pub struct SimulationSnapshot { last_clock_values: BitSet, unknown_clock_values: BitSet, process_wakeups: BinaryHeap, + budget_blocked_processes: BTreeSet, waiting: BTreeSet, tick_clocks: BTreeMap>, clock_waits: BTreeMap, @@ -2338,6 +2357,7 @@ impl Clone for SimulationSnapshot { last_clock_values: self.last_clock_values.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + budget_blocked_processes: self.budget_blocked_processes.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8129c8696b9..49d3841bd28 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -2882,3 +2882,74 @@ mod scheduled_pulse_tests { } } } + +#[cfg(test)] +mod budget_resume_review_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let done = m.output("done", bit).unwrap(); + let delayed = m.output("delayed", bit).unwrap(); + for signal in [q, done, delayed] { + m.set_initial(signal, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let q_target = m.whole(q).unwrap(); + m.register(q_target, one, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(1u8, 64).unwrap()); + let delay = m.constant(Constant::two_state(4u8, 64).unwrap()); + let done_target = m.whole(done).unwrap(); + let delayed_target = m.whole(delayed).unwrap(); + m.process(vec![ + Statement::ClockCycles { clock: clk, count }, + Statement::Assign { + target: done_target, + value: one, + }, + ]) + .unwrap(); + m.process(vec![ + Statement::Delay { amount: delay }, + Statement::Assign { + target: delayed_target, + value: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.state.set_tick_budget(Some(1)); + sim.run_until(4).unwrap(); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("done")), 0u8.into()); + assert_eq!(sim.get(sim.signal("delayed")), 0u8.into()); + assert!(!sim.is_finished()); + let blocked = sim.checkpoint().unwrap(); + for budget in [Some(1), None] { + sim.restore(&blocked).unwrap(); + sim.state.set_tick_budget(budget); + sim.run_until(4).unwrap(); + assert!(sim.state.all_processes_done()); + assert_eq!(sim.get(sim.signal("delayed")), 1u8.into()); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + } + } + #[test] + fn exhausted_budgets_preserve_clock_resumptions_and_unrelated_delays() { + let build = || Simulator::from_frontend(design()); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 0e4c944718a..e14467c70df 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -450,12 +450,14 @@ impl Simulator { .collect(), // State files are rejected for designs with processes. process_wakeups: Vec::new(), + budget_blocked_processes: Vec::new(), waiting_processes: Vec::new(), process_clocks: Vec::new(), clock_waits: Vec::new(), pending_releases: Vec::new(), done_processes: Vec::new(), ticks: 0, + tick_budget: None, scheduled_clock_time: record.time, scheduled_clock_drives: Vec::new(), inactive_processes: Vec::new(), diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 72dc95b35eb..8d11b13eb57 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2,7 +2,7 @@ use celox::testbench::{ compile_initial_testbench, run_compiled_testbench, run_compiled_testbench_to_finish, run_compiled_testbench_with_tick_limit, }; -use celox::{Simulator, TestResult}; +use celox::{SimBackend, Simulator, TestResult}; // These runtime-specific tests use package-local snapshots of the shared suite's // testbench fixtures. Keep them in celox's archive: sibling crate directories @@ -1340,3 +1340,34 @@ fn unselected_constant_case_arms_leave_host_clocks_unchanged() { assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); assert_eq!(sim.get(clk), 1u8.into()); } + +#[test] +fn fatal_settle_stops_the_continuation_and_other_processes() { + let code = r#"#[test(Top)] module Top { + var go: logic; + var marker: u32; + var later: u32; + var observed: u32; + always_comb { observed = marker + later; $assert(go == 0, "fatal settle"); } + initial { go = 1; if go { marker = 1; } $finish(); } + initial { later = 2; } + }"#; + fn check(mut sim: Simulator) { + let testbench = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench(&mut sim, &testbench); + assert!( + matches!(&result, TestResult::Fail(message) if message.contains("fatal settle")), + "{result:?}" + ); + let marker = sim.signal("marker"); + assert_eq!(sim.backend_ref().get(marker), 0u8.into()); + let later = sim.signal("later"); + assert_eq!(sim.backend_ref().get(later), 0u8.into()); + } + let build = || Simulator::builder(code, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} From 5d0fad36e18328cc7a2ba3c0887595ac025f1385 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 07:38:21 +0900 Subject: [PATCH 30/72] test(runtime): distinguish retained and legacy unknown edge metadata --- crates/celox/tests/state_file.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/celox/tests/state_file.rs b/crates/celox/tests/state_file.rs index eb705119c9d..6316844285d 100644 --- a/crates/celox/tests/state_file.rs +++ b/crates/celox/tests/state_file.rs @@ -552,7 +552,10 @@ fn timed_state_files_preserve_unknown_edge_detection_baselines() { source.settle().unwrap(); let expected = source.get(q) + 1u8; let file = through_bytes(&source.save_state().unwrap()); - assert_eq!(file.schedule.as_ref().unwrap().unknown_events, ["clk"]); + assert_eq!( + file.schedule.as_ref().unwrap().unknown_events, + Some(vec!["clk".to_owned()]) + ); let mut restored = builder(); restored.load_state(&file).unwrap(); let clk = restored.signal("clk"); From 19b198be59096412bc22dc32011e0c06356c1f03 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:08:33 +0900 Subject: [PATCH 31/72] fix(veryl): execute file requests and reset automatic kernel storage --- crates/celox-design/src/lib.rs | 43 +++- .../celox-frontend-veryl/src/lowering/ff.rs | 1 + .../src/lowering/ff/function_call.rs | 4 +- .../src/lowering/ff/inline_call.rs | 15 +- .../src/lowering/process.rs | 192 +++++++++++++++--- .../src/lowering/process/expressions.rs | 15 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulator.rs | 41 ++++ crates/celox/src/testbench/kernels.rs | 97 ++++++++- .../celox/tests/concurrent_initial_runtime.rs | 131 ++++++++++++ 10 files changed, 503 insertions(+), 38 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index a3ceaa5dd05..b9202d7e0c1 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -372,7 +372,10 @@ impl HostValue { #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum HostRequest { /// Seed the random stream `handle` from `value`. - RandomSeed { handle: String, value: HostValue }, + RandomSeed { + handle: String, + value: HostValue, + }, /// A random value of the result's width from the stream `handle`. RandomGet { handle: String, @@ -403,11 +406,49 @@ pub enum HostRequest { /// expression form of the call carries at most 64 bits. strict: bool, }, + /// Open a testbench file, replacing any previously open file of this handle. + FileOpen { + handle: String, + path: HostValue, + append: bool, + }, + /// Write formatted bytes to an open testbench file, without a newline. + FileWrite { + handle: String, + template: Option, + args: Vec>, + }, + FileFlush { + handle: String, + }, + FileClose { + handle: String, + }, } impl HostRequest { pub fn map(self, mut map: impl FnMut(A) -> B) -> HostRequest { match self { + Self::FileOpen { + handle, + path, + append, + } => HostRequest::FileOpen { + handle, + path: path.map(&mut map), + append, + }, + Self::FileWrite { + handle, + template, + args, + } => HostRequest::FileWrite { + handle, + template, + args: args.into_iter().map(|arg| arg.map(&mut map)).collect(), + }, + Self::FileFlush { handle } => HostRequest::FileFlush { handle }, + Self::FileClose { handle } => HostRequest::FileClose { handle }, Self::RandomSeed { handle, value } => HostRequest::RandomSeed { handle, value: value.map(&mut map), diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 25360be4a91..6ac8364916b 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -337,6 +337,7 @@ mod expression; pub(crate) use expression::expression_has_side_effect; mod function_call; mod inline_call; +pub(crate) use inline_call::collect_statement_variables; pub enum Domain { Ff, // TODO: add clock diff --git a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs index a7c82db7d33..ad8d7a230e5 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs @@ -723,7 +723,7 @@ impl<'a> FfParser<'a> { ) } - pub(super) fn coerce_function_input_expression( + pub(crate) fn coerce_function_input_expression( &self, expr: Expression, formal_id: VarId, @@ -1760,7 +1760,7 @@ impl<'a> FfParser<'a> { } } - pub(super) fn coerce_register_to_variable_type( + pub(crate) fn coerce_register_to_variable_type( &self, reg: RegisterId, var_id: VarId, diff --git a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs index a08dbca3271..c2785543241 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs @@ -543,7 +543,7 @@ impl<'a> FfParser<'a> { } } -fn collect_statement_variables(statements: &[Statement], out: &mut HashSet) { +pub(crate) fn collect_statement_variables(statements: &[Statement], out: &mut HashSet) { for statement in statements { match statement { Statement::Assign(assign) => { @@ -593,10 +593,15 @@ fn collect_statement_variables(statements: &[Statement], out: &mut HashSet collect_system_call_variables(call, out), Statement::FunctionCall(call) => collect_call_variables(call, out), - Statement::TbMethodCall(_) - | Statement::Break - | Statement::Unsupported(_) - | Statement::Null => {} + Statement::TbMethodCall(tb) => { + for expr in crate::lowering::process::expressions::statement_inputs(statement) { + collect_expression_variables(expr, out); + } + if let Some(destination) = tb.ret.as_deref() { + collect_destination_variables(destination, out); + } + } + Statement::Break | Statement::Unsupported(_) | Statement::Null => {} } } } diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 626511b0af5..4e23e1d7e9b 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -42,7 +42,7 @@ use crate::{ }; use celox_frontend_core::ScheduledRtl; -mod expressions; +pub(crate) mod expressions; use veryl_parser::token_range::TokenRange; type SourceAddr = AbsoluteAddrBase; @@ -71,7 +71,7 @@ pub struct BlockStorage { /// the function. pub private: HashMap, /// Values preserved while nested expression calls suspend. - pub expression_values: HashMap, + pub expression_values: HashMap, } /// The hidden state of a module's `initial` blocks, in declaration order. @@ -162,11 +162,13 @@ pub(crate) fn declare_storage( ir, statements, &mut HashSet::default(), + None, &mut expression_needs, ); let mut expression_needs = expression_needs.into_iter().collect::>(); - expression_needs.sort_by_key(|(token, _)| { + expression_needs.sort_by_key(|((frame, token), _)| { ( + frame.clone(), token .beg .source @@ -252,6 +254,7 @@ fn constant_truth(expr: &Expression) -> Option { } type FunctionKey = (VarId, Option>); +type ExpressionStorageKey = (Option, TokenRange); fn function_key(call: &veryl_analyzer::ir::FunctionCall) -> FunctionKey { (call.id, call.index.clone()) } @@ -486,29 +489,43 @@ fn collect_expression_storage( ir: &Module, statements: &[Statement], active: &mut HashSet, - values: &mut HashMap, + frame: Option, + values: &mut HashMap, ) { fn expr( ir: &Module, value: &Expression, active: &mut HashSet, - values: &mut HashMap, + frame: Option, + values: &mut HashMap, ) { if expressions::has_call(value) { - values.insert(value.token_range(), expressions::storage_width(value)); + values.insert( + (frame.clone(), value.token_range()), + expressions::storage_width(value), + ); for child in expressions::children(value) { - values.insert(child.token_range(), expressions::storage_width(child)); + values.insert( + (frame.clone(), child.token_range()), + expressions::storage_width(child), + ); } } for child in expressions::children(value) { - expr(ir, child, active, values); + expr(ir, child, active, frame.clone(), values); } if let Expression::Term(factor) = value && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() && active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { - collect_expression_storage(ir, &body.statements, active, values); + collect_expression_storage( + ir, + &body.statements, + active, + Some(function_key(call)), + values, + ); } active.remove(&function_key(call)); } @@ -517,15 +534,18 @@ fn collect_expression_storage( let inputs = expressions::statement_inputs(statement); if inputs.iter().any(|expr| expressions::has_call(expr)) { for input in &inputs { - values.insert(input.token_range(), expressions::storage_width(input)); + values.insert( + (frame.clone(), input.token_range()), + expressions::storage_width(input), + ); } } for value in inputs { - expr(ir, value, active, values); + expr(ir, value, active, frame.clone(), values); } if let Statement::Case(stmt) = statement { values.insert( - stmt.case_target.token_range(), + (frame.clone(), stmt.case_target.token_range()), expressions::storage_width(&stmt.case_target), ); } @@ -533,19 +553,28 @@ fn collect_expression_storage( && call.inputs.values().any(expressions::has_call) { for input in call.inputs.values() { - values.insert(input.token_range(), expressions::storage_width(input)); + values.insert( + (frame.clone(), input.token_range()), + expressions::storage_width(input), + ); } } if let Statement::FunctionCall(call) = statement && active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { - collect_expression_storage(ir, &body.statements, active, values); + collect_expression_storage( + ir, + &body.statements, + active, + Some(function_key(call)), + values, + ); } active.remove(&function_key(call)); } for body in expressions::statement_bodies(statement) { - collect_expression_storage(ir, body, active, values); + collect_expression_storage(ir, body, active, frame.clone(), values); } } } @@ -670,6 +699,16 @@ fn collect_scratch_needs( } } Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::FileOpen { name, .. } => need(needs, "file_arg", argument_width(name)), + TbMethod::FileWrite { args } => { + let skip = usize::from( + args.first() + .is_some_and(|arg| FfParser::static_string_expr(&arg.0).is_some()), + ); + for arg in &args[skip..] { + need(needs, "file_arg", argument_width(arg)); + } + } TbMethod::RandomSeed { .. } => need(needs, "random_seed", 64), TbMethod::RandomGet { width, .. } => { need(needs, "random_value", (*width as usize).max(1)); @@ -694,8 +733,6 @@ fn collect_scratch_needs( } TbMethod::ClockNext { .. } | TbMethod::ResetAssert { .. } - | TbMethod::FileOpen { .. } - | TbMethod::FileWrite { .. } | TbMethod::FileClose | TbMethod::FileFlush => {} }, @@ -766,7 +803,7 @@ struct BlockLowering<'a> { module_id: celox_design::ModuleId, hierarchical: HashMap, private: HashMap, - expression_values: HashMap, + expression_values: HashMap, scratch: Vec<(ScratchNeed, SourceVarId)>, clocks: Vec<(StrId, ProcessClock)>, releases: Vec>, @@ -774,6 +811,7 @@ struct BlockLowering<'a> { clock_periods: &'a HashMap, resource_prefix: String, active_functions: HashSet, + expression_frame: Option, site_base: u32, targets: Vec>, sources: Vec>, @@ -877,6 +915,7 @@ fn lower_block( clock_periods: &source.clock_periods, resource_prefix, active_functions: HashSet::default(), + expression_frame: None, site_base, targets: Vec::new(), sources: Vec::new(), @@ -2668,7 +2707,11 @@ impl<'a> BlockLowering<'a> { let freeze = inputs.iter().any(|(_, expr)| expressions::has_call(expr)); let mut values = Vec::new(); for (path, expr) in &inputs { - let value = self.expression(expr)?; + let actual = body.arg_map.get(*path).map(|formal| { + self.parser + .coerce_function_input_expression((*expr).clone(), *formal) + }); + let value = self.expression(actual.as_ref().unwrap_or(expr))?; if freeze { self.save_expression(expr, value)?; } @@ -2681,6 +2724,33 @@ impl<'a> BlockLowering<'a> { Some(&call.comptime.token), )); } + let mut storage = HashSet::default(); + super::ff::collect_statement_variables(&body.statements, &mut storage); + storage.extend(body.arg_map.values().copied()); + storage.extend(body.ret); + let mut storage = storage + .into_iter() + .filter(|id| self.ir.variables[id].affiliation == Affiliation::Function) + .collect::>(); + storage.sort(); + for id in storage { + let variable = &self.ir.variables[&id]; + let width = resolve_total_width(self.ir, variable)?.max(1); + let two_state = variable.r#type.is_2state(); + let builder = self.kernel.builder(); + let reg = if two_state { + builder.alloc_bit(width, variable.r#type.signed) + } else { + builder.alloc_logic(width) + }; + let value = if two_state { + SIRValue::new(0u8) + } else { + SIRValue::new_four_state(0u8, (BigUint::from(1u8) << width) - BigUint::from(1u8)) + }; + builder.emit(SIRInstruction::Imm(reg, value)); + self.store(&self.destination(id, call.comptime.token), reg)?; + } for (path, expr, value) in values { if let Some(&formal) = body.arg_map.get(path) { let value = if freeze { @@ -2688,11 +2758,20 @@ impl<'a> BlockLowering<'a> { } else { value }; + let value = self.parser.coerce_register_to_variable_type( + value, + formal, + expression_signed(expr), + self.kernel.builder(), + )?; let destination = self.destination(formal, call.comptime.token); self.store(&destination, value)?; } } - let flow = self.lower_statements(&body.statements)?; + let previous_frame = self.expression_frame.replace(function_key(call)); + let flow = self.lower_statements(&body.statements); + self.expression_frame = previous_frame; + let flow = flow?; self.active_functions.remove(&function_key(call)); if let Flow::Ended = flow { return Ok(Flow::Ended); @@ -2714,6 +2793,38 @@ impl<'a> BlockLowering<'a> { Ok(Flow::Continue) } + fn file_argument( + &mut self, + arg: &SystemFunctionInput, + ) -> Result, ParserError> { + let width = argument_width(arg); + let signed = expression_signed(&arg.0); + let (mut value, slot) = self.host_scratch( + "file_arg", + width, + signed, + arg.0.comptime().r#type.is_string(), + )?; + let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { + if text.is_empty() { + value.width = 0; + } + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm( + reg, + SIRValue::new(BigUint::from_bytes_be(text.as_bytes())), + )); + reg + } else { + let reg = self.expression(&arg.0)?; + self.parser + .cast_reg_width_ext(self.kernel.builder(), reg, width, signed) + }; + self.store_scratch(slot, width, reg); + Ok(value) + } + fn lower_tb_method(&mut self, tb: &TbMethodCall) -> Result { match &tb.method { TbMethod::ClockNext { count, .. } => { @@ -2934,10 +3045,43 @@ impl<'a> BlockLowering<'a> { } Ok(Flow::Continue) } - TbMethod::FileOpen { .. } - | TbMethod::FileWrite { .. } - | TbMethod::FileClose - | TbMethod::FileFlush => Ok(Flow::Continue), + TbMethod::FileOpen { name, append } => { + let path = self.file_argument(name)?; + self.host_request(HostRequest::FileOpen { + handle: self.resource_name(tb.inst), + path, + append: *append, + })?; + Ok(Flow::Continue) + } + TbMethod::FileWrite { args } => { + let template = args + .first() + .and_then(|arg| FfParser::static_string_expr(&arg.0)); + let skip = usize::from(template.is_some()); + let mut values = Vec::new(); + for arg in &args[skip..] { + values.push(self.file_argument(arg)?); + } + self.host_request(HostRequest::FileWrite { + handle: self.resource_name(tb.inst), + template, + args: values, + })?; + Ok(Flow::Continue) + } + TbMethod::FileClose => { + self.host_request(HostRequest::FileClose { + handle: self.resource_name(tb.inst), + })?; + Ok(Flow::Continue) + } + TbMethod::FileFlush => { + self.host_request(HostRequest::FileFlush { + handle: self.resource_name(tb.inst), + })?; + Ok(Flow::Continue) + } } } } diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index cb3b2eb66dd..14b04851e30 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -77,7 +77,7 @@ pub(super) fn has_call(expr: &Expression) -> bool { matches!(expr, Expression::Term(factor) if matches!(factor.as_ref(),Factor::FunctionCall(_))) || children(expr).into_iter().any(has_call) } -pub(super) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { +pub(crate) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { match statement { Statement::Assign(assign) => std::iter::once(&assign.expr) .chain( @@ -129,6 +129,8 @@ pub(super) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { TbMethod::ResetAssert { duration, .. } => duration.iter().collect(), TbMethod::RandomSeed { value, .. } => vec![value], TbMethod::RandomGetRange { min, max, .. } => vec![min, max], + TbMethod::FileOpen { name, .. } => vec![&name.0], + TbMethod::FileWrite { args } => args.iter().map(|arg| &arg.0).collect(), TbMethod::Component { args, .. } => args.iter().map(|arg| &arg.0).collect(), _ => Vec::new(), }; @@ -248,7 +250,7 @@ impl BlockLowering<'_> { ) -> Result<(), ParserError> { let (width, id) = self .expression_values - .get(&expr.token_range()) + .get(&(self.expression_frame.clone(), expr.token_range())) .copied() .ok_or_else(|| { self.error( @@ -267,7 +269,8 @@ impl BlockLowering<'_> { Ok(()) } pub(super) fn saved_expression(&mut self, expr: &Expression) -> RegisterId { - let (width, id) = self.expression_values[&expr.token_range()]; + let (width, id) = + self.expression_values[&(self.expression_frame.clone(), expr.token_range())]; let builder = self.kernel.builder(); let value = if expr.comptime().r#type.is_2state() { builder.alloc_bit(width, expression_signed(expr)) @@ -291,8 +294,12 @@ impl BlockLowering<'_> { expr: &Expression, values: HashMap, ) -> Result { + // The bound children are runtime results. Analyzer constant values + // of a compound call expression cannot replace those results. + let mut evaluated = expr.clone(); + evaluated.comptime_mut().is_const = false; self.parser.push_process_expression_values(values); - let result = self.raw_expression(expr); + let result = self.raw_expression(&evaluated); self.parser.pop_process_expression_values(); result } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 09a5bea0070..bf56d0ffba8 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -7,7 +7,7 @@ use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; // Version 19 adds the drain-only kernel status to the runtime protocol. -const CONTAINER_VERSION: u16 = 19; +const CONTAINER_VERSION: u16 = 20; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index bf3df8600e9..cbe24815b81 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -107,6 +107,7 @@ mod host { pub(crate) component_simulation: Option>, /// The random number generators of a running kernel testbench. pub(crate) testbench_random: Option, + pub(crate) testbench_files: Option, /// Runtime events of a running kernel testbench the executor took /// out of the ring when a kernel yielded, until the runner drains /// them. @@ -373,6 +374,45 @@ mod host { } } + pub(crate) fn render_host_message( + sim: &Simulator, + template: Option, + args: &[celox_design::HostValue], + time: u64, + ) -> Vec { + let values = args + .iter() + .map(|arg| { + let signal = sim.backend.resolve_signal(&arg.signal); + let (value, mask) = sim.backend.get_four_state(signal); + RuntimeEventArgValue { + values: value.to_u64_digits(), + masks: mask.to_u64_digits(), + width: arg.width, + signed: arg.signed, + is_string: arg.is_string, + } + }) + .collect::>(); + render_runtime_event_message( + &RuntimeEventSite { + kind: RuntimeEventKind::Write, + template, + sizing: DisplaySizing::Veryl, + scope: None, + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + location: None, + }, + &values, + RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }, + ) + } + fn render_runtime_event_message( site: &RuntimeEventSite, args: &[RuntimeEventArgValue], @@ -726,6 +766,7 @@ mod host { components: Default::default(), component_simulation: None, testbench_random: None, + testbench_files: None, testbench_events: Vec::new(), runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_finish_state: Arc::new(Mutex::new(RuntimeFinishState::default())), diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index b025f10fd13..3f3ed59d1ea 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -18,6 +18,21 @@ use celox_design::{HostRequest, HostValue}; use num_bigint::BigUint; use num_traits::ToPrimitive as _; +pub(crate) struct FileTable { + files: crate::HashMap, + base: Option, +} + +impl FileTable { + fn flush(&mut self) -> Result<(), String> { + use std::io::Write; + for file in self.files.values_mut() { + file.flush().map_err(|error| error.to_string())?; + } + Ok(()) + } +} + /// Whether the simulator's testbench runs as process kernels: the schema /// marks them (a design's own processes alone do not make a kernel /// testbench). @@ -131,6 +146,10 @@ fn run( } apply_component_writes(sim, initial_writes); sim.testbench_random = Some(RandomTable::new(seed)); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: testbench.component_file_base().map(|base| base.to_owned()), + }); // A run starts every process at its beginning, whatever an earlier run // of the same simulator left in the control slots, and every process // clock low, as the bytecode testbench does: the first `clk.next()` @@ -155,6 +174,7 @@ fn run( // The components were installed above; take them down again. let _ = sim.components.finish(0); sim.testbench_random = None; + sim.testbench_files = None; return failed(error.to_string()); } sim.dirty = false; @@ -213,6 +233,13 @@ fn run( } } sim.testbench_random = None; + if let Some(mut files) = sim.testbench_files.take() + && let Err(message) = files.flush() + && error.is_none() + { + error = Some(message); + } + // A completion a component requested is read before the teardown // clears the components. let component_finished = sim.components.finish_requested(); @@ -228,7 +255,11 @@ fn run( finished, ticks: state.ticks(), tick_limit_reached: tick_limit.is_some_and(|limit| state.ticks() >= limit) - && !state.all_processes_done() + && !sim + .program + .runtime_schema + .testbench_kernels + .is_some_and(|first| state.processes_done_from(first)) && !finished, } } @@ -321,7 +352,71 @@ pub(crate) fn serve_host_request( .and_then(|slots| slots.host_requests.get(request)) .cloned() .ok_or_else(|| format!("process {process} made unknown host request {request}"))?; + let close_file = matches!(request, HostRequest::FileClose { .. }); match request { + HostRequest::FileOpen { + handle, + path, + append, + } => { + let bytes = read(sim, &path).to_bytes_be(); + let path = String::from_utf8(bytes) + .map_err(|error| format!("testbench file path: {error}"))?; + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + let path = match &files.base { + Some(base) => base.join(path), + None => path.into(), + }; + let file = std::fs::OpenOptions::new() + .create(true) + .write(true) + .append(append) + .truncate(!append) + .open(&path) + .map_err(|error| format!("testbench file {}: {error}", path.display()))?; + if let Some(mut previous) = files.files.insert(handle, file) { + use std::io::Write; + previous.flush().map_err(|error| error.to_string())?; + } + } + HostRequest::FileWrite { + handle, + template, + args, + } => { + use std::io::Write; + let bytes = crate::simulator::render_host_message(sim, template, &args, time); + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + files + .files + .get_mut(&handle) + .ok_or_else(|| format!("testbench file {handle} is not open"))? + .write_all(&bytes) + .map_err(|error| error.to_string())?; + } + HostRequest::FileFlush { handle } | HostRequest::FileClose { handle } => { + use std::io::Write; + + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + let file = files + .files + .get_mut(&handle) + .ok_or_else(|| format!("testbench file {handle} is not open"))?; + file.flush().map_err(|error| error.to_string())?; + if close_file { + files.files.remove(&handle); + } + } + HostRequest::RandomSeed { handle, value } => { let seed = read(sim, &value).to_u64().unwrap_or(u64::MAX); random(sim)?.seed(&handle, seed); diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 8d11b13eb57..17ebe0cc847 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1371,3 +1371,134 @@ fn fatal_settle_stops_the_continuation_and_other_processes() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(build().build_native().unwrap()); } + +#[test] +fn automatic_function_storage_is_reset_on_every_call() { + let code = r#"#[test(Top)] module Top(value:output logic<8>,out:output logic<8>) { + function only_zero(x:input u32, o:output logic<8>) -> logic<8> { + var tmp:logic<8>; + if x==0 { tmp=7; o=tmp; return tmp; } + o=tmp; + } + initial {value=only_zero(0,out);value=only_zero(5,out);$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + for name in ["value", "out"] { + assert_eq!( + sim.get_four_state(sim.signal(name)).1, + 255u8.into(), + "{name}" + ); + } + } + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_native() + .unwrap(), + ); +} + +#[test] +fn specialized_helpers_preserve_expression_storage() { + let code = r#"#[test(Top)] module Top(a:output u32,b:output u32) { + function leaf(x:input u32) -> u32 {return x+20;} + function helper::(x:input logic) -> u32 {return x*10+leaf(x);} + initial {a=helper::<2>(2);b=helper::<1>(1);$assert(helper::<2>(2)==42,"two");$assert(helper::<1>(1)==31,"one");$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("a")), 42u8.into(), "a"); + assert_eq!(sim.get(sim.signal("b")), 31u8.into(), "b"); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn file_methods_execute_and_evaluate_arguments() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("kernel.txt"); + let code = format!( + r#"#[test(Top)] module Top {{ + var f:$tb::file; var calls:u32; + function value()->u32 {{calls+=1;return 42;}} + function emit() {{f.write("value=%d",value());}} + initial {{calls=0;f.open("{}");emit();f.flush();f.close(); + f.append("{}");f.write("!");f.close();$assert(calls==1);$finish();}} + }}"#, + path.display(), + path.display() + ); + fn check(mut sim: Simulator, path: &std::path::Path) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"value=42!"); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top").build_cranelift().unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top").build_wasm().unwrap(), + &path, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top").build_native().unwrap(), + &path, + ); +} + +#[test] +fn file_io_failures_stop_later_kernel_effects() { + let code = r#"#[test(Top)] module Top(after:output u32) {var f:$tb::file;initial {f.write("closed");after=1;$finish();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_to_finish(&mut sim, &tb); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("not open")), + "{result:?}" + ); + assert_eq!(sim.get(sim.signal("after")), 0u8.into()); +} From a8e172e8c9173ba3f13b19553a92ff0aa7ec54b6 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:10:07 +0900 Subject: [PATCH 32/72] test(veryl): preserve file requests through native image roundtrips --- .../celox/tests/concurrent_initial_runtime.rs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 17ebe0cc847..d89be2e94d4 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1490,6 +1490,33 @@ fn file_methods_execute_and_evaluate_arguments() { ); } +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn native_images_preserve_file_host_requests() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("image.txt"); + let code = format!( + r#"#[test(Top)] module Top {{var f:$tb::file;initial{{f.open("{}");f.write("image");f.flush();f.close();$finish();}}}}"#, + path.display() + ); + let original = Simulator::builder(&code, "Top").build_native().unwrap(); + let bytes = original + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + let mut sim = Simulator::builder("invalid", "unused") + .build_native_from_image(image) + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"image"); +} + #[test] fn file_io_failures_stop_later_kernel_effects() { let code = r#"#[test(Top)] module Top(after:output u32) {var f:$tb::file;initial {f.write("closed");after=1;$finish();}}"#; From 78471465150fa0cef5257b323a8e28b1435d3c7d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 08:32:44 +0900 Subject: [PATCH 33/72] fix(veryl): retain four-state process argument storage and X defaults --- .../src/lowering/process.rs | 87 +++++++++++-------- .../celox/tests/concurrent_initial_runtime.rs | 54 +++++++++++- 2 files changed, 102 insertions(+), 39 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 4e23e1d7e9b..33de8e0645e 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -115,36 +115,41 @@ pub(crate) fn declare_storage( .collect::>(); event_variables.sort_unstable(); let mut next = variables.len() as u32; - let mut declare = |path: Vec, template: Option<&SymbolicVariable>, width: usize| { - let id = SourceVarId(next); - next += 1; - let variable = match template { - Some(template) => SymbolicVariable { - path, - source: None, - module_affiliated: false, - ..template.clone() - }, - None => SymbolicVariable { - path, - kind: VariableKind::Variable, - signed: false, - metadata: VariableMetadata { - width, - is_4state: false, - kind: celox_design::DomainKind::Other, - type_kind: PortTypeKind::Bit, - array_dims: Vec::new(), + let mut declare = + |path: Vec, template: Option<&SymbolicVariable>, width: usize, is_4state: bool| { + let id = SourceVarId(next); + next += 1; + let variable = match template { + Some(template) => SymbolicVariable { + path, + source: None, + module_affiliated: false, + ..template.clone() }, - packed_dims: vec![width], - source: None, - // Hidden state is not a signal of the design. - module_affiliated: false, - }, + None => SymbolicVariable { + path, + kind: VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state, + kind: celox_design::DomainKind::Other, + type_kind: if is_4state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }, + array_dims: Vec::new(), + }, + packed_dims: vec![width], + source: None, + // Hidden state is not a signal of the design. + module_affiliated: false, + }, + }; + variables.insert(id, variable); + id }; - variables.insert(id, variable); - id - }; let mut blocks = Vec::new(); for (index, statements) in initial_blocks(ir).enumerate() { let name = |slot: &str| vec![format!("$initial[{index}]"), slot.to_string()]; @@ -153,7 +158,12 @@ pub(crate) fn declare_storage( .into_iter() .enumerate() .map(|(slot, need)| { - let id = declare(name(&format!("{}@{slot}", need.purpose)), None, need.width); + let id = declare( + name(&format!("{}@{slot}", need.purpose)), + None, + need.width, + need.purpose == "file_arg", + ); (need, id) }) .collect(); @@ -184,7 +194,7 @@ pub(crate) fn declare_storage( .into_iter() .enumerate() .map(|(slot, (token, width))| { - let id = declare(name(&format!("expression@{slot}")), None, width); + let id = declare(name(&format!("expression@{slot}")), None, width, true); (token, (width, id)) }) .collect(); @@ -192,15 +202,15 @@ pub(crate) fn declare_storage( .iter() .map(|(local, template)| { let path = name(&format!("{}@private", template.path.join("."))); - (*local, declare(path, Some(template), 0)) + (*local, declare(path, Some(template), 0, false)) }) .collect(); blocks.push(BlockStorage { - resume: declare(name("resume"), None, PROCESS_RESUME_WIDTH), - status: declare(name("status"), None, PROCESS_STATUS_WIDTH), - delay: declare(name("delay"), None, PROCESS_DELAY_WIDTH), - clock: declare(name("clock"), None, PROCESS_CLOCK_WIDTH), - release: declare(name("release"), None, PROCESS_RELEASE_WIDTH), + resume: declare(name("resume"), None, PROCESS_RESUME_WIDTH, false), + status: declare(name("status"), None, PROCESS_STATUS_WIDTH, false), + delay: declare(name("delay"), None, PROCESS_DELAY_WIDTH, false), + clock: declare(name("clock"), None, PROCESS_CLOCK_WIDTH, false), + release: declare(name("release"), None, PROCESS_RELEASE_WIDTH, false), event_counters: event_variables .iter() .map(|&var| { @@ -210,11 +220,13 @@ pub(crate) fn declare_storage( name(&format!("event_rises@{}", ids[&var].0)), None, celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, ), declare( name(&format!("event_falls@{}", ids[&var].0)), None, celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, ), ) }) @@ -2746,7 +2758,8 @@ impl<'a> BlockLowering<'a> { let value = if two_state { SIRValue::new(0u8) } else { - SIRValue::new_four_state(0u8, (BigUint::from(1u8) << width) - BigUint::from(1u8)) + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + SIRValue::new_four_state(mask.clone(), mask) }; builder.emit(SIRInstruction::Imm(reg, value)); self.store(&self.destination(id, call.comptime.token), reg)?; diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index d89be2e94d4..0b923d128a3 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1390,8 +1390,8 @@ fn automatic_function_storage_is_reset_on_every_call() { ); for name in ["value", "out"] { assert_eq!( - sim.get_four_state(sim.signal(name)).1, - 255u8.into(), + sim.get_four_state(sim.signal(name)), + (255u8.into(), 255u8.into()), "{name}" ); } @@ -1529,3 +1529,53 @@ fn file_io_failures_stop_later_kernel_effects() { ); assert_eq!(sim.get(sim.signal("after")), 0u8.into()); } + +#[test] +fn file_arguments_preserve_unknown_automatic_values() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("mask.txt"); + let code = format!( + r#"#[test(Top)] module Top {{var f:$tb::file; + function emit() {{var value:logic<8>;f.write("%h",value);}} + initial{{f.open("{}");emit();f.flush();f.close();$finish();}} + }}"#, + path.display() + ); + fn check(mut sim: Simulator, path: &std::path::Path) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"xx"); + } + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_interpreter() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_cranelift() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_wasm() + .unwrap(), + &path, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_native() + .unwrap(), + &path, + ); +} From 1a8c05781e42a5aa7109f89d8a07a500acb87c14 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 09:40:52 +0900 Subject: [PATCH 34/72] fix(veryl): preserve dynamic assertion messages and settle event yields once --- .../src/lowering/process.rs | 56 +++++++++- crates/celox/src/testbench/kernels.rs | 103 +++++++++++++++++- .../celox/tests/concurrent_initial_runtime.rs | 61 +++++++++++ 3 files changed, 214 insertions(+), 6 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 33de8e0645e..fbf0490ff9a 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -605,6 +605,13 @@ fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result { /// gave the host a chance to drain them (see /// [`BlockLowering::yield_for_runtime_event`]). event_yield: Option, + /// Runtime branch state: the most recent event yield already settled a write. + event_yield_clean: Option, event_counters: HashMap, } @@ -933,6 +942,7 @@ fn lower_block( sources: Vec::new(), dirty: false, event_yield: None, + event_yield_clean: None, event_counters: storage .event_counters .iter() @@ -941,6 +951,7 @@ fn lower_block( }; if contains_runtime_event(ir, statements, &mut HashSet::default()) { lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); + lowering.event_yield_clean = Some(lowering.take_scratch("event_yield_clean", 1)?.1); } lowering.declare_clocks(statements); // A block that ends right after a store settles, so a process that runs @@ -1594,7 +1605,7 @@ impl<'a> BlockLowering<'a> { })?; } if !self.private.contains_key(&destination.id) { - self.dirty = true; + self.mark_dirty(); } let counters = self.event_counters.get(&destination.id).copied(); let before = if counters.is_some() { @@ -1697,15 +1708,46 @@ impl<'a> BlockLowering<'a> { } } + fn mark_dirty(&mut self) { + self.dirty = true; + if let Some(slot) = self.event_yield_clean { + let zero = self.constant(0, 1); + self.store_scratch(slot, 1, zero); + } + } + /// Settle the combinational logic before a read of design state that /// follows a store, as the statements of a testbench are sequential. fn settle_if_dirty(&mut self) -> Result<(), ParserError> { if !self.dirty { return Ok(()); } + let after = if let Some(slot) = self.event_yield_clean { + let clean = self.load_scratch(slot, 1, false); + let builder = self.kernel.builder(); + let settle = builder.new_block(); + let after = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: clean, + true_block: (after, Vec::new()), + false_block: (settle, Vec::new()), + }); + builder.switch_to_block(settle); + Some(after) + } else { + None + }; self.kernel .settle() .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + if let Some(after) = after { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(after); + let zero = self.constant(0, 1); + self.store_scratch(self.event_yield_clean.unwrap(), 1, zero); + } self.suspended(); Ok(()) } @@ -2492,7 +2534,7 @@ impl<'a> BlockLowering<'a> { self.lower_assert(call, *kind, cond, args) } SystemFunctionKind::Readmemh(_, SystemFunctionOutput::Local(_)) => { - self.dirty = true; + self.mark_dirty(); self.system_task(call) } SystemFunctionKind::Readmemh(filename, SystemFunctionOutput::Hier(reference)) => { @@ -2518,7 +2560,7 @@ impl<'a> BlockLowering<'a> { ), comptime: call.comptime.clone(), }; - self.dirty = true; + self.mark_dirty(); self.system_task(&local) } SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => { @@ -2679,12 +2721,16 @@ impl<'a> BlockLowering<'a> { }; yielded .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + if dirty && let Some(slot) = self.event_yield_clean { + let one = self.constant(1, 1); + self.store_scratch(slot, 1, one); + } self.kernel .builder() .seal_block(SIRTerminator::Jump(after, Vec::new())); self.kernel.builder().switch_to_block(after); - // Registers do not survive the yield path; the dirty state is the - // one before it, as the other path kept it. + // Registers do not survive the yield path. The static dirty state + // includes the keep path; scratch distinguishes its runtime state. self.parser.clear_register_cache(); self.dirty = dirty; Ok(()) diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 3f3ed59d1ea..75e3ab4b7d9 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -305,7 +305,7 @@ fn drain( passed: true, message: site .and_then(|id| sim.program.runtime_schema.runtime_event_sites.get(id)) - .and_then(|site| site.template.as_ref()) + .filter(|site| site.template.is_some() || !site.arg_widths.is_empty()) .map(|_| message), location, }), @@ -528,3 +528,104 @@ fn write( let mask = (BigUint::from(1u8) << target.width) - BigUint::from(1u8); sim.backend.set_wide(signal, value & mask); } + +#[cfg(test)] +mod event_yield_settle_tests { + use super::*; + use crate::RuntimeErrorCode; + use celox_runtime::SimulationExecutor; + + struct CountingExecutor { + sim: Simulator, + settles: usize, + } + impl SimulationExecutor for CountingExecutor { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::run_process(&mut self.sim, index, time)?; + let slot = self.sim.program.runtime_schema.processes[index].status; + let signal = self.sim.backend.resolve_signal(&slot); + if celox_design::ProcessStatus::from_code(self.sim.backend.get_as(signal)) + == Some(celox_design::ProcessStatus::Settle) + { + self.settles += 1; + } + Ok(()) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn finish_requested(&mut self, time: u64) -> bool { + SimulationExecutor::finish_requested(&mut self.sim, time) + } + } + fn count(mut sim: Simulator, iterations: usize) -> usize { + let limit = sim.signal("limit"); + sim.modify(|io| { + io.set(limit, iterations as u32); + }) + .unwrap(); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { sim, settles: 0 }; + for _ in 0..10000 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + return executor.settles; + } + } + panic!("process did not finish"); + } + #[test] + fn event_yield_does_not_settle_a_write_twice() { + let code = r#"#[test(Top)]module Top(limit:input u32){var source:u32;var derived:u32; + always_comb{derived=source;} + function mark(x:input u32,o:output u32)->u32{o=x;return 1;} + initial{for i in 0..limit{$assert(1,"tb %d",mark(i,source));$assert(derived==i,"read");$assert(1);}$assert(derived==limit-1,"end");$finish();}}"#; + macro_rules! check { + ($method:ident) => {{ + let run = |n| { + count( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + n, + ) + }; + let small_delta = run(2) - run(1); + let before_yield = run(85); + let at_yield = run(86); + let after_yield = run(87); + assert_eq!( + at_yield - before_yield, + small_delta, + "256th event settled twice" + ); + assert_eq!( + after_yield - at_yield, + small_delta, + "post-yield write must settle" + ); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 0b923d128a3..35533c69ff2 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1579,3 +1579,64 @@ fn file_arguments_preserve_unknown_automatic_values() { &path, ); } + +#[test] +fn passing_dynamic_assertions_keep_their_messages() { + let code = r#"#[test(Top)]module Top{var value:logic<8>;initial{value=42;$assert(1,value);$finish();}}"#; + for kernels in [false, true] { + let result = Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .run_test_detailed() + .unwrap(); + assert!(result.passed); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"2a".as_slice()) + ); + } +} + +#[test] +fn event_yields_preserve_comb_assertions() { + fn check(mut sim: Simulator, count: usize) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_to_finish(&mut sim, &tb); + let TestResult::Fail(message) = result else { + panic!("expected nonfatal comb assertions"); + }; + assert_eq!( + message.lines().filter(|message| *message == "comb").count(), + count - 1, + "{count}: {}", + std::any::type_name::() + ); + } + for count in [256, 257] { + let code = format!( + r#"#[test(Top)]module Top {{var source:u32;var derived:u32; + always_comb {{derived=source;if(source){{$assert_continue(0,"comb");}}}} + function mark(x:input u32,o:output u32)->u32{{o=x;return 1;}} + initial{{for i in 0..{count}{{$assert(1,"tb %d",mark(i,source));}}$assert(derived=={count}-1,"end");$finish();}} + }}"# + ); + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + count, + ); + check( + Simulator::builder(&code, "Top").build_cranelift().unwrap(), + count, + ); + check( + Simulator::builder(&code, "Top").build_wasm().unwrap(), + count, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top").build_native().unwrap(), + count, + ); + } +} From 406314f3178835eab4afcf3a7a571b98d81c3fde Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 09:49:54 +0900 Subject: [PATCH 35/72] fix(runtime): retain falling phases alongside testbench tick budgets --- crates/celox-runtime/src/simulation.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 4dc13762b4e..cc4268f6a17 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -676,6 +676,18 @@ impl SimulationState { self.scheduled_clock_drives.insert(*id); } } + let mut falling = Vec::new(); + for (id, clock) in &self.tick_clocks { + if clock.falling_edge == Some(current_time) { + falling.push(*id); + events_to_process.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 0, + }); + } + } let ready = self.take_ready_processes(executor, current_time, &mut events_to_process); let rising: Vec = self .tick_clocks @@ -712,7 +724,7 @@ impl SimulationState { ready, true, ); - self.finish_clock_round(current_time, rising, &[], result)?; + self.finish_clock_round(current_time, rising, &falling, result)?; self.run_remaining_rounds(executor, current_time, limit)?; executor.finish_timed_step(self.scheduler.time); // Fused ticks may have moved the time on. From 9539e4cc2095f019472d4c71fd4f27a911e88f98 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 12:09:22 +0900 Subject: [PATCH 36/72] test(testbench): keep FF fatal coverage on the bytecode runner --- crates/celox-runtime/src/simulation.rs | 4 +++- crates/celox/tests/native_testbench.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 32557755f60..4089cf7722f 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -21,7 +21,9 @@ pub trait SimulationExecutor { type Backend: SimBackend; /// Whether individual scheduled writes have observable combinational /// effects even without an event waiter. - fn scheduled_updates_need_settle(&self) -> bool { false } + fn scheduled_updates_need_settle(&self) -> bool { + false + } fn backend(&self) -> &Self::Backend; fn backend_mut(&mut self) -> &mut Self::Backend; diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 3bdb52a9ee2..1e5c7ba9127 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2905,7 +2905,10 @@ fn test_run_test_stops_on_ff_fatal_runtime_event() { } } "#; - let result = Simulator::builder(code, "t").run_test().unwrap(); + let result = Simulator::builder(code, "t") + .testbench_kernels(false) + .run_test() + .unwrap(); assert_eq!(result, TestResult::Fail("ff fatal".to_string())); } From 1006c821cda6e2c92bc27a4a48d18261e1f09350 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 12:55:06 +0900 Subject: [PATCH 37/72] fix(veryl): retain branch dirtiness and hierarchical event edges --- .../src/lowering/process.rs | 166 +++++++++++++----- crates/celox/src/testbench/kernels.rs | 34 ++++ .../celox/tests/concurrent_initial_runtime.rs | 55 ++++++ 3 files changed, 211 insertions(+), 44 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index fbf0490ff9a..6b05e304645 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -65,6 +65,7 @@ pub struct BlockStorage { pub clock: SourceVarId, pub release: SourceVarId, pub event_counters: Vec<(VarId, SourceVarId, SourceVarId)>, + pub hierarchical_event_counters: Vec<(SourceVarId, SourceVarId)>, pub scratch: Vec<(ScratchNeed, SourceVarId)>, /// The block's own copy of each function-local variable, so a call /// that waits keeps its arguments and locals while another block calls @@ -231,6 +232,26 @@ pub(crate) fn declare_storage( ) }) .collect(), + hierarchical_event_counters: hierarchical_references(ir, statements) + .iter() + .enumerate() + .map(|(index, _)| { + ( + declare( + name(&format!("hier_event_rises@{index}")), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + declare( + name(&format!("hier_event_falls@{index}")), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + ) + }) + .collect(), scratch, private, expression_values, @@ -374,9 +395,10 @@ fn constant_nonempty_range(range: &ForRange) -> bool { fn contains_loop_break(statements: &[Statement]) -> bool { statements.iter().any(|stmt| { matches!(stmt, Statement::Break) - || expressions::statement_bodies(stmt) - .iter() - .any(|body| contains_loop_break(body)) + || (!matches!(stmt, Statement::For(_)) + && expressions::statement_bodies(stmt) + .iter() + .any(|body| contains_loop_break(body))) }) } @@ -597,21 +619,21 @@ fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result = storage + .event_counters + .iter() + .map(|(var, rises, falls)| (*var, (*rises, *falls))) + .collect(); + let mut counter_targets: Vec<_> = storage + .event_counters + .iter() + .map(|(var, rises, falls)| { + ( + SourceAddr { + instance_id: instance, + var_id: ids[var], + }, + *rises, + *falls, + ) + }) + .collect(); + for (reference, &(rises, falls)) in references + .into_iter() + .zip(&storage.hierarchical_event_counters) + { let key = (reference.inst_path.clone(), reference.var_path.clone()); if hierarchical_vars.contains_key(&key) { continue; @@ -893,6 +931,13 @@ fn lower_block( variable.id = id; module.variables.insert(id, variable); hierarchical_vars.insert(key, id); + if let Some(signal) = lookup.state_address(&resolved.target) { + let signal = scheduled.design.events.canonical(signal); + if scheduled.design.events.ordered_events.contains(&signal) { + event_counters.insert(id, (rises, falls)); + counter_targets.push((resolved.target, rises, falls)); + } + } hierarchical.insert(id, resolved.target); } let site_base = scheduled.runtime_schema.runtime_event_sites.len() as u32; @@ -943,15 +988,13 @@ fn lower_block( dirty: false, event_yield: None, event_yield_clean: None, - event_counters: storage - .event_counters - .iter() - .map(|(var, rises, falls)| (*var, (*rises, *falls))) - .collect(), + event_counters, }; + lowering.event_yield_clean = Some(lowering.take_scratch("event_yield_clean", 1)?.1); + let clean = lowering.constant(1, 1); + lowering.store_scratch(lowering.event_yield_clean.unwrap(), 1, clean); if contains_runtime_event(ir, statements, &mut HashSet::default()) { lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); - lowering.event_yield_clean = Some(lowering.take_scratch("event_yield_clean", 1)?.1); } lowering.declare_clocks(statements); // A block that ends right after a store settles, so a process that runs @@ -1061,11 +1104,8 @@ fn lower_block( .runtime_schema .testbench_kernels .get_or_insert(scheduled.runtime_schema.processes.len()); - for (var, rises, falls) in &storage.event_counters { - let signal = to_state(&SourceAddr { - instance_id: instance, - var_id: ids[var], - })?; + for (target, rises, falls) in &counter_targets { + let signal = to_state(target)?; let signal = scheduled.design.events.canonical(signal); if scheduled.design.events.ordered_events.contains(&signal) { let counters = celox_design::ProcessEventCounters { @@ -1144,6 +1184,21 @@ fn resolve_hierarchical( }) } +/// Stable unique reference order shared by storage declaration and lowering. +fn hierarchical_references(ir: &Module, statements: &[Statement]) -> Vec { + let mut references = Vec::new(); + collect_hierarchical_references( + statements, + &ir.functions, + &mut HashSet::default(), + &mut references, + ); + let mut seen = HashSet::default(); + references + .retain(|reference| seen.insert((reference.inst_path.clone(), reference.var_path.clone()))); + references +} + /// Every hierarchical reference the statements make, reads and writes. fn collect_hierarchical_references( statements: &[Statement], @@ -1745,8 +1800,8 @@ impl<'a> BlockLowering<'a> { .builder() .seal_block(SIRTerminator::Jump(after, Vec::new())); self.kernel.builder().switch_to_block(after); - let zero = self.constant(0, 1); - self.store_scratch(self.event_yield_clean.unwrap(), 1, zero); + let clean = self.constant(1, 1); + self.store_scratch(self.event_yield_clean.unwrap(), 1, clean); } self.suspended(); Ok(()) @@ -1771,6 +1826,10 @@ impl<'a> BlockLowering<'a> { fn suspended(&mut self) { self.parser.clear_register_cache(); self.dirty = false; + if let Some(slot) = self.event_yield_clean { + let clean = self.constant(1, 1); + self.store_scratch(slot, 1, clean); + } } fn host_scratch( @@ -1831,11 +1890,14 @@ impl<'a> BlockLowering<'a> { match statement { Statement::Assign(assign) => { self.lower_assign(assign)?; - self.dirty |= assign.hier_dst.is_some() + if assign.hier_dst.is_some() || assign .dst .iter() - .any(|destination| !self.private.contains_key(&destination.id)); + .any(|destination| !self.private.contains_key(&destination.id)) + { + self.mark_dirty(); + } Ok(Flow::Continue) } Statement::If(stmt) => { @@ -2071,17 +2133,33 @@ impl<'a> BlockLowering<'a> { let statement = Statement::Assign(assign.clone()); let bindings = self.expression_bindings(&expressions::statement_inputs(&statement))?; self.parser.push_process_expression_values(bindings); - let (parser, kernel, targets, sources, convert) = parts!(self); - let result = parser.parse_assign_statement( - assign, - targets, - &Domain::Process, - &convert, - sources, - kernel.builder(), - ); + let mut counter_values = Vec::new(); + for destination in &assign.dst { + if let Some(&(rises, falls)) = self.event_counters.get(&destination.id) { + self.parser.clear_register_cache(); + let before = self.load_var(destination.id)?; + counter_values.push((destination.id, rises, falls, before)); + } + } + let result = { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_assign_statement( + assign, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ) + }; self.parser.pop_process_expression_values(); - result + result?; + for (var, rises, falls, before) in counter_values { + self.parser.clear_register_cache(); + let after = self.load_var(var)?; + self.record_event_edges(before, after, rises, falls); + } + Ok(()) } /// A `for` loop whose counter and bounds live in state, so its body diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 75e3ab4b7d9..6b1f4354f4e 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -589,6 +589,40 @@ mod event_yield_settle_tests { } panic!("process did not finish"); } + #[test] + fn clean_conditional_paths_do_not_request_a_settle() { + for statement in [ + "if limit != 0 {source=1;}", + "case limit {0:{} default:{source=1;}}", + ] { + let code = format!( + "#[test(Top)]module Top(limit:input u32){{var source:u32;var derived:u32;always_comb{{derived=source;}}initial{{{statement}$assert(derived==source);$finish();}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + for (input, expected) in [(0, 0), (1, 1)] { + assert_eq!( + count( + Simulator::builder(&code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + input + ), + expected, + "{statement}, input={input}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + } + #[test] fn event_yield_does_not_settle_a_write_twice() { let code = r#"#[test(Top)]module Top(limit:input u32){var source:u32;var derived:u32; diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 35533c69ff2..1b201c051f6 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1640,3 +1640,58 @@ fn event_yields_preserve_comb_assertions() { ); } } + +#[test] +fn nested_loop_breaks_do_not_register_clocks_after_outer_finish() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{for j in 0..1{break;}$finish();}clk.next();}}"#; + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(code, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn hierarchical_clock_pulses_survive_a_settling_read() { + let code = r#"module Child(clk:input clock,q:output logic){always_ff(clk){q=1;}} + #[test(Top)]module Top{var q:logic;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;}} + "#; + fn check(mut sim: Simulator) { + sim.set(sim.signal("q"), 0u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + check(build().build_native().unwrap()); + let image = build().compile_native().unwrap().into_program_image(); + let image = celox::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + check( + Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); + } + } +} From 718dd24be245185bc78ec6ce4da3a0483668ed84 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 13:46:13 +0900 Subject: [PATCH 38/72] fix(veryl): scope testbench execution and private loop updates --- .../src/lowering/process.rs | 18 +++- crates/celox/src/simulation.rs | 88 ++++++++++++++++++- crates/celox/src/testbench/kernels.rs | 23 +++++ 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 6b05e304645..223519e9b50 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -844,6 +844,7 @@ struct BlockLowering<'a> { module_id: celox_design::ModuleId, hierarchical: HashMap, private: HashMap, + loop_counters: HashSet, expression_values: HashMap, scratch: Vec<(ScratchNeed, SourceVarId)>, clocks: Vec<(StrId, ProcessClock)>, @@ -973,6 +974,7 @@ fn lower_block( module_id, hierarchical, private: storage.private.clone(), + loop_counters: HashSet::default(), expression_values: storage.expression_values.clone(), scratch: storage.scratch.clone(), clocks: Vec::new(), @@ -1659,7 +1661,7 @@ impl<'a> BlockLowering<'a> { other => other, })?; } - if !self.private.contains_key(&destination.id) { + if self.is_design_variable(destination.id) { self.mark_dirty(); } let counters = self.event_counters.get(&destination.id).copied(); @@ -1763,6 +1765,17 @@ impl<'a> BlockLowering<'a> { } } + fn is_design_variable(&self, id: VarId) -> bool { + self.hierarchical.contains_key(&id) + || (!self.private.contains_key(&id) + && !self.loop_counters.contains(&id) + && self + .ir + .variables + .get(&id) + .is_some_and(|variable| variable.affiliation == Affiliation::Module)) + } + fn mark_dirty(&mut self) { self.dirty = true; if let Some(slot) = self.event_yield_clean { @@ -1894,7 +1907,7 @@ impl<'a> BlockLowering<'a> { || assign .dst .iter() - .any(|destination| !self.private.contains_key(&destination.id)) + .any(|destination| self.is_design_variable(destination.id)) { self.mark_dirty(); } @@ -2165,6 +2178,7 @@ impl<'a> BlockLowering<'a> { /// A `for` loop whose counter and bounds live in state, so its body /// may suspend. See [`LoopShape`] for the semantics. fn lower_for(&mut self, stmt: &veryl_analyzer::ir::ForStatement) -> Result { + self.loop_counters.insert(stmt.var_id); let shape = loop_shape(self.ir, stmt)?; let LoopShape { inclusive, diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4f1d5958f8f..0a677907dbe 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -266,6 +266,9 @@ impl SimulationExecutor for Simulator { // ── Backend-specific constructors ─────────────────────────────────── impl Simulation { + /// Build a scheduler for design processes. Veryl `#[test]` kernels run + /// through [`crate::testbench::run_compiled_testbench`], which initializes + /// their random, file and component services. pub fn builder<'a>(code: &'a str, top: &'a str) -> crate::SimulatorBuilder<'a, Simulation> { crate::SimulatorBuilder::::new(code, top) } @@ -300,7 +303,15 @@ impl Simulation { // ── Generic methods available for any backend ─────────────────────── +/// Scheduler state used by a testbench runner, including its kernels. pub(crate) fn simulation_state(simulator: &Simulator) -> SimulationState { + simulation_state_with_process_count(simulator, simulator.program.runtime_schema.processes.len()) +} + +fn simulation_state_with_process_count( + simulator: &Simulator, + process_count: usize, +) -> SimulationState { let num_events = simulator.backend.num_events(); let topo_signals: Vec<(SignalRef, usize, usize)> = simulator .program @@ -375,6 +386,7 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul .runtime_schema .processes .iter() + .take(process_count) .map(|slots| ProcessRefs { status: simulator.backend.resolve_signal(&slots.status), delay: simulator.backend.resolve_signal(&slots.delay), @@ -439,7 +451,12 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul impl Simulation { pub(crate) fn new(simulator: Simulator) -> Self { - let state = simulation_state(&simulator); + let process_count = simulator + .program + .runtime_schema + .testbench_kernels + .unwrap_or(simulator.program.runtime_schema.processes.len()); + let state = simulation_state_with_process_count(&simulator, process_count); Self { simulator, state } } @@ -789,7 +806,12 @@ impl Simulation { } fn has_processes(&self) -> bool { - !self.simulator.program.runtime_schema.processes.is_empty() + self.simulator + .program + .runtime_schema + .testbench_kernels + .unwrap_or(self.simulator.program.runtime_schema.processes.len()) + != 0 } /// Whether a process of the design requested the end of the simulation. @@ -2468,7 +2490,11 @@ mod tick_budget_snapshot_tests { fn restoring_a_checkpoint_restores_the_remaining_tick_budget() { let code = "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{clk.next(3);$finish();}}"; - let mut sim = Simulation::new(Simulator::builder(code, "Top").build_interpreter().unwrap()); + let simulator = Simulator::builder(code, "Top").build_interpreter().unwrap(); + // This budget belongs to a testbench run, whose scheduler includes + // its kernels. Ordinary Simulation constructors leave them inactive. + let state = simulation_state(&simulator); + let mut sim = Simulation { simulator, state }; sim.state.set_tick_budget(Some(1)); let saved = sim.checkpoint().unwrap(); sim.run_until(0).unwrap(); @@ -4002,3 +4028,59 @@ mod host_finish_edge_review_tests { } } } + +#[cfg(test)] +mod ordinary_simulation_testbench_scope_tests { + use super::*; + #[cfg(feature = "systemverilog")] + #[test] + fn ordinary_simulation_keeps_design_processes_active() { + let veryl = r#"#[test(Top)]module Top{var q:logic;var r:$tb::random::;var marker:u8;inst dut:$sv::Worker(q);initial{marker=r.get_range(5,5);$finish();}}"#; + let sv = "module Worker(output bit q);initial begin #1;q=1;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("marker")), 0u8.into()); + assert!(!sim.is_finished()); + } + let build = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("worker.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + + #[test] + fn ordinary_simulation_does_not_start_testbench_host_requests() { + let code = r#"#[test(Top)]module Top{var r:$tb::random::;var marker:u8;initial{r.seed(7);marker=r.get_range(5,5);$assert(marker==5);$finish();}}"#; + fn check(mut sim: Simulation) { + assert_eq!(sim.step().unwrap(), None); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("marker")), 0u8.into()); + assert!(!sim.is_finished()); + let tb = crate::testbench::compile_initial_testbench(&sim.simulator).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim.simulator, &tb), + crate::TestResult::Pass + ); + assert_eq!( + sim.simulator.get(sim.simulator.signal("marker")), + 5u8.into() + ); + } + check(Simulation::builder(code, "Top").build().unwrap()); + let build = || Simulator::builder(code, "Top").testbench_kernels(true); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 6b1f4354f4e..cfe0ab1ac54 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -590,6 +590,29 @@ mod event_yield_settle_tests { panic!("process did not finish"); } #[test] + fn private_loop_counters_do_not_request_settles() { + let code = r#"#[test(Top)]module Top(limit:input u32){initial{for i in 0..limit{$assert(1);}$finish();}}"#; + macro_rules! check { + ($method:ident) => {{ + assert_eq!( + count( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + 3 + ), + 0 + ); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] fn clean_conditional_paths_do_not_request_a_settle() { for statement in [ "if limit != 0 {source=1;}", From 4e6d260b992662b6480c5de7872708efdc36584d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 15:07:07 +0900 Subject: [PATCH 39/72] fix(runtime): preserve clean process continuations and kernel tick fusion --- crates/celox-design/src/lib.rs | 7 + crates/celox-frontend-core/src/sdk.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 1 + .../src/lowering/process.rs | 72 +++++++--- crates/celox-runtime/src/simulation.rs | 35 ++++- crates/celox/src/backend/native/backend.rs | 16 ++- crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/simulation.rs | 10 ++ crates/celox/src/testbench/kernels.rs | 136 +++++++++++++++++- .../celox/tests/concurrent_initial_runtime.rs | 77 ++++++++++ 10 files changed, 333 insertions(+), 26 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index b9202d7e0c1..675cfc4a275 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -503,6 +503,10 @@ impl HostRequest { /// state objects, so checkpoints capture a suspended process. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { + /// Optional two-state flag: no design store since this kernel's last + /// combinational settle. Missing flags conservatively require a settle. + #[serde(default = "Option::default")] + pub comb_clean: Option, pub resume: A, pub status: A, pub delay: A, @@ -524,6 +528,7 @@ impl ProcessSlots { /// Slots for a process without clocks, releases or host requests. pub fn new(resume: A, status: A, delay: A, clock: A, release: A) -> Self { Self { + comb_clean: None, resume, status, delay, @@ -537,6 +542,7 @@ impl ProcessSlots { pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { + comb_clean: self.comb_clean.map(&mut map), resume: map(self.resume), status: map(self.status), delay: map(self.delay), @@ -570,6 +576,7 @@ impl ProcessSlots { &self.release, ] .into_iter() + .chain(self.comb_clean.iter()) } } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index bc02b6ad11f..b4b6369bca6 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1195,6 +1195,7 @@ fn lower_processes( let mut clocks = Vec::new(); celox_frontend_sdk::collect_process_clocks(process.body(), &mut clocks); let slots = ProcessSlots { + comb_clean: None, resume: declare(name("resume"), PROCESS_RESUME_WIDTH), status: declare(name("status"), PROCESS_STATUS_WIDTH), delay: declare(name("delay"), PROCESS_DELAY_WIDTH), diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 49567f08cda..0e94e6c2daa 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -3564,6 +3564,7 @@ fn lower_initial_processes( id }; ProcessSlots { + comb_clean: None, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 223519e9b50..ebfe884c36d 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1010,6 +1010,7 @@ fn lower_block( clocks, releases, host_requests, + event_yield_clean, .. } = lowering; let mut unit = kernel.build(); @@ -1078,6 +1079,7 @@ fn lower_block( }) })?; let slots = ProcessSlots { + comb_clean: event_yield_clean.map(|id| stable(id).into_absolute()), resume: stable(storage.resume).into_absolute(), status: stable(storage.status).into_absolute(), delay: stable(storage.delay).into_absolute(), @@ -1125,6 +1127,9 @@ fn lower_block( .push(counters); } } + if let Some(flag) = slots.comb_clean { + scheduled.runtime_schema.testbench_read_roots.insert(flag); + } scheduled.sir.processes.push(unit); scheduled.runtime_schema.processes.push(slots); Ok(()) @@ -1385,10 +1390,15 @@ impl<'a> BlockLowering<'a> { /// periods. fn declare_clocks(&mut self, statements: &[Statement]) { let mut active = HashSet::default(); - self.scan_clocks(statements, &mut active); + self.scan_clocks(statements, &mut active, true); } - fn scan_clocks(&mut self, statements: &[Statement], active: &mut HashSet) -> bool { + fn scan_clocks( + &mut self, + statements: &[Statement], + active: &mut HashSet, + declare: bool, + ) -> bool { for statement in statements { let mut calls = Vec::new(); let mut unconditional = Vec::new(); @@ -1399,7 +1409,7 @@ impl<'a> BlockLowering<'a> { for call in calls { if active.insert(function_key(call)) { if let Some(body) = function_body(&self.ir.functions, call) { - let continues = self.scan_clocks(&body.statements, active); + let continues = self.scan_clocks(&body.statements, active, declare); active.remove(&function_key(call)); if !continues && unconditional @@ -1423,21 +1433,25 @@ impl<'a> BlockLowering<'a> { .or_else(|| period.as_deref().and_then(try_eval_const)) .unwrap_or(2) .max(2); - self.declare_clock(tb.inst, period); + if declare { + self.declare_clock(tb.inst, period); + } } TbMethod::ResetAssert { clock, .. } => { let period = self.clock_periods.get(clock).copied().unwrap_or(2).max(2); - self.declare_clock(*clock, period); + if declare { + self.declare_clock(*clock, period); + } } _ => {} }, Statement::If(stmt) => { let continues = match constant_truth(&stmt.cond) { - Some(true) => self.scan_clocks(&stmt.true_side, active), - Some(false) => self.scan_clocks(&stmt.false_side, active), + Some(true) => self.scan_clocks(&stmt.true_side, active, declare), + Some(false) => self.scan_clocks(&stmt.false_side, active, declare), None => { - let a = self.scan_clocks(&stmt.true_side, active); - let b = self.scan_clocks(&stmt.false_side, active); + let a = self.scan_clocks(&stmt.true_side, active, declare); + let b = self.scan_clocks(&stmt.false_side, active, declare); a || b } }; @@ -1446,26 +1460,26 @@ impl<'a> BlockLowering<'a> { } } Statement::IfReset(stmt) => { - self.scan_clocks(&stmt.true_side, active); - self.scan_clocks(&stmt.false_side, active); + self.scan_clocks(&stmt.true_side, active, declare); + self.scan_clocks(&stmt.false_side, active, declare); } Statement::Case(stmt) => { if let Some(body) = selected_case_body(stmt) { - if !self.scan_clocks(body, active) { + if !self.scan_clocks(body, active, declare) { return false; } continue; } - let mut continues = self.scan_clocks(&stmt.default, active); + let mut continues = self.scan_clocks(&stmt.default, active, declare); for arm in &stmt.arms { - continues |= self.scan_clocks(&arm.body, active); + continues |= self.scan_clocks(&arm.body, active, declare); } if !continues { return false; } } Statement::For(stmt) if !constant_empty_range(&stmt.range) => { - let continues = self.scan_clocks(&stmt.body, active); + let continues = self.scan_clocks(&stmt.body, active, declare); if !continues && constant_nonempty_range(&stmt.range) && !contains_loop_break(&stmt.body) @@ -1477,7 +1491,7 @@ impl<'a> BlockLowering<'a> { if active.insert(function_key(call)) && let Some(body) = function_body(&self.ir.functions, call) { - let continues = self.scan_clocks(&body.statements, active); + let continues = self.scan_clocks(&body.statements, active, declare); active.remove(&function_key(call)); if !continues { return false; @@ -2672,6 +2686,7 @@ impl<'a> BlockLowering<'a> { fn system_task(&mut self, call: &SystemFunctionCall) -> Result { let bindings = self.expression_bindings(&expressions::system_inputs(&call.kind))?; self.parser.push_process_expression_values(bindings); + let first_site = self.parser.runtime_event_sites().len(); let (parser, kernel, targets, sources, convert) = parts!(self); let result = parser.parse_system_task_statement( call, @@ -2683,6 +2698,12 @@ impl<'a> BlockLowering<'a> { ); self.parser.pop_process_expression_values(); result?; + // Kernel events execute at suspension boundaries, unlike RTL events + // emitted on every fused edge. Preserve their source ownership marker. + let location = event_location(&call.comptime.token); + for site in &mut self.parser.runtime_event_sites_mut()[first_site..] { + site.location = location.clone(); + } Ok(Flow::Continue) } @@ -2977,6 +2998,25 @@ impl<'a> BlockLowering<'a> { } fn lower_tb_method(&mut self, tb: &TbMethodCall) -> Result { + if matches!( + tb.method, + TbMethod::ClockNext { .. } | TbMethod::ResetAssert { .. } + ) { + let statement = Statement::TbMethodCall(tb.clone()); + if !self.scan_clocks( + std::slice::from_ref(&statement), + &mut HashSet::default(), + false, + ) { + // Evaluate the terminating argument, then seal only its dead + // continuation. The outer wait has no reachable clock metadata. + for expr in expressions::statement_inputs(&statement) { + self.expression(expr)?; + } + self.kernel.finish(); + return Ok(Flow::Ended); + } + } match &tb.method { TbMethod::ClockNext { count, .. } => { let clock = self.clock_index(tb.inst)?; diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 28894575ac0..e3c8b454b30 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -46,6 +46,11 @@ pub trait SimulationExecutor { self.backend_mut().run_process(index) } + /// Whether this process has made no design store since its last settle. + fn process_is_clean(&self, _index: usize) -> bool { + false + } + /// Whether an internal settle or process execution emitted a finish event. fn finish_requested(&mut self, _time: u64) -> bool { false @@ -1250,6 +1255,7 @@ impl SimulationState { executor: &mut E, current_time: u64, ready: Vec, + comb_current: &mut bool, ) -> Result where E: SimulationExecutor, @@ -1285,6 +1291,9 @@ impl SimulationState { .backend_mut() .set(self.processes[process].delay, 0u64); executor.run_process(process, current_time)?; + if !executor.process_is_clean(process) { + *comb_current = false; + } if executor.finish_requested(current_time) { self.finish_round = true; self.finished = true; @@ -1314,6 +1323,7 @@ impl SimulationState { } Some(ProcessStatus::Settle) => { executor.eval_comb()?; + *comb_current = true; if executor.finish_requested(current_time) { self.finished = true; return Ok(true); @@ -1422,6 +1432,9 @@ impl SimulationState { self.finished = true; return Ok(true); } + // A component or host service may write design + // state outside this kernel's store instrumentation. + *comb_current = false; any_ran = true; continue; } @@ -1508,6 +1521,7 @@ impl SimulationState { where E: SimulationExecutor, { + let mut comb_current = false; self.scheduler.time = current_time; self.round_published_domains.make_empty(); self.round_triggered_domains.make_empty(); @@ -1625,7 +1639,8 @@ impl SimulationState { .iter() .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect(); - let progressed = self.run_processes(executor, current_time, ready_processes)?; + let progressed = + self.run_processes(executor, current_time, ready_processes, &mut comb_current)?; if self.finished && self.finish_round { return Ok(true); } @@ -1699,6 +1714,9 @@ impl SimulationState { .checked_add(self.tick_clocks[&id].period) .ok_or_else(|| clock_overflow(id))?; } + if !generated_events.is_empty() { + comb_current = false; + } for event in &generated_events { executor.backend_mut().set(event.signal, event.next_val); } @@ -1735,7 +1753,9 @@ impl SimulationState { } } - executor.eval_comb()?; + if !comb_current { + executor.eval_comb()?; + } self.round_evaluated = true; if executor.finish_requested(current_time) { self.finished = true; @@ -1872,7 +1892,8 @@ impl SimulationState { // batch, including evaluations a combinational settle woke. let inactive_counter_values = self.process_counter_values(executor.backend()); let mut inactive_samples = None; - let mut active_ran = self.run_processes(executor, current_time, Vec::new())?; + let mut active_ran = + self.run_processes(executor, current_time, Vec::new(), &mut comb_current)?; if !active_ran { // Drain active combinational effects of blocking FF stores // before either inactive continuations or NBA publication. @@ -1898,7 +1919,8 @@ impl SimulationState { } executor.backend_mut().clear_triggered_bits(); } - active_ran = self.run_processes(executor, current_time, Vec::new())?; + active_ran = + self.run_processes(executor, current_time, Vec::new(), &mut comb_current)?; } if self.finished && self.finish_round { return Ok(true); @@ -1943,7 +1965,7 @@ impl SimulationState { } } inactive_samples = Some(before); - self.run_processes(executor, current_time, ready)? + self.run_processes(executor, current_time, ready, &mut comb_current)? }; if progressed { let mut driven = @@ -2023,7 +2045,8 @@ impl SimulationState { if polled { let counter_values = self.process_counter_values(executor.backend()); - any_process_ran |= self.run_processes(executor, current_time, Vec::new())?; + any_process_ran |= + self.run_processes(executor, current_time, Vec::new(), &mut comb_current)?; if self.finished && self.finish_round { return Ok(true); } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index e429df3af2d..86f5fcdd5b6 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -577,6 +577,19 @@ impl NativeProgramImage { } let mut process_clock_periods = fxhash::FxHashMap::default(); for process in &self.runtime_schema.processes { + if let Some(flag) = process.comb_clean + && !self + .design + .state_objects + .get(&flag) + .is_some_and(|metadata| { + metadata.width == 1 && !metadata.is_4state && metadata.array_dims.is_empty() + }) + { + return Err( + "a process combinational-clean flag has an invalid state object".into(), + ); + } if !self .design .state_objects @@ -3458,13 +3471,14 @@ mod process_metadata_tests { fn process_clock_metadata_is_checked_before_image_attachment() { let original = image(); original.to_container_bytes().unwrap(); - for corruption in 0..5 { + for corruption in 0..6 { let mut broken = original.clone(); let slots = &mut broken.runtime_schema.processes[0]; match corruption { 0 => slots.clocks[0].signal = slots.delay, 1 => slots.clocks[0].period = 1, 2 => slots.clock = slots.status, + 5 => slots.comb_clean = Some(slots.delay), 4 => { let signal = slots.clocks[0].signal; broken diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index bf56d0ffba8..ce1db047a63 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 19 adds the drain-only kernel status to the runtime protocol. -const CONTAINER_VERSION: u16 = 20; +// Version 21 adds the optional process combinational-clean flag to the schema. +const CONTAINER_VERSION: u16 = 21; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 0df3bf15dc7..600c5850752 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -121,6 +121,16 @@ impl SimulationExecutor for Simulator { result } + fn process_is_clean(&self, index: usize) -> bool { + self.program.runtime_schema.processes[index] + .comb_clean + .is_some_and(|flag| { + self.backend + .get_as::(self.backend.resolve_signal(&flag)) + != 0 + }) + } + fn finish_requested(&mut self, time: u64) -> bool { if self.testbench_random.is_some() { let ctx = crate::simulator::RuntimeFormatContext { diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index cfe0ab1ac54..44ce2c6daba 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -538,6 +538,9 @@ mod event_yield_settle_tests { struct CountingExecutor { sim: Simulator, settles: usize, + combs: usize, + fused: u64, + combs_before_edge: Option, } impl SimulationExecutor for CountingExecutor { type Backend = B; @@ -548,8 +551,25 @@ mod event_yield_settle_tests { &mut self.sim.backend } fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + self.combs += 1; SimulationExecutor::eval_comb(&mut self.sim) } + fn process_is_clean(&self, index: usize) -> bool { + SimulationExecutor::process_is_clean(&self.sim, index) + } + fn fused_ticks_allowed(&self) -> bool { + SimulationExecutor::fused_ticks_allowed(&self.sim) + } + fn tick_many( + &mut self, + event: B::Event, + count: u64, + ) -> (u64, Result<(), RuntimeErrorCode>) { + self.combs_before_edge.get_or_insert(self.combs); + let result = SimulationExecutor::tick_many(&mut self.sim, event, count); + self.fused = self.fused.max(count); + result + } fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { SimulationExecutor::run_process(&mut self.sim, index, time)?; let slot = self.sim.program.runtime_schema.processes[index].status; @@ -562,6 +582,7 @@ mod event_yield_settle_tests { Ok(()) } fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + self.combs_before_edge.get_or_insert(self.combs); SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) } fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -581,7 +602,13 @@ mod event_yield_settle_tests { }) .unwrap(); let mut state = crate::simulation::simulation_state(&sim); - let mut executor = CountingExecutor { sim, settles: 0 }; + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + }; for _ in 0..10000 { if state.step(&mut executor).unwrap().is_none() || state.is_finished() { return executor.settles; @@ -685,4 +712,111 @@ mod event_yield_settle_tests { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check!(build_native); } + fn execution_counts(sim: Simulator, steps: usize) -> (usize, u64, u64) { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + }; + for _ in 0..steps { + if state.step(&mut executor).unwrap().is_none() { + break; + } + if state.is_finished() { + break; + } + } + if let Ok(q) = executor.sim.try_signal("q") { + assert_eq!(executor.sim.backend.get_as::(q), state.ticks() as u32); + } + if let (Ok(source), Ok(derived)) = ( + executor.sim.try_signal("source"), + executor.sim.try_signal("derived"), + ) { + assert_eq!( + executor.sim.backend.get_as::(derived), + executor.sim.backend.get_as::(source) + ); + } + ( + executor.combs_before_edge.unwrap_or(executor.combs), + executor.fused, + state.ticks(), + ) + } + #[test] + fn kernel_output_after_wait_preserves_fusion_but_design_output_does_not() { + for task in ["$display(\"done\");", "$write(\"done\");"] { + let code = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;var q:u32;always_ff(clk){{q+=1;}}initial{{clk.next(1000);{task}$assert(q==1000);$finish();}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + let (_, fused, ticks) = + execution_counts(Simulator::builder(&code, "Top").$method().unwrap(), 3000); + assert_eq!(fused, 1000); + assert_eq!(ticks, 1000); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + let code = "#[test(Top)]module Top{inst clk:$tb::clock_gen;always_ff(clk){$display(\"edge\");}initial{clk.next(1000);$finish();}}"; + let (_, fused, _) = execution_counts( + Simulator::builder(code, "Top").build_interpreter().unwrap(), + 2, + ); + assert_eq!(fused, 0); + } + #[test] + fn clean_clock_wait_continuations_do_not_repeat_comb_settles() { + for (body, expected) in [ + ("source=1;", 1), + ("source=1;clk.next(1);", 2), + ("source=1;$assert(derived==1);source=2;", 2), + ("source=1;$assert(derived==1);clk.next(write());", 3), + ] { + let code = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;var source:u32;var derived:u32;always_comb{{derived=source;$assert(1,\"comb\");}}function write()->u32{{source=2;return 1;}}initial{{{body}}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + let (combs, _, _) = + execution_counts(Simulator::builder(&code, "Top").$method().unwrap(), 1); + assert_eq!(combs, expected, "{body}"); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn native_image_preserves_clean_continuation_after_optimization() { + let code = "#[test(Top)]module Top{var source:u32;var derived:u32;always_comb{derived=source;}initial{source=1;}}"; + let original = Simulator::builder(code, "Top") + .opt_level(crate::OptLevel::O2) + .build_native() + .unwrap(); + let bytes = original + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = crate::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + assert!(image.runtime_schema().processes[0].comb_clean.is_some()); + let restored = Simulator::builder("unused", "unused") + .build_native_from_image(image) + .unwrap(); + assert_eq!(execution_counts(restored, 1).0, 1); + } } diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 1b201c051f6..95014bf03bd 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1695,3 +1695,80 @@ fn hierarchical_clock_pulses_survive_a_settling_read() { } } } + +#[test] +fn terminating_clock_arguments_leave_unreachable_clock_and_reset_untouched() { + for wait in ["clk.next(stop());", "rst.assert(stop());"] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk: $tb::clock_gen; + inst rst: $tb::reset_gen(clk); + function stop()->u32 {{$finish();return 1;}} + initial {{{wait} $assert(0,"continued after finish");}} + }}"# + ); + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + let rst = sim.signal("rst"); + sim.set(clk, 1u8); + sim.set(rst, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); + assert_eq!(sim.get(rst), 1u8.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn bounded_testbench_with_background_delay_returns_after_clock_and_reset_boundary() { + let veryl = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 10); + inst rst: $tb::reset_gen(clk); + var background: u32; + inst worker: $sv::Worker(background); + initial { rst.assert(1); $assert(0,"resumed after budget"); } + initial { clk.next(100); $assert(0,"resumed after budget"); } + }"#; + let sv = + "module Worker(output bit[31:0] background);always #1 background=background+1;endmodule"; + fn check(mut sim: Simulator, limit: u64) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, limit); + assert_eq!(result.result, TestResult::Pass); + assert_eq!(result.ticks, limit); + assert!(result.tick_limit_reached); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.get(sim.signal("rst")), u8::from(limit > 0).into()); + // At time zero the first tick consumes the budget. Background delay + // resumptions are blocked too; only clock falls/releases still drain. + assert_eq!(sim.get(sim.signal("background")), 0u32.into()); + } + for limit in [0, 1] { + let build = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("bounded.veryl"))], + vec![(sv, std::path::Path::new("background.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), limit); + check(build().build_cranelift().unwrap(), limit); + check(build().build_wasm().unwrap(), limit); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), limit); + } +} From b98acd430b44d4e16f889c429acbdb56440f98ef Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 15:42:31 +0900 Subject: [PATCH 40/72] fix(veryl): prune skipped case calls and reset kernel event counts --- .../src/lowering/process.rs | 3 + .../src/lowering/process/expressions.rs | 4 + crates/celox/src/testbench/kernels.rs | 48 +++++++++++ .../celox/tests/concurrent_initial_runtime.rs | 79 +++++++++++++++++++ 4 files changed, 134 insertions(+) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index ebfe884c36d..9f5856a0ff2 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -997,6 +997,9 @@ fn lower_block( lowering.store_scratch(lowering.event_yield_clean.unwrap(), 1, clean); if contains_runtime_event(ir, statements, &mut HashSet::default()) { lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); + // Resume-zero entry starts a new run of this compiled kernel. + let zero = lowering.constant(0, EVENT_YIELD_WIDTH); + lowering.store_scratch(lowering.event_yield.unwrap(), EVENT_YIELD_WIDTH, zero); } lowering.declare_clocks(statements); // A block that ends right after a store settles, so a process that runs diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index 14b04851e30..d1b969a0cf3 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -88,6 +88,10 @@ pub(crate) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { ) .collect(), Statement::If(stmt) => vec![&stmt.cond], + // A statically selected arm never evaluates later pattern helpers. + Statement::Case(stmt) if selected_case_body(stmt).is_some() => { + vec![stmt.case_target.as_ref()] + } Statement::Case(stmt) => std::iter::once(stmt.case_target.as_ref()) .chain(stmt.arms.iter().flat_map(|arm| { arm.patterns.iter().flat_map(|pattern| match pattern { diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 44ce2c6daba..90cf580d75a 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -819,4 +819,52 @@ mod event_yield_settle_tests { .unwrap(); assert_eq!(execution_counts(restored, 1).0, 1); } + #[test] + fn repeated_kernel_entries_restart_the_event_yield_count() { + let code = r#"#[test(Top)]module Top{var source:u32;var derived:u32; + always_comb{derived=source;} + function mark(o:output u32)->u32{o=1;return 1;} + initial{$assert(1,"value %d",mark(source));$finish();}} + "#; + fn check(sim: Simulator) { + let source = sim.signal("source"); + let derived = sim.signal("derived"); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + }; + for run in 1..=256 { + // Restart control slots as the public runner does, retaining + // the same compiled kernel and its other scratch storage. + for slots in &executor.sim.program.runtime_schema.processes { + for address in slots.iter() { + let signal = executor.sim.backend.resolve_signal(address); + executor.sim.backend.set(signal, 0u64); + } + } + executor.sim.backend.set(source, 0u32); + executor.eval_comb().unwrap(); + let mut state = crate::simulation::simulation_state(&executor.sim); + let before = executor.settles; + while !state.is_finished() { + assert!(state.step(&mut executor).unwrap().is_some()); + } + assert_eq!( + executor.settles - before, + 0, + "run {run} inherited an event-yield budget" + ); + assert_eq!(executor.sim.backend.get_as::(source), 1); + assert_eq!(executor.sim.backend.get_as::(derived), 1); + } + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); + } } diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 95014bf03bd..ede071581e8 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1772,3 +1772,82 @@ fn bounded_testbench_with_background_delay_returns_after_clock_and_reset_boundar check(build().build_native().unwrap(), limit); } } + +#[test] +fn skipped_case_pattern_finish_does_not_hide_a_reachable_clock_wait() { + for (target, helper) in [(1, "$finish();"), (2, "")] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; + var q:u32; always_ff(clk) {{q+=1;}} + function later()->u32 {{{helper}return 2;}} + initial {{case {target} {{1:{{$assert({target}==1);}} later():{{$assert({target}==2);}}}} + clk.next(1);$finish();}} + }}"# + ); + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u32.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[test] +fn repeated_clockless_runs_settle_residual_writes_before_entry_reads() { + let code = r#"#[test(Top)] module Top {var source:u32;var derived:u32; + always_comb {derived=source;} + initial {$assert(derived==source,"entry read");source=1;$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + for _ in 0..2 { + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + // Raw reads prove the final TB settle happened without a lazy get. + assert_eq!(sim.backend_ref().get_as::(sim.signal("source")), 1); + assert_eq!(sim.backend_ref().get_as::(sim.signal("derived")), 1); + } + } + for kernels in [false, true] { + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_native() + .unwrap(), + ); + } +} From 3c514f80322c68ce6bb2a7879caf7c1a15326109 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 17:01:18 +0900 Subject: [PATCH 41/72] ci(lydite): cache replay builds and allow cold verification --- .github/workflows/lydite.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/lydite.yml b/.github/workflows/lydite.yml index 5054e3b000d..9e410d18d3d 100644 --- a/.github/workflows/lydite.yml +++ b/.github/workflows/lydite.yml @@ -98,7 +98,9 @@ jobs: # checks lydite's own Veryl lowering against a pinned upstream corpus. celox-replay: runs-on: ubuntu-26.04 - timeout-minutes: 30 + # The measured cold debug/release builds take about 28 minutes alone. + # Keep enough time for verifier test builds and the complete replay gates. + timeout-minutes: 60 steps: - uses: actions/checkout@v7 with: @@ -106,6 +108,10 @@ jobs: - uses: ./.github/actions/setup-rust with: components: rustfmt + - uses: Swatinem/rust-cache@v2 + with: + shared-key: lydite-replay + cache-on-failure: true - name: Reproduce source violations and AXI4-Lite protocol regressions with Celox run: ./conformance/axi4lite/run_ci.sh "$RUNNER_TEMP/celox-replay" - name: Upload complete replay evidence From dafef54ed0081654343b1e1169fb6547b0a42511 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 14 Oct 2026 17:41:50 +0900 Subject: [PATCH 42/72] fix(veryl): follow execution paths when discovering process clocks --- .../src/lowering/process.rs | 247 ++++++++++++++---- .../src/lowering/process/expressions.rs | 38 +-- .../celox/tests/concurrent_initial_runtime.rs | 78 ++++++ 3 files changed, 270 insertions(+), 93 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 9f5856a0ff2..30fdc0ed7cb 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1403,27 +1403,34 @@ impl<'a> BlockLowering<'a> { declare: bool, ) -> bool { for statement in statements { - let mut calls = Vec::new(); - let mut unconditional = Vec::new(); - for expr in expressions::statement_inputs(statement) { - expressions::expression_calls(expr, &mut calls); - expressions::unconditional_expression_calls(expr, &mut unconditional); - } - for call in calls { - if active.insert(function_key(call)) { - if let Some(body) = function_body(&self.ir.functions, call) { - let continues = self.scan_clocks(&body.statements, active, declare); - active.remove(&function_key(call)); - if !continues - && unconditional - .iter() - .any(|required| std::ptr::eq(*required, call)) - { - return false; - } + // Calls and case patterns have their own conditional evaluation + // order; a flat input list cannot describe their continuation. + match statement { + Statement::FunctionCall(call) => { + if !self.scan_call_clocks(call, active, declare) { + return false; + } + continue; + } + Statement::Case(stmt) => { + if !self.scan_expression_clocks(&stmt.case_target, active, declare) { + return false; + } + let continues = if let Some(body) = selected_case_body(stmt) { + self.scan_clocks(body, active, declare) } else { - active.remove(&function_key(call)); + self.scan_case_clock_arms(stmt, 0, active, declare) + }; + if !continues { + return false; } + continue; + } + _ => {} + } + for expr in expressions::statement_inputs(statement) { + if !self.scan_expression_clocks(expr, active, declare) { + return false; } } match statement { @@ -1466,21 +1473,6 @@ impl<'a> BlockLowering<'a> { self.scan_clocks(&stmt.true_side, active, declare); self.scan_clocks(&stmt.false_side, active, declare); } - Statement::Case(stmt) => { - if let Some(body) = selected_case_body(stmt) { - if !self.scan_clocks(body, active, declare) { - return false; - } - continue; - } - let mut continues = self.scan_clocks(&stmt.default, active, declare); - for arm in &stmt.arms { - continues |= self.scan_clocks(&arm.body, active, declare); - } - if !continues { - return false; - } - } Statement::For(stmt) if !constant_empty_range(&stmt.range) => { let continues = self.scan_clocks(&stmt.body, active, declare); if !continues @@ -1490,17 +1482,6 @@ impl<'a> BlockLowering<'a> { return false; } } - Statement::FunctionCall(call) => { - if active.insert(function_key(call)) - && let Some(body) = function_body(&self.ir.functions, call) - { - let continues = self.scan_clocks(&body.statements, active, declare); - active.remove(&function_key(call)); - if !continues { - return false; - } - } - } Statement::SystemFunctionCall(call) if matches!(call.kind, SystemFunctionKind::Finish) => { @@ -1513,6 +1494,129 @@ impl<'a> BlockLowering<'a> { true } + fn scan_expression_clocks( + &mut self, + expr: &Expression, + active: &mut HashSet, + declare: bool, + ) -> bool { + if let Expression::Term(factor) = expr + && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() + { + return self.scan_call_clocks(call, active, declare); + } + match expr { + Expression::Binary(lhs, op, rhs, _) if matches!(op, Op::LogicAnd | Op::LogicOr) => { + if !self.scan_expression_clocks(lhs, active, declare) { + return false; + } + match constant_truth(lhs) { + Some(truth) + if (*op == Op::LogicAnd && !truth) || (*op == Op::LogicOr && truth) => + { + true + } + Some(_) => self.scan_expression_clocks(rhs, active, declare), + None => { + // RHS runs only on the non-short-circuit path. + self.scan_expression_clocks(rhs, active, declare); + true + } + } + } + Expression::Ternary(cond, yes, no, _) => { + if !self.scan_expression_clocks(cond, active, declare) { + return false; + } + match constant_truth(cond) { + Some(true) => self.scan_expression_clocks(yes, active, declare), + Some(false) => self.scan_expression_clocks(no, active, declare), + None => { + let yes = self.scan_expression_clocks(yes, active, declare); + let no = self.scan_expression_clocks(no, active, declare); + yes || no + } + } + } + _ => expressions::children(expr) + .into_iter() + .all(|child| self.scan_expression_clocks(child, active, declare)), + } + } + + fn scan_call_clocks( + &mut self, + call: &veryl_analyzer::ir::FunctionCall, + active: &mut HashSet, + declare: bool, + ) -> bool { + // Match lower_function_call's formal argument and copy-back order. + let paths = self.ir.functions[&call.id] + .args + .iter() + .flat_map(|arg| arg.members.iter().map(|(path, _, _)| path.clone())) + .collect::>(); + for path in &paths { + if let Some(expr) = call + .inputs + .iter() + .find_map(|(input, expr)| (input == path).then_some(expr)) + && !self.scan_expression_clocks(expr, active, declare) + { + return false; + } + } + if active.insert(function_key(call)) { + let continues = function_body(&self.ir.functions, call) + .is_none_or(|body| self.scan_clocks(&body.statements, active, declare)); + active.remove(&function_key(call)); + if !continues { + return false; + } + } + for path in &paths { + if let Some(destinations) = call + .outputs + .iter() + .find_map(|(output, destinations)| (output == path).then_some(destinations)) + { + for destination in destinations { + for expr in expressions::selection(&destination.index, &destination.select) { + if !self.scan_expression_clocks(expr, active, declare) { + return false; + } + } + } + } + } + true + } + + fn scan_case_clock_arms( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + active: &mut HashSet, + declare: bool, + ) -> bool { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.scan_clocks(&stmt.default, active, declare); + }; + let condition = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + if !self.scan_expression_clocks(&condition, active, declare) { + return false; + } + match constant_truth(&condition) { + Some(true) => self.scan_clocks(&case_arm.body, active, declare), + Some(false) => self.scan_case_clock_arms(stmt, arm + 1, active, declare), + None => { + let matched = self.scan_clocks(&case_arm.body, active, declare); + let unmatched = self.scan_case_clock_arms(stmt, arm + 1, active, declare); + matched || unmatched + } + } + } + fn declare_clock(&mut self, inst: StrId, period: u64) { if self.clocks.iter().any(|(name, _)| *name == inst) { return; @@ -1649,13 +1753,28 @@ impl<'a> BlockLowering<'a> { &mut self, destination: &AssignDestination, load: impl FnOnce(&mut Self) -> Result, - ) -> Result<(), ParserError> { + ) -> Result { let inputs = expressions::selection(&destination.index, &destination.select); - let bindings = self.expression_bindings(&inputs)?; + let mut bindings = HashMap::default(); + if inputs.iter().any(|expr| expressions::has_call(expr)) { + for expr in &inputs { + let value = self.expression(expr)?; + if !self.scan_expression_clocks(expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } + self.save_expression(expr, value)?; + } + bindings = inputs + .into_iter() + .map(|expr| (expr.token_range(), self.saved_expression(expr))) + .collect(); + } self.parser.push_process_expression_values(bindings); let result = load(self).and_then(|value| self.store(destination, value)); self.parser.pop_process_expression_values(); - result + result?; + Ok(Flow::Continue) } fn store( @@ -2035,6 +2154,10 @@ impl<'a> BlockLowering<'a> { stmt: &veryl_analyzer::ir::CaseStatement, ) -> Result { let value = self.expression(&stmt.case_target)?; + if !self.scan_expression_clocks(&stmt.case_target, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } self.save_expression(&stmt.case_target, value)?; if let Some(body) = selected_case_body(stmt) { return self.lower_statements(body); @@ -2061,6 +2184,10 @@ impl<'a> BlockLowering<'a> { let condition = self.condition(&condition_expr); self.parser.pop_process_expression_values(); let condition = condition?; + if !self.scan_expression_clocks(&condition_expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } let builder = self.kernel.builder(); let then_block = builder.new_block(); let else_block = builder.new_block(); @@ -2886,6 +3013,10 @@ impl<'a> BlockLowering<'a> { .coerce_function_input_expression((*expr).clone(), *formal) }); let value = self.expression(actual.as_ref().unwrap_or(expr))?; + if !self.scan_expression_clocks(expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } if freeze { self.save_expression(expr, value)?; } @@ -2961,7 +3092,11 @@ impl<'a> BlockLowering<'a> { }; if let Some(&formal) = body.arg_map.get(path) { for destination in destinations { - self.copy_back(destination, |this| this.load_var(formal))?; + if let Flow::Ended = + self.copy_back(destination, |this| this.load_var(formal))? + { + return Ok(Flow::Ended); + } } } } @@ -3128,9 +3263,9 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - self.copy_back(ret, |this| { + return self.copy_back(ret, |this| { Ok(this.load_scratch(slot, result_width, *signed)) - })?; + }); } Ok(Flow::Continue) } @@ -3167,9 +3302,9 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - self.copy_back(ret, |this| { + return self.copy_back(ret, |this| { Ok(this.load_scratch(slot, result_width, *signed)) - })?; + }); } Ok(Flow::Continue) } @@ -3180,7 +3315,7 @@ impl<'a> BlockLowering<'a> { result, })?; if let Some(ret) = tb.ret.as_deref() { - self.copy_back(ret, |this| Ok(this.load_scratch(slot, 64, false)))?; + return self.copy_back(ret, |this| Ok(this.load_scratch(slot, 64, false))); } Ok(Flow::Continue) } @@ -3233,9 +3368,9 @@ impl<'a> BlockLowering<'a> { strict: tb.ret_strict, })?; if let (Some(ret), Some((value, slot))) = (tb.ret.as_deref(), result) { - self.copy_back(ret, |this| { + return self.copy_back(ret, |this| { Ok(this.load_scratch(slot, value.width, tb.ret_signed)) - })?; + }); } Ok(Flow::Continue) } diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index d1b969a0cf3..92a86ef1cd8 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -167,43 +167,7 @@ pub(super) fn statement_bodies(statement: &Statement) -> Vec<&[Statement]> { _ => Vec::new(), } } -/// Calls that every evaluation of this expression must reach. -pub(super) fn unconditional_expression_calls<'s>( - expr: &'s Expression, - calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, -) { - let inputs = match expr { - Expression::Binary(lhs, Op::LogicAnd, rhs, _) => { - if constant_truth(lhs) == Some(true) { - vec![lhs.as_ref(), rhs.as_ref()] - } else { - vec![lhs.as_ref()] - } - } - Expression::Binary(lhs, Op::LogicOr, rhs, _) => { - if constant_truth(lhs) == Some(false) { - vec![lhs.as_ref(), rhs.as_ref()] - } else { - vec![lhs.as_ref()] - } - } - Expression::Ternary(cond, yes, no, _) => match constant_truth(cond) { - Some(true) => vec![cond.as_ref(), yes.as_ref()], - Some(false) => vec![cond.as_ref(), no.as_ref()], - None => vec![cond.as_ref()], - }, - _ => children(expr), - }; - for child in inputs { - unconditional_expression_calls(child, calls); - } - if let Expression::Term(factor) = expr - && let Factor::FunctionCall(call) = factor.as_ref() - { - calls.push(call); - } -} - +/// Calls in potentially evaluated branches of this expression. pub(super) fn expression_calls<'s>( expr: &'s Expression, calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index ede071581e8..23fde7620c6 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1851,3 +1851,81 @@ fn repeated_clockless_runs_settle_residual_writes_before_entry_reads() { ); } } + +#[test] +fn output_selectors_are_scanned_after_the_timed_callee() { + for (selector, tail) in [ + ( + "$finish(); return 0;", + "unused.next();$assert(0,\"continued after selector finish\");", + ), + ("return 0;", "$assert(words[0]==7); $finish();"), + ] { + let code = format!( + r#"#[test(Top)]module Top {{ + inst clk:$tb::clock_gen;inst unused:$tb::clock_gen;var q:u32;var words:u32[2]; + always_ff(clk){{q+=1;}} + function index()->u32 {{{selector}}} + function give(o:output u32){{clk.next(1);o=7;}} + initial {{give(words[index()]);{tail}}} + }}"# + ); + fn check(mut sim: Simulator) { + sim.set(sim.signal("unused"), 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u32.into()); + assert_eq!(sim.get(sim.signal("unused")), 1u8.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[test] +fn runtime_case_scans_only_the_unmatched_path_to_later_patterns() { + let code = r#"#[test(Top)]module Top(choose:input u32){ + inst clk:$tb::clock_gen;inst unused:$tb::clock_gen;var selector:u32;var q:u32; + always_ff(clk){q+=1;} + function stop()->u32{$finish();return 1;} + initial{selector=choose;case selector{0:{}stop():{}default:{unused.next();}} + clk.next(1);$assert(q==1);$finish();} + }"#; + fn check(mut sim: Simulator, input: u32) { + sim.set(sim.signal("unused"), 1u8); + sim.set(sim.signal("choose"), input); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), u32::from(input == 0).into()); + assert_eq!(sim.get(sim.signal("unused")), 1u8.into()); + } + for input in [0, 1] { + check( + Simulator::builder(code, "Top").build_interpreter().unwrap(), + input, + ); + check( + Simulator::builder(code, "Top").build_cranelift().unwrap(), + input, + ); + check(Simulator::builder(code, "Top").build_wasm().unwrap(), input); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top").build_native().unwrap(), + input, + ); + } +} From 44c26e0711ee93ed8081c86631a291ada0d656e9 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:00:08 +0900 Subject: [PATCH 43/72] fix(native): validate process release and host-request storage --- crates/celox/src/backend/native/backend.rs | 90 +++++++++++++++++++ .../celox/tests/concurrent_initial_runtime.rs | 11 +++ 2 files changed, 101 insertions(+) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 86f5fcdd5b6..fc7f3860c24 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -614,6 +614,51 @@ impl NativeProgramImage { { return Err("a process clock control slot has an invalid state object".into()); } + for release in &process.releases { + if !self + .design + .state_objects + .get(&release.signal) + .is_some_and(|m| m.width == 1 && m.array_dims.is_empty()) + || release.value > 1 + || release + .clock + .is_some_and(|clock| !process.clocks.iter().any(|c| c.signal == clock)) + { + return Err("a process release has an invalid signal, value or clock".into()); + } + } + let valid_host_value = |value: &celox_design::HostValue<_>| { + value.width > 0 + && self + .design + .state_objects + .get(&value.signal) + .is_some_and(|m| { + m.width == value.width && !m.is_4state && m.array_dims.is_empty() + }) + }; + for request in &process.host_requests { + use celox_design::HostRequest; + let valid = match request { + HostRequest::RandomSeed { value, .. } => valid_host_value(value), + HostRequest::RandomGet { result, .. } + | HostRequest::RandomGetSeed { result, .. } => valid_host_value(result), + HostRequest::RandomGetRange { + min, max, result, .. + } => [min, max, result].into_iter().all(valid_host_value), + HostRequest::Component { args, result, .. } => { + args.iter().all(valid_host_value) + && result.as_ref().is_none_or(valid_host_value) + } + HostRequest::FileOpen { path, .. } => valid_host_value(path), + HostRequest::FileWrite { args, .. } => args.iter().all(valid_host_value), + HostRequest::FileFlush { .. } | HostRequest::FileClose { .. } => true, + }; + if !valid { + return Err("a process host request has an invalid state value".into()); + } + } for clock in &process.clocks { if clock.period < 2 || !self.event_map.contains_key(&clock.signal) @@ -3467,6 +3512,51 @@ mod process_metadata_tests { .into_program_image() } + #[test] + fn process_release_and_host_values_are_checked_before_attachment() { + let original = image(); + for kind in 0..5 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes[0]; + let unknown = if kind == 4 { + celox_design::StateAddr { + var_id: celox_design::StateObjectId::from_raw(u32::MAX), + ..slots.delay + } + } else { + slots.delay + }; + match kind { + 0 => slots.releases.push(celox_design::ProcessRelease { + signal: slots.delay, + value: 0, + clock: None, + }), + 1 => slots.releases.push(celox_design::ProcessRelease { + signal: slots.clocks[0].signal, + value: 0, + clock: Some(slots.delay), + }), + _ => slots + .host_requests + .push(celox_design::HostRequest::RandomGet { + handle: "test".into(), + result: celox_design::HostValue { + signal: unknown, + width: if kind == 2 { 0 } else { 1 }, + signed: false, + is_string: false, + }, + }), + } + assert!(broken.validate().is_err(), "corruption {kind} accepted"); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + } + #[test] fn process_clock_metadata_is_checked_before_image_attachment() { let original = image(); diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 23fde7620c6..370134b1ed6 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1929,3 +1929,14 @@ fn runtime_case_scans_only_the_unmatched_path_to_later_patterns() { ); } } + +#[test] +fn output_selector_scratch_follows_a_looping_callee() { + let code = r#"#[test(Top)] module Top { + var random:$tb::random::; var words:u8[2]; + function index()->u32 { var sample:u8; sample=random.get(); return (sample & 0) as u32; } + function give(value:output u8) { value=0; for i in 0..3 { value+=1; } } + initial { give(words[index()]); $assert(words[0]==3); $finish(); } + }"#; + check_passes_on_every_backend(code); +} From 329869f14d7712fd77e633585e4257100777a014 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:06:51 +0900 Subject: [PATCH 44/72] fix(native): preserve four-state host argument storage validation --- crates/celox/src/backend/native/backend.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index fc7f3860c24..718f1e33900 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -634,9 +634,7 @@ impl NativeProgramImage { .design .state_objects .get(&value.signal) - .is_some_and(|m| { - m.width == value.width && !m.is_4state && m.array_dims.is_empty() - }) + .is_some_and(|m| m.width == value.width && m.array_dims.is_empty()) }; for request in &process.host_requests { use celox_design::HostRequest; From 1f978e6293105538ca51cc491fa3031c5f281c36 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 00:48:32 +0900 Subject: [PATCH 45/72] fix(native): check testbench boundaries and empty string backing slots --- crates/celox/src/backend/native/backend.rs | 25 ++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 718f1e33900..e7f06fdc9e7 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -534,6 +534,13 @@ impl NativeProgramImage { if self.code.is_empty() { return Err("code image is empty".into()); } + if self + .runtime_schema + .testbench_kernels + .is_some_and(|start| start > self.runtime_schema.processes.len()) + { + return Err("testbench kernel boundary exceeds process count".into()); + } let mut entry_offsets = HashSet::default(); let mut previous_end = 0usize; for entry in &self.code_entries { @@ -629,12 +636,12 @@ impl NativeProgramImage { } } let valid_host_value = |value: &celox_design::HostValue<_>| { - value.width > 0 + (value.width > 0 || value.is_string) && self .design .state_objects .get(&value.signal) - .is_some_and(|m| m.width == value.width && m.array_dims.is_empty()) + .is_some_and(|m| m.width == value.width.max(1) && m.array_dims.is_empty()) }; for request in &process.host_requests { use celox_design::HostRequest; @@ -3510,6 +3517,20 @@ mod process_metadata_tests { .into_program_image() } + #[test] + fn testbench_boundary_must_fit_process_table() { + let mut image = image(); + for start in [0, image.runtime_schema.processes.len()] { + image.runtime_schema.testbench_kernels = Some(start); + image.to_container_bytes().unwrap(); + } + image.runtime_schema.testbench_kernels = Some(image.runtime_schema.processes.len() + 1); + assert!(matches!( + image.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + #[test] fn process_release_and_host_values_are_checked_before_attachment() { let original = image(); From 83fbaf18f15434119f0ecd87ac7afb1475ed0c47 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 01:32:50 +0900 Subject: [PATCH 46/72] fix(veryl): end expression continuations and preserve clean host requests --- .../src/lowering/process.rs | 20 ++++++ .../src/lowering/process/expressions.rs | 19 +++++- crates/celox-runtime/src/simulation.rs | 11 ++- crates/celox/src/simulation.rs | 9 +++ crates/celox/src/testbench/kernels.rs | 68 +++++++++++++++++++ .../celox/tests/concurrent_initial_runtime.rs | 62 +++++++++++++++++ 6 files changed, 187 insertions(+), 2 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 30fdc0ed7cb..f80c1a45899 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -2028,6 +2028,21 @@ impl<'a> BlockLowering<'a> { } fn lower_statement(&mut self, statement: &Statement) -> Result { + let flow = self.lower_statement_body(statement)?; + if matches!(flow, Flow::Continue) + && !self.scan_clocks( + std::slice::from_ref(statement), + &mut HashSet::default(), + false, + ) + { + self.kernel.finish(); + return Ok(Flow::Ended); + } + Ok(flow) + } + + fn lower_statement_body(&mut self, statement: &Statement) -> Result { let reads = match statement { Statement::Null | Statement::Break => false, Statement::SystemFunctionCall(call) => !matches!(call.kind, SystemFunctionKind::Finish), @@ -2057,6 +2072,11 @@ impl<'a> BlockLowering<'a> { Some(false) => self.lower_statements(&stmt.false_side), None => { let condition = self.condition(&stmt.cond)?; + if !self.scan_expression_clocks(&stmt.cond, &mut HashSet::default(), false) + { + self.kernel.finish(); + return Ok(Flow::Ended); + } self.branch(condition, &stmt.true_side, &stmt.false_side) } } diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index 92a86ef1cd8..dc9c6978f43 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -126,7 +126,15 @@ pub(crate) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { .flat_map(|dst| selection(&dst.index, &dst.select)) })) .collect(), - Statement::SystemFunctionCall(call) => system_inputs(&call.kind), + Statement::SystemFunctionCall(call) => match call.kind { + SystemFunctionKind::Bits(_) + | SystemFunctionKind::Size(..) + | SystemFunctionKind::Clog2(_) + | SystemFunctionKind::Onehot(_) + | SystemFunctionKind::Signed(_) + | SystemFunctionKind::Unsigned(_) => Vec::new(), + _ => system_inputs(&call.kind), + }, Statement::TbMethodCall(tb) => { let mut inputs: Vec<&Expression> = match &tb.method { TbMethod::ClockNext { count, .. } => count.iter().collect(), @@ -356,6 +364,9 @@ impl BlockLowering<'_> { }; for child in &inputs { let value = self.expression(child)?; + if !self.scan_expression_clocks(child, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } self.save_expression(child, value)?; } let values = inputs @@ -372,6 +383,9 @@ impl BlockLowering<'_> { is_and: bool, ) -> Result { let left = self.expression(lhs)?; + if !self.scan_expression_clocks(lhs, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } self.save_expression(lhs, left)?; let builder = self.kernel.builder(); let not = builder.alloc_logic(1); @@ -441,6 +455,9 @@ impl BlockLowering<'_> { return Ok(self.saved_expression(expr)); } let value = self.expression(cond)?; + if !self.scan_expression_clocks(cond, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } self.save_expression(cond, value)?; let truth = self .parser diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index ab7e8b5ae4d..d622fb43a4c 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -97,6 +97,13 @@ pub trait SimulationExecutor { true } + /// Whether this request can modify design state outside kernel stores. + /// Unknown hosts remain conservative; random/file scratch-only services + /// can preserve an already completed combinational settle. + fn host_request_changes_design(&self, _process: usize, _request: usize) -> bool { + true + } + /// Serve host request `request` of process `process` at `time`, reading /// and writing the scratch state the request names. Returns whether the /// process resumes; `false` ends the simulation, as when a host @@ -1449,7 +1456,9 @@ impl SimulationState { } // A component or host service may write design // state outside this kernel's store instrumentation. - *comb_current = false; + if executor.host_request_changes_design(process, request as usize) { + *comb_current = false; + } any_ran = true; continue; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index c38ed9254d6..da25eb6d5d9 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -184,6 +184,15 @@ impl SimulationExecutor for Simulator { && !self.program.runtime_schema.clock_phase_sensitive_comb } + fn host_request_changes_design(&self, process: usize, request: usize) -> bool { + self.program + .runtime_schema + .processes + .get(process) + .and_then(|process| process.host_requests.get(request)) + .is_none_or(|request| matches!(request, celox_design::HostRequest::Component { .. })) + } + fn host_request( &mut self, process: usize, diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 90cf580d75a..530dd151738 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -544,6 +544,17 @@ mod event_yield_settle_tests { } impl SimulationExecutor for CountingExecutor { type Backend = B; + fn host_request_changes_design(&self, process: usize, request: usize) -> bool { + SimulationExecutor::host_request_changes_design(&self.sim, process, request) + } + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + SimulationExecutor::host_request(&mut self.sim, process, request, time) + } fn backend(&self) -> &B { &self.sim.backend } @@ -617,6 +628,63 @@ mod event_yield_settle_tests { panic!("process did not finish"); } #[test] + fn clean_random_host_requests_preserve_settled_design_state() { + fn count_host(mut sim: Simulator) -> usize { + sim.testbench_random = Some(RandomTable::new(7)); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: None, + }); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + }; + state.step(&mut executor).unwrap(); + assert!(state.is_finished()); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 1 + ); + executor.combs + } + let source = |body: &str| { + format!( + "#[test(Top)]module Top{{var random:$tb::random::;var f:$tb::file;var source:u8;var derived:u8;always_comb{{derived=source;}}initial{{source=1;{body}$finish();}}}}" + ) + }; + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("clean.txt"); + let file_body = format!( + "f.open(\"{}\");f.write(\"x\");f.flush();f.close();", + file.display() + ); + macro_rules! check { + ($build:ident) => {{ + let baseline = source(""); + let expected = count_host(Simulator::builder(&baseline, "Top").$build().unwrap()); + for body in ["random.seed(7);", file_body.as_str()] { + let seeded = source(body); + assert_eq!( + count_host(Simulator::builder(&seeded, "Top").$build().unwrap()), + expected + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] fn private_loop_counters_do_not_request_settles() { let code = r#"#[test(Top)]module Top(limit:input u32){initial{for i in 0..limit{$assert(1);}$finish();}}"#; macro_rules! check { diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 370134b1ed6..309d0bb9f7c 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -1940,3 +1940,65 @@ fn output_selector_scratch_follows_a_looping_callee() { }"#; check_passes_on_every_backend(code); } + +#[test] +fn value_system_statement_operands_leave_reachable_clocks_registered() { + let code = r#"#[test(Top)] module Top {inst clk:$tb::clock_gen;var q:u32; + always_ff(clk){q+=1;} function stop()->u32{$finish();return 0;} + initial{$bits(stop());clk.next(1);$assert(q==1);$finish();}} + "#; + check_passes_on_every_backend(code); +} +#[test] +fn terminating_assignment_expressions_do_not_lower_their_clock_tail() { + for statement in ["value=stop();", "value=1+stop();", "value=stop()+other();"] { + let code = format!( + r#"#[test(Top)] module Top {{inst clk:$tb::clock_gen;var value:u32; + function stop()->u32{{$finish();return 0;}} function other()->u32{{clk.next();return 1;}} + initial{{{statement}clk.next();}}}}"# + ); + + check_passes_on_every_backend(&code); + } +} + +#[test] +fn clean_random_seed_does_not_replay_combinational_observers() { + let count = |body: &str| { + let code = format!( + r#"#[test(Top)]module Top{{var random:$tb::random::;var source:u8;var derived:u8;always_comb{{derived=source;$assert(1,"comb");}}initial{{source=1;{body}$finish();}}}}"# + ); + let result = Simulator::builder(&code, "Top") + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) + .count() + }; + assert_eq!(count("random.seed(7);"), count("")); +} + +#[test] +fn no_op_value_operands_do_not_initialize_an_unused_clock() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;inst unused:$tb::clock_gen; + function hidden()->u32{unused.next();return 0;} + initial{$bits(hidden());clk.next();$finish();}}"#; + fn check(mut sim: Simulator) { + let unused = sim.signal("unused"); + sim.set(unused, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(unused), 1u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} From 17b631bbe698bcfd1bbdf717d8b5135d24285c7f Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 02:17:46 +0900 Subject: [PATCH 47/72] fix(runtime): preserve component host settles when resuming kernels --- crates/celox-runtime/src/simulation.rs | 10 +- crates/celox/src/simulation.rs | 4 +- crates/celox/src/testbench/kernels.rs | 130 +++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 6 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 6ea09c5af44..1c567b93aed 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -97,9 +97,9 @@ pub trait SimulationExecutor { true } - /// Whether this request can modify design state outside kernel stores. - /// Unknown hosts remain conservative; random/file scratch-only services - /// can preserve an already completed combinational settle. + /// Whether a served request leaves design writes needing a settle. + /// Unknown hosts remain conservative; scratch-only services or hosts + /// that already settled their writes can preserve a completed settle. fn host_request_changes_design(&self, _process: usize, _request: usize) -> bool { true } @@ -1454,8 +1454,8 @@ impl SimulationState { self.finished = true; return Ok(true); } - // A component or host service may write design - // state outside this kernel's store instrumentation. + // A host may leave design writes outside this + // kernel's store instrumentation that need settling. if executor.host_request_changes_design(process, request as usize) { *comb_current = false; } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index c72d39bbaa1..af13a92645b 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -190,7 +190,9 @@ impl SimulationExecutor for Simulator { .processes .get(process) .and_then(|process| process.host_requests.get(request)) - .is_none_or(|request| matches!(request, celox_design::HostRequest::Component { .. })) + .is_none_or(|request| { + matches!(request, celox_design::HostRequest::Component { .. }) && self.dirty + }) } fn host_request( diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 530dd151738..a4e75b84fe7 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -684,6 +684,136 @@ mod event_yield_settle_tests { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check!(build_native); } + #[cfg(feature = "host-runtime")] + #[test] + fn writing_component_host_request_preserves_completed_settle() { + use std::ffi::c_void; + use veryl_component_sys as sys; + struct Host { + api: *const sys::VrlHostApi, + output: u32, + } + unsafe extern "C" fn create( + ctx: *mut sys::VrlCtx, + api: *const sys::VrlHostApi, + ) -> *mut c_void { + let clock = unsafe { + ((*api).port_index)(ctx, sys::VrlStr::from_str("clk"), sys::VRL_DIR_CLOCK) + }; + let output = unsafe { + ((*api).port_index)(ctx, sys::VrlStr::from_str("q"), sys::VRL_DIR_OUTPUT) + }; + if clock < 0 || output < 0 { + return std::ptr::null_mut(); + } + Box::into_raw(Box::new(Host { + api, + output: output as u32, + })) + .cast() + } + unsafe extern "C" fn destroy(state: *mut c_void) { + drop(unsafe { Box::from_raw(state.cast::()) }); + } + unsafe extern "C" fn hook(_: *mut c_void, _: *mut sys::VrlCtx) -> i32 { + 0 + } + unsafe extern "C" fn call( + state: *mut c_void, + ctx: *mut sys::VrlCtx, + name: sys::VrlStr, + args: *const sys::VrlValue, + nargs: usize, + _: *mut sys::VrlValue, + ) -> i32 { + if unsafe { name.as_str() } != "drive" || nargs != 1 { + return 1; + } + let state = unsafe { &*state.cast::() }; + let value = unsafe { (*args).words.as_ref() }.copied().unwrap(); + unsafe { ((*state.api).write_output)(ctx, state.output, &value, std::ptr::null()) }; + 0 + } + static COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + abi_version: sys::VRL_COMPONENT_ABI_VERSION, + kind: sys::VRL_KIND_CLOCKED, + create, + destroy, + on_init: hook, + on_reset: hook, + on_clock: hook, + call_method: call, + on_finish: hook, + }; + crate::register_static_component("settled_writer", &COMPONENT); + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("component")).unwrap(); + std::fs::write(dir.path().join("Veryl.toml"), "[project]\nname=\"settled_writer_test\"\nversion=\"0.1.0\"\n[[components]]\npath=\"component\"\n").unwrap(); + std::fs::write(dir.path().join("component/veryl.manifest.json"), r#"{"types":{"settled_writer":{"kind":"clocked","ports":[{"name":"clk","dir":"input","role":"clock"},{"name":"q","dir":"output"}],"methods":[{"name":"drive","args":[{"name":"value","type":"value"}]}]}}}"#).unwrap(); + let code = r#"#[test(Top)]module Top{ + inst clk:$tb::clock_gen;var q:u8;var source:u8;var derived:u8; + inst c:$comp::settled_writer(clk,q); + always_comb{derived=q+source;} + initial{source=1;c.drive(7);$finish();}} + "#; + fn check(mut sim: Simulator) { + let tb = super::super::compile_initial_testbench(&sim).unwrap(); + let initial = sim + .components + .initialize( + tb.components(), + tb.component_bindings(), + tb.component_libraries(), + tb.component_file_base(), + 7, + "Top", + false, + &mut sim.backend, + ) + .unwrap(); + apply_component_writes(&mut sim, initial); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + }; + state.step(&mut executor).unwrap(); + assert!(state.is_finished()); + assert_eq!( + executor.sim.backend.get_as::(executor.sim.signal("q")), + 7 + ); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 8 + ); + assert_eq!(executor.combs, 1, "{}", std::any::type_name::()); + } + macro_rules! check_backend { + ($build:ident) => { + let metadata = + veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + check( + Simulator::builder(code, "Top") + .with_metadata(metadata) + .$build() + .unwrap(), + ); + }; + } + check_backend!(build_interpreter); + check_backend!(build_cranelift); + check_backend!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_backend!(build_native); + } + #[test] fn private_loop_counters_do_not_request_settles() { let code = r#"#[test(Top)]module Top(limit:input u32){initial{for i in 0..limit{$assert(1);}$finish();}}"#; From 6713ba25b6f3c2cbf577d8938420cefe2bf4b539 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 03:54:02 +0900 Subject: [PATCH 48/72] fix(veryl): settle component output writes before finishing --- crates/celox/src/testbench/kernels.rs | 30 +++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index a4e75b84fe7..cad104db0ea 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -470,6 +470,10 @@ pub(crate) fn serve_host_request( )?; apply_component_writes(sim, writes); if sim.components.finish_requested() { + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } return Ok(false); } let Some(result) = result else { @@ -726,12 +730,16 @@ mod event_yield_settle_tests { nargs: usize, _: *mut sys::VrlValue, ) -> i32 { - if unsafe { name.as_str() } != "drive" || nargs != 1 { + let method = unsafe { name.as_str() }; + if !matches!(method, "drive" | "drive_finish") || nargs != 1 { return 1; } let state = unsafe { &*state.cast::() }; let value = unsafe { (*args).words.as_ref() }.copied().unwrap(); unsafe { ((*state.api).write_output)(ctx, state.output, &value, std::ptr::null()) }; + if method == "drive_finish" { + unsafe { ((*state.api).finish)(ctx) }; + } 0 } static COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { @@ -749,7 +757,7 @@ mod event_yield_settle_tests { let dir = tempfile::tempdir().unwrap(); std::fs::create_dir(dir.path().join("component")).unwrap(); std::fs::write(dir.path().join("Veryl.toml"), "[project]\nname=\"settled_writer_test\"\nversion=\"0.1.0\"\n[[components]]\npath=\"component\"\n").unwrap(); - std::fs::write(dir.path().join("component/veryl.manifest.json"), r#"{"types":{"settled_writer":{"kind":"clocked","ports":[{"name":"clk","dir":"input","role":"clock"},{"name":"q","dir":"output"}],"methods":[{"name":"drive","args":[{"name":"value","type":"value"}]}]}}}"#).unwrap(); + std::fs::write(dir.path().join("component/veryl.manifest.json"), r#"{"types":{"settled_writer":{"kind":"clocked","ports":[{"name":"clk","dir":"input","role":"clock"},{"name":"q","dir":"output"}],"methods":[{"name":"drive","args":[{"name":"value","type":"value"}]},{"name":"drive_finish","args":[{"name":"value","type":"value"}]}]}}}"#).unwrap(); let code = r#"#[test(Top)]module Top{ inst clk:$tb::clock_gen;var q:u8;var source:u8;var derived:u8; inst c:$comp::settled_writer(clk,q); @@ -796,22 +804,26 @@ mod event_yield_settle_tests { assert_eq!(executor.combs, 1, "{}", std::any::type_name::()); } macro_rules! check_backend { - ($build:ident) => { + ($build:ident, $source:expr) => { let metadata = veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); check( - Simulator::builder(code, "Top") + Simulator::builder($source, "Top") .with_metadata(metadata) .$build() .unwrap(), ); }; } - check_backend!(build_interpreter); - check_backend!(build_cranelift); - check_backend!(build_wasm); - #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] - check_backend!(build_native); + for method in ["drive", "drive_finish"] { + let code = code.replace("c.drive(7)", &format!("c.{method}(7)")); + let code = code.as_str(); + check_backend!(build_interpreter, code); + check_backend!(build_cranelift, code); + check_backend!(build_wasm, code); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_backend!(build_native, code); + } } #[test] From 1b23b035a009a681268a32d147ef59142a3381de Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 04:11:58 +0900 Subject: [PATCH 49/72] fix(veryl): sample host waiters at the current kernel timestamp --- crates/celox-runtime/src/simulation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index c524d76b86a..18cc99f7c1d 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1171,7 +1171,7 @@ impl SimulationState { return Ok(false); } let time = self.scheduler.time; - self.sample_waiting_events(executor)?; + self.sample_waiting_events(executor, time)?; let result = self.step_round(executor, time, Vec::new(), Vec::new(), Vec::new(), false); let progressed = result.as_ref().is_ok_and(|ran| *ran); self.finish_clock_round(time, Vec::new(), &[], result)?; From 50dafaae03b2b2cb0aafe9623c4025dbc3ea20a9 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 04:40:57 +0900 Subject: [PATCH 50/72] fix(veryl): propagate terminating host and event argument flow --- .../src/lowering/process.rs | 66 ++++++++++++++++--- .../src/lowering/process/expressions.rs | 17 +++-- .../celox/tests/concurrent_initial_runtime.rs | 37 +++++++++++ 3 files changed, 104 insertions(+), 16 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index f80c1a45899..3652ca31ba5 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -2053,7 +2053,9 @@ impl<'a> BlockLowering<'a> { } match statement { Statement::Assign(assign) => { - self.lower_assign(assign)?; + if let Flow::Ended = self.lower_assign(assign)? { + return Ok(Flow::Ended); + } if assign.hier_dst.is_some() || assign .dst @@ -2237,7 +2239,7 @@ impl<'a> BlockLowering<'a> { self.join(join, joined) } - fn lower_assign(&mut self, assign: &AssignStatement) -> Result<(), ParserError> { + fn lower_assign(&mut self, assign: &AssignStatement) -> Result { // A constant index or part select outside the destination is an // error of the testbench, as it was for the interpreter. for destination in &assign.dst { @@ -2308,7 +2310,11 @@ impl<'a> BlockLowering<'a> { assign }; let statement = Statement::Assign(assign.clone()); - let bindings = self.expression_bindings(&expressions::statement_inputs(&statement))?; + let Some(bindings) = + self.expression_bindings(&expressions::statement_inputs(&statement))? + else { + return Ok(Flow::Ended); + }; self.parser.push_process_expression_values(bindings); let mut counter_values = Vec::new(); for destination in &assign.dst { @@ -2336,7 +2342,7 @@ impl<'a> BlockLowering<'a> { let after = self.load_var(var)?; self.record_event_edges(before, after, rises, falls); } - Ok(()) + Ok(Flow::Continue) } /// A `for` loop whose counter and bounds live in state, so its body @@ -2821,6 +2827,9 @@ impl<'a> BlockLowering<'a> { } SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => { let flow = self.system_task(call)?; + if matches!(flow, Flow::Ended) { + return Ok(flow); + } self.yield_for_runtime_event()?; Ok(flow) } @@ -2834,7 +2843,10 @@ impl<'a> BlockLowering<'a> { } fn system_task(&mut self, call: &SystemFunctionCall) -> Result { - let bindings = self.expression_bindings(&expressions::system_inputs(&call.kind))?; + let Some(bindings) = self.expression_bindings(&expressions::system_inputs(&call.kind))? + else { + return Ok(Flow::Ended); + }; self.parser.push_process_expression_values(bindings); let first_site = self.parser.runtime_event_sites().len(); let (parser, kernel, targets, sources, convert) = parts!(self); @@ -2865,6 +2877,9 @@ impl<'a> BlockLowering<'a> { args: &[SystemFunctionInput], ) -> Result { let mut condition = self.condition(&cond.0)?; + if self.argument_ended(&cond.0) { + return Ok(Flow::Ended); + } let argument_calls = args.iter().any(|arg| expressions::has_call(&arg.0)); let freeze_condition = argument_calls || expressions::has_call(&cond.0); if freeze_condition { @@ -2872,7 +2887,9 @@ impl<'a> BlockLowering<'a> { } self.settle_if_dirty()?; let inputs = args.iter().map(|arg| &arg.0).collect::>(); - let bindings = self.expression_bindings(&inputs)?; + let Some(bindings) = self.expression_bindings(&inputs)? else { + return Ok(Flow::Ended); + }; if freeze_condition { let value = self.saved_expression(&cond.0); condition = self @@ -3123,10 +3140,19 @@ impl<'a> BlockLowering<'a> { Ok(Flow::Continue) } + fn argument_ended(&mut self, expression: &Expression) -> bool { + if self.scan_expression_clocks(expression, &mut HashSet::default(), false) { + false + } else { + self.kernel.finish(); + true + } + } + fn file_argument( &mut self, arg: &SystemFunctionInput, - ) -> Result, ParserError> { + ) -> Result>, ParserError> { let width = argument_width(arg); let signed = expression_signed(&arg.0); let (mut value, slot) = self.host_scratch( @@ -3148,11 +3174,14 @@ impl<'a> BlockLowering<'a> { reg } else { let reg = self.expression(&arg.0)?; + if self.argument_ended(&arg.0) { + return Ok(None); + } self.parser .cast_reg_width_ext(self.kernel.builder(), reg, width, signed) }; self.store_scratch(slot, width, reg); - Ok(value) + Ok(Some(value)) } fn lower_tb_method(&mut self, tb: &TbMethodCall) -> Result { @@ -3265,6 +3294,9 @@ impl<'a> BlockLowering<'a> { } TbMethod::RandomSeed { value } => { let seed = self.expression(value)?; + if self.argument_ended(value) { + return Ok(Flow::Ended); + } let seed = self.unsigned_bits(seed, 64); let (host_value, slot) = self.host_scratch("random_seed", 64, false, false)?; self.store_scratch(slot, 64, seed); @@ -3297,10 +3329,16 @@ impl<'a> BlockLowering<'a> { } => { let freeze = expressions::has_call(min) || expressions::has_call(max); let min_reg = self.expression(min)?; + if self.argument_ended(min) { + return Ok(Flow::Ended); + } if freeze { self.save_expression(min, min_reg)?; } let max_reg = self.expression(max)?; + if self.argument_ended(max) { + return Ok(Flow::Ended); + } let min_reg = if freeze { self.saved_expression(min) } else { @@ -3362,6 +3400,9 @@ impl<'a> BlockLowering<'a> { reg } else { let reg = self.expression(&arg.0)?; + if self.argument_ended(&arg.0) { + return Ok(Flow::Ended); + } self.unsigned_bits(reg, width) }; self.store_scratch(slot, width, reg); @@ -3395,7 +3436,9 @@ impl<'a> BlockLowering<'a> { Ok(Flow::Continue) } TbMethod::FileOpen { name, append } => { - let path = self.file_argument(name)?; + let Some(path) = self.file_argument(name)? else { + return Ok(Flow::Ended); + }; self.host_request(HostRequest::FileOpen { handle: self.resource_name(tb.inst), path, @@ -3410,7 +3453,10 @@ impl<'a> BlockLowering<'a> { let skip = usize::from(template.is_some()); let mut values = Vec::new(); for arg in &args[skip..] { - values.push(self.file_argument(arg)?); + let Some(value) = self.file_argument(arg)? else { + return Ok(Flow::Ended); + }; + values.push(value); } self.host_request(HostRequest::FileWrite { handle: self.resource_name(tb.inst), diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index dc9c6978f43..4b7d7a0b76a 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -292,9 +292,9 @@ impl BlockLowering<'_> { pub(super) fn expression_bindings( &mut self, inputs: &[&Expression], - ) -> Result, ParserError> { + ) -> Result>, ParserError> { if !inputs.iter().any(|expr| has_call(expr)) { - return Ok(HashMap::default()); + return Ok(Some(HashMap::default())); } let inputs = inputs .iter() @@ -303,12 +303,17 @@ impl BlockLowering<'_> { .collect::>(); for expr in &inputs { let value = self.expression(expr)?; + if self.argument_ended(expr) { + return Ok(None); + } self.save_expression(expr, value)?; } - Ok(inputs - .into_iter() - .map(|expr| (expr.token_range(), self.saved_expression(expr))) - .collect()) + Ok(Some( + inputs + .into_iter() + .map(|expr| (expr.token_range(), self.saved_expression(expr))) + .collect(), + )) } pub(super) fn expression(&mut self, expr: &Expression) -> Result { diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 309d0bb9f7c..6616683f7fd 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2002,3 +2002,40 @@ fn no_op_value_operands_do_not_initialize_an_unused_clock() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulator::builder(code, "Top").build_native().unwrap()); } + +#[test] +fn terminating_host_argument_skips_later_clock_argument() { + for call in [ + "value=random.get_range(stop(),later());", + "f.write(\"%d %d\",stop(),later());", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; var random:$tb::random::; var f:$tb::file; var value:u32; + function stop()->u32 {{$finish();return 0;}} + function later()->u32 {{clk.next();return 10;}} + initial {{{call}}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} + +#[test] +fn terminating_event_argument_skips_later_clock_argument() { + for call in [ + "$display(\"%d %d\",stop(),later());", + "$write(\"%d %d\",stop(),later());", + "$assert(1,\"%d %d\",stop(),later());", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; + function stop()->u32 {{$finish();return 0;}} + function later()->u32 {{clk.next();return 10;}} + initial {{{call}}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} From dfc76dad3c962bb7b2d9c99ecbd5f4330dfcaa33 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 06:52:45 +0900 Subject: [PATCH 51/72] fix(runtime): retain process edge counts and bound native controls --- .../src/dynamic_for_check.rs | 46 ++++++++++ .../src/lowering/process.rs | 23 +++++ crates/celox-runtime/src/simulation.rs | 75 +++++++++++++++- crates/celox/src/backend/native/backend.rs | 85 ++++++++++++++++--- crates/celox/src/backend/native/image_file.rs | 4 +- .../celox/tests/concurrent_initial_runtime.rs | 32 +++++++ 6 files changed, 250 insertions(+), 15 deletions(-) diff --git a/crates/celox-frontend-veryl/src/dynamic_for_check.rs b/crates/celox-frontend-veryl/src/dynamic_for_check.rs index f186e9b4a9d..82310668f80 100644 --- a/crates/celox-frontend-veryl/src/dynamic_for_check.rs +++ b/crates/celox-frontend-veryl/src/dynamic_for_check.rs @@ -306,6 +306,9 @@ fn check_elaborated_for( hints: &FusedSirOptimizationHints, diagnostics: &mut Vec, ) { + if initial_bound_finishes(statement, module) { + return; + } let continuation_bound = match &statement.range { ForRange::Forward { end, .. } | ForRange::Stepped { end, .. } => end, ForRange::Reverse { start, .. } => start, @@ -1269,12 +1272,55 @@ fn check_statements( } } +fn initial_bound_finishes(statement: &ForStatement, module: &Module) -> bool { + let first = match &statement.range { + ForRange::Forward { start, .. } | ForRange::Stepped { start, .. } => start, + ForRange::Reverse { end, .. } => end, + }; + let ForBound::Expression(expression) = first else { + return false; + }; + let Expression::Term(factor) = expression.as_ref() else { + return false; + }; + let Factor::FunctionCall(call) = factor.as_ref() else { + return false; + }; + let body = module.functions.get(&call.id).and_then(|function| { + call.index + .as_deref() + .and_then(|index| function.get_function(index)) + .or_else(|| function.get_function(&[])) + }); + body.is_some_and(|body| { + for statement in &body.statements { + match statement { + Statement::SystemFunctionCall(call) + if matches!(call.kind, SystemFunctionKind::Finish) => + { + return true; + } + Statement::Assign(_) + | Statement::Null + | Statement::FunctionCall(_) + | Statement::SystemFunctionCall(_) + | Statement::TbMethodCall(_) => {} + _ => return false, + } + } + false + }) +} + fn check_for( statement: &ForStatement, module: &Module, diagnostics: &mut Vec, from_ff: bool, ) { + if initial_bound_finishes(statement, module) { + return; + } let continuation_bound = match &statement.range { ForRange::Forward { end, .. } | ForRange::Stepped { end, .. } => end, ForRange::Reverse { start, .. } => start, diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 3652ca31ba5..be84266440c 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -772,6 +772,11 @@ fn collect_scratch_needs( ); } } + TbMethod::ClockNext { + count: Some(count), .. + } if expressions::has_call(count) => { + need(needs, "clock_count", PROCESS_DELAY_WIDTH) + } TbMethod::ClockNext { .. } | TbMethod::ResetAssert { .. } | TbMethod::FileClose @@ -2369,8 +2374,18 @@ impl<'a> BlockLowering<'a> { None }; let start_reg = self.for_bound(shape.start, width, cmp_signed)?; + if let ForBound::Expression(expression) = shape.start + && self.argument_ended(expression) + { + return Ok(Flow::Ended); + } self.store_scratch(start_slot, width, start_reg); let end_reg = self.for_bound(shape.end, width, cmp_signed)?; + if let ForBound::Expression(expression) = shape.end + && self.argument_ended(expression) + { + return Ok(Flow::Ended); + } self.store_scratch(end_slot, width, end_reg); // Bounds can write design state even when the range is empty. self.settle_if_dirty()?; @@ -3214,6 +3229,14 @@ impl<'a> BlockLowering<'a> { } None => self.constant(1, PROCESS_DELAY_WIDTH), }; + let count = if self.dirty { + let (_, slot) = self.take_scratch("clock_count", PROCESS_DELAY_WIDTH)?; + self.store_scratch(slot, PROCESS_DELAY_WIDTH, count); + self.settle_if_dirty()?; + self.load_scratch(slot, PROCESS_DELAY_WIDTH, false) + } else { + count + }; self.kernel .wait_clock(clock, count, None) .map_err(|error| { diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 11b16bac28a..02de01f1a6b 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1281,6 +1281,43 @@ impl SimulationState { .collect() } + fn add_process_edge_replays( + &self, + backend: &B, + before: &[(u32, u32)], + replays: &mut std::collections::BTreeMap, + ) { + let mut extra = std::collections::BTreeMap::::new(); + for ((id, rises, falls), (old_rises, old_falls)) in + self.process_event_counters.iter().zip(before) + { + let rise = backend.get_as::(*rises).wrapping_sub(*old_rises) as u64; + let fall = backend.get_as::(*falls).wrapping_sub(*old_falls) as u64; + let count = match self.domain_kinds[*id] { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => fall, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => rise, + _ => rise + fall, + }; + let canonical = self.event_info[*id].canonical_id; + let Some(info) = self.event_info.get(canonical) else { + continue; + }; + if info.eval_ff_event.is_none() + && info.eval_only_event.is_none() + && info.apply_event.is_none() + { + continue; + } + extra + .entry(canonical) + .and_modify(|n| *n = (*n).max(count.saturating_sub(1))) + .or_insert(count.saturating_sub(1)); + } + for (id, count) in extra { + *replays.entry(id).or_default() += count; + } + } + fn process_counter_edges(&self, backend: &B, before: &[(u32, u32)]) -> BitSet { let mut edges = BitSet::with_capacity(backend.num_events()); for ((id, rises, falls), (old_rises, old_falls)) in @@ -1290,7 +1327,13 @@ impl SimulationState { Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { backend.get_as::(*falls) != *old_falls } - _ => backend.get_as::(*rises) != *old_rises, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + backend.get_as::(*rises) != *old_rises + } + _ => { + backend.get_as::(*rises) != *old_rises + || backend.get_as::(*falls) != *old_falls + } }; if changed { edges.insert(*id); @@ -1816,6 +1859,8 @@ impl SimulationState { let mut discovered_in_this_step = BitSet::with_capacity(num_events); // Counter-recorded kernel edges survive later blocking stores that // restored the signal before the kernel returned. + let mut edge_replays = std::collections::BTreeMap::new(); + self.add_process_edge_replays(executor.backend(), &counter_values, &mut edge_replays); let mut recorded_edges = self.process_counter_edges(executor.backend(), &counter_values); recorded_edges.union_with(&scheduled_edges); let mut scheduled_trigger_ids = recorded_edges.clone(); @@ -1965,6 +2010,7 @@ impl SimulationState { self.finished = true; return Ok(true); } + self.add_process_edge_replays(executor.backend(), &before, &mut edge_replays); ff_body_edges .union_with(&self.process_counter_edges(executor.backend(), &before)); } @@ -2075,6 +2121,11 @@ impl SimulationState { )? }; if progressed { + self.add_process_edge_replays( + executor.backend(), + &inactive_counter_values, + &mut edge_replays, + ); let mut driven = self.process_counter_edges(executor.backend(), &inactive_counter_values); recorded_edges.union_with(&driven); @@ -2109,7 +2160,22 @@ impl SimulationState { } if newly_triggered.is_empty() && !any_new_outer_loop_trigger { - break; + let replay = edge_replays + .iter() + .filter_map(|(&id, &count)| (count > 0).then_some(id)) + .collect::>(); + if replay.is_empty() { + break; + } + discovered_in_this_step.make_empty(); + triggered_domains.make_empty(); + executor.backend_mut().clear_triggered_bits(); + for id in replay { + *edge_replays.get_mut(&id).unwrap() -= 1; + recorded_edges.insert(id); + executor.backend_mut().mark_triggered_bit(id); + } + continue; } // Publish all simultaneous NBA updates before polling waiters. @@ -2163,6 +2229,11 @@ impl SimulationState { return Ok(true); } if any_process_ran { + self.add_process_edge_replays( + executor.backend(), + &counter_values, + &mut edge_replays, + ); let mut driven = self.process_counter_edges(executor.backend(), &counter_values); recorded_edges.union_with(&driven); diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index cc47a0bb6bf..c423fb2389e 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -413,8 +413,8 @@ pub struct NativeProgramImage { comb_unit_offsets: Vec, /// Entry offset of each process kernel. process_offsets: Vec, - /// Clock-control addresses and byte offsets used to compile each process kernel. - compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, + /// Control addresses and byte offsets used to compile each process kernel. + compiled_process_controls: Vec>, required_native_features: u8, #[serde(serialize_with = "celox_design::serde_sorted::map")] event_map: HashMap, @@ -584,18 +584,33 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } - if self.compiled_process_clocks.len() != self.runtime_schema.processes.len() + if self.compiled_process_controls.len() != self.runtime_schema.processes.len() || self - .compiled_process_clocks + .compiled_process_controls .iter() .zip(&self.runtime_schema.processes) - .any(|((address, offset), process)| { - process.clock != *address || self.layout.offsets.get(address) != Some(offset) + .any(|(bindings, process)| { + let addresses = [ + process.resume, + process.status, + process.delay, + process.clock, + process.release, + ] + .into_iter() + .chain(process.comb_clean) + .collect::>(); + bindings.len() != addresses.len() + || bindings + .iter() + .zip(addresses) + .any(|((address, offset), expected)| { + *address != expected + || self.layout.offsets.get(address) != Some(offset) + }) }) { - return Err( - "process clock control slots disagree with compiled kernel bindings".into(), - ); + return Err("process control slots disagree with compiled kernel bindings".into()); } let mut process_clock_periods = fxhash::FxHashMap::default(); for process in &self.runtime_schema.processes { @@ -2423,12 +2438,24 @@ fn compile_program( comb_offset, comb_unit_offsets, process_offsets, - compiled_process_clocks: sir + compiled_process_controls: sir .runtime() .runtime_schema .processes .iter() - .map(|process| (process.clock, layout.offsets[&process.clock])) + .map(|process| { + [ + process.resume, + process.status, + process.delay, + process.clock, + process.release, + ] + .into_iter() + .chain(process.comb_clean) + .map(|address| (address, layout.offsets[&address])) + .collect() + }) .collect(), required_native_features, event_map, @@ -3605,6 +3632,42 @@ mod process_metadata_tests { } } + #[test] + fn process_release_control_bindings_cannot_be_swapped() { + let original = image(); + original.to_container_bytes().unwrap(); + for control in 0..5 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes; + let get = |p: &celox_design::ProcessSlots| match control { + 0 => p.resume, + 1 => p.status, + 2 => p.delay, + 3 => p.clock, + _ => p.release, + }; + let a = get(&slots[0]); + let b = get(&slots[1]); + assert_ne!(a, b); + for (p, value) in [(0, b), (1, a)] { + match control { + 0 => slots[p].resume = value, + 1 => slots[p].status = value, + 2 => slots[p].delay = value, + 3 => slots[p].clock = value, + _ => slots[p].release = value, + } + } + assert!( + matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + ), + "control {control}" + ); + } + } + #[test] fn process_clock_control_cannot_name_an_unrelated_register() { let original = image(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 4711d5de05b..8e71f670159 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 22 binds each process clock control to its compiled address and offset. -const CONTAINER_VERSION: u16 = 22; +// Version 23 binds every process control to its compiled address and offset. +const CONTAINER_VERSION: u16 = 23; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 6616683f7fd..b9997ff90da 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2039,3 +2039,35 @@ fn terminating_event_argument_skips_later_clock_argument() { check_passes_on_every_backend(&code); } } + +#[test] +fn terminating_for_start_skips_a_later_clock_bound() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var seed:u32;function stop()->u32{$finish();return seed;}function later()->u32{clk.next();return 2;}initial{for i in stop()..later(){$assert(0);}}}"#; + check_passes_on_every_backend(code); +} +#[test] +fn zero_clock_count_keeps_helper_design_writes_dirty() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var source:u32;let derived:u32=source+1;function change(dst:output u32)->u32{dst=7;return 0;}initial{source=1;clk.next(change(source));$assert(derived==source+1);$finish();}}"#; + check_passes_on_every_backend(code); +} +#[test] +fn repeated_hierarchical_clock_edges_keep_their_count() { + let code = r#"module Child(clk:input clock,q:output u32){always_ff(clk){q=q+1;}}#[test(Top)]module Top{var q:u32;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;$assert(dut.q==0);dut.clk=1;$assert(dut.q==0);dut.clk=0;}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} From b0e738883ebc73ea6e0e0dd2cc0cb0be682e5c4a Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:18:11 +0900 Subject: [PATCH 52/72] fix(runtime): complete pending clock falls during retries --- crates/celox-runtime/src/simulation.rs | 2 +- crates/celox/src/backend/native/backend.rs | 16 ++++++ packages/celox/src/e2e.test.ts | 58 ++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 2c58120791a..79a8058d42c 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -913,7 +913,7 @@ impl SimulationState { }); } let mut rising = Vec::with_capacity(due.len()); - let mut falling = Vec::new(); + let mut falling = falling.to_vec(); for id in due { let clock = &self.tick_clocks[id]; let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index ed41bca5d43..0598afac2f9 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -3672,6 +3672,22 @@ mod process_metadata_tests { } } + #[test] + fn clean_control_cannot_redirect_to_another_valid_bit() { + let source = "#[test(Top)] module Top (spare: output logic) { var source: u32; let derived: u32=source+1; initial {source=1;$assert(derived==2);source=7;} initial {spare=1;$assert(spare==1);spare=0;} }"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let flag = original.runtime_schema.processes[0].comb_clean.unwrap(); + let mut broken = original.clone(); + let address = original.runtime_schema.processes[1].comb_clean.unwrap(); + assert_ne!(flag, address); + broken.runtime_schema.processes[0].comb_clean = Some(address); + assert!(broken.to_container_bytes().is_err()); + } #[test] fn process_release_control_bindings_cannot_be_swapped() { let original = image(); diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 29b3097cc18..7d35fefe8df 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -4017,3 +4017,61 @@ test.each(["step", "run", "bounded"])( } }, ); + +test("retained NAPI memory cannot inject a generated clock edge", () => { + const artifact = JSON.parse(FRONTEND_FINISH_ARTIFACT); + artifact.format_version = 3; + artifact.signals[0].initial = { + payload: [0], + mask: [], + value_type: artifact.signals[0].value_type, + }; + artifact.signals.push({ + id: 1, + name: "clk", + direction: "Internal", + value_type: { width: 1, signed: false, four_state: false }, + initial: null, + }); + artifact.expressions[0].node.Constant.payload = [1]; + artifact.expressions.push({ + id: 2, + node: { Signal: { signal: 0, lsb: 0, width: 8 } }, + value_type: artifact.signals[0].value_type, + }); + artifact.expressions.push({ + id: 3, + node: { Binary: { op: "Add", lhs: 2, rhs: 0 } }, + value_type: artifact.signals[0].value_type, + }); + artifact.registers = [ + { + target: { signal: 0, lsb: 0, width: 8 }, + next: 3, + clock: 1, + edge: "Posedge", + async_reset: null, + enable: null, + }, + ]; + artifact.clock_periods = [[1, 2]]; + artifact.processes[0].body = [{ ClockCycles: { clock: 1, count: 1 } }]; + const Handle = loadNativeAddon().NativeSimulationHandle; + if (!Handle) throw new Error("native simulation unavailable"); + for (const explicit of [false, true]) { + const raw = Handle.fromFrontendArtifact(JSON.stringify(artifact)); + try { + const memory = raw.sharedMemory(); + const layout = parseNapiLayout(raw.layoutJson).forDut; + raw.runUntil(1); + expect(memory[layout.y.offset]).toBe(1); + memory[layout.clk.offset] = 1; + expect(() => (explicit ? raw.evalComb() : raw.runUntil(2))).toThrow( + /direct host write/, + ); + expect(memory[layout.y.offset]).toBe(1); + } finally { + raw.dispose(); + } + } +}); From e32ba57c1c7d1caca4fc15935458b909ddeb9d2e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:26:14 +0900 Subject: [PATCH 53/72] fix(runtime): sum distinct edge counters and bind host scratch --- crates/celox-runtime/src/simulation.rs | 18 ++++-- crates/celox/src/backend/native/backend.rs | 64 +++++++++++++++++++ crates/celox/src/backend/native/image_file.rs | 4 +- .../celox/tests/concurrent_initial_runtime.rs | 22 +++++++ 4 files changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 79a8058d42c..e994a85ea83 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1303,7 +1303,7 @@ impl SimulationState { before: &[(u32, u32)], replays: &mut std::collections::BTreeMap, ) { - let mut extra = std::collections::BTreeMap::::new(); + let mut counters = std::collections::BTreeMap::new(); for ((id, rises, falls), (old_rises, old_falls)) in self.process_event_counters.iter().zip(before) { @@ -1324,13 +1324,17 @@ impl SimulationState { { continue; } - extra - .entry(canonical) - .and_modify(|n| *n = (*n).max(count.saturating_sub(1))) - .or_insert(count.saturating_sub(1)); + counters + .entry((canonical, *rises, *falls)) + .and_modify(|n: &mut u64| *n = (*n).max(count)) + .or_insert(count); } - for (id, count) in extra { - *replays.entry(id).or_default() += count; + let mut totals = std::collections::BTreeMap::::new(); + for ((id, _, _), count) in counters { + *totals.entry(id).or_default() += count; + } + for (id, count) in totals { + *replays.entry(id).or_default() += count.saturating_sub(1); } } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 0598afac2f9..47e68fa20ac 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -417,6 +417,7 @@ pub struct NativeProgramImage { compiled_process_controls: Vec>, compiled_process_clock_lists: Vec>>, compiled_clock_phase_sensitive_comb: bool, + compiled_process_host_requests: Vec>>, required_native_features: u8, #[serde(serialize_with = "celox_design::serde_sorted::map")] event_map: HashMap, @@ -744,6 +745,34 @@ impl NativeProgramImage { { return Err("process clock lists disagree with compiled kernel indices".into()); } + if self.compiled_process_host_requests.len() != self.runtime_schema.processes.len() + || self + .compiled_process_host_requests + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| { + let bound = process + .host_requests + .iter() + .cloned() + .map(|request| { + request.map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + compiled != &bound + }) + { + return Err("process host requests disagree with compiled scratch bindings".into()); + } if self.compiled_clock_phase_sensitive_comb != self.runtime_schema.clock_phase_sensitive_comb { @@ -2480,6 +2509,20 @@ fn compile_program( .iter() .map(|process| process.clocks.clone()) .collect(), + compiled_process_host_requests: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| { + process + .host_requests + .iter() + .cloned() + .map(|request| request.map(|address| (address, layout.offsets[&address]))) + .collect() + }) + .collect(), compiled_clock_phase_sensitive_comb: sir .runtime() .runtime_schema @@ -3672,6 +3715,27 @@ mod process_metadata_tests { } } + #[test] + fn host_request_values_bind_to_compiled_scratch() { + let source = "#[test(Top)]module Top{var random:$tb::random::;var value:u32;initial{value=random.get_range(1,2);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let mut broken = original.clone(); + let request = broken.runtime_schema.processes[0] + .host_requests + .iter_mut() + .find(|request| matches!(request, celox_design::HostRequest::RandomGetRange { .. })) + .unwrap(); + if let celox_design::HostRequest::RandomGetRange { min, max, .. } = request { + assert_ne!(min.signal, max.signal); + min.signal = max.signal; + } + assert!(broken.to_container_bytes().is_err()); + } #[test] fn clean_control_cannot_redirect_to_another_valid_bit() { let source = "#[test(Top)] module Top (spare: output logic) { var source: u32; let derived: u32=source+1; initial {source=1;$assert(derived==2);source=7;} initial {spare=1;$assert(spare==1);spare=0;} }"; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index fa9c296c543..9ed8d9847b6 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 24 also binds process clock lists and clock-phase sensitivity. -const CONTAINER_VERSION: u16 = 24; +// Version 25 also binds host requests to compiled scratch addresses. +const CONTAINER_VERSION: u16 = 25; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index b9997ff90da..2cffe092276 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2071,3 +2071,25 @@ fn repeated_hierarchical_clock_edges_keep_their_count() { check(build().build_native().unwrap()); } } + +#[test] +fn distinct_kernels_add_clock_edge_counts() { + let code = r#"module Child(clk:input clock,q:output u32){always_ff(clk){q=q+1;}}#[test(Top)]module Top{var q:u32;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;}initial{dut.clk=1;$assert(dut.q==0);dut.clk=0;}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} From 37f1b8b43b653d1b597939711dad8902b3cc9cfe Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:30:42 +0900 Subject: [PATCH 54/72] test(napi): reject escaped clock writes before checkpointing --- packages/celox/src/e2e.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 7d35fefe8df..cd57a440dd3 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -4066,6 +4066,8 @@ test("retained NAPI memory cannot inject a generated clock edge", () => { raw.runUntil(1); expect(memory[layout.y.offset]).toBe(1); memory[layout.clk.offset] = 1; + if (!raw.checkpoint) throw new Error("checkpoint unavailable"); + expect(() => raw.checkpoint?.()).toThrow(/direct host write/); expect(() => (explicit ? raw.evalComb() : raw.runUntil(2))).toThrow( /direct host write/, ); From f908072da83779550863274f5ae2b7e578e781a2 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:43:21 +0900 Subject: [PATCH 55/72] fix(arm64): mask rounded wide value and unknown loads --- .../src/isel/instruction.rs | 25 +++- crates/celox-backend-arm64/src/isel/tests.rs | 1 + .../src/isel/tests/partial_load.rs | 121 ++++++++++++++++++ 3 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 crates/celox-backend-arm64/src/isel/tests/partial_load.rs diff --git a/crates/celox-backend-arm64/src/isel/instruction.rs b/crates/celox-backend-arm64/src/isel/instruction.rs index e233dceacbb..2cc6e9efbef 100644 --- a/crates/celox-backend-arm64/src/isel/instruction.rs +++ b/crates/celox-backend-arm64/src/isel/instruction.rs @@ -341,12 +341,25 @@ pub(super) fn lower_instruction( let chunk_vreg = ctx.alloc_vreg(SpillDesc::sim_state( *addr, bit_pos, chunk_bits, false, )); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + chunk_vreg + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: chunk_vreg, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != chunk_vreg { + ctx.emit_and_imm( + block, + chunk_vreg, + raw, + mask_for_width(chunk_bits), + ); + } chunks.push((chunk_vreg, chunk_bits)); bit_pos += chunk_bits; remaining -= chunk_bits; @@ -366,12 +379,20 @@ pub(super) fn lower_instruction( let chunk_byte_off = ctx.mask_byte_offset(addr, m_bit_pos); let chunk_size = ISelContext::op_size_for_width(chunk_bits); let mv = ctx.alloc_vreg(SpillDesc::transient()); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + mv + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: mv, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != mv { + ctx.emit_and_imm(block, mv, raw, mask_for_width(chunk_bits)); + } mchunks.push((mv, chunk_bits)); m_bit_pos += chunk_bits; m_remaining -= chunk_bits; diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 3e2569fc504..45edb81ff51 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -1,3 +1,4 @@ +mod partial_load; mod shifts; mod strided; diff --git a/crates/celox-backend-arm64/src/isel/tests/partial_load.rs b/crates/celox-backend-arm64/src/isel/tests/partial_load.rs new file mode 100644 index 00000000000..cda6f3aac36 --- /dev/null +++ b/crates/celox-backend-arm64/src/isel/tests/partial_load.rs @@ -0,0 +1,121 @@ +//! A rounded wide load must not import padding or neighbouring value/mask bytes. +use super::*; + +#[test] +fn rounded_wide_value_loads_keep_adjacent_bits_out_of_comparisons() { + check(false); +} +#[test] +fn rounded_wide_mask_loads_keep_adjacent_bits_out_of_comparisons() { + check(true); +} + +fn check(four_state: bool) { + for width in [100usize, 65, 72, 73, 80, 81, 96, 97, 113, 127, 128] { + let input = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(0), + }; + let output = AbsoluteAddr { + var_id: StateObjectId(1), + ..input + }; + let address = |absolute| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, absolute); + let loaded = RegisterId(0); + let zero = RegisterId(1); + let equal = RegisterId(2); + let widened = RegisterId(3); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(loaded, address(input), SIROffset::Static(0), width), + SIRInstruction::Imm(zero, SIRValue::new(0u8)), + SIRInstruction::Unary(widened, UnaryOp::Ident, zero), + SIRInstruction::Binary(equal, loaded, BinaryOp::Eq, widened), + SIRInstruction::Store( + address(output), + SIROffset::Static(0), + 1, + equal, + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: [(loaded, width), (zero, 8), (widened, width), (equal, 1)] + .into_iter() + .map(|(r, width)| { + ( + r, + if four_state { + RegisterType::Logic { width } + } else { + RegisterType::Bit { + width, + signed: false, + } + }, + ) + }) + .collect(), + }; + let mut layout = layout_for(input, width, four_state); + layout.offsets.insert(output, 64); + layout.widths.insert(output, 1); + layout.is_4states.insert(output, four_state); + layout.total_size = 96; + layout.working_base_offset = 96; + layout.sparse_base_offset = 96; + layout.sparse_active_bits_offset = 96; + layout.merged_total_size = 96; + layout.triggered_bits_offset = 96; + layout.scratch_base_offset = 96; + let image = crate::scalar::emit_prepared_eu( + &unit, + &layout, + four_state, + "wide_load", + false, + None, + || false, + ) + .unwrap(); + assert!(!image.code.is_empty()); + #[cfg(all(target_arch = "aarch64", target_os = "linux"))] + { + let jit = crate::jit_mem::JitCode::new(&image.code).unwrap(); + let mut state = vec![0xa5u8; 96]; + for bit in 0..width { + state[bit / 8] &= !(1 << (bit % 8)); + if four_state { + state[width.div_ceil(8) + bit / 8] &= !(1 << (bit % 8)); + } + } + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 1, "width={width} four_state={four_state}"); + if four_state { + assert_eq!(state[65] & 1, 0, "width={width} mask"); + } + let high = width - 1; + state[high / 8] |= 1 << (high % 8); + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 0, "width={width} last value bit"); + if four_state { + assert_eq!(state[65] & 1, 0, "width={width} known mismatch"); + state[width.div_ceil(8) + high / 8] |= 1 << (high % 8); + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 1, "width={width} X value"); + assert_eq!(state[65] & 1, 1, "width={width} last mask bit"); + } + } + } +} From af5045c4cc177975401f3a12dc152a3163413928 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 07:59:55 +0900 Subject: [PATCH 56/72] fix(testbench): reset RTL termination before repeated runs --- crates/celox/src/simulator.rs | 2 +- crates/celox/src/testbench/kernels.rs | 1 + .../celox/tests/concurrent_initial_runtime.rs | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index bfeba192b24..3100f66d5fb 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1106,7 +1106,7 @@ mod host { finish.requested } - pub(super) fn reset_runtime_finish(&self, finished: bool) { + pub(crate) fn reset_runtime_finish(&self, finished: bool) { let mut finish = self.runtime_finish_state.lock().unwrap(); finish.read_seq = self.runtime_event_write_seq(); finish.requested = finished; diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index cad104db0ea..670aee77384 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -166,6 +166,7 @@ fn run( } } sim.testbench_events.clear(); + sim.reset_runtime_finish(false); // The scheduler samples the clocks it detects edges on from settled // state. diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 2cffe092276..10800a6ab95 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2093,3 +2093,21 @@ fn distinct_kernels_add_clock_edge_counts() { check(build().build_native().unwrap()); } } + +#[test] +fn repeated_runs_reset_the_rtl_finish_tracker() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;var count:u32;var starts:u32;always_ff(clk){count+=1;$finish();}initial{starts+=1;clk.next(2);}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + for run in 1u8..=2 { + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("starts")), run.into()); + } + } + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} From decca201996bcf6a6fc022104810ad54542a7d16 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:36:01 +0900 Subject: [PATCH 57/72] fix(runtime): retain settled process edges and bind release order --- .../src/lowering/process.rs | 24 ++++-- crates/celox-runtime/src/simulation.rs | 85 ++++++++++++++++++- crates/celox/src/backend/native/backend.rs | 57 +++++++++++++ crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/simulator/state_file.rs | 1 + .../celox/tests/concurrent_initial_runtime.rs | 46 ++++++++++ 6 files changed, 204 insertions(+), 13 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index be84266440c..13d721f8c45 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -393,13 +393,23 @@ fn constant_nonempty_range(range: &ForRange) -> bool { && !constant_empty_range(range) } fn contains_loop_break(statements: &[Statement]) -> bool { - statements.iter().any(|stmt| { - matches!(stmt, Statement::Break) - || (!matches!(stmt, Statement::For(_)) - && expressions::statement_bodies(stmt) - .iter() - .any(|body| contains_loop_break(body))) - }) + for statement in statements { + if matches!(statement, Statement::Break) { + return true; + } + if !matches!(statement, Statement::For(_)) + && expressions::statement_bodies(statement) + .iter() + .any(|body| contains_loop_break(body)) + { + return true; + } + if matches!(statement,Statement::SystemFunctionCall(call) if matches!(call.kind,SystemFunctionKind::Finish)) + { + break; + } + } + false } /// How a `for` loop compares and steps, following the testbench diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 8146509292c..7402e4e3be8 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -320,6 +320,7 @@ pub struct SimulationState { periodic_events: FxHashMap, last_clock_values: BitSet, pending_host_edges: BitSet, + settled_process_edges: BTreeMap, /// Events whose signal was x or z when edge detection last sampled it: /// a change to a known value is an edge (IEEE 1800-2023 9.4.2). unknown_clock_values: BitSet, @@ -398,6 +399,7 @@ impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.pending_host_edges.make_empty(); + self.settled_process_edges.clear(); self.sample_event_values(backend); } @@ -514,6 +516,7 @@ impl SimulationState { periodic_events: FxHashMap::default(), last_clock_values, pending_host_edges: BitSet::new(), + settled_process_edges: BTreeMap::new(), unknown_clock_values, topo_signals, domain_kinds, @@ -1216,7 +1219,9 @@ impl SimulationState { E: SimulationExecutor, { if self.finished - || (self.waiting.is_empty() && self.pending_host_edges.is_empty()) + || (self.waiting.is_empty() + && self.pending_host_edges.is_empty() + && self.settled_process_edges.is_empty()) || self.scheduler.time > limit { return Ok(false); @@ -1333,13 +1338,19 @@ impl SimulationState { for ((id, _, _), count) in counters { *totals.entry(id).or_default() += count; } + for (&id, &count) in &self.settled_process_edges { + *totals.entry(id).or_default() += count; + } for (id, count) in totals { *replays.entry(id).or_default() += count.saturating_sub(1); } } - fn process_counter_edges(&self, backend: &B, before: &[(u32, u32)]) -> BitSet { + fn process_counter_edges(&mut self, backend: &B, before: &[(u32, u32)]) -> BitSet { let mut edges = BitSet::with_capacity(backend.num_events()); + for (id, _) in std::mem::take(&mut self.settled_process_edges) { + edges.insert(id); + } for ((id, rises, falls), (old_rises, old_falls)) in self.process_event_counters.iter().zip(before) { @@ -1408,6 +1419,12 @@ impl SimulationState { ) }) .collect::>(); + let before_signals = self + .topo_signals + .iter() + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) + .collect::>(); + let mut counter_recorded = BitSet::new(); executor .backend_mut() .set(self.processes[process].delay, 0u64); @@ -1427,10 +1444,20 @@ impl SimulationState { Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { executor.backend().get_as::(*falls) != old_falls } - _ => executor.backend().get_as::(*rises) != old_rises, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + executor.backend().get_as::(*rises) != old_rises + } + _ => { + executor.backend().get_as::(*rises) != old_rises + || executor.backend().get_as::(*falls) != old_falls + } }; if changed { executor.backend_mut().mark_triggered_bit(*id); + let canonical = self.event_info[*id].canonical_id; + if canonical != usize::MAX { + counter_recorded.insert(canonical); + } } } @@ -1444,6 +1471,38 @@ impl SimulationState { } Some(ProcessStatus::Settle) => { executor.eval_comb()?; + let mut seen = BitSet::new(); + for ((signal, id, canonical), before) in + self.topo_signals.iter().zip(before_signals) + { + if *id == usize::MAX || *canonical == usize::MAX { + continue; + } + let info = &self.event_info[*canonical]; + if info.eval_ff_event.is_none() + && info.eval_only_event.is_none() + && info.apply_event.is_none() + { + continue; + } + let after = sample_event_signal(executor.backend(), *signal); + let active = match self.domain_kinds[*id] { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => self.edge_triggers(*id, before, after), + _ => before != after, + }; + if active + && !counter_recorded.contains(*canonical) + && seen.insert(*canonical) + { + *self.settled_process_edges.entry(*canonical).or_default() += 1; + } + } + self.sample_waiting_events(executor, current_time)?; *comb_current = true; if executor.finish_requested(current_time) { self.finished = true; @@ -1787,6 +1846,7 @@ impl SimulationState { && !settle_idle && events_to_process.is_empty() && scheduled_edges.is_empty() + && self.settled_process_edges.is_empty() { return Ok(false); } @@ -2382,7 +2442,7 @@ impl SimulationState { if self.finished { return None; } - if !self.pending_host_edges.is_empty() { + if !self.pending_host_edges.is_empty() || !self.settled_process_edges.is_empty() { return Some(self.scheduler.time); } let process = if self.inactive.is_empty() { @@ -2428,6 +2488,7 @@ impl SimulationState { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), pending_host_edges: self.pending_host_edges.clone(), + settled_process_edges: self.settled_process_edges.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), budget_blocked_processes: self.budget_blocked_processes.clone(), @@ -2489,6 +2550,8 @@ impl SimulationState { .clone_from(&snapshot.last_clock_values); self.pending_host_edges .clone_from(&snapshot.pending_host_edges); + self.settled_process_edges + .clone_from(&snapshot.settled_process_edges); self.unknown_clock_values .clone_from(&snapshot.unknown_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); @@ -2524,6 +2587,8 @@ pub struct ScheduleParts { /// Events whose signal was high when edge detection last sampled it. pub high_events: Vec, pub captured_edges: Vec, + /// Unpublished FF occurrences sampled during process-internal settling. + pub settled_process_edges: Vec<(B::Event, u64)>, pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, @@ -2580,6 +2645,11 @@ impl SimulationState { }) .collect(), high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + settled_process_edges: self + .settled_process_edges + .iter() + .map(|(&id, &count)| (events[id], count)) + .collect(), captured_edges: self .pending_host_edges .iter() @@ -2662,6 +2732,11 @@ impl SimulationState { for event in parts.unknown_events { self.unknown_clock_values.insert(event.id()); } + self.settled_process_edges = parts + .settled_process_edges + .into_iter() + .map(|(event, count)| (event.id(), count)) + .collect(); self.pending_host_edges = parts .captured_edges .into_iter() @@ -2727,6 +2802,7 @@ pub struct SimulationSnapshot { periodic_events: FxHashMap, last_clock_values: BitSet, pending_host_edges: BitSet, + settled_process_edges: BTreeMap, unknown_clock_values: BitSet, process_wakeups: BinaryHeap, budget_blocked_processes: BTreeSet, @@ -2752,6 +2828,7 @@ impl Clone for SimulationSnapshot { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), pending_host_edges: self.pending_host_edges.clone(), + settled_process_edges: self.settled_process_edges.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), budget_blocked_processes: self.budget_blocked_processes.clone(), diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 47e68fa20ac..59285a64de3 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -417,6 +417,7 @@ pub struct NativeProgramImage { compiled_process_controls: Vec>, compiled_process_clock_lists: Vec>>, compiled_clock_phase_sensitive_comb: bool, + compiled_process_releases: Vec>>, compiled_process_host_requests: Vec>>, required_native_features: u8, #[serde(serialize_with = "celox_design::serde_sorted::map")] @@ -745,6 +746,34 @@ impl NativeProgramImage { { return Err("process clock lists disagree with compiled kernel indices".into()); } + if self.compiled_process_releases.len() != self.runtime_schema.processes.len() + || self + .compiled_process_releases + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| { + let bound = process + .releases + .iter() + .cloned() + .map(|release| { + release.map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + compiled != &bound + }) + { + return Err("process releases disagree with compiled release indices".into()); + } if self.compiled_process_host_requests.len() != self.runtime_schema.processes.len() || self .compiled_process_host_requests @@ -2509,6 +2538,20 @@ fn compile_program( .iter() .map(|process| process.clocks.clone()) .collect(), + compiled_process_releases: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| { + process + .releases + .iter() + .cloned() + .map(|release| release.map(|address| (address, layout.offsets[&address]))) + .collect() + }) + .collect(), compiled_process_host_requests: sir .runtime() .runtime_schema @@ -3715,6 +3758,20 @@ mod process_metadata_tests { } } + #[test] + fn ordered_release_bindings_match_compiled_indices() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;inst a:$tb::reset_gen(clk);inst b:$tb::reset_gen(clk);initial{a.assert(1);b.assert(1);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let mut broken = original.clone(); + assert_eq!(broken.runtime_schema.processes[0].releases.len(), 2); + broken.runtime_schema.processes[0].releases.swap(0, 1); + assert!(broken.to_container_bytes().is_err()); + } #[test] fn host_request_values_bind_to_compiled_scratch() { let source = "#[test(Top)]module Top{var random:$tb::random::;var value:u32;initial{value=random.get_range(1,2);$finish();}}"; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 9ed8d9847b6..74f9c8f6127 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 25 also binds host requests to compiled scratch addresses. -const CONTAINER_VERSION: u16 = 25; +// Version 26 also binds ordered process releases to compiled indices. +const CONTAINER_VERSION: u16 = 26; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 61d56e13549..8838822b22d 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -493,6 +493,7 @@ impl Simulator { .filter(|name| !saved_unknown.contains(name.as_str()) || supports_unknown(name)) .map(|name| events[name]) .collect(), + settled_process_edges: Vec::new(), captured_edges: record .captured_edges .iter() diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 10800a6ab95..dbafb94ff91 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2111,3 +2111,49 @@ fn repeated_runs_reset_the_rtl_finish_tracker() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(build().build_native().unwrap()); } + +#[test] +fn unreachable_breaks_after_finish_do_not_declare_clocks() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{$finish();break;}clk.next();}}"; + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} +#[test] +fn derived_clock_pulses_survive_process_settles() { + for expression in ["go", "go & enable"] { + for four_state in [false, true] { + for pulses in [1, 2] { + let body = "go=1;$assert(q==0);go=0;$assert(q==0);".repeat(pulses); + let source = format!( + "module Child(clk:input clock,q:output u32){{always_ff(clk){{q+=1;}}}}#[test(Top)]module Top{{var go:logic;var enable:logic;let gated:clock={expression};var q:u32;inst dut:Child(clk:gated,q);initial{{enable=1;dut.q=0;{body}}}}}" + ); + fn check(mut sim: Simulator, pulses: usize) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), pulses.into()); + } + let build = || { + Simulator::builder(&source, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap(), pulses); + check(build().build_cranelift().unwrap(), pulses); + check(build().build_wasm().unwrap(), pulses); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), pulses); + } + } + } +} From 465622de08a5d4f945cdbcbfb4c8003d145623cc Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 08:51:02 +0900 Subject: [PATCH 58/72] fix(test): preserve integrated regression module boundaries --- crates/celox/src/simulation.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 7a2b06104ee..571cf92b9fe 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -5276,7 +5276,12 @@ mod nba_waiter_sampling_review { check(Simulation::new(build().build_interpreter().unwrap())); check(Simulation::new(build().build_cranelift().unwrap())); check(Simulation::new(build().build_wasm().unwrap())); - #[cfg(test)] + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + +#[cfg(test)] mod host_clock_activation_review { use super::*; use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; From d9be5dc93729ef5e6c08f42844420e920e94f8bf Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 09:10:28 +0900 Subject: [PATCH 59/72] fix(testbench): preserve host paths and compiled process boundaries --- .../src/lowering/process.rs | 3 + crates/celox/src/backend/native/backend.rs | 45 ++++++++++--- crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/testbench/kernels.rs | 63 ++++++++++++++++++- .../celox/tests/concurrent_initial_runtime.rs | 18 ++++++ 5 files changed, 120 insertions(+), 13 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 13d721f8c45..fe6bf4f9110 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -1770,6 +1770,9 @@ impl<'a> BlockLowering<'a> { load: impl FnOnce(&mut Self) -> Result, ) -> Result { let inputs = expressions::selection(&destination.index, &destination.select); + if !inputs.is_empty() { + self.settle_if_dirty()?; + } let mut bindings = HashMap::default(); if inputs.iter().any(|expr| expressions::has_call(expr)) { for expr in &inputs { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 59285a64de3..137fd6979b8 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -418,6 +418,7 @@ pub struct NativeProgramImage { compiled_process_clock_lists: Vec>>, compiled_clock_phase_sensitive_comb: bool, compiled_process_releases: Vec>>, + compiled_testbench_kernels: Option, compiled_process_host_requests: Vec>>, required_native_features: u8, #[serde(serialize_with = "celox_design::serde_sorted::map")] @@ -540,6 +541,9 @@ impl NativeProgramImage { if self.code.is_empty() { return Err("code image is empty".into()); } + if self.runtime_schema.testbench_kernels != self.compiled_testbench_kernels { + return Err("testbench kernel boundary differs from compiled image".into()); + } if self .runtime_schema .testbench_kernels @@ -2538,6 +2542,7 @@ fn compile_program( .iter() .map(|process| process.clocks.clone()) .collect(), + compiled_testbench_kernels: sir.runtime().runtime_schema.testbench_kernels, compiled_process_releases: sir .runtime() .runtime_schema @@ -3700,17 +3705,37 @@ mod process_metadata_tests { } #[test] - fn testbench_boundary_must_fit_process_table() { - let mut image = image(); - for start in [0, image.runtime_schema.processes.len()] { - image.runtime_schema.testbench_kernels = Some(start); - image.to_container_bytes().unwrap(); + fn testbench_boundary_must_match_compiled_boundary() { + let original = image(); + original.to_container_bytes().unwrap(); + for start in [ + 0, + original.runtime_schema.processes.len(), + original.runtime_schema.processes.len() + 1, + ] { + let mut changed = original.clone(); + changed.runtime_schema.testbench_kernels = Some(start); + assert!(matches!( + changed.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + let source = + "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{clk.next(2);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + for boundary in [None, Some(original.runtime_schema.processes.len())] { + let mut changed = original.clone(); + changed.runtime_schema.testbench_kernels = boundary; + assert!(matches!( + changed.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); } - image.runtime_schema.testbench_kernels = Some(image.runtime_schema.processes.len() + 1); - assert!(matches!( - image.to_container_bytes(), - Err(NativeImageContainerError::InvalidImage(_)) - )); } #[test] diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 74f9c8f6127..0f0feef5360 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 26 also binds ordered process releases to compiled indices. -const CONTAINER_VERSION: u16 = 26; +// Version 27 also binds the testbench process boundary to the compiled image. +const CONTAINER_VERSION: u16 = 27; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 670aee77384..987059355c3 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -360,7 +360,13 @@ pub(crate) fn serve_host_request( path, append, } => { - let bytes = read(sim, &path).to_bytes_be(); + // BigUint omits leading zero bytes; the declared string width + // is part of the path and must survive conversion (including NUL). + let value = read(sim, &path).to_bytes_be(); + let mut bytes = vec![0; path.width.div_ceil(8)]; + let count = bytes.len().min(value.len()); + let start = bytes.len() - count; + bytes[start..].copy_from_slice(&value[value.len() - count..]); let path = String::from_utf8(bytes) .map_err(|error| format!("testbench file path: {error}"))?; let files = sim @@ -1079,3 +1085,58 @@ mod event_yield_settle_tests { check(Simulator::builder(code, "Top").build_native().unwrap()); } } + +#[cfg(test)] +mod file_path_width_tests { + use super::*; + #[test] + fn leading_nul_host_path_does_not_open_the_stripped_filename() { + fn check(mut sim: Simulator, filename: &std::path::Path, zeros: usize) { + std::fs::write(filename, b"keep").unwrap(); + let (process, request, path) = + sim.program + .runtime_schema + .processes + .iter() + .enumerate() + .find_map(|(p, slots)| { + slots.host_requests.iter().enumerate().find_map( + |(r, request)| match request { + HostRequest::FileOpen { path, .. } => Some((p, r, path.clone())), + _ => None, + }, + ) + }) + .unwrap(); + let text = filename.to_str().unwrap(); + assert!(path.is_string); + assert_eq!(path.width, (text.len() + zeros) * 8); + // The compiled scratch has room for the declared leading bytes. + // Set its payload directly: Veryl source literals cannot spell NUL. + let signal = sim.backend.resolve_signal(&path.signal); + sim.backend + .set_wide(signal, BigUint::from_bytes_be(text.as_bytes())); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: None, + }); + let result = serve_host_request(&mut sim, process, request, 0); + assert!(result.is_err(), "leading NUL path was accepted: {result:?}"); + assert_eq!(std::fs::read(filename).unwrap(), b"keep"); + } + let dir = tempfile::tempdir().unwrap(); + let filename = dir.path().join("output"); + for zeros in [1, 2] { + let text = format!("{}{}", " ".repeat(zeros), filename.display()); + let source = format!( + r#"#[test(Top)]module Top{{var f:$tb::file;initial{{f.open("{text}");$finish();}}}}"# + ); + let build = || crate::Simulator::builder(&source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap(), &filename, zeros); + check(build().build_cranelift().unwrap(), &filename, zeros); + check(build().build_wasm().unwrap(), &filename, zeros); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), &filename, zeros); + } + } +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index dbafb94ff91..cdd24f18556 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2157,3 +2157,21 @@ fn derived_clock_pulses_survive_process_settles() { } } } + +#[test] +fn plain_output_selectors_see_the_callee_final_design_write() { + let source = r#"#[test(Top)]module Top{var source:u32;let index:u32=source;var words:u32[2];function give(value:output u32){value=7;source=1;}initial{source=0;give(words[index]);$assert(words[0]==0,"old index");$assert(words[1]==7,"new index");$finish();}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let build = || Simulator::builder(source, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} From aa889428668f127a785bd8be7573a2e0ff342901 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 09:38:36 +0900 Subject: [PATCH 60/72] fix(testbench): snapshot outgoing calls and bind emitted counters --- .../src/lowering/process.rs | 198 +++++++++++++++--- crates/celox/src/backend/native/backend.rs | 51 +++++ crates/celox/src/backend/native/image_file.rs | 4 +- .../celox/tests/concurrent_initial_runtime.rs | 97 +++++++++ 4 files changed, 323 insertions(+), 27 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index fe6bf4f9110..1955124a26a 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -163,7 +163,7 @@ pub(crate) fn declare_storage( name(&format!("{}@{slot}", need.purpose)), None, need.width, - need.purpose == "file_arg", + matches!(need.purpose, "file_arg" | "function_output"), ); (need, id) }) @@ -392,25 +392,6 @@ fn constant_nonempty_range(range: &ForRange) -> bool { matches!((start, end), (ForBound::Const(..), ForBound::Const(..))) && !constant_empty_range(range) } -fn contains_loop_break(statements: &[Statement]) -> bool { - for statement in statements { - if matches!(statement, Statement::Break) { - return true; - } - if !matches!(statement, Statement::For(_)) - && expressions::statement_bodies(statement) - .iter() - .any(|body| contains_loop_break(body)) - { - return true; - } - if matches!(statement,Statement::SystemFunctionCall(call) if matches!(call.kind,SystemFunctionKind::Finish)) - { - break; - } - } - false -} /// How a `for` loop compares and steps, following the testbench /// interpreter: the counter is kept at its own width, bounds compare in @@ -529,6 +510,45 @@ fn function_body( } } +// Output selectors can reenter the completed callee. Preserve its outgoing +// values (and expression result) before evaluating any selector calls. +fn output_snapshot_formals( + call: &veryl_analyzer::ir::FunctionCall, + body: &FunctionBody, +) -> Vec { + if !call.outputs.values().flatten().any(|destination| { + expressions::selection(&destination.index, &destination.select) + .into_iter() + .any(expressions::has_call) + }) { + return Vec::new(); + } + let mut formals = call + .outputs + .iter() + .filter_map(|(path, _)| body.arg_map.get(path).copied()) + .chain(body.ret) + .collect::>(); + formals.sort(); + formals.dedup(); + formals +} + +fn collect_output_scratch( + ir: &Module, + call: &veryl_analyzer::ir::FunctionCall, + body: &FunctionBody, + needs: &mut Vec, +) -> Result<(), ParserError> { + for formal in output_snapshot_formals(call, body) { + needs.push(ScratchNeed { + purpose: "function_output", + width: resolve_total_width(ir, &ir.variables[&formal])?.max(1), + }); + } + Ok(()) +} + fn collect_expression_storage( ir: &Module, statements: &[Statement], @@ -707,6 +727,7 @@ fn collect_scratch_needs( if active.insert(function_key(call)) { if let Some(body) = function_body(&ir.functions, call) { collect_scratch_needs(ir, &body.statements, active, needs)?; + collect_output_scratch(ir, call, &body, needs)?; } active.remove(&function_key(call)); } @@ -746,6 +767,7 @@ fn collect_scratch_needs( && let Some(body) = function_body(&ir.functions, call) { collect_scratch_needs(ir, &body.statements, active, needs)?; + collect_output_scratch(ir, call, &body, needs)?; active.remove(&function_key(call)); } } @@ -1411,6 +1433,89 @@ impl<'a> BlockLowering<'a> { self.scan_clocks(statements, &mut active, true); } + fn contains_loop_break( + &mut self, + statements: &[Statement], + active: &mut HashSet, + ) -> bool { + for statement in statements { + if matches!(statement, Statement::Break) { + return true; + } + // The call scanner follows input/body/copy-back order. A break + // inside a callee or nested loop does not exit this loop. + if let Statement::FunctionCall(call) = statement { + if !self.scan_call_clocks(call, active, false) { + return false; + } + continue; + } + if let Statement::Case(stmt) = statement { + if !self.scan_expression_clocks(&stmt.case_target, active, false) { + return false; + } + let found = if let Some(body) = selected_case_body(stmt) { + self.contains_loop_break(body, active) + } else { + self.contains_case_break(stmt, 0, active) + }; + if found { + return true; + } + } else { + for expr in expressions::statement_inputs(statement) { + if !self.scan_expression_clocks(expr, active, false) { + return false; + } + } + let found = match statement { + Statement::For(_) => false, + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => self.contains_loop_break(&stmt.true_side, active), + Some(false) => self.contains_loop_break(&stmt.false_side, active), + None => { + self.contains_loop_break(&stmt.true_side, active) + || self.contains_loop_break(&stmt.false_side, active) + } + }, + _ => expressions::statement_bodies(statement) + .iter() + .any(|body| self.contains_loop_break(body, active)), + }; + if found { + return true; + } + } + if !self.scan_clocks(std::slice::from_ref(statement), active, false) { + return false; + } + } + false + } + + fn contains_case_break( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + active: &mut HashSet, + ) -> bool { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.contains_loop_break(&stmt.default, active); + }; + let condition = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + if !self.scan_expression_clocks(&condition, active, false) { + return false; + } + match constant_truth(&condition) { + Some(true) => self.contains_loop_break(&case_arm.body, active), + Some(false) => self.contains_case_break(stmt, arm + 1, active), + None => { + self.contains_loop_break(&case_arm.body, active) + || self.contains_case_break(stmt, arm + 1, active) + } + } + } + fn scan_clocks( &mut self, statements: &[Statement], @@ -1492,7 +1597,7 @@ impl<'a> BlockLowering<'a> { let continues = self.scan_clocks(&stmt.body, active, declare); if !continues && constant_nonempty_range(&stmt.range) - && !contains_loop_break(&stmt.body) + && !self.contains_loop_break(&stmt.body, active) { return false; } @@ -1749,6 +1854,28 @@ impl<'a> BlockLowering<'a> { reg } + fn load_output_scratch( + &mut self, + id: SourceVarId, + width: usize, + signed: bool, + two_state: bool, + ) -> RegisterId { + if two_state { + return self.load_scratch(id, width, signed); + } + let address = self.scratch_addr(id); + let builder = self.kernel.builder(); + let reg = builder.alloc_logic(width); + builder.emit(SIRInstruction::Load( + reg, + address, + SIROffset::Static(0), + width, + )); + reg + } + fn destination( &self, var_id: VarId, @@ -2751,7 +2878,7 @@ impl<'a> BlockLowering<'a> { self.parser.clear_register_cache(); if matches!(body_flow, Flow::Ended) && constant_nonempty_range(&stmt.range) - && !contains_loop_break(&stmt.body) + && !self.contains_loop_break(&stmt.body, &mut HashSet::default()) { // The exit is unreachable for this known nonempty terminating body. self.kernel.finish(); @@ -3147,6 +3274,17 @@ impl<'a> BlockLowering<'a> { if let Flow::Ended = flow { return Ok(Flow::Ended); } + let mut outgoing = HashMap::default(); + for formal in output_snapshot_formals(call, &body) { + let variable = &self.ir.variables[&formal]; + let width = resolve_total_width(self.ir, variable)?.max(1); + let signed = variable.r#type.signed; + let two_state = variable.r#type.is_2state(); + let (_, slot) = self.take_scratch("function_output", width)?; + let value = self.load_var(formal)?; + self.store_scratch(slot, width, value); + outgoing.insert(formal, (slot, width, signed, two_state)); + } for path in &paths { let Some(destinations) = call .outputs @@ -3157,14 +3295,24 @@ impl<'a> BlockLowering<'a> { }; if let Some(&formal) = body.arg_map.get(path) { for destination in destinations { - if let Flow::Ended = - self.copy_back(destination, |this| this.load_var(formal))? - { + let snapshot = outgoing.get(&formal).copied(); + if let Flow::Ended = self.copy_back(destination, |this| match snapshot { + Some((slot, width, signed, two_state)) => { + Ok(this.load_output_scratch(slot, width, signed, two_state)) + } + None => this.load_var(formal), + })? { return Ok(Flow::Ended); } } } } + if let Some(formal) = body.ret + && let Some(&(slot, width, signed, two_state)) = outgoing.get(&formal) + { + let value = self.load_output_scratch(slot, width, signed, two_state); + self.store(&self.destination(formal, call.comptime.token), value)?; + } Ok(Flow::Continue) } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 137fd6979b8..6bd58bb0f24 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -419,6 +419,7 @@ pub struct NativeProgramImage { compiled_clock_phase_sensitive_comb: bool, compiled_process_releases: Vec>>, compiled_testbench_kernels: Option, + compiled_process_event_counters: Vec<[(AbsoluteAddr, usize); 3]>, compiled_process_host_requests: Vec>>, required_native_features: u8, #[serde(serialize_with = "celox_design::serde_sorted::map")] @@ -811,6 +812,26 @@ impl NativeProgramImage { { return Err("clock phase sensitivity disagrees with compiled kernels".into()); } + let counter_bindings = self + .runtime_schema + .process_event_counters + .iter() + .map(|counter| { + [counter.signal, counter.rises, counter.falls].map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + if self.compiled_process_event_counters != counter_bindings { + return Err("process edge counters disagree with compiled bindings".into()); + } for counters in &self.runtime_schema.process_event_counters { if !self.event_map.contains_key(&counters.signal) { return Err("a process edge counter names an unknown event domain".into()); @@ -2543,6 +2564,20 @@ fn compile_program( .map(|process| process.clocks.clone()) .collect(), compiled_testbench_kernels: sir.runtime().runtime_schema.testbench_kernels, + compiled_process_event_counters: sir + .runtime() + .runtime_schema + .process_event_counters + .iter() + .map(|counter| { + [counter.signal, counter.rises, counter.falls].map(|address| { + ( + address, + layout.offsets.get(&address).copied().unwrap_or(usize::MAX), + ) + }) + }) + .collect(), compiled_process_releases: sir .runtime() .runtime_schema @@ -3783,6 +3818,22 @@ mod process_metadata_tests { } } + #[test] + fn emitted_edge_counter_bindings_match_compiled_storage() { + let source = "module Counter(clk:input clock,q:output u32){always_ff(clk){q+=1;}}#[test(Top)]module Top{var go:clock;var q:u32;inst dut:Counter(clk:go,q);initial{go=1;go=0;$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + assert!(!original.runtime_schema.process_event_counters.is_empty()); + let mut broken = original.clone(); + let counter = &mut broken.runtime_schema.process_event_counters[0]; + std::mem::swap(&mut counter.rises, &mut counter.falls); + assert!(broken.to_container_bytes().is_err()); + } + #[test] fn ordered_release_bindings_match_compiled_indices() { let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;inst a:$tb::reset_gen(clk);inst b:$tb::reset_gen(clk);initial{a.assert(1);b.assert(1);$finish();}}"; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0f0feef5360..3c4a06f5796 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 27 also binds the testbench process boundary to the compiled image. -const CONTAINER_VERSION: u16 = 27; +// Version 28 also binds ordered process edge counters to compiled storage. +const CONTAINER_VERSION: u16 = 28; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index cdd24f18556..bbb276aa94b 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2175,3 +2175,100 @@ fn plain_output_selectors_see_the_callee_final_design_write() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(build().build_native().unwrap()); } + +#[test] +fn reentrant_output_selectors_preserve_outer_formals() { + let source = "#[test(Top)]module Top{var words:u32[2];function give(v:input u32,o:output u32){o=v;}function index()->u32{var tmp:u32;give(9,tmp);return 0;}initial{give(7,words[index()]);$assert(words[0]==7);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let build = || Simulator::builder(source, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn helper_termination_hides_unreachable_loop_breaks() { + for (helper, body) in [ + ("function stop(){$finish();}", "stop();break;"), + ( + "var seed:u32;function stop()->u32{$finish();return seed;}", + "if stop()==seed {break;}", + ), + ] { + let source = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;{helper}initial{{for i in 0..1{{{body}}}clk.next();}}}}" + ); + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(&source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} + +#[test] +fn recorded_pulses_join_the_first_generated_clock_batch() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen #(period:4);var go:clock;var source:u32;var sampled:u32;always_ff(go){source=1;}always_ff(clk){sampled=source;}initial{go=1;go=0;clk.next(1);$assert(source==1);$assert(sampled==0);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn reentrant_output_snapshots_keep_all_masks_and_return_across_waits() { + let source = "#[test(Top)]module Top(words:output logic<16>,other:output logic<8>,result:output logic<8>){inst clk:$tb::clock_gen;function give(v:input logic<8>,a:output logic<8>,b:output logic<8>)->logic<8>{a=v;b=~v;return v;}function index()->u32{var a:logic<8>;var b:logic<8>;var r:logic<8>;r=give(8'h09,a,b);clk.next(1);return 0;}initial{words=0;result=give(8'b10xz0101,words[index()+:8],other);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + for (name, value, mask) in [ + ("words", 0xa5u32, 0x30u32), + ("other", 0x7a, 0x30), + ("result", 0xa5, 0x30), + ] { + assert_eq!( + sim.get_four_state(sim.signal(name)), + (value.into(), mask.into()), + "{name}" + ); + } + } + let build = || { + Simulator::builder(source, "Top") + .four_state(true) + .testbench_kernels(true) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} From 649538b0abd9a93ce41401b8998f407e45a8b2f2 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 09:45:54 +0900 Subject: [PATCH 61/72] test(runtime): cover coincident direct and derived kernel pulses --- .../celox/tests/concurrent_initial_runtime.rs | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index bbb276aa94b..6a21d95e96f 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2232,12 +2232,21 @@ fn recorded_pulses_join_the_first_generated_clock_batch() { TestResult::Pass ); } - let build = || Simulator::builder(source, "Top").testbench_kernels(true); - check(build().build_interpreter().unwrap()); - check(build().build_cranelift().unwrap()); - check(build().build_wasm().unwrap()); - #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] - check(build().build_native().unwrap()); + let derived = source + .replace( + "var source:u32;", + "var source:u32;var enable:logic;let gated:'_ clock=go & enable;", + ) + .replace("always_ff(go)", "always_ff(gated)") + .replace("initial{go=1;", "initial{enable=1;go=1;"); + for source in [source, derived.as_str()] { + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } } #[test] From e7b4f31eee14607728540f97710d188f7f635150 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 10:07:24 +0900 Subject: [PATCH 62/72] fix(runtime): retain component-settle edges before kernel continuation --- crates/celox-runtime/src/simulation.rs | 94 +++++++++++++++++--------- crates/celox/src/testbench/kernels.rs | 22 ++++++ 2 files changed, 84 insertions(+), 32 deletions(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 4ecd90d8185..26a33f84c7d 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1473,37 +1473,11 @@ impl SimulationState { } Some(ProcessStatus::Settle) => { executor.eval_comb()?; - let mut seen = BitSet::new(); - for ((signal, id, canonical), before) in - self.topo_signals.iter().zip(before_signals) - { - if *id == usize::MAX || *canonical == usize::MAX { - continue; - } - let info = &self.event_info[*canonical]; - if info.eval_ff_event.is_none() - && info.eval_only_event.is_none() - && info.apply_event.is_none() - { - continue; - } - let after = sample_event_signal(executor.backend(), *signal); - let active = match self.domain_kinds[*id] { - Some( - DomainKind::ClockPosedge - | DomainKind::ClockNegedge - | DomainKind::ResetAsyncHigh - | DomainKind::ResetAsyncLow, - ) => self.edge_triggers(*id, before, after), - _ => before != after, - }; - if active - && !counter_recorded.contains(*canonical) - && seen.insert(*canonical) - { - *self.settled_process_edges.entry(*canonical).or_default() += 1; - } - } + self.record_process_settle_edges( + executor.backend(), + &before_signals, + &counter_recorded, + ); self.sample_waiting_events(executor, current_time)?; *comb_current = true; if executor.finish_requested(current_time) { @@ -1608,7 +1582,15 @@ impl SimulationState { Some(ProcessStatus::Host) => { let request: u64 = executor.backend().get_as(refs.delay); self.waiting.remove(&process); + let before_host = self + .topo_signals + .iter() + .map(|(signal, _, _)| { + sample_event_signal(executor.backend(), *signal) + }) + .collect::>(); if !executor.host_request(process, request as usize, current_time)? { + self.finish_round = true; self.done.insert(process); self.finished = true; return Ok(true); @@ -1616,7 +1598,19 @@ impl SimulationState { // A host may leave design writes outside this // kernel's store instrumentation that need settling. if executor.host_request_changes_design(process, request as usize) { - *comb_current = false; + executor.eval_comb()?; + *comb_current = true; + } + self.record_process_settle_edges( + executor.backend(), + &before_host, + &BitSet::new(), + ); + self.sample_waiting_events(executor, current_time)?; + if executor.finish_requested(current_time) { + self.finish_round = true; + self.finished = true; + return Ok(true); } any_ran = true; continue; @@ -1638,6 +1632,42 @@ impl SimulationState { } } + fn record_process_settle_edges( + &mut self, + backend: &B, + before: &[(bool, bool)], + counter_recorded: &BitSet, + ) { + let mut seen = BitSet::new(); + for ((signal, id, canonical), before) in + self.topo_signals.iter().zip(before.iter().copied()) + { + if *id == usize::MAX || *canonical == usize::MAX { + continue; + } + let info = &self.event_info[*canonical]; + if info.eval_ff_event.is_none() + && info.eval_only_event.is_none() + && info.apply_event.is_none() + { + continue; + } + let after = sample_event_signal(backend, *signal); + let active = match self.domain_kinds[*id] { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => self.edge_triggers(*id, before, after), + _ => before != after, + }; + if active && !counter_recorded.contains(*canonical) && seen.insert(*canonical) { + *self.settled_process_edges.entry(*canonical).or_default() += 1; + } + } + } + /// Whether all processes at or beyond the testbench boundary are done. pub fn processes_done_from(&self, first: usize) -> bool { first <= self.processes.len() diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 987059355c3..23ad1905782 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -831,6 +831,28 @@ mod event_yield_settle_tests { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check_backend!(build_native, code); } + let pulse = "module Counter(clk:input clock,count:output u8){always_ff(clk){count+=1;}}#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:u8;var enable:logic;let gated:'_ clock=q[0] & enable;var count:u8;inst c:$comp::settled_writer(clk,q);inst dut:Counter(clk:gated,count);initial{enable=1;c.drive(1);enable=0;clk.next(1);$assert(count==1,\"component edge lost\");$finish();}}"; + macro_rules! check_pulse { + ($build:ident) => {{ + let metadata = + veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + let mut sim = Simulator::builder(pulse, "Top") + .with_metadata(metadata) + .testbench_kernels(true) + .$build() + .unwrap(); + let tb = super::super::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + super::super::run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + }}; + } + check_pulse!(build_interpreter); + check_pulse!(build_cranelift); + check_pulse!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_pulse!(build_native); } #[test] From a73cb03992812c9e2dab0d3039a68538ac5d26e5 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 10:16:44 +0900 Subject: [PATCH 63/72] fix(veryl): publish prior testbench writes before completion --- crates/celox-design/src/lib.rs | 7 +++++++ crates/celox-frontend-core/src/process.rs | 5 +++++ crates/celox-frontend-veryl/src/lowering/process.rs | 2 +- crates/celox-runtime/src/simulation.rs | 7 +++++-- crates/celox/src/backend/native/image_file.rs | 4 ++-- 5 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 675cfc4a275..caeff3d09ef 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -265,6 +265,11 @@ pub enum ProcessStatus { Yield, /// An event occurred while sampling queued drives; resume its body after the batch. Ready, + /// End a sequential testbench after publishing writes and captured edges + /// from the current round. No later process or generated clock runs. + /// Veryl testbenches use this completion boundary; HDL `$finish` uses + /// [`Self::Finish`] and suppresses all subsequent publication. + FinishAfterPublication, } impl ProcessStatus { @@ -283,6 +288,7 @@ impl ProcessStatus { Self::Settle => 8, Self::Yield => 10, Self::Ready => 11, + Self::FinishAfterPublication => 12, } } @@ -299,6 +305,7 @@ impl ProcessStatus { 8 => Some(Self::Settle), 10 => Some(Self::Yield), 11 => Some(Self::Ready), + 12 => Some(Self::FinishAfterPublication), _ => None, } } diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 20fbb563a8d..dc8f3ba6d3d 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -349,6 +349,11 @@ impl ProcessKernelBuilder { self.end(ProcessStatus::Finish); } + /// End a sequential testbench after publishing this round's prior writes. + pub fn finish_after_publication(&mut self) { + self.end(ProcessStatus::FinishAfterPublication); + } + /// Complete the kernel. If a block is still open, the process ends there. pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs index 1955124a26a..2cad569b63e 100644 --- a/crates/celox-frontend-veryl/src/lowering/process.rs +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -2944,7 +2944,7 @@ impl<'a> BlockLowering<'a> { fn lower_system_function(&mut self, call: &SystemFunctionCall) -> Result { match &call.kind { SystemFunctionKind::Finish => { - self.kernel.finish(); + self.kernel.finish_after_publication(); Ok(Flow::Ended) } SystemFunctionKind::Assert { kind, cond, args } => { diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index ab62a5696d6..c123214d541 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1514,8 +1514,11 @@ impl SimulationState { self.done.insert(process); any_ran = true; } - Some(ProcessStatus::Finish) => { - self.finish_round = true; + Some( + status + @ (ProcessStatus::Finish | ProcessStatus::FinishAfterPublication), + ) => { + self.finish_round = status == ProcessStatus::Finish; self.waiting.remove(&process); self.done.insert(process); self.finished = true; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 3c4a06f5796..47d1fc88ebb 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Version 28 also binds ordered process edge counters to compiled storage. -const CONTAINER_VERSION: u16 = 28; +// Version 29 distinguishes immediate finish from testbench publication completion. +const CONTAINER_VERSION: u16 = 29; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; From 9b8999c80e4f9ca5bd053401cdad60dfed09c1e7 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 16:12:33 +0900 Subject: [PATCH 64/72] fix(veryl): preserve termination in constant-valued loop bounds --- .../src/dynamic_for_check.rs | 67 +++++++++----- crates/celox-frontend-veryl/src/lib.rs | 2 + .../src/runtime_functions.rs | 88 +++++++++++++++++++ crates/celox/src/simulator/builder.rs | 21 +++-- .../celox/tests/concurrent_initial_runtime.rs | 20 ++++- 5 files changed, 166 insertions(+), 32 deletions(-) create mode 100644 crates/celox-frontend-veryl/src/runtime_functions.rs diff --git a/crates/celox-frontend-veryl/src/dynamic_for_check.rs b/crates/celox-frontend-veryl/src/dynamic_for_check.rs index 82310668f80..bea657363d1 100644 --- a/crates/celox-frontend-veryl/src/dynamic_for_check.rs +++ b/crates/celox-frontend-veryl/src/dynamic_for_check.rs @@ -1286,30 +1286,53 @@ fn initial_bound_finishes(statement: &ForStatement, module: &Module) -> bool { let Factor::FunctionCall(call) = factor.as_ref() else { return false; }; - let body = module.functions.get(&call.id).and_then(|function| { - call.index - .as_deref() - .and_then(|index| function.get_function(index)) - .or_else(|| function.get_function(&[])) - }); - body.is_some_and(|body| { - for statement in &body.statements { - match statement { - Statement::SystemFunctionCall(call) - if matches!(call.kind, SystemFunctionKind::Finish) => - { - return true; + fn expression_finishes( + expression: &Expression, + module: &Module, + active: &mut HashSet, + ) -> bool { + matches!(expression, Expression::Term(factor) if matches!(factor.as_ref(), Factor::FunctionCall(call) if call_finishes(call, module, active))) + } + fn call_finishes(call: &FunctionCall, module: &Module, active: &mut HashSet) -> bool { + if !active.insert(call.id) { + return false; + } + let body = module.functions.get(&call.id).and_then(|function| { + call.index + .as_deref() + .and_then(|index| function.get_function(index)) + .or_else(|| function.get_function(&[])) + }); + let finishes = body.is_some_and(|body| { + for statement in &body.statements { + match statement { + Statement::SystemFunctionCall(call) + if matches!(call.kind, SystemFunctionKind::Finish) => + { + return true; + } + Statement::Assign(assign) => { + if expression_finishes(&assign.expr, module, active) { + return true; + } + } + Statement::FunctionCall(call) => { + if call_finishes(call, module, active) { + return true; + } + } + Statement::Null + | Statement::SystemFunctionCall(_) + | Statement::TbMethodCall(_) => {} + _ => return false, } - Statement::Assign(_) - | Statement::Null - | Statement::FunctionCall(_) - | Statement::SystemFunctionCall(_) - | Statement::TbMethodCall(_) => {} - _ => return false, } - } - false - }) + false + }); + active.remove(&call.id); + finishes + } + call_finishes(call, module, &mut HashSet::default()) } fn check_for( diff --git a/crates/celox-frontend-veryl/src/lib.rs b/crates/celox-frontend-veryl/src/lib.rs index c40be7d1f60..0973360841e 100644 --- a/crates/celox-frontend-veryl/src/lib.rs +++ b/crates/celox-frontend-veryl/src/lib.rs @@ -16,6 +16,7 @@ pub(crate) mod lowering; pub mod module; mod portability_check; mod readmem; +mod runtime_functions; mod schedule; mod source; mod testbench; @@ -41,6 +42,7 @@ pub use interface_captures::lower_interface_captures; pub use lowering::types::{resolve_dims, resolve_total_width}; pub use module::external_port_formal_names; pub use portability_check::{check_array_literal_side_effects, check_function_output_aliases}; +pub use runtime_functions::{RuntimeFunctions, preserve_terminating_function_calls}; pub use schedule::schedule_symbolic_rtl; pub use source::{ AbsoluteAddr, GlueAddr, GlueBlock, ModuleInitialMemoryValue, RegionedAbsoluteAddr, diff --git a/crates/celox-frontend-veryl/src/runtime_functions.rs b/crates/celox-frontend-veryl/src/runtime_functions.rs new file mode 100644 index 00000000000..944b82e7cbc --- /dev/null +++ b/crates/celox-frontend-veryl/src/runtime_functions.rs @@ -0,0 +1,88 @@ +//! Preserve runtime termination before the analyzer folds loop bounds. + +use veryl_analyzer::{ + AnalyzerError, analyzer_error::UnevaluableValueKind, symbol::SymbolKind, symbol_table, +}; +use veryl_parser::{ + veryl_grammar_trait::{DollarIdentifier, FunctionDeclaration, InitialDeclaration, Veryl}, + veryl_walker::VerylWalker, +}; + +/// Source contexts where the kernel supports runtime case conditions. +#[derive(Default)] +pub struct RuntimeFunctions { + initials: Vec, +} +impl RuntimeFunctions { + /// Kernel initial blocks evaluate case patterns at runtime. Keep the + /// analyzer's constant-case requirement for RTL and other contexts. + pub fn is_runtime_case_condition(&self, error: &AnalyzerError) -> bool { + let AnalyzerError::UnevaluableValue { + kind: UnevaluableValueKind::CaseCondition, + error_location, + token_source, + .. + } = error + else { + return false; + }; + self.initials.iter().any(|range| { + let span: miette::SourceSpan = range.into(); + &range.beg.source == token_source + && span.offset() <= error_location.offset() + && error_location.offset() + error_location.len() <= span.offset() + span.len() + }) + } +} + +/// Call after pass 1 and before its global post-pass. A function containing +/// `$finish` cannot be constant evaluated even if its return value is constant. +/// Seeding that fact before the analyzer resolves functions also propagates it +/// to callers through its normal constant-function dependency analysis. +pub fn preserve_terminating_function_calls<'a>( + asts: impl IntoIterator, +) -> RuntimeFunctions { + #[derive(Default)] + struct Finish { + found: bool, + } + impl VerylWalker for Finish { + fn dollar_identifier(&mut self, identifier: &DollarIdentifier) { + self.found |= identifier.dollar_identifier_token.token.text.to_string() == "$finish"; + } + } + #[derive(Default)] + struct Functions { + tokens: crate::HashSet, + initials: Vec, + } + impl VerylWalker for Functions { + fn initial_declaration(&mut self, initial: &InitialDeclaration) { + self.initials.push(initial.into()); + self.statement_block(&initial.statement_block); + } + fn function_declaration(&mut self, function: &FunctionDeclaration) { + let mut finish = Finish::default(); + finish.statement_block(&function.statement_block); + if finish.found { + self.tokens + .insert(function.identifier.identifier_token.token.id); + } + } + } + let mut functions = Functions::default(); + for ast in asts { + functions.veryl(ast); + } + for mut symbol in symbol_table::get_all() { + if functions.tokens.contains(&symbol.token.id) + && let SymbolKind::Function(property) = &mut symbol.kind + { + property.constantable = Some(false); + symbol_table::update(symbol); + } + } + RuntimeFunctions { + initials: functions.initials, + } +} diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 9b9e38ec89d..100e0cff9d4 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -398,18 +398,20 @@ fn analyze( let loop_sources = parser::loop_provenance::LoopSourceTable::collect(parsers.iter().map(|x| &x.veryl)); - // Global post-pass1 + let has_testbench = symbol_table::get_all() + .iter() + .any(|symbol| matches!(&symbol.kind, SymbolKind::Module(module) if module.test.is_some())); + let runtime_functions = if testbench_kernels && has_testbench { + celox_frontend_veryl::preserve_terminating_function_calls(parsers.iter().map(|x| &x.veryl)) + } else { + Default::default() + }; + // Resolve constant-function dependencies only after runtime termination + // has been classified, so transitive callers retain those effects too. errors.append(&mut Analyzer::analyze_post_pass1()); - // Shared context for pass2 let mut context = Context::default(); - // The analyzer's constant evaluator does not retain testbench runtime - // effects. Keep calls in kernel testbench IR; SIR lowering can still fold - // their values after executing the process effects. - context.disalbe_const_opt = testbench_kernels - && symbol_table::get_all().iter().any( - |symbol| matches!(&symbol.kind, SymbolKind::Module(module) if module.test.is_some()), - ); + context.disalbe_const_opt = testbench_kernels && has_testbench; let mut ir = Ir::default(); @@ -426,6 +428,7 @@ fn analyze( } errors.append(&mut context.drain_errors()); errors.append(&mut Analyzer::analyze_post_pass2(&ir)); + errors.retain(|error| !runtime_functions.is_runtime_case_condition(error)); // Veryl reports combinational loops before Celox can apply its path-level // false-loop and true-loop authorizations. When the caller supplied such diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index 6a21d95e96f..ddce7866102 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2043,7 +2043,16 @@ fn terminating_event_argument_skips_later_clock_argument() { #[test] fn terminating_for_start_skips_a_later_clock_bound() { let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var seed:u32;function stop()->u32{$finish();return seed;}function later()->u32{clk.next();return 2;}initial{for i in stop()..later(){$assert(0);}}}"#; - check_passes_on_every_backend(code); + for source in [ + code.to_owned(), + code.replace("return seed", "return 0"), + code.replace( + "function stop()->u32{$finish();return seed;}", + "function inner()->u32{$finish();return 0;}function stop()->u32{return inner();}", + ), + ] { + check_passes_on_every_backend(&source); + } } #[test] fn zero_clock_count_keeps_helper_design_writes_dirty() { @@ -2281,3 +2290,12 @@ fn reentrant_output_snapshots_keep_all_masks_and_return_across_waits() { #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(build().build_native().unwrap()); } + +#[test] +fn runtime_case_exceptions_do_not_relax_rtl_case_conditions() { + let source = "#[test(Top)]module Top{var label:u32;var q:u32;always_comb{q=0;case 0{label:{q=1;}}}initial{$finish();}}"; + let error = Simulator::builder(source, "Top") + .build_interpreter() + .unwrap_err(); + assert!(format!("{error:?}").contains("CaseCondition"), "{error}"); +} From d1f0d0213fb9d914c8bdfc38b96745aaa63a6c2b Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 16:13:09 +0900 Subject: [PATCH 65/72] test(runtime): publish the last edge before terminating edge-count stimulus --- crates/celox/tests/processes.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 8f6c65ecd9f..b89f0e1774c 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -869,6 +869,9 @@ fn four_state_edges_count_transitions_into_and_out_of_unknown() { body.push(Statement::Assign { target, value }); } } + // Publish the final sampled edge before terminating. Finish itself must + // not execute FF work after the kernel has requested termination. + body.push(Statement::Delay { amount: five }); body.push(Statement::Finish); module.process(body).unwrap(); let artifact = module.finish(); From 3aff5f9c11c1fdd8ad6c2525f58b5081815dee0a Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 18:20:43 +0900 Subject: [PATCH 66/72] fix(runtime): retain FF edges from zero-count releases --- crates/celox-runtime/src/simulation.rs | 18 +++++ crates/celox/src/simulation.rs | 107 +++++++++++++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 215b0558b64..9c0ab1eaac1 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1555,10 +1555,28 @@ impl SimulationState { // count documents. if let Some(release) = release { let release = refs.releases[release].clone(); + let before_release = self + .topo_signals + .iter() + .map(|(signal, _, _)| { + sample_event_signal(executor.backend(), *signal) + }) + .collect::>(); executor .backend_mut() .set_wide(release.signal, release.value.into()); executor.eval_comb()?; + self.record_process_settle_edges( + executor.backend(), + &before_release, + &BitSet::new(), + ); + self.sample_waiting_events(executor, current_time)?; + *comb_current = true; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } } any_ran = true; count_delta_pass(delta_rounds)?; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 197f66461b7..71011890538 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -5931,3 +5931,110 @@ mod sampled_host_review { ); } } + +#[cfg(test)] +mod zero_release_review { + use super::*; + + // Veryl reset.assert(0) deliberately holds for one cycle. Exercise the + // lower-level kernel contract by reporting a zero-count release from + // an actual compiled kernel, then delegate the rest to the real backend. + struct ZeroRelease<'a, B: SimBackend> { + sim: &'a mut Simulator, + controls: Vec<(SignalRef, SignalRef, SignalRef)>, + } + impl SimulationExecutor for ZeroRelease<'_, B> { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(self.sim, event) + } + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::run_process(self.sim, index, time)?; + let (status, delay, release) = self.controls[index]; + if self.sim.backend.get_as::(status) + == celox_design::ProcessStatus::WaitClock.code() + && self.sim.backend.get_as::(release) != 0 + { + self.sim.backend.set(delay, 0u64); + } + Ok(()) + } + } + + #[test] + fn zero_count_releases_capture_edges_before_the_continuation_restores_them() { + fn check(mut sim: Simulator) { + let rst = sim.signal("rst"); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + sim.eval_comb().unwrap(); + let mut state = simulation_state(&sim); + let controls = sim + .program + .runtime_schema + .processes + .iter() + .map(|slots| { + ( + sim.backend.resolve_signal(&slots.status), + sim.backend.resolve_signal(&slots.delay), + sim.backend.resolve_signal(&slots.release), + ) + }) + .collect(); + let mut executor = ZeroRelease { + sim: &mut sim, + controls, + }; + while state.next_event_time().is_some_and(|time| time <= 10) { + state.step(&mut executor).unwrap(); + } + let count = sim.signal("count"); + assert_eq!(sim.get(count), 1u8.into()); + assert_eq!(sim.get(rst), 0u8.into()); + } + let code = r#" + module Counter(clk: input clock, count: output logic<8>) { + always_ff(clk) { count += 1; } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 10); + inst rst: $tb::reset_gen(clk); + var gate: logic; + let released: '_ clock = ~rst & gate; + var count: logic<8>; + inst dut: Counter(clk: released, count); + initial { gate = 1; rst.assert(1); gate = 0; clk.next(1); } + }"#; + macro_rules! build { + ($method:ident) => { + check( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .reset_type(crate::ResetType::AsyncHigh) + .$method() + .unwrap(), + ); + }; + } + build!(build_interpreter); + build!(build_cranelift); + build!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + build!(build_native); + } +} From 552667502fa3d334373c6c0e51bc9f00259b2f22 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:15:29 +0900 Subject: [PATCH 67/72] fix(testbench): reset generated clocks before component startup --- crates/celox/src/testbench/kernels.rs | 30 +++++----- crates/celox/tests/component_method.rs | 76 ++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 15 deletions(-) diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 23ad1905782..5617f6e59cf 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -125,6 +125,21 @@ fn run( let test_name = root_testbench_name(sim); let use_4state = sim.backend.layout().four_state; let seed = execution_random_seed(testbench.configured_random_seed()); + // A run starts every process at its beginning, whatever an earlier run + // of the same simulator left in the control slots, and every process + // clock low, as the bytecode testbench does: the first `clk.next()` + // then counts a real rising edge. + for slots in &sim.program.runtime_schema.processes.clone() { + for slot in slots.iter() { + let signal = sim.backend.resolve_signal(slot); + sim.backend.set_wide(signal, BigUint::ZERO); + } + for clock in &slots.clocks { + let signal = sim.backend.resolve_signal(&clock.signal); + sim.backend.set_wide(signal, BigUint::ZERO); + sim.dirty = true; + } + } let initial_writes = match sim.components.initialize( testbench.components(), testbench.component_bindings(), @@ -150,21 +165,6 @@ fn run( files: crate::HashMap::default(), base: testbench.component_file_base().map(|base| base.to_owned()), }); - // A run starts every process at its beginning, whatever an earlier run - // of the same simulator left in the control slots, and every process - // clock low, as the bytecode testbench does: the first `clk.next()` - // then counts a real rising edge. - for slots in &sim.program.runtime_schema.processes.clone() { - for slot in slots.iter() { - let signal = sim.backend.resolve_signal(slot); - sim.backend.set_wide(signal, BigUint::ZERO); - } - for clock in &slots.clocks { - let signal = sim.backend.resolve_signal(&clock.signal); - sim.backend.set_wide(signal, BigUint::ZERO); - sim.dirty = true; - } - } sim.testbench_events.clear(); sim.reset_runtime_finish(false); diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index aeffc9c775f..97aef7aaf3b 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -406,6 +406,32 @@ static CLOCK_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { on_finish: hook, }; +unsafe extern "C" fn clock_init_from_clock(state: *mut c_void, ctx: *mut sys::VrlCtx) -> i32 { + let state = unsafe { &mut *state.cast::() }; + let api = unsafe { &*state.api }; + let clock = unsafe { (api.port_index)(ctx, sys::VrlStr::from_str("clk"), sys::VRL_DIR_CLOCK) }; + if clock < 0 { + return 1; + } + let mut value = 0; + let mut mask = 0; + unsafe { (api.read_input)(ctx, clock as u32, &mut value, &mut mask) }; + unsafe { (api.write_output)(ctx, state.output, &value, &mask) }; + 0 +} + +static INIT_CLOCK_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + abi_version: sys::VRL_COMPONENT_ABI_VERSION, + kind: sys::VRL_KIND_CLOCKED, + create: create_clock, + destroy: destroy_clock, + on_init: clock_init_from_clock, + on_reset: hook, + on_clock: hook, + call_method: clock_call_method, + on_finish: hook, +}; + static INIT_INPUT_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { abi_version: sys::VRL_COMPONENT_ABI_VERSION, kind: sys::VRL_KIND_CLOCKED, @@ -759,6 +785,7 @@ fn register_component() { celox::register_static_component("celox_param", &COMPONENT); celox::register_static_component("celox_clocked", &CLOCK_COMPONENT); celox::register_static_component("celox_init_input", &INIT_INPUT_COMPONENT); + celox::register_static_component("celox_init_clock", &INIT_CLOCK_COMPONENT); celox::register_static_component("celox_wide_clocked", &WIDE_CLOCK_COMPONENT); celox::register_static_component("celox_modport", &MODPORT_COMPONENT); celox::register_static_component("celox_bad_clock", &BAD_CLOCK_COMPONENT); @@ -830,6 +857,14 @@ fn component_metadata() -> (tempfile::TempDir, veryl_metadata::Metadata) { ], "params": [{"name":"STEP","type":"value"}] }, + "celox_init_clock": { + "kind": "clocked", + "ports": [ + {"name":"clk","dir":"input","role":"clock"}, + {"name":"d","dir":"input"}, + {"name":"q","dir":"output"} + ] + }, "celox_init_input": { "kind": "clocked", "ports": [ @@ -1048,6 +1083,47 @@ fn connected_clocked_component_stages_inputs_and_applies_outputs() { ); } +#[test] +fn repeated_kernel_runs_stage_low_clocks_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + var q: logic<8>; + inst probe: $comp::celox_init_clock(clk, d: 8'h0, q); + inst finisher: $comp::celox_finisher(clk); + initial { + $assert(q == 0, "on_init must observe a low generated clock: %h", q); + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + #[test] fn component_on_init_observes_connected_inputs() { register_component(); From 91798484618305c42819c1a13efb75c2073ee036 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 21:57:56 +0900 Subject: [PATCH 68/72] fix(testbench): pass time when sampling blocking FF waiters --- crates/celox-runtime/src/simulation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 32e3b27a073..4313d0e9c06 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -2318,7 +2318,7 @@ impl SimulationState { } // Latch every waiter before another active FF or // continuation can erase a propagated blocking edge. - self.sample_waiting_events(executor)?; + self.sample_waiting_events(executor, current_time)?; self.replace_triggers_with_stable_edges(executor.backend_mut()); for id in ff_body_edges.iter() { executor.backend_mut().mark_triggered_bit(id); From 077ea003d900729dca697dd1a41292f5bc19c124 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 15 Oct 2026 23:42:55 +0900 Subject: [PATCH 69/72] fix(veryl): settle derived inputs before component initialization --- crates/celox/src/testbench/kernels.rs | 25 ++++++++++++++- crates/celox/tests/component_method.rs | 42 ++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 5617f6e59cf..b3781914c29 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -129,6 +129,7 @@ fn run( // of the same simulator left in the control slots, and every process // clock low, as the bytecode testbench does: the first `clk.next()` // then counts a real rising edge. + let mut reset_clocks = crate::HashSet::default(); for slots in &sim.program.runtime_schema.processes.clone() { for slot in slots.iter() { let signal = sim.backend.resolve_signal(slot); @@ -137,9 +138,32 @@ fn run( for clock in &slots.clocks { let signal = sim.backend.resolve_signal(&clock.signal); sim.backend.set_wide(signal, BigUint::ZERO); + reset_clocks.insert(signal); sim.dirty = true; } } + // Component on_init stages connected inputs immediately, including logic + // derived from the clocks reset above. Settle that logic before staging. + sim.reset_runtime_finish(false); + let stage_derived_inputs = testbench.component_bindings().iter().any(|component| { + component.connections.iter().any(|connection| { + connection.input.as_ref().is_some_and(|input| { + input.constant_u64().is_none() + && !connection.input_target.as_ref().is_some_and(|target| { + target.selection.is_none() && reset_clocks.contains(&target.signal) + }) + }) + }) + }); + // Constants and directly reset clocks already have their startup values. + // Avoid running unrelated comb observers when on_init needs no settle: + // an init hook may finish the test before those observers should run. + if sim.dirty && stage_derived_inputs { + if let Err(error) = sim.eval_comb_checked() { + return failed(error.to_string()); + } + sim.dirty = false; + } let initial_writes = match sim.components.initialize( testbench.components(), testbench.component_bindings(), @@ -166,7 +190,6 @@ fn run( base: testbench.component_file_base().map(|base| base.to_owned()), }); sim.testbench_events.clear(); - sim.reset_runtime_finish(false); // The scheduler samples the clocks it detects edges on from settled // state. diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 97aef7aaf3b..efb630e68e4 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -1124,6 +1124,48 @@ fn repeated_kernel_runs_stage_low_clocks_before_component_init() { check!(build_native); } +#[test] +fn repeated_kernel_runs_settle_derived_clock_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + var q: logic<8>; + let derived: logic<8> = (clk as u8) + 8'h1; + inst probe: $comp::celox_init_input(clk, d: derived, q); + inst finisher: $comp::celox_finisher(clk); + initial { + $assert(q == 1, "on_init must observe a settled derived clock: %h", q); + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + #[test] fn component_on_init_observes_connected_inputs() { register_component(); From 45437174c2f2e41a8e129b2b897c4985365ea3e2 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 00:33:20 +0900 Subject: [PATCH 70/72] test(veryl): adapt clean waiter regression to release-aware kernels --- crates/celox/src/simulation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3e7cbd9b270..3787282af0b 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -7221,7 +7221,7 @@ mod clean_waiter_settle_review { kernel .builder() .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); - kernel.wait_clock(0, count).unwrap(); + kernel.wait_clock(0, count, None).unwrap(); let one = kernel.builder().alloc_bit(1, false); kernel .builder() From bcdd8ee3380d39fbad53dd93d2254bab29832101 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 01:07:37 +0900 Subject: [PATCH 71/72] fix(testbench): preserve host order and clean continuation state --- .../src/lowering/process/expressions.rs | 106 ++++--- crates/celox-runtime/src/simulation.rs | 1 + crates/celox/src/simulation.rs | 5 + crates/celox/src/testbench/kernels.rs | 262 +++++++++++++++++- crates/celox/tests/component_method.rs | 48 ++++ 5 files changed, 379 insertions(+), 43 deletions(-) diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs index 4b7d7a0b76a..273ac153377 100644 --- a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -424,25 +424,31 @@ impl BlockLowering<'_> { .builder() .seal_block(SIRTerminator::Jump(join, Vec::new())); self.kernel.builder().switch_to_block(full); + let full_reaches_join = self.scan_expression_clocks(rhs, &mut HashSet::default(), false); let right = self.expression(rhs)?; - let left = self.saved_expression(lhs); - let builder = self.kernel.builder(); - let value = builder.alloc_logic(1); - builder.emit(SIRInstruction::Binary( - value, - left, - if is_and { - BinaryOp::LogicAnd - } else { - BinaryOp::LogicOr - }, - right, - )); - self.save_expression(expr, value)?; - self.dirty |= dirty_before; - self.kernel - .builder() - .seal_block(SIRTerminator::Jump(join, Vec::new())); + if full_reaches_join { + let left = self.saved_expression(lhs); + let builder = self.kernel.builder(); + let value = builder.alloc_logic(1); + builder.emit(SIRInstruction::Binary( + value, + left, + if is_and { + BinaryOp::LogicAnd + } else { + BinaryOp::LogicOr + }, + right, + )); + self.save_expression(expr, value)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + // expression() leaves an unreachable block after a finishing call. + self.kernel.builder().seal_block(SIRTerminator::Return); + } + self.dirty = dirty_before || (full_reaches_join && self.dirty); self.kernel.builder().switch_to_block(join); self.parser.clear_register_cache(); Ok(self.saved_expression(expr)) @@ -480,12 +486,17 @@ impl BlockLowering<'_> { }); let dirty_before = self.dirty; self.kernel.builder().switch_to_block(yes_block); + let yes_reaches_join = self.scan_expression_clocks(yes, &mut HashSet::default(), false); let result = self.expression(yes)?; - self.save_expression(expr, result)?; - let yes_dirty = self.dirty; - self.kernel - .builder() - .seal_block(SIRTerminator::Jump(join, Vec::new())); + let yes_dirty = yes_reaches_join && self.dirty; + if yes_reaches_join { + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } self.kernel.builder().switch_to_block(decide); self.dirty = dirty_before; let condition = self.saved_expression(cond); @@ -500,29 +511,46 @@ impl BlockLowering<'_> { false_block: (unknown, Vec::new()), }); self.kernel.builder().switch_to_block(no_block); + let no_reaches_join = self.scan_expression_clocks(no, &mut HashSet::default(), false); let result = self.expression(no)?; - self.save_expression(expr, result)?; - let no_dirty = self.dirty; - self.kernel - .builder() - .seal_block(SIRTerminator::Jump(join, Vec::new())); + let no_dirty = no_reaches_join && self.dirty; + if no_reaches_join { + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } self.kernel.builder().switch_to_block(unknown); self.dirty = dirty_before; - for child in [yes, no] { + let mut unknown_reaches_join = true; + for (child, reaches) in [(yes, yes_reaches_join), (no, no_reaches_join)] { let value = self.expression(child)?; + if !reaches { + unknown_reaches_join = false; + break; + } self.save_expression(child, value)?; } - let values = [cond, yes, no] - .into_iter() - .map(|child| (child.token_range(), self.saved_expression(child))) - .collect(); - let result = self.parse_with_values(expr, values)?; - self.save_expression(expr, result)?; - self.kernel - .builder() - .seal_block(SIRTerminator::Jump(join, Vec::new())); + let unknown_dirty = unknown_reaches_join && self.dirty; + if unknown_reaches_join { + let values = [cond, yes, no] + .into_iter() + .map(|child| (child.token_range(), self.saved_expression(child))) + .collect(); + let result = self.parse_with_values(expr, values)?; + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } self.kernel.builder().switch_to_block(join); - self.dirty |= yes_dirty || no_dirty; + // The unknown path evaluates both arms in order; a terminating arm + // never contributes a continuation to this join. + self.dirty = dirty_before || yes_dirty || no_dirty || unknown_dirty; self.parser.clear_register_cache(); Ok(self.saved_expression(expr)) } diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index faa22ac7f76..80975030eb3 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -2012,6 +2012,7 @@ impl SimulationState { && (!ready_processes.is_empty() || !self.waiting.is_empty()) { executor.eval_comb()?; + comb_current = true; } for (id, count) in batch_edge_counts { // The first occurrence is already in scheduled_edges, unless a diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 3787282af0b..f2f45e10841 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -201,6 +201,11 @@ impl SimulationExecutor for Simulator { request: usize, time: u64, ) -> Result { + // Keep output observable before the following host-side effect, while + // retaining assertion/finish events for the runner's normal drain. + if self.testbench_random.is_some() { + crate::testbench::kernels::forward_pending_output(self); + } crate::testbench::kernels::serve_host_request(self, process, request, time).map_err( |message| RuntimeErrorCode::Runtime { message, diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index b3781914c29..3c0e9e092cf 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -129,16 +129,29 @@ fn run( // of the same simulator left in the control slots, and every process // clock low, as the bytecode testbench does: the first `clk.next()` // then counts a real rising edge. - let mut reset_clocks = crate::HashSet::default(); + let restarting = sim.program.runtime_schema.processes.iter().any(|slots| { + sim.backend + .get_as::(sim.backend.resolve_signal(&slots.status)) + != 0 + }); + let mut reset_signals = crate::HashSet::default(); for slots in &sim.program.runtime_schema.processes.clone() { for slot in slots.iter() { let signal = sim.backend.resolve_signal(slot); sim.backend.set_wide(signal, BigUint::ZERO); } + // A previous run may have finished while another process held a + // reset. The old scheduler's pending release does not survive a run. + for release in slots.releases.iter().filter(|_| restarting) { + let signal = sim.backend.resolve_signal(&release.signal); + sim.backend.set_wide(signal, release.value.into()); + reset_signals.insert(signal); + sim.dirty = true; + } for clock in &slots.clocks { let signal = sim.backend.resolve_signal(&clock.signal); sim.backend.set_wide(signal, BigUint::ZERO); - reset_clocks.insert(signal); + reset_signals.insert(signal); sim.dirty = true; } } @@ -150,12 +163,12 @@ fn run( connection.input.as_ref().is_some_and(|input| { input.constant_u64().is_none() && !connection.input_target.as_ref().is_some_and(|target| { - target.selection.is_none() && reset_clocks.contains(&target.signal) + target.selection.is_none() && reset_signals.contains(&target.signal) }) }) }) }); - // Constants and directly reset clocks already have their startup values. + // Constants and directly restored control signals already have startup values. // Avoid running unrelated comb observers when on_init needs no settle: // an init hook may finish the test before those observers should run. if sim.dirty && stage_derived_inputs { @@ -361,6 +374,20 @@ fn drain( drained } +pub(crate) fn forward_pending_output(sim: &mut Simulator) { + sim.testbench_events.retain(|(_, event)| match event { + RuntimeEvent::Display { message } => { + forward_display(message, true); + false + } + RuntimeEvent::Write { message } => { + forward_display(message, false); + false + } + _ => true, + }); +} + /// Serve host request `request` of process `process` at `time`. pub(crate) fn serve_host_request( sim: &mut Simulator, @@ -575,6 +602,7 @@ mod event_yield_settle_tests { combs: usize, fused: u64, combs_before_edge: Option, + combs_at_finish: Option, } impl SimulationExecutor for CountingExecutor { type Backend = B; @@ -619,6 +647,15 @@ mod event_yield_settle_tests { SimulationExecutor::run_process(&mut self.sim, index, time)?; let slot = self.sim.program.runtime_schema.processes[index].status; let signal = self.sim.backend.resolve_signal(&slot); + if matches!( + celox_design::ProcessStatus::from_code(self.sim.backend.get_as(signal)), + Some( + celox_design::ProcessStatus::Finish + | celox_design::ProcessStatus::FinishAfterPublication + ) + ) { + self.combs_at_finish = Some(self.combs); + } if celox_design::ProcessStatus::from_code(self.sim.backend.get_as(signal)) == Some(celox_design::ProcessStatus::Settle) { @@ -653,6 +690,7 @@ mod event_yield_settle_tests { combs: 0, fused: 0, combs_before_edge: None, + combs_at_finish: None, }; for _ in 0..10000 { if state.step(&mut executor).unwrap().is_none() || state.is_finished() { @@ -662,6 +700,218 @@ mod event_yield_settle_tests { panic!("process did not finish"); } #[test] + fn round60_terminating_expression_branches_do_not_dirty_the_join() { + fn count(sim: Simulator) -> usize { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..20 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + break; + } + } + assert!(state.is_finished()); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 1 + ); + executor.combs + } + let source = |expression: &str| { + format!( + "#[test(Top)]module Top(cond:input logic){{var value:u8;var derived:u8;always_comb{{derived=value;}}function stop()->u8{{value=2;$finish();return 0;}}initial{{value=1;$assert(({expression})==0);$assert(derived==1);$finish();}}}}" + ) + }; + // Compare reachable generated control flow with an otherwise identical + // terminating helper that makes no design write. Runtime clean flags + // can suppress the redundant settle, masking the bad compile-time join. + let branches = |source: &str| { + let compilation = Simulator::builder(source, "Top") + .testbench_kernels(true) + .trace_post_optimized_sir() + .build_with_trace(); + compilation.res.unwrap(); + let program = compilation.trace.post_optimized_sir.unwrap(); + assert!( + !program.sir.processes.is_empty(), + "inspect actual testbench kernels" + ); + program + .sir + .processes + .iter() + .flat_map(|p| p.blocks.values()) + .filter(|block| matches!(block.terminator, celox_sir::SIRTerminator::Branch { .. })) + .count() + }; + for expr in [ + "if cond ? stop() : 8'd0", + "cond && (stop()!=0)", + "!( !cond || (stop()!=0))", + ] { + let writing = source(expr); + let clean = writing.replace("value=2;", ""); + assert_eq!( + branches(&writing), + branches(&clean), + "unreachable writes add a settle guard at {expr}" + ); + } + macro_rules! check { + ($build:ident) => {{ + let active = source("if !cond ? stop() : 8'd0") + .replace("value=2;$finish();return 0;", "value=2;return 0;") + .replace("$assert(derived==1)", "$assert(derived==2)"); + let mut sim = Simulator::builder(&active, "Top").$build().unwrap(); + let tb = crate::testbench::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim, &tb), + TestResult::Pass + ); + + let baseline = count(Simulator::builder(&source("8'd0"), "Top").$build().unwrap()); + for expr in [ + "if cond ? stop() : 8'd0", + "cond && (stop()!=0)", + "!( !cond || (stop()!=0))", + ] { + assert_eq!( + count(Simulator::builder(&source(expr), "Top").$build().unwrap()), + baseline, + "{expr}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] + fn round60_release_reuses_completed_settle() { + fn check(sim: Simulator, writing: bool) { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..20 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + break; + } + } + assert!(state.is_finished()); + let before_finish = executor.combs_at_finish.expect("finish continuation ran"); + if writing { + assert!( + executor.combs > before_finish, + "a design write still needs settling" + ); + } else { + assert_eq!( + executor.combs, before_finish, + "clean finish must reuse the release settle" + ); + } + } + for writing in [false, true] { + let source = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;inst rst:$tb::reset_gen(clk);var value:u8;var derived:u8;always_comb{{derived=value;}}initial{{rst.assert(1);{}$finish();}}}}", + if writing { "value=1;" } else { "" } + ); + check( + Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(), + writing, + ); + check( + Simulator::builder(&source, "Top") + .build_cranelift() + .unwrap(), + writing, + ); + check( + Simulator::builder(&source, "Top").build_wasm().unwrap(), + writing, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&source, "Top").build_native().unwrap(), + writing, + ); + } + } + // A child process captures real flushed stderr bytes, including file host + // effects; inspecting the event queue alone cannot establish visibility. + #[cfg(unix)] + #[test] + fn round60_output_visibility_and_release_settle() { + const CHILD: &str = "CELOX_ROUND60_OUTPUT_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "testbench::kernels::event_yield_settle_tests::round60_output_visibility_and_release_settle", "--nocapture"]) + .env(CHILD, "1").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + output.status.success(), + "{}\n{stderr}", + String::from_utf8_lossy(&output.stdout) + ); + assert_eq!(stderr.matches("before|host|after\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-clean\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-write=0\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-write=1\n").count(), 4, "{stderr}"); + return; + } + fn execute(mut sim: Simulator) { + let tb = crate::testbench::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim, &tb), + TestResult::Pass + ); + } + let ordered = r#"#[test(Top)] module Top {var f:$tb::file;initial {f.open("/dev/stderr");$write("before|");f.write("host|");f.flush();$display("after");f.close();$assert(1==1);$finish();}}"#; + let release = |writing: bool| { + format!( + r#"#[test(Top)] module Top {{inst clk:$tb::clock_gen;inst rst:$tb::reset_gen(clk);var value:u8;var armed:logic;always_comb {{if armed && (rst as u8)!=0 {{ {} }} }}initial {{armed=1;rst.assert(1);{}$finish();}}}}"#, + if writing { + r#"$display("release-write=%d",value);"# + } else { + r#"$display("release-clean");"# + }, + if writing { "value=1;" } else { "" } + ) + }; + macro_rules! check { + ($build:ident) => {{ + for source in [ordered.to_owned(), release(false), release(true)] { + execute(Simulator::builder(&source, "Top").$build().unwrap()); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] fn clean_random_host_requests_preserve_settled_design_state() { fn count_host(mut sim: Simulator) -> usize { sim.testbench_random = Some(RandomTable::new(7)); @@ -676,6 +926,7 @@ mod event_yield_settle_tests { combs: 0, fused: 0, combs_before_edge: None, + combs_at_finish: None, }; state.step(&mut executor).unwrap(); assert!(state.is_finished()); @@ -817,6 +1068,7 @@ mod event_yield_settle_tests { combs: 0, fused: 0, combs_before_edge: None, + combs_at_finish: None, }; state.step(&mut executor).unwrap(); assert!(state.is_finished()); @@ -982,6 +1234,7 @@ mod event_yield_settle_tests { combs: 0, fused: 0, combs_before_edge: None, + combs_at_finish: None, }; for _ in 0..steps { if state.step(&mut executor).unwrap().is_none() { @@ -1097,6 +1350,7 @@ mod event_yield_settle_tests { combs: 0, fused: 0, combs_before_edge: None, + combs_at_finish: None, }; for run in 1..=256 { // Restart control slots as the public runner does, retaining diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index efb630e68e4..e6472d5a116 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -1166,6 +1166,54 @@ fn repeated_kernel_runs_settle_derived_clock_before_component_init() { check!(build_native); } +#[test] +fn repeated_kernel_runs_deassert_interrupted_reset_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + inst rst: $tb::reset_gen(clk); + var q: logic<8>; + let derived: logic<8> = (rst as u8) + 8'h1; + inst probe: $comp::celox_init_input(clk, d: derived, q); + inst finisher: $comp::celox_finisher(clk); + initial { rst.assert(5); $assert(0, "reset must be interrupted"); } + initial { + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + assert_eq!( + sim.get(sim.signal("q")), + (if run == 0 { 1u8 } else { 2u8 }).into(), + "on_init on run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + #[test] fn component_on_init_observes_connected_inputs() { register_component(); From ff76599b46af741271417b6b9ea7684a5c274c91 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 16 Oct 2026 01:18:21 +0900 Subject: [PATCH 72/72] test(testbench): scope subprocess marker access to output regression --- crates/celox/src/testbench/kernels.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs index 3c0e9e092cf..9aec0764149 100644 --- a/crates/celox/src/testbench/kernels.rs +++ b/crates/celox/src/testbench/kernels.rs @@ -863,7 +863,12 @@ mod event_yield_settle_tests { #[test] fn round60_output_visibility_and_release_settle() { const CHILD: &str = "CELOX_ROUND60_OUTPUT_CHILD"; - if std::env::var_os(CHILD).is_none() { + #[expect( + clippy::disallowed_methods, + reason = "test subprocess marker only; no simulator diagnostics are read" + )] + let child = std::env::var_os(CHILD).is_some(); + if !child { let output = std::process::Command::new(std::env::current_exe().unwrap()) .args(["--exact", "testbench::kernels::event_yield_settle_tests::round60_output_visibility_and_release_settle", "--nocapture"]) .env(CHILD, "1").output().unwrap();