diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 412ab44f11a..a7c52360619 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -216,11 +216,31 @@ pub struct RuntimeErrorInfo { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ProcessStatus { /// Resume after the number of time units stored in [`ProcessSlots::delay`]. + /// A zero delay resumes at the same time after the nonblocking + /// assignments of that time are published. Delay, /// The process ran to the end of its body. Done, /// The process requested the end of the simulation. Finish, + /// Like [`Self::Delay`], but a zero delay resumes in the inactive region + /// of the same time, before nonblocking assignments are published (IEEE + /// 1800-2023 4.4.2.3). + InactiveDelay, + /// The process suspended at an event or level wait. The delay slot holds + /// the index of its [`WaitSite`]. The runtime resumes the process when a + /// counter of that site moves; the kernel then checks the wait itself. + Wait, + /// The process was resumed at a wait whose condition does not hold. It + /// ran no statement and waits at the same site. + Pending, + /// The process staged one nonblocking assignment. The delay slot holds + /// the index of its [`NbaSite`]. The runtime queues the staged value and + /// resumes the process at once. + Nba, + /// The process returned so the runtime can charge its time-slot budget. + /// It resumes at once. + Yield, } impl ProcessStatus { @@ -231,6 +251,11 @@ impl ProcessStatus { Self::Delay => 1, Self::Done => 2, Self::Finish => 3, + Self::InactiveDelay => 4, + Self::Wait => 5, + Self::Pending => 6, + Self::Nba => 7, + Self::Yield => 8, } } @@ -239,6 +264,11 @@ impl ProcessStatus { 1 => Some(Self::Delay), 2 => Some(Self::Done), 3 => Some(Self::Finish), + 4 => Some(Self::InactiveDelay), + 5 => Some(Self::Wait), + 6 => Some(Self::Pending), + 7 => Some(Self::Nba), + 8 => Some(Self::Yield), _ => None, } } @@ -277,6 +307,191 @@ pub const PROCESS_STATUS_WIDTH: usize = 8; /// Width of [`ProcessSlots::delay`]. pub const PROCESS_DELAY_WIDTH: usize = 64; +/// Width of every occurrence counter of an [`EventWatch`]. Counters wrap; +/// only their inequality is meaningful. +pub const EVENT_COUNTER_WIDTH: usize = 32; + +/// The occurrences an event counter counts on its watched signal (IEEE +/// 1800-2023 9.4.2, Table 9-2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum CounterKind { + /// Any change of the value, including the unknown bits. + Changes, + /// A positive edge of the least significant bit. + Rises, + /// A negative edge of the least significant bit. + Falls, +} + +impl CounterKind { + pub const ALL: [Self; 3] = [Self::Changes, Self::Rises, Self::Falls]; + + /// The counter kind that wakes an event domain of `kind`. + pub const fn for_domain(kind: DomainKind) -> Self { + match kind { + DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh => Self::Rises, + DomainKind::ClockNegedge | DomainKind::ResetAsyncLow => Self::Falls, + DomainKind::Other => Self::Changes, + } + } +} + +/// A counted signal: a signal that an event control or flip-flop domain +/// watches and that one unit may store twice without the runtime checking +/// in between. Its occurrences are counted in two-state counter objects. +/// +/// Generated code bumps the counters around each such store (see +/// `celox_frontend_core::watch`) and the host and the scheduler bump them on +/// their writes. Every other watched signal is checked by value. The +/// counters are ordinary state. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventWatch { + pub signal: A, + pub width: usize, + pub four_state: bool, + pub changes: Option, + pub rises: Option, + pub falls: Option, + /// Canonical event domains that the counter of the given kind triggers + /// instead of edge detection by value. + pub domains: Vec<(A, CounterKind)>, +} + +impl EventWatch { + pub fn counter(&self, kind: CounterKind) -> Option { + match kind { + CounterKind::Changes => self.changes, + CounterKind::Rises => self.rises, + CounterKind::Falls => self.falls, + } + } + + /// The present counters and their kinds. + pub fn counters(&self) -> impl Iterator + '_ { + CounterKind::ALL + .into_iter() + .filter_map(|kind| Some((kind, self.counter(kind)?))) + } + + pub fn map(&self, mut map: impl FnMut(A) -> B) -> EventWatch { + EventWatch { + signal: map(self.signal), + width: self.width, + four_state: self.four_state, + changes: self.changes.map(&mut map), + rises: self.rises.map(&mut map), + falls: self.falls.map(&mut map), + domains: self + .domains + .iter() + .map(|&(event, kind)| (map(event), kind)) + .collect(), + } + } +} + +/// Counter objects a frontend declares for a signal that one of its units +/// may store twice between two runtime checks. Assembly turns them into an +/// [`EventWatch`] only if something watches the signal. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CounterSlots { + pub signal: A, + pub changes: A, + pub rises: A, + pub falls: A, +} + +impl CounterSlots { + pub fn counter(&self, kind: CounterKind) -> A { + match kind { + CounterKind::Changes => self.changes, + CounterKind::Rises => self.rises, + CounterKind::Falls => self.falls, + } + } + + pub fn map(self, mut map: impl FnMut(A) -> B) -> CounterSlots { + CounterSlots { + signal: map(self.signal), + changes: map(self.changes), + rises: map(self.rises), + falls: map(self.falls), + } + } +} + +/// An event or level wait of a process kernel. A kernel suspended with +/// [`ProcessStatus::Wait`] stores the index of the site among its process's +/// sites in its delay slot. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WaitSite { + /// Index of the process in [`RuntimeSchema::processes`]. + pub process: usize, + /// Occurrences that may satisfy the wait. The runtime resumes the + /// process at the first one after the wait began; a site whose kernel + /// checks a condition at its resume point decides itself whether it + /// continues. + pub terms: Vec<(A, CounterKind)>, +} + +impl WaitSite { + pub fn map(&self, mut map: impl FnMut(A) -> B) -> WaitSite { + WaitSite { + process: self.process, + terms: self + .terms + .iter() + .map(|&(signal, kind)| (map(signal), kind)) + .collect(), + } + } +} + +/// A nonblocking assignment of a process kernel. A kernel that returns +/// [`ProcessStatus::Nba`] stores the index of the site among its process's +/// sites in its delay slot. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct NbaSite { + /// Index of the process in [`RuntimeSchema::processes`]. + pub process: usize, + /// The assigned object and the static part of the assigned bit range. + pub target: A, + pub lsb: usize, + pub width: usize, + /// Staging object of `width` bits holding the assigned value, with the + /// target's state representation. + pub value: A, + /// Two-state staging object holding a bit offset added to `lsb`, for an + /// assignment whose position is computed at run time. + pub offset: Option, + /// One-bit flag of a site whose destination receives no other + /// nonblocking assignment: a variable of the module with no other + /// nonblocking site in the module and no writer outside it (not a port, + /// not bound to a package variable, not the target of a hierarchical + /// reference). A frontend that cannot tell leaves it `None`, so the + /// assignment goes through the ordered queue. + /// + /// The kernel stages the value and sets the flag without returning; + /// publication commits flagged sites and clears the flags. A kernel + /// reaching the site again while the flag is set returns + /// [`ProcessStatus::Nba`] first, so the runtime queues the staged value. + pub pending: Option, +} + +impl NbaSite { + pub fn map(&self, mut map: impl FnMut(A) -> B) -> NbaSite { + NbaSite { + process: self.process, + target: map(self.target), + lsb: self.lsb, + width: self.width, + value: map(self.value), + offset: self.offset.map(&mut map), + pending: self.pending.map(&mut map), + } + } +} + /// Controls which combinational stores dead store elimination preserves. /// /// The policy is part of the runtime contract: host-side handles resolve @@ -325,6 +540,14 @@ pub struct RuntimeSchema { pub live_signals: HashSet, /// Control slots of the process kernels, in kernel order. pub processes: Vec>, + /// Counted signals and their occurrence counters. + pub watches: Vec>, + /// Wait sites of the process kernels. A process's sites appear in the + /// order of its local site indices. + pub wait_sites: Vec>, + /// Nonblocking assignment sites of the process kernels, ordered like + /// `wait_sites`. + pub nba_sites: Vec>, } impl Default for RuntimeSchema { @@ -341,6 +564,9 @@ impl Default for RuntimeSchema { dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), + watches: Vec::new(), + wait_sites: Vec::new(), + nba_sites: Vec::new(), } } } diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs index 0594d9fe192..05e833c6575 100644 --- a/crates/celox-frontend-core/src/lib.rs +++ b/crates/celox-frontend-core/src/lib.rs @@ -7,6 +7,7 @@ mod sdk; pub mod shared; pub mod symbolic; mod trace; +pub mod watch; pub use error::{LoweringPhase, ParserError, SourceLocation}; pub use sdk::{FrontendArtifactError, LoweredFrontendArtifact, lower_frontend_artifact}; diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 4dd6aac955a..8b7b42e9480 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -6,13 +6,23 @@ //! 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 the first +//! occurrence of one of the terms of its [`WaitSite`] after the wait began. +//! A level wait, or an event control on an expression, checks its condition +//! at the resume point and either continues or reports +//! [`ProcessStatus::Pending`]. +//! //! The builder is source-independent: a frontend lowers statements and //! expressions into [`ProcessKernelBuilder::builder`] and calls the -//! suspension methods where the source suspends. +//! suspension methods where the source suspends. Wait and nonblocking +//! sites are numbered per process, in the order the frontend lists them in +//! the module's metadata. +//! +//! [`WaitSite`]: celox_design::WaitSite use celox_design::{ - PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase, - STABLE_REGION, + NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, + RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRSwitchCase, @@ -40,12 +50,18 @@ pub enum ProcessKernelError { TooManySuspensions, } +/// Width of the bit offset staged by a nonblocking assignment whose position +/// is computed at run time ([`NbaSite::offset`]). +pub const NBA_OFFSET_WIDTH: usize = 64; + /// Builder of one process kernel. pub struct ProcessKernelBuilder { builder: SIRBuilder, slots: ProcessSlots, /// The block each resume point continues in; point 0 is the start. resume_blocks: Vec, + /// The wait site whose resume point is being lowered. + wait_site: Option, } impl ProcessKernelBuilder { @@ -58,6 +74,7 @@ impl ProcessKernelBuilder { builder, slots, resume_blocks: vec![start], + wait_site: None, } } @@ -95,25 +112,167 @@ impl ProcessKernelBuilder { 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 `value` into the delay slot. + fn store_delay_constant(&mut self, value: u64) { + self.store_constant(self.slots.delay, PROCESS_DELAY_WIDTH, value); + } + + /// Store the next resume point, return with `status` and continue in a + /// new block at that point. + 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.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. A zero delay resumes after the nonblocking + /// assignments of the time are published. + pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); + self.suspend(ProcessStatus::Delay) + } + + /// A delay with the scheduling of IEEE 1800-2023: a zero delay resumes + /// in the inactive region of the same time (4.4.2.3), before + /// nonblocking assignments are published. + pub fn inactive_delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); + self.suspend(ProcessStatus::InactiveDelay) + } + + /// Return to the runtime, which charges its time-slot budget and + /// resumes the process at once. Frontends place this in loops without + /// timing controls so that a runaway process is reported, not hung in. + pub fn yield_now(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Yield) + } + + /// Suspend at wait site `site` of this process. The open block + /// afterwards is the site's resume point: the caller lowers the wait's + /// condition there and ends it with [`Self::wake_if`]. + pub fn suspend_wait(&mut self, site: u32) -> Result<(), ProcessKernelError> { + self.store_delay_constant(u64::from(site)); + self.suspend(ProcessStatus::Wait)?; + self.wait_site = Some(site); + Ok(()) + } + + /// At the resume point of a [`Self::suspend_wait`]: continue when + /// `condition`, a one-bit two-state register, holds; otherwise report + /// that the wait is still pending and return to the same resume point. + /// The continuation block is open afterwards. + pub fn wake_if(&mut self, condition: RegisterId) { + let site = self.wait_site.take().expect("wake_if follows suspend_wait"); + let woken = self.builder.new_block(); + let pending = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (woken, Vec::new()), + false_block: (pending, Vec::new()), + }); + self.builder.switch_to_block(pending); + self.store_delay_constant(u64::from(site)); + self.end(ProcessStatus::Pending); + self.builder.switch_to_block(woken); + } + + /// `wait (condition)` (IEEE 1800-2023 9.4.3) at wait site `site`: + /// `predicate` lowers the condition to a one-bit two-state register at + /// the open block. It is evaluated once before suspending, so a + /// condition that already holds does not suspend, and again whenever + /// the process is resumed. + pub fn wait_level( + &mut self, + site: u32, + mut predicate: impl FnMut(&mut SIRBuilder) -> RegisterId, + ) -> Result<(), ProcessKernelError> { + let holds = predicate(&mut self.builder); + let join = self.builder.new_block(); + let wait = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: holds, + true_block: (join, Vec::new()), + false_block: (wait, Vec::new()), + }); + self.builder.switch_to_block(wait); + self.suspend_wait(site)?; + let holds = predicate(&mut self.builder); + self.wake_if(holds); + self.builder + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.builder.switch_to_block(join); + Ok(()) + } + + /// The nonblocking assignment of nonblocking site `index` of this + /// process, described by `site`: schedule a value for the NBA region of + /// the current time (IEEE 1800-2023 10.4.2). `lower` lowers the + /// right-hand side at the open block and returns the value, a register + /// of `site.width` bits, and for a site with a run-time position the + /// bit offset, an unsigned two-state register of [`NBA_OFFSET_WIDTH`] + /// bits. + /// + /// A site with a `pending` flag stages the value without returning. If + /// the flag is still set from an earlier execution in the same time + /// slot, the kernel first returns [`ProcessStatus::Nba`] so the runtime + /// queues the earlier value, and evaluates the right-hand side only + /// after that. + pub fn nonblocking>( + &mut self, + index: u32, + site: &NbaSite, + lower: impl FnOnce( + &mut SIRBuilder, + ) -> Result<(RegisterId, Option), E>, + ) -> Result<(), E> { + if let Some(pending) = site.pending { + let flag = self.builder.alloc_bit(1, false); + self.builder.emit(SIRInstruction::Load( + flag, + stable(pending), + SIROffset::Static(0), + 1, + )); + let flush = self.builder.new_block(); + let stage = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: flag, + true_block: (flush, Vec::new()), + false_block: (stage, Vec::new()), + }); + self.builder.switch_to_block(flush); + self.store_delay_constant(u64::from(index)); + self.suspend(ProcessStatus::Nba)?; + self.builder + .seal_block(SIRTerminator::Jump(stage, Vec::new())); + self.builder.switch_to_block(stage); + } + let (value, offset) = lower(&mut self.builder)?; + self.store(site.value, site.width, value); + if let (Some(slot), Some(offset)) = (site.offset, offset) { + self.store(slot, NBA_OFFSET_WIDTH, offset); + } + if let Some(pending) = site.pending { + self.store_constant(pending, 1, 1); + return Ok(()); + } + self.store_delay_constant(u64::from(index)); + self.suspend(ProcessStatus::Nba)?; + Ok(()) + } + /// End the simulation. No block is open afterwards. pub fn finish(&mut self) { + self.wait_site = None; self.end(ProcessStatus::Finish); } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 9ee5423d4bf..a73e773440e 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1,13 +1,14 @@ //! Projection from the stable frontend SDK into Celox symbolic internals. use celox_design::{ - BinaryOp, BitAccess, DomainKind, InitialStateData, InitialStateValue, ModuleId, - PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, - STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, VariableMetadata, WORKING_REGION, + BinaryOp, BitAccess, CounterKind, DomainKind, InitialStateData, InitialStateValue, ModuleId, + NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, + RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, VariableMetadata, + WORKING_REGION, WaitSite, }; use celox_frontend_sdk::{ - ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice, - Statement, ValueType, + ActiveLevel, Direction, Edge, EventEdge, ExprId, ExprNode, FrontendArtifact, SignalId, + SignalSlice, Statement, ValueType, }; use celox_sir::{ BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, @@ -1029,34 +1030,222 @@ fn lower_registers( Ok(()) } +/// Hidden state objects the lowering declares after the artifact's signals: +/// process control slots, counters, staging and gate objects. None of them +/// is a signal of the design. +struct HiddenObjects<'a> { + next_id: u32, + variables: &'a mut HashMap, +} + +impl HiddenObjects<'_> { + fn declare(&mut self, path: Vec, width: usize, four_state: bool) -> SourceVarId { + let id = SourceVarId(self.next_id); + self.next_id += 1; + self.variables.insert( + id, + SymbolicVariable { + path, + kind: VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: four_state, + kind: DomainKind::Other, + type_kind: if four_state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }, + array_dims: Vec::new(), + }, + packed_dims: vec![width], + source: None, + module_affiliated: false, + }, + ); + id + } +} + +/// Timing metadata collected while lowering the processes of an artifact. +struct ProcessLowering<'a, 'h> { + artifact: &'a FrontendArtifact, + hidden: &'a mut HiddenObjects<'h>, + wait_sites: Vec>, + nba_sites: Vec>, + /// Signals that exactly one nonblocking statement of the artifact + /// assigns. An artifact is one flat module whose processes never run + /// inside another design, so nothing outside it writes its signals and + /// these sites stage a single pending value. + single_nba_targets: HashSet, + process: usize, + process_wait_sites: u32, + process_nba_sites: u32, + /// Loops given an iteration counter so far. + counted_loops: usize, +} + +fn collect_nonblocking_targets(statements: &[Statement], targets: &mut Vec) { + for statement in statements { + match statement { + Statement::Nonblocking { target, .. } => targets.push(target.signal()), + Statement::If { + then_body, + else_body, + .. + } => { + collect_nonblocking_targets(then_body, targets); + collect_nonblocking_targets(else_body, targets); + } + Statement::While { body, .. } | Statement::Forever { body } => { + collect_nonblocking_targets(body, targets); + } + _ => {} + } + } +} + +/// A one-bit two-state register that holds when `condition` is nonzero: some +/// bit is a known one. +fn truth( + artifact: &FrontendArtifact, + condition: ExprId, + builder: &mut SIRBuilder, +) -> Result { + let value_type = artifact + .expression(condition) + .ok_or(FrontendArtifactError::UnknownExpression(condition.index()))? + .value_type(); + let value = lower_sir_expression(artifact, condition, builder, &mut HashMap::default())?; + let any = alloc_register( + builder, + ValueType::new(1, false, value_type.is_four_state())?, + ); + builder.emit(SIRInstruction::Unary(any, UnaryOp::Or, value)); + if !value_type.is_four_state() { + return Ok(any); + } + let known = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, any)); + Ok(known) +} + +fn store_assignment( + artifact: &FrontendArtifact, + builder: &mut SIRBuilder, + target: SignalSlice, + value: ExprId, + cache: &mut HashMap, +) -> Result<(), FrontendArtifactError> { + let target_type = signal_slice_type(artifact, target)?; + let value = coerce_sir_expression(artifact, value, target_type, builder, cache)?; + builder.emit(SIRInstruction::Store( + RegionedSourceAddr { + region: STABLE_REGION, + var_id: source_id(target.signal()), + }, + SIROffset::Static(target.lsb()), + target.width(), + value, + Vec::new(), + Vec::new(), + )); + Ok(()) +} + /// Lower `statements` at the kernel's open block. Returns whether control /// can continue after them; if not, no block is left open. +/// Whether `statements` always suspend the process: a loop around them +/// returns to the runtime in each iteration. A level wait whose condition +/// holds does not suspend. +fn always_suspends(statements: &[Statement]) -> bool { + statements.iter().any(|statement| { + matches!( + statement, + Statement::Delay { .. } | Statement::InactiveDelay { .. } | Statement::WaitEvent { .. } + ) + }) +} + +/// Iterations, as a power of two, between the yields of a loop that may not +/// suspend. A finite loop pays one counter update per iteration, and only a +/// loop of about 2^40 iterations in one time slot exhausts the runtime's +/// return budget. +const LOOP_YIELD_BITS: usize = 16; + +/// Close a loop iteration that may not suspend: count it, yield every +/// 2^[`LOOP_YIELD_BITS`] iterations, and continue at `header`. The count +/// lives in a hidden object, so it survives the yield. +fn yield_now_and_then( + lowering: &mut ProcessLowering<'_, '_>, + kernel: &mut ProcessKernelBuilder, + header: BlockId, +) -> Result<(), FrontendArtifactError> { + let counter = stable(lowering.hidden.declare( + vec![ + format!("$loop[{}]", lowering.counted_loops), + "iterations".to_string(), + ], + LOOP_YIELD_BITS, + false, + )); + lowering.counted_loops += 1; + let builder = kernel.builder(); + let count = builder.alloc_bit(LOOP_YIELD_BITS, false); + builder.emit(SIRInstruction::Load( + count, + counter, + SIROffset::Static(0), + LOOP_YIELD_BITS, + )); + let one = builder.alloc_bit(LOOP_YIELD_BITS, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let next = builder.alloc_bit(LOOP_YIELD_BITS, false); + builder.emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + builder.emit(SIRInstruction::Store( + counter, + SIROffset::Static(0), + LOOP_YIELD_BITS, + next, + Vec::new(), + Vec::new(), + )); + let zero = builder.alloc_bit(LOOP_YIELD_BITS, false); + builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let wrapped = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(wrapped, next, BinaryOp::Eq, zero)); + let yield_block = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: wrapped, + true_block: (yield_block, Vec::new()), + false_block: (header, Vec::new()), + }); + builder.switch_to_block(yield_block); + kernel.yield_now()?; + kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + Ok(()) +} + +/// Lower `statements` into `kernel`. A loop whose body may not suspend +/// yields every 2^[`LOOP_YIELD_BITS`] iterations, so that the runtime +/// charges it against the time slot's budget instead of spinning in the +/// kernel. fn lower_statements( - artifact: &FrontendArtifact, + lowering: &mut ProcessLowering<'_, '_>, kernel: &mut ProcessKernelBuilder, statements: &[Statement], ) -> Result { + let artifact = lowering.artifact; for statement in statements { // Registers do not live across statements: a suspension in between // returns to the runtime, and each read must see the current state. let mut cache = HashMap::default(); match statement { Statement::Assign { target, value } => { - let target_type = signal_slice_type(artifact, *target)?; - let builder = kernel.builder(); - let value = - coerce_sir_expression(artifact, *value, target_type, builder, &mut cache)?; - builder.emit(SIRInstruction::Store( - RegionedSourceAddr { - region: STABLE_REGION, - var_id: source_id(target.signal()), - }, - SIROffset::Static(target.lsb()), - target.width(), - value, - Vec::new(), - Vec::new(), - )); + store_assignment(artifact, kernel.builder(), *target, *value, &mut cache)?; } Statement::If { condition, @@ -1075,7 +1264,7 @@ fn lower_statements( let mut join = None; for (block, body) in [(then_block, then_body), (else_block, else_body)] { kernel.builder().switch_to_block(block); - if lower_statements(artifact, kernel, body)? { + if lower_statements(lowering, kernel, body)? { let builder = kernel.builder(); let target = *join.get_or_insert_with(|| builder.new_block()); builder.seal_block(SIRTerminator::Jump(target, Vec::new())); @@ -1100,10 +1289,14 @@ fn lower_statements( false_block: (exit, Vec::new()), }); builder.switch_to_block(body_block); - if lower_statements(artifact, kernel, body)? { - kernel - .builder() - .seal_block(SIRTerminator::Jump(header, Vec::new())); + if lower_statements(lowering, kernel, body)? { + if always_suspends(body) { + kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + } else { + yield_now_and_then(lowering, kernel, header)?; + } } kernel.builder().switch_to_block(exit); } @@ -1112,14 +1305,18 @@ fn lower_statements( let header = builder.new_block(); builder.seal_block(SIRTerminator::Jump(header, Vec::new())); builder.switch_to_block(header); - if lower_statements(artifact, kernel, body)? { - kernel - .builder() - .seal_block(SIRTerminator::Jump(header, Vec::new())); + if lower_statements(lowering, kernel, body)? { + if always_suspends(body) { + kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + } else { + yield_now_and_then(lowering, kernel, header)?; + } } return Ok(false); } - Statement::Delay { amount } => { + Statement::Delay { amount } | Statement::InactiveDelay { amount } => { let amount = coerce_sir_expression( artifact, *amount, @@ -1127,7 +1324,101 @@ fn lower_statements( kernel.builder(), &mut cache, )?; - kernel.delay(amount)?; + if matches!(statement, Statement::Delay { .. }) { + kernel.delay(amount)?; + } else { + kernel.inactive_delay(amount)?; + } + } + Statement::WaitEvent { terms } => { + let index = lowering.process_wait_sites; + lowering.process_wait_sites += 1; + lowering.wait_sites.push(WaitSite { + process: lowering.process, + terms: terms + .iter() + .map(|term| { + let kind = match term.edge { + EventEdge::Change => CounterKind::Changes, + EventEdge::Posedge => CounterKind::Rises, + EventEdge::Negedge => CounterKind::Falls, + }; + (source_id(term.signal), kind) + }) + .collect(), + }); + // The runtime resumes the process at the first occurrence + // after the wait began; no condition is left to check. + kernel.suspend_wait(index)?; + let woken = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(woken, SIRValue::new(1u8))); + kernel.wake_if(woken); + } + Statement::WaitLevel { condition } => { + let index = lowering.process_wait_sites; + lowering.process_wait_sites += 1; + let mut sources = HashSet::default(); + expression_sources(artifact, *condition, &mut sources, &mut HashSet::default())?; + let mut signals = sources.into_iter().map(|atom| atom.id).collect::>(); + signals.sort_unstable(); + signals.dedup(); + lowering.wait_sites.push(WaitSite { + process: lowering.process, + terms: signals + .into_iter() + .map(|signal| (signal, CounterKind::Changes)) + .collect(), + }); + let mut error = None; + kernel.wait_level(index, |builder| { + truth(artifact, *condition, builder).unwrap_or_else(|e| { + error = Some(e); + let never = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8))); + never + }) + })?; + if let Some(error) = error { + return Err(error); + } + } + Statement::Nonblocking { target, value } => { + let index = lowering.process_nba_sites; + lowering.process_nba_sites += 1; + let target_type = signal_slice_type(artifact, *target)?; + let site_index = lowering.nba_sites.len(); + let name = |slot: &str| vec![format!("$nba[{site_index}]"), slot.to_string()]; + let staged = lowering.hidden.declare( + name("value"), + target.width(), + target_type.is_four_state(), + ); + let pending = lowering + .single_nba_targets + .contains(&target.signal()) + .then(|| lowering.hidden.declare(name("pending"), 1, false)); + let site = NbaSite { + process: lowering.process, + target: source_id(target.signal()), + lsb: target.lsb(), + width: target.width(), + value: staged, + offset: None, + pending, + }; + kernel.nonblocking(index, &site, |builder| { + let value = coerce_sir_expression( + artifact, + *value, + target_type, + builder, + &mut HashMap::default(), + )?; + Ok::<_, FrontendArtifactError>((value, None)) + })?; + lowering.nba_sites.push(site); } Statement::Finish => { kernel.finish(); @@ -1139,56 +1430,308 @@ fn lower_statements( Ok(true) } +/// Lower the statements of a combinational process: assignments and +/// conditionals, writing stable state as they execute. +fn lower_comb_statements( + artifact: &FrontendArtifact, + builder: &mut SIRBuilder, + statements: &[Statement], +) -> Result<(), FrontendArtifactError> { + for statement in statements { + let mut cache = HashMap::default(); + match statement { + Statement::Assign { target, value } => { + store_assignment(artifact, builder, *target, *value, &mut cache)?; + } + Statement::If { + condition, + then_body, + else_body, + } => { + let condition = lower_sir_expression(artifact, *condition, builder, &mut cache)?; + 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()), + }); + for (block, body) in [(then_block, then_body), (else_block, else_body)] { + builder.switch_to_block(block); + lower_comb_statements(artifact, builder, body)?; + builder.seal_block(SIRTerminator::Jump(join, Vec::new())); + } + builder.switch_to_block(join); + } + _ => return Err(FrontendArtifactError::UnsupportedOperation), + } + } + Ok(()) +} + +/// The bits of `atom` outside every range of `written`. +fn unwritten_bits( + atom: VarAtomBase, + written: &[VarAtomBase], +) -> Vec> { + let mut ranges = vec![(atom.access.lsb, atom.access.msb)]; + for written in written.iter().filter(|written| written.id == atom.id) { + ranges = ranges + .into_iter() + .flat_map(|(lsb, msb)| { + if written.access.msb < lsb || written.access.lsb > msb { + return vec![(lsb, msb)]; + } + let mut kept = Vec::new(); + if lsb < written.access.lsb { + kept.push((lsb, written.access.lsb - 1)); + } + if written.access.msb < msb { + kept.push((written.access.msb + 1, msb)); + } + kept + }) + .collect(); + } + ranges + .into_iter() + .map(|(lsb, msb)| VarAtomBase::new(atom.id, lsb, msb)) + .collect() +} + +fn statement_sources( + artifact: &FrontendArtifact, + statements: &[Statement], + sources: &mut HashSet>, +) -> Result<(), FrontendArtifactError> { + for statement in statements { + let mut visited = HashSet::default(); + match statement { + Statement::Assign { value, .. } => { + expression_sources(artifact, *value, sources, &mut visited)? + } + Statement::If { + condition, + then_body, + else_body, + } => { + expression_sources(artifact, *condition, sources, &mut visited)?; + statement_sources(artifact, then_body, sources)?; + statement_sources(artifact, else_body, sources)?; + } + _ => return Err(FrontendArtifactError::UnsupportedOperation), + } + } + Ok(()) +} + +fn stable(var_id: SourceVarId) -> RegionedSourceAddr { + RegionedSourceAddr { + region: STABLE_REGION, + var_id, + } +} + +fn stable_signal(address: &RegionedSourceAddr, signals: usize) -> Option { + (address.region == STABLE_REGION && (address.var_id.0 as usize) < signals) + .then_some(address.var_id) +} + +/// Lower each combinational process to one unit that runs only when it has +/// not run yet or bits it reads and does not write changed (IEEE 1800-2023 +/// 9.2.2.2, 9.2.2.2.1), and to a path for each slice it assigns. +fn lower_comb_processes( + artifact: &FrontendArtifact, + hidden: &mut HiddenObjects<'_>, + arena: &mut SLTNodeArena, + candidates: &mut Vec, +) -> Result>, FrontendArtifactError> { + let mut paths = Vec::new(); + for (index, process) in artifact.comb_processes().iter().enumerate() { + let mut builder = SIRBuilder::new(); + lower_comb_statements(artifact, &mut builder, process.body())?; + let body = seal_builder(builder); + candidates.extend(crate::watch::multi_store_candidates(&body, |address| { + stable_signal(address, artifact.signals().len()) + })); + + let mut targets = Vec::new(); + for block in body.blocks.values() { + for instruction in &block.instructions { + if let SIRInstruction::Store(address, SIROffset::Static(lsb), width, ..) = + instruction + { + let atom = VarAtomBase::new(address.var_id, *lsb, lsb + width - 1); + if !targets.contains(&atom) { + targets.push(atom); + } + } + } + } + targets.sort_unstable_by_key(|atom| (atom.id, atom.access.lsb, atom.access.msb)); + // One path per range the process drives, however often it writes it. + let mut merged: Vec> = Vec::new(); + for target in targets { + match merged.last_mut() { + Some(last) if last.id == target.id && target.access.lsb <= last.access.msb + 1 => { + last.access.msb = last.access.msb.max(target.access.msb); + } + _ => merged.push(target), + } + } + let targets = merged; + // A process is not sensitive to what it writes (IEEE 1800-2023 + // 9.2.2.2.1): its inputs are the bits it reads outside its targets. + let mut reads = HashSet::default(); + statement_sources(artifact, process.body(), &mut reads)?; + let mut sources: Vec> = reads + .into_iter() + .flat_map(|atom| unwritten_bits(atom, &targets)) + .collect(); + sources.sort_unstable_by_key(|atom| (atom.id, atom.access.lsb, atom.access.msb)); + let mut merged: Vec> = Vec::new(); + for source in sources { + match merged.last_mut() { + Some(last) if last.id == source.id && source.access.lsb <= last.access.msb + 1 => { + last.access.msb = last.access.msb.max(source.access.msb); + } + _ => merged.push(source), + } + } + let sources = merged; + let name = |slot: String| vec![format!("$comb[{index}]"), slot]; + let gate_inputs = sources + .iter() + .map(|atom| { + let value_type = artifact + .signals() + .get(atom.id.0 as usize) + .ok_or(FrontendArtifactError::UnknownSignal(atom.id.0))? + .value_type(); + let width = atom.access.msb - atom.access.lsb + 1; + Ok(crate::watch::GateInput { + input: stable(atom.id), + lsb: atom.access.lsb, + shadow: stable(hidden.declare( + name(format!( + "input[{}][{}:{}]", + atom.id.0, atom.access.msb, atom.access.lsb + )), + width, + value_type.is_four_state(), + )), + width, + four_state: value_type.is_four_state(), + }) + }) + .collect::, FrontendArtifactError>>()?; + let ran = hidden.declare(name("ran".to_string()), 1, false); + let unit = crate::watch::gate_on_input_change(&body, &gate_inputs, &stable(ran)) + .into_map_addr(&mut |address| address.var_id); + let sources: HashSet<_> = sources.into_iter().collect(); + for target in targets { + let expr = arena.alloc(SLTNode::Input { + variable: target.id, + signed: false, + index: Vec::new(), + access: target.access, + })?; + paths.push(LogicPath { + target: LogicPathTarget::Process { + process: ran, + after_initials: true, + target, + unit: Box::new(unit.clone()), + }, + sources: sources.clone(), + previous_sources: HashSet::default(), + address_sources: HashSet::default(), + local_inputs: Vec::new(), + order_before: HashSet::default(), + comb_capture_enable_sites: Vec::new(), + comb_capture_enable_always: false, + pre_lower_nodes: Vec::new(), + expr, + }); + } + } + Ok(paths) +} + +/// Lowered processes of an artifact and their timing metadata. +struct LoweredProcesses { + processes: Vec, + wait_sites: Vec>, + nba_sites: Vec>, +} + /// Declare the control slots of every process after the artifact's signals /// and lower each process body to a kernel. fn lower_processes( artifact: &FrontendArtifact, - variables: &mut HashMap, -) -> Result, FrontendArtifactError> { - let mut next_id = artifact.signals().len() as u32; - let mut declare = |path: Vec, width: usize| { - let id = SourceVarId(next_id); - next_id += 1; - variables.insert( - id, - SymbolicVariable { - path, - kind: VariableKind::Variable, - signed: false, - metadata: VariableMetadata { - width, - is_4state: false, - kind: DomainKind::Other, - type_kind: PortTypeKind::Bit, - array_dims: Vec::new(), - }, - packed_dims: vec![width], - source: None, - // Control slots are not signals of the design. - module_affiliated: false, - }, - ); - id - }; - artifact - .processes() - .iter() - .enumerate() - .map(|(index, process)| { - let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; - let slots = ProcessSlots { - resume: declare(name("resume"), PROCESS_RESUME_WIDTH), - status: declare(name("status"), PROCESS_STATUS_WIDTH), - delay: declare(name("delay"), PROCESS_DELAY_WIDTH), - }; - let mut kernel = ProcessKernelBuilder::new(slots); - lower_statements(artifact, &mut kernel, process.body())?; - Ok(SymbolicProcess { - kernel: kernel.build(), - slots, + hidden: &mut HiddenObjects<'_>, + candidates: &mut Vec, +) -> Result { + let mut nonblocking_targets = Vec::new(); + for process in artifact.processes() { + collect_nonblocking_targets(process.body(), &mut nonblocking_targets); + } + let mut counts: HashMap = HashMap::default(); + for target in nonblocking_targets { + *counts.entry(target).or_default() += 1; + } + let mut lowering = ProcessLowering { + artifact, + hidden, + wait_sites: Vec::new(), + nba_sites: Vec::new(), + // A port may have writers outside the module (`NbaSite::pending`). + single_nba_targets: counts + .into_iter() + .filter(|&(target, count)| { + count == 1 + && artifact + .signal(target) + .is_some_and(|signal| signal.direction() == Direction::Internal) }) - }) - .collect() + .map(|(target, _)| target) + .collect(), + process: 0, + process_wait_sites: 0, + process_nba_sites: 0, + counted_loops: 0, + }; + let mut processes = Vec::new(); + for (index, process) in artifact.processes().iter().enumerate() { + let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; + let slots = ProcessSlots { + resume: lowering + .hidden + .declare(name("resume"), PROCESS_RESUME_WIDTH, false), + status: lowering + .hidden + .declare(name("status"), PROCESS_STATUS_WIDTH, false), + delay: lowering + .hidden + .declare(name("delay"), PROCESS_DELAY_WIDTH, false), + }; + lowering.process = index; + lowering.process_wait_sites = 0; + lowering.process_nba_sites = 0; + let mut kernel = ProcessKernelBuilder::new(slots); + lower_statements(&mut lowering, &mut kernel, process.body())?; + let kernel = kernel.build(); + candidates.extend(crate::watch::multi_store_candidates(&kernel, |address| { + stable_signal(address, artifact.signals().len()) + })); + processes.push(SymbolicProcess { kernel, slots }); + } + Ok(LoweredProcesses { + processes, + wait_sites: lowering.wait_sites, + nba_sites: lowering.nba_sites, + }) } fn set_role( @@ -1281,9 +1824,21 @@ pub fn lower_frontend_artifact( }) .collect(); - let processes = lower_processes(artifact, &mut variables)?; - + let mut hidden = HiddenObjects { + next_id: artifact.signals().len() as u32, + variables: &mut variables, + }; + let mut candidates = Vec::new(); + let LoweredProcesses { + processes, + wait_sites, + nba_sites, + } = lower_processes(artifact, &mut hidden, &mut candidates)?; let mut arena = SLTNodeArena::new(); + let comb_process_paths = + lower_comb_processes(artifact, &mut hidden, &mut arena, &mut candidates)?; + let counter_slots = crate::watch::declare_counter_slots(hidden.variables, candidates); + let mut node_cache = HashMap::default(); let mut comb_blocks = Vec::new(); for assignment in artifact.assignments() { @@ -1310,6 +1865,7 @@ pub fn lower_frontend_artifact( )?, }); } + comb_blocks.extend(comb_process_paths); let mut eval_only_ff_blocks = HashMap::default(); let mut apply_ff_blocks = HashMap::default(); @@ -1362,6 +1918,9 @@ pub fn lower_frontend_artifact( reset_clock_map, processes, package_bindings: HashMap::default(), + counter_slots, + wait_sites, + nba_sites, }; let symbolic = SymbolicRtl { modules: [(module_id, sim_module.clone())].into_iter().collect(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index fb7b4fa02a6..2916167c90b 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -1,8 +1,9 @@ use std::{collections::BTreeSet, fmt}; use celox_design::{ - ExternFunction, InitialStateValue, ModuleId, ProcessSlots, RegionedAbsoluteAddrBase, - RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet, VariableMetadata, + CounterSlots, ExternFunction, InitialStateValue, ModuleId, NbaSite, ProcessSlots, + RegionedAbsoluteAddrBase, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet, + VariableMetadata, WaitSite, }; use celox_sir::ExecutionUnit; use celox_slt::{CombObserver, FfAccessSummary, GlueBlockBase, LogicPath, SLTNodeArena}; @@ -87,6 +88,17 @@ pub struct SimModule { /// 1800-2023 26.2). Every instance of the module refers to that one /// object instead of a state object of its own. pub package_bindings: HashMap, + /// Counter objects of the signals that a unit of the module may store + /// twice between two runtime checks (see + /// `crate::watch::multi_store_candidates`). Assembly counts a signal's + /// occurrences only if a flip-flop domain or a wait watches it. + pub counter_slots: Vec>, + /// Wait sites of the module's processes; `process` indexes + /// [`Self::processes`]. + pub wait_sites: Vec>, + /// Nonblocking sites of the module's processes; `process` indexes + /// [`Self::processes`]. + pub nba_sites: Vec>, } /// The package variable a module variable denotes. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 44298ea22e2..ee3b11c38f8 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -9,11 +9,11 @@ use crate::{ SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, }; use celox_design::{ - BitAccess, CombDerivedClock, DomainKind, ElaboratedDesign, EventTopology, ExternFunction, - GateOp, InitialStateValue, InstanceId, ModuleId, ProcessSlots, RegionedAbsoluteAddrBase, - RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, - RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase, - VariableMetadata, + BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, + EventTopology, EventWatch, ExternFunction, GateOp, InitialStateValue, InstanceId, ModuleId, + NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver, + RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr, + StateObjectId, TriggerSet, VarAtomBase, VariableMetadata, WaitSite, }; use celox_sir::{ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIRTerminator, @@ -645,7 +645,7 @@ pub fn schedule_symbolic_rtl( runtime_event_sites, extern_functions, next_runtime_error_code, - processes, + mut processes, ) = timed_sub!( "relocate_units", relocate_units( @@ -663,6 +663,39 @@ pub fn schedule_symbolic_rtl( &mut trace, ) )?; + let timing = relocate_timing(bindings, &instance_modules, &modules, &processes); + let counted = { + // Flip-flop event domains and the aliases that resolve to them. + let event_addresses: HashSet = eval_apply_ffs + .keys() + .copied() + .chain( + clock_domains + .iter() + .filter(|(_, canonical)| eval_apply_ffs.contains_key(canonical)) + .map(|(alias, _)| *alias), + ) + .collect(); + let variables: HashMap = instance_modules + .iter() + .flat_map(|(&instance, module)| { + modules[module].variables.iter().map(move |(&var_id, var)| { + ( + bindings.locate(instance, var_id), + (var.metadata.width, var.metadata.is_4state), + ) + }) + }) + .collect(); + instrument_counted_signals( + &timing, + &event_addresses, + &variables, + four_state, + &mut processes, + &mut comb_blocks, + ) + }; check_package_variable_drivers( bindings, &instance_modules, @@ -1145,7 +1178,12 @@ pub fn schedule_symbolic_rtl( .values() .filter(|units| !units.is_empty()) .count(); - let needs_split_path = active_ff_domains > 1 || !cascaded_clocks.is_empty(); + // With process kernels, a round in which a zero delay is pending after + // domains triggered evaluates them before the inactive region and + // publishes them in the NBA region (IEEE 1800-2023 4.5). Only those + // rounds use the split units; the fused units stay the default. + let needs_split_path = + active_ff_domains > 1 || !cascaded_clocks.is_empty() || !processes.is_empty(); let parallel_sir = parallel.enabled().then(|| { let mut events = eval_apply_ffs .iter() @@ -1238,6 +1276,11 @@ pub fn schedule_symbolic_rtl( .into_iter() .map(|process| (process.kernel, process.slots)) .unzip(); + let TimingMetadata { + wait_sites, + nba_sites, + .. + } = timing; let source_sir = SirProgram { eval_apply_ffs, eval_comb_apply_ffs, @@ -1432,6 +1475,63 @@ pub fn schedule_symbolic_rtl( .into_iter() .map(|slots| slots.map(project)) .collect(); + let watches: Vec> = { + let event_kinds = ElaboratedDesign { + state_objects: state_objects.clone(), + events: events.clone(), + initial_state: Vec::new(), + } + .event_kinds(); + counted + .values() + .map(|slots| { + let signal = project(slots.signal); + let object = &state_objects[&signal]; + let canonical = events.canonical(signal); + let domains = event_kinds + .get(&canonical) + .filter(|_| events.ordered_events.contains(&signal) || canonical != signal) + .map(|&kind| (canonical, CounterKind::for_domain(kind))) + .into_iter() + .collect(); + EventWatch { + signal, + width: object.width, + four_state: object.is_4state, + changes: Some(project(slots.changes)), + rises: Some(project(slots.rises)), + falls: Some(project(slots.falls)), + domains, + } + }) + .collect() + }; + let wait_sites: Vec> = + wait_sites.iter().map(|site| site.map(project)).collect(); + let nba_sites: Vec> = + nba_sites.iter().map(|site| site.map(project)).collect(); + // The runtime reads counters, the signals waits watch and staged + // nonblocking values directly; no unit loads a wait's signal. + let timing_read_roots = watches + .iter() + .flat_map(|watch| { + watch + .counters() + .map(|(_, counter)| counter) + .collect::>() + }) + .chain( + wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)), + ) + .chain( + nba_sites + .iter() + .flat_map(|site| [Some(site.value), site.offset, site.pending]) + .flatten(), + ) + .collect(); // A package variable's state object maps back to the package's own // variable, not to one of its aliases. let state_to_source = source_to_state @@ -1465,13 +1565,16 @@ pub fn schedule_symbolic_rtl( runtime_event_sites, extern_functions, comb_observers, - testbench_read_roots: Default::default(), + testbench_read_roots: timing_read_roots, rtl_writes, comb_writes: Default::default(), persistent_comb_state, dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, + watches, + wait_sites, + nba_sites, }, }; @@ -2516,6 +2619,7 @@ fn relocate_units( &extern_function_map, ), slots: process.slots.map(|var_id| bindings.locate(*id, var_id)), + key: (*id, index), }, )); } @@ -2606,6 +2710,128 @@ fn relocate_units( struct RelocatedProcess { kernel: ExecutionUnit, slots: ProcessSlots, + /// The instance and the module-local index of the process. + key: (InstanceId, usize), +} + +/// Counter slots, wait sites and nonblocking sites of the whole design. +struct TimingMetadata { + counter_slots: Vec>, + wait_sites: Vec>, + nba_sites: Vec>, +} + +/// Place the timing metadata of every instance. Sites name the global index +/// of their process; a kernel numbers its sites in the order they appear +/// here, which is the module's order. +fn relocate_timing( + bindings: &PackageBindings, + instance_modules: &HashMap, + modules: &HashMap, + processes: &[RelocatedProcess], +) -> TimingMetadata { + let process_index: HashMap<(InstanceId, usize), usize> = processes + .iter() + .enumerate() + .map(|(index, process)| (process.key, index)) + .collect(); + let mut instances = instance_modules.iter().collect::>(); + instances.sort_unstable_by_key(|(instance, _)| **instance); + let mut metadata = TimingMetadata { + counter_slots: Vec::new(), + wait_sites: Vec::new(), + nba_sites: Vec::new(), + }; + for (&instance, module) in instances { + let module = &modules[module]; + let locate = |var_id| bindings.locate(instance, var_id); + metadata + .counter_slots + .extend(module.counter_slots.iter().map(|slots| slots.map(locate))); + metadata + .wait_sites + .extend(module.wait_sites.iter().map(|site| WaitSite { + process: process_index[&(instance, site.process)], + ..site.map(locate) + })); + metadata + .nba_sites + .extend(module.nba_sites.iter().map(|site| NbaSite { + process: process_index[&(instance, site.process)], + ..site.map(locate) + })); + } + metadata +} + +/// Counted signals: those a unit may store twice between two runtime checks +/// (a frontend declared counters for them) and that a flip-flop domain or a +/// wait watches. Returns their counters by signal and instruments the +/// process kernels and combinational process units that write them; no +/// other unit changes. +fn instrument_counted_signals( + timing: &TimingMetadata, + event_addresses: &HashSet, + variables: &HashMap, + four_state: bool, + processes: &mut [RelocatedProcess], + comb_blocks: &mut [LogicPath], +) -> BTreeMap> { + let waited: HashSet = timing + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)) + .collect(); + let counted: BTreeMap> = timing + .counter_slots + .iter() + .filter(|slots| event_addresses.contains(&slots.signal) || waited.contains(&slots.signal)) + .map(|slots| (slots.signal, *slots)) + .collect(); + if counted.is_empty() { + return counted; + } + let code = |signal: AbsoluteAddr| { + let slots = counted.get(&signal)?; + let (width, is_4state) = variables[&signal]; + Some((slots, width, four_state && is_4state)) + }; + for process in processes { + crate::watch::instrument_unit(&mut process.kernel, |address| { + if address.region != STABLE_REGION { + return None; + } + let (slots, width, four_state) = code(address.absolute_addr())?; + let stable = + |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var); + Some(crate::watch::WatchCode { + signal: stable(slots.signal), + width, + four_state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, stable(slots.counter(kind)))) + .collect(), + }) + }); + } + for path in comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + crate::watch::instrument_unit(unit, |address| { + let (slots, width, four_state) = code(*address)?; + Some(crate::watch::WatchCode { + signal: slots.signal, + width, + four_state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, slots.counter(kind))) + .collect(), + }) + }); + } + } + counted } fn build_comb_observer_capture_paths( diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs new file mode 100644 index 00000000000..3d9b80a809e --- /dev/null +++ b/crates/celox-frontend-core/src/watch.rs @@ -0,0 +1,590 @@ +//! SIR for watched signals and change-gated combinational units. +//! +//! A watched signal ([`EventWatch`]) counts its occurrences in counter +//! objects. [`emit_watched`] surrounds one store or commit to the signal +//! with the code that bumps those counters, so an occurrence is counted even +//! when a later store of the same execution overwrites it. Frontends use it +//! on every path that writes a watched signal: process kernels, flip-flop +//! evaluation and publication, and imperative combinational units. The code +//! is ordinary SIR, so every backend runs it unchanged. +//! +//! An instrumented combinational unit must only run when one of its inputs +//! changed (IEEE 1800-2023 9.2.2.2); otherwise re-running it, for example +//! `y = 0; if (a) y = 1;` with a steady `a`, would count a pulse on `y` at +//! every settle. [`gate_on_input_change`] adds that gate. + +use celox_design::{BinaryOp, CounterKind, EVENT_COUNTER_WIDTH, EventWatch}; +use celox_sir::{ + ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue, +}; + +/// A watched signal and its counters, addressed in the code being built. +#[derive(Clone, Debug)] +pub struct WatchCode { + /// The signal's stable state. + pub signal: A, + pub width: usize, + /// Whether the signal is held in four-state form. + pub four_state: bool, + pub counters: Vec<(CounterKind, A)>, +} + +impl WatchCode { + /// The code view of `watch`, addressing each object through `address`. + /// `four_state` is whether the build keeps the signal in four-state form. + pub fn new(watch: &EventWatch, four_state: bool, address: impl Fn(V) -> A) -> Self { + Self { + signal: address(watch.signal), + width: watch.width, + four_state: four_state && watch.four_state, + counters: watch + .counters() + .map(|(kind, counter)| (kind, address(counter))) + .collect(), + } + } +} + +fn load( + b: &mut SIRBuilder, + address: &A, + width: usize, + four_state: bool, +) -> RegisterId { + load_bits(b, address, 0, width, four_state) +} + +/// Load bits `lsb..lsb + width` of `address`. +fn load_bits( + b: &mut SIRBuilder, + address: &A, + lsb: usize, + width: usize, + four_state: bool, +) -> RegisterId { + let register = if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Load( + register, + address.clone(), + SIROffset::Static(lsb), + width, + )); + register +} + +fn binary( + b: &mut SIRBuilder, + lhs: RegisterId, + op: BinaryOp, + rhs: RegisterId, +) -> RegisterId { + let result = b.alloc_bit(1, false); + b.emit(SIRInstruction::Binary(result, lhs, op, rhs)); + result +} + +/// Emit `write`, a store or commit that may change `watch.signal`, and +/// count the occurrence it causes. `value_type` is the type of a store's +/// source register. +pub fn emit_watched( + b: &mut SIRBuilder, + watch: &WatchCode, + write: SIRInstruction, + value_type: Option<&celox_sir::RegisterType>, +) { + let old = load(b, &watch.signal, watch.width, watch.four_state); + // A store of the whole signal stores the new value itself; any other + // write is read back. + let stored = match &write { + SIRInstruction::Store(_, SIROffset::Static(0), width, value, ..) + if *width == watch.width + && value_type + == Some(&if watch.four_state { + celox_sir::RegisterType::Logic { width: *width } + } else { + celox_sir::RegisterType::Bit { + width: *width, + signed: false, + } + }) => + { + Some(*value) + } + _ => None, + }; + // Everything derived from the old value is computed before the write, + // so no backend can re-read the written state for it. + let old_lsb = lsb(b, old, watch.width, watch.four_state); + b.emit(write); + if watch.counters.is_empty() { + return; + } + let new = match stored { + Some(value) => value, + None => load(b, &watch.signal, watch.width, watch.four_state), + }; + let new_lsb = lsb(b, new, watch.width, watch.four_state); + for &(kind, ref counter) in &watch.counters { + let occurred = occurrence( + b, + kind, + (old, old_lsb), + (new, new_lsb), + watch.width, + watch.four_state, + ); + bump(b, counter, occurred); + } +} + +/// The least significant bit of `value`, kept at the signal's width: the +/// value masked with one. A `Slice` would do, but the native backends may +/// re-read a sliced load from state, which the write has changed. +fn lsb(b: &mut SIRBuilder, value: RegisterId, width: usize, four_state: bool) -> RegisterId { + let one = constant(b, 1, width, four_state); + let bit = if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Binary(bit, value, BinaryOp::And, one)); + bit +} + +fn constant(b: &mut SIRBuilder, value: u8, width: usize, four_state: bool) -> RegisterId { + let register = if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Imm(register, SIRValue::new(value))); + register +} + +/// Whether the change from `old` to `new`, each a value and its least +/// significant bit, is an occurrence of `kind`. +fn occurrence( + b: &mut SIRBuilder, + kind: CounterKind, + (old, old_lsb): (RegisterId, RegisterId), + (new, new_lsb): (RegisterId, RegisterId), + width: usize, + four_state: bool, +) -> RegisterId { + if kind == CounterKind::Changes { + // Case inequality distinguishes every unknown bit as well. + return binary(b, old, BinaryOp::NeCase, new); + } + // IEEE 1800-2023 Table 9-2: a positive edge leaves 0 or reaches 1, a + // negative edge leaves 1 or reaches 0, and either changes the bit. In + // two-state form this is `old == 0 && new == 1` for a positive edge. + let (from, to) = if kind == CounterKind::Rises { + (0, 1) + } else { + (1, 0) + }; + let from = constant(b, from, width, four_state); + let to = constant(b, to, width, four_state); + let changed = binary(b, old_lsb, BinaryOp::NeCase, new_lsb); + let left = binary(b, old_lsb, BinaryOp::EqCase, from); + let reached = binary(b, new_lsb, BinaryOp::EqCase, to); + let either = binary(b, left, BinaryOp::Or, reached); + binary(b, changed, BinaryOp::And, either) +} + +/// Add `occurred`, a one-bit two-state register, to the counter at +/// `counter`. +fn bump(b: &mut SIRBuilder, counter: &A, occurred: RegisterId) { + let value = load(b, counter, EVENT_COUNTER_WIDTH, false); + let one = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let incremented = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Binary( + incremented, + value, + BinaryOp::Add, + one, + )); + let next = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Mux(next, occurred, incremented, value)); + b.emit(SIRInstruction::Store( + counter.clone(), + SIROffset::Static(0), + EVENT_COUNTER_WIDTH, + next, + Vec::new(), + Vec::new(), + )); +} + +/// One input of a change-gated unit: bits `lsb..lsb + width` of the input's +/// stable state and a private object of that width and representation that +/// remembers their value. +#[derive(Clone, Debug)] +pub struct GateInput { + pub input: A, + pub lsb: usize, + pub shadow: A, + pub width: usize, + pub four_state: bool, +} + +/// Wrap `unit` so that it runs on its first execution and afterwards only +/// when an input differs from its value at the previous run. `ran` is a +/// private one-bit two-state object, zero before the first run. +/// +/// Inputs are remembered before the body runs, so the unit's own writes do +/// not re-trigger it; a frontend excludes the variables the unit writes from +/// `inputs` (IEEE 1800-2023 9.2.2.2.1). +pub fn gate_on_input_change( + unit: &ExecutionUnit, + inputs: &[GateInput], + ran: &A, +) -> ExecutionUnit { + let mut b = SIRBuilder::new(); + let has_run = load(&mut b, ran, 1, false); + let first = b.alloc_bit(1, false); + b.emit(SIRInstruction::Unary( + first, + celox_design::UnaryOp::LogicNot, + has_run, + )); + let mut run = first; + let mut currents = Vec::with_capacity(inputs.len()); + for input in inputs { + let current = load_bits( + &mut b, + &input.input, + input.lsb, + input.width, + input.four_state, + ); + let previous = load(&mut b, &input.shadow, input.width, input.four_state); + let differs = binary(&mut b, current, BinaryOp::NeCase, previous); + run = binary(&mut b, run, BinaryOp::Or, differs); + currents.push(current); + } + let execute = b.new_block(); + let done = b.new_block(); + b.seal_block(SIRTerminator::Branch { + cond: run, + true_block: (execute, Vec::new()), + false_block: (done, Vec::new()), + }); + b.switch_to_block(execute); + for (input, current) in inputs.iter().zip(currents) { + b.emit(SIRInstruction::Store( + input.shadow.clone(), + SIROffset::Static(0), + input.width, + current, + Vec::new(), + Vec::new(), + )); + } + let one = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + b.emit(SIRInstruction::Store( + ran.clone(), + SIROffset::Static(0), + 1, + one, + Vec::new(), + Vec::new(), + )); + b.inline_execution_unit(unit); + b.seal_block(SIRTerminator::Jump(done, Vec::new())); + b.switch_to_block(done); + b.flush_eu().expect("a gated unit has instructions") +} + +fn successors(terminator: &SIRTerminator) -> Vec { + match terminator { + SIRTerminator::Jump(target, _) => vec![*target], + SIRTerminator::Branch { + true_block, + false_block, + .. + } => vec![true_block.0, false_block.0], + SIRTerminator::Switch { cases, default, .. } => cases + .iter() + .map(|case| case.target) + .chain(std::iter::once(*default)) + .collect(), + SIRTerminator::Return | SIRTerminator::Error(_) => Vec::new(), + } +} + +/// The destination of a store or commit. +pub fn write_destination(instruction: &SIRInstruction) -> Option<&A> { + match instruction { + SIRInstruction::Store(address, ..) | SIRInstruction::Commit(_, address, ..) => { + Some(address) + } + _ => None, + } +} + +/// Destinations, by `key`, that one execution of `unit` may write twice +/// without returning in between: a write from which another write of the +/// same destination is reachable, including itself around a loop. A +/// process kernel returns at every suspension, so for a kernel this is +/// "twice between two suspensions"; a write in one branch and another in +/// the other branch is not. +/// +/// The result is a syntactic superset; a candidate costs only counter +/// objects unless something watches it. +pub fn multi_store_candidates( + unit: &ExecutionUnit, + key: impl Fn(&A) -> Option, +) -> Vec { + let writes = |block: &celox_sir::BasicBlock| -> Vec> { + block + .instructions + .iter() + .map(|instruction| write_destination(instruction).and_then(&key)) + .collect() + }; + let block_writes: crate::HashMap>> = unit + .blocks + .iter() + .map(|(&id, block)| (id, writes(block))) + .collect(); + let mut blocks: Vec<_> = unit.blocks.keys().copied().collect(); + blocks.sort_unstable(); + let mut candidates: Vec = Vec::new(); + for &start in &blocks { + for (position, written) in block_writes[&start].iter().enumerate() { + let Some(written) = written else { + continue; + }; + if candidates.contains(written) { + continue; + } + let rewritten = |block: &celox_sir::BlockId, from: usize| { + block_writes[block][from..] + .iter() + .any(|other| other.as_ref() == Some(written)) + }; + let mut found = rewritten(&start, position + 1); + let mut seen = crate::HashSet::default(); + let mut work = successors(&unit.blocks[&start].terminator); + while !found && let Some(block) = work.pop() { + if !seen.insert(block) || !unit.blocks.contains_key(&block) { + continue; + } + found = rewritten(&block, 0); + work.extend(successors(&unit.blocks[&block].terminator)); + } + if found { + candidates.push(written.clone()); + } + } + } + candidates +} + +/// Surround every store or commit in `unit` whose destination `watch_for` +/// maps to a counted signal with the code that counts its occurrences. +pub fn instrument_unit( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&A) -> Option>, +) { + let mut next_register = unit + .register_map + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0); + for block in unit.blocks.values_mut() { + if !block.instructions.iter().any(|instruction| { + write_destination(instruction) + .and_then(&watch_for) + .is_some() + }) { + continue; + } + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in std::mem::take(&mut block.instructions) { + let Some(watch) = write_destination(&instruction).and_then(&watch_for) else { + instructions.push(instruction); + continue; + }; + let value_type = match &instruction { + SIRInstruction::Store(_, _, _, value, ..) => unit.register_map.get(value).cloned(), + _ => None, + }; + let mut b = SIRBuilder::new_with(next_register); + emit_watched(&mut b, &watch, instruction, value_type.as_ref()); + b.seal_block(SIRTerminator::Return); + let (mut blocks, registers, next) = b.drain(); + next_register = next; + unit.register_map.extend(registers); + instructions.extend( + blocks + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions, + ); + } + block.instructions = instructions; + } +} + +/// Declare counter objects for `candidates` among the variables of a module +/// and return them. Candidates that are not signals of the design +/// (`module_affiliated`) are skipped, since nothing outside the module +/// watches hidden state, and so are unpacked arrays, which no event control +/// watches as a whole. +pub fn declare_counter_slots( + variables: &mut crate::HashMap, + candidates: impl IntoIterator, +) -> Vec> { + use celox_design::{DomainKind, PortTypeKind, VariableMetadata}; + let mut candidates: Vec<_> = candidates + .into_iter() + .filter(|id| { + variables + .get(id) + .is_some_and(|var| var.module_affiliated && var.metadata.array_dims.is_empty()) + }) + .collect(); + candidates.sort_unstable(); + candidates.dedup(); + let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0); + candidates + .into_iter() + .map(|signal| { + let name = variables[&signal].path.join("."); + let mut counter = |kind: &str| { + let id = crate::SourceVarId(next); + next += 1; + variables.insert( + id, + crate::symbolic::artifact::SymbolicVariable { + path: vec![format!("$counter[{name}]"), kind.to_string()], + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width: EVENT_COUNTER_WIDTH, + is_4state: false, + kind: DomainKind::Other, + type_kind: PortTypeKind::Bit, + array_dims: Vec::new(), + }, + packed_dims: vec![EVENT_COUNTER_WIDTH], + source: None, + module_affiliated: false, + }, + ); + id + }; + celox_design::CounterSlots { + signal, + changes: counter("changes"), + rises: counter("rises"), + falls: counter("falls"), + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; + + use super::multi_store_candidates; + + /// Store a constant to `address` at the open block. + fn store(b: &mut SIRBuilder, address: u32) { + let value = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(1u8))); + b.emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + 1, + value, + Vec::new(), + Vec::new(), + )); + } + + fn candidates(b: &mut SIRBuilder) -> Vec { + let unit = b.flush_eu().unwrap(); + multi_store_candidates(&unit, |address| Some(*address)) + } + + #[test] + fn two_stores_on_one_path_are_candidates() { + let mut b = SIRBuilder::new(); + store(&mut b, 1); + store(&mut b, 2); + store(&mut b, 1); + assert_eq!(candidates(&mut b), [1]); + } + + #[test] + fn stores_in_exclusive_branches_are_not() { + let mut b = SIRBuilder::new(); + let condition = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(condition, SIRValue::new(1u8))); + let (then_block, else_block, join) = (b.new_block(), b.new_block(), b.new_block()); + b.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (then_block, Vec::new()), + false_block: (else_block, Vec::new()), + }); + for block in [then_block, else_block] { + b.switch_to_block(block); + store(&mut b, 1); + b.seal_block(SIRTerminator::Jump(join, Vec::new())); + } + b.switch_to_block(join); + assert!(candidates(&mut b).is_empty()); + } + + #[test] + fn a_store_in_a_loop_is_a_candidate() { + let mut b = SIRBuilder::new(); + let header = b.new_block(); + b.seal_block(SIRTerminator::Jump(header, Vec::new())); + b.switch_to_block(header); + store(&mut b, 3); + let condition = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(condition, SIRValue::new(0u8))); + let exit = b.new_block(); + b.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (header, Vec::new()), + false_block: (exit, Vec::new()), + }); + b.switch_to_block(exit); + assert_eq!(candidates(&mut b), [3]); + } + + #[test] + fn a_return_separates_stores() { + // A kernel suspends by returning; the next resume point is entered + // from the dispatch, not from the store before the suspension. + let mut b = SIRBuilder::new(); + let resume = b.new_block(); + let dispatch_condition = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(dispatch_condition, SIRValue::new(0u8))); + let start = b.new_block(); + b.seal_block(SIRTerminator::Branch { + cond: dispatch_condition, + true_block: (resume, Vec::new()), + false_block: (start, Vec::new()), + }); + b.switch_to_block(start); + store(&mut b, 4); + b.seal_block(SIRTerminator::Return); + b.switch_to_block(resume); + store(&mut b, 4); + assert!(candidates(&mut b).is_empty()); + } +} diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index 8b83123dc8d..1bb61f0881d 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -15,7 +15,7 @@ use thiserror::Error; /// /// Version 2 adds [`Process`]es. An artifact without processes is still /// written as version 1, so older consumers keep accepting it. -pub const ARTIFACT_FORMAT_VERSION: u32 = 2; +pub const ARTIFACT_FORMAT_VERSION: u32 = 3; /// Oldest JSON interchange version [`FrontendArtifact::from_json`] accepts. pub const MIN_ARTIFACT_FORMAT_VERSION: u32 = 1; @@ -476,6 +476,62 @@ pub enum Statement { Delay { amount: ExprId }, /// End the simulation. Finish, + /// Suspend the process for `amount` time units with the scheduling of + /// IEEE 1800-2023 `#amount`: a zero delay resumes in the inactive + /// region of the same time, before nonblocking assignments of that time + /// are published. Unknown bits of the amount count as zero. + InactiveDelay { amount: ExprId }, + /// Suspend until one of `terms` occurs (an event control `@(...)`). + /// Every occurrence counts, including a pulse that another process + /// writes and undoes without suspending in between. + WaitEvent { terms: Vec }, + /// Suspend until `condition` is nonzero (`wait (condition)`); continue + /// at once if it already is. + WaitLevel { condition: ExprId }, + /// Nonblocking assignment: `value` is evaluated now and assigned to + /// `target` in the NBA region of the current time. + Nonblocking { target: SignalSlice, value: ExprId }, +} + +/// What a term of a [`Statement::WaitEvent`] waits for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum EventEdge { + /// Any change of the signal's value. + Change, + /// A positive edge of its least significant bit (IEEE 1800-2023 9.4.2). + Posedge, + /// A negative edge of its least significant bit. + Negedge, +} + +/// One term of a [`Statement::WaitEvent`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct EventTerm { + pub signal: SignalId, + pub edge: EventEdge, +} + +impl EventTerm { + pub const fn new(signal: SignalId, edge: EventEdge) -> Self { + Self { signal, edge } + } +} + +/// A combinational process such as `always_comb`: its body runs at time +/// zero and again whenever a signal it reads changes, but not when only a +/// signal it writes changes (IEEE 1800-2023 9.2.2.2). Every write is +/// visible as it happens, so `y = 0; if (a) y = 1;` pulses `y` each time an +/// input change re-runs the body. Its statements are assignments and +/// conditionals. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CombProcess { + body: Vec, +} + +impl CombProcess { + pub fn body(&self) -> &[Statement] { + &self.body + } } /// A procedural process that starts at time zero, such as an `initial` @@ -509,6 +565,37 @@ pub struct FrontendArtifact { port_order: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] processes: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + comb_processes: Vec, +} + +/// Whether `statements` use a statement of format version 3. +fn uses_format_3(statements: &[Statement]) -> bool { + statements.iter().any(|statement| match statement { + Statement::If { + then_body, + else_body, + .. + } => uses_format_3(then_body) || uses_format_3(else_body), + Statement::While { body, .. } | Statement::Forever { body } => uses_format_3(body), + Statement::Assign { .. } | Statement::Delay { .. } | Statement::Finish => false, + Statement::InactiveDelay { .. } + | Statement::WaitEvent { .. } + | Statement::WaitLevel { .. } + | Statement::Nonblocking { .. } => true, + }) +} + +/// The oldest format version that can carry `processes` and +/// `comb_processes`. +fn required_format_version(processes: &[Process], comb_processes: &[CombProcess]) -> u32 { + if !comb_processes.is_empty() || processes.iter().any(|process| uses_format_3(&process.body)) { + 3 + } else if !processes.is_empty() { + 2 + } else { + MIN_ARTIFACT_FORMAT_VERSION + } } impl FrontendArtifact { @@ -526,7 +613,8 @@ impl FrontendArtifact { let artifact: Self = serde_json::from_str(json)?; if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION) .contains(&artifact.format_version) - || (artifact.format_version < 2 && !artifact.processes.is_empty()) + || artifact.format_version + < required_format_version(&artifact.processes, &artifact.comb_processes) { return Err(ArtifactJsonError::UnsupportedVersion { expected: ARTIFACT_FORMAT_VERSION, @@ -847,6 +935,19 @@ impl FrontendArtifact { } insert_driver_target(&mut driver_ranges, register.target, &target.name)?; } + for process in &self.comb_processes { + validate_comb_body(&process.body)?; + self.validate_statements(&process.body, &driver_ranges)?; + } + for process in &self.comb_processes { + for target in comb_process_targets(&process.body) { + let name = &self + .signal(target.signal) + .ok_or(BuildError::UnknownSignal(target.signal.index()))? + .name; + insert_driver_target(&mut driver_ranges, target, name)?; + } + } for process in &self.processes { self.validate_statements(&process.body, &driver_ranges)?; } @@ -902,6 +1003,10 @@ impl FrontendArtifact { &self.port_order } + pub fn comb_processes(&self) -> &[CombProcess] { + &self.comb_processes + } + pub fn processes(&self) -> &[Process] { &self.processes } @@ -989,6 +1094,10 @@ pub enum BuildError { ProcessDriverConflict { name: String }, #[error("delay amount is {width} bits wide; at most {MAX_DELAY_WIDTH} bits are supported")] DelayTooWide { width: usize }, + #[error("an event control needs at least one term")] + EmptyEventControl, + #[error("a combinational process contains only assignments and conditionals")] + UnsupportedCombStatement, } /// JSON interchange failures for frontend artifacts. @@ -1014,6 +1123,7 @@ pub struct ModuleBuilder { driver_ranges: FxHashMap>, port_order: Vec, processes: Vec, + comb_processes: Vec, } impl ModuleBuilder { @@ -1033,6 +1143,7 @@ impl ModuleBuilder { driver_ranges: FxHashMap::default(), port_order: Vec::new(), processes: Vec::new(), + comb_processes: Vec::new(), }) } @@ -1370,13 +1481,26 @@ impl ModuleBuilder { Ok(()) } + /// Add a combinational process (see [`CombProcess`]). The signals it + /// assigns become driven like the target of a continuous assignment. + pub fn comb_process(&mut self, body: Vec) -> Result<(), BuildError> { + validate_comb_body(&body)?; + validate_statements( + &body, + &|signal| self.signals.get(signal.index() as usize), + &|expression| self.expressions.get(expression.index() as usize), + &self.driver_ranges, + )?; + for target in comb_process_targets(&body) { + self.record_driver_target(target)?; + } + self.comb_processes.push(CombProcess { body }); + Ok(()) + } + pub fn finish(self) -> FrontendArtifact { FrontendArtifact { - format_version: if self.processes.is_empty() { - MIN_ARTIFACT_FORMAT_VERSION - } else { - ARTIFACT_FORMAT_VERSION - }, + format_version: required_format_version(&self.processes, &self.comb_processes), module_name: self.name, signals: self.signals, expressions: self.expressions, @@ -1384,6 +1508,7 @@ impl ModuleBuilder { registers: self.registers, port_order: self.port_order, processes: self.processes, + comb_processes: self.comb_processes, } } @@ -1461,7 +1586,9 @@ fn slices_overlap(a: SignalSlice, b: SignalSlice) -> bool { fn collect_process_targets(statements: &[Statement], targets: &mut Vec) { for statement in statements { match statement { - Statement::Assign { target, .. } => targets.push(*target), + Statement::Assign { target, .. } | Statement::Nonblocking { target, .. } => { + targets.push(*target) + } Statement::If { then_body, else_body, @@ -1473,9 +1600,51 @@ fn collect_process_targets(statements: &[Statement], targets: &mut Vec { collect_process_targets(body, targets); } - Statement::Delay { .. } | Statement::Finish => {} + Statement::Delay { .. } + | Statement::InactiveDelay { .. } + | Statement::WaitEvent { .. } + | Statement::WaitLevel { .. } + | Statement::Finish => {} + } + } +} + +/// The ranges a combinational process drives: the slices it assigns, with +/// overlapping or adjacent slices of one signal merged, since one process is +/// one driver however many times it writes a bit. +fn comb_process_targets(statements: &[Statement]) -> Vec { + let mut targets = Vec::new(); + collect_process_targets(statements, &mut targets); + targets.sort_by_key(|target| (target.signal, target.lsb)); + let mut merged: Vec = Vec::new(); + for target in targets { + match merged.last_mut() { + Some(last) if last.signal == target.signal && target.lsb <= last.lsb + last.width => { + let end = (last.lsb + last.width).max(target.lsb + target.width); + last.width = end - last.lsb; + } + _ => merged.push(target), } } + merged +} + +fn validate_comb_body(statements: &[Statement]) -> Result<(), BuildError> { + for statement in statements { + match statement { + Statement::Assign { .. } => {} + Statement::If { + then_body, + else_body, + .. + } => { + validate_comb_body(then_body)?; + validate_comb_body(else_body)?; + } + _ => return Err(BuildError::UnsupportedCombStatement), + } + } + Ok(()) } /// Check the statements of one process against the module's signals, @@ -1493,7 +1662,7 @@ fn validate_statements<'a>( }; for statement in statements { match statement { - Statement::Assign { target, value } => { + Statement::Assign { target, value } | Statement::Nonblocking { target, value } => { let target_signal = signal(target.signal) .ok_or(BuildError::UnknownSignal(target.signal.index()))?; if target.width == 0 { @@ -1546,12 +1715,23 @@ fn validate_statements<'a>( Statement::Forever { body } => { validate_statements(body, signal, expression, driver_ranges)?; } - Statement::Delay { amount } => { + Statement::Delay { amount } | Statement::InactiveDelay { amount } => { let width = expression_type(*amount)?.width(); if width > MAX_DELAY_WIDTH { return Err(BuildError::DelayTooWide { width }); } } + Statement::WaitEvent { terms } => { + if terms.is_empty() { + return Err(BuildError::EmptyEventControl); + } + for term in terms { + signal(term.signal).ok_or(BuildError::UnknownSignal(term.signal.index()))?; + } + } + Statement::WaitLevel { condition } => { + expression_type(*condition)?; + } Statement::Finish => {} } } @@ -1592,6 +1772,123 @@ mod tests { assert_eq!(artifact.port_order().len(), 3); } + #[test] + fn timing_statements_and_comb_processes_need_format_3() { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Timed").unwrap(); + let go = module.input("go", bit).unwrap(); + let done = module.output("done", bit).unwrap(); + let y = module.output("y", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let done_target = module.whole(done).unwrap(); + module + .process(vec![Statement::Delay { amount: one }]) + .unwrap(); + module + .process(vec![ + Statement::WaitEvent { + terms: vec![EventTerm::new(go, EventEdge::Posedge)], + }, + Statement::Nonblocking { + target: done_target, + value: one, + }, + ]) + .unwrap(); + let read_go = module.read(go).unwrap(); + let y_target = module.whole(y).unwrap(); + module + .comb_process(vec![Statement::Assign { + target: y_target, + value: read_go, + }]) + .unwrap(); + let artifact = module.finish(); + assert_eq!(artifact.format_version(), 3); + let json = artifact.to_json().unwrap(); + assert_eq!( + FrontendArtifact::from_json(&json) + .unwrap() + .processes() + .len(), + 2 + ); + + // Version 2 cannot carry them. + let mut value: serde_json::Value = serde_json::from_str(&json).unwrap(); + value["format_version"] = 2.into(); + assert!(FrontendArtifact::from_json(&value.to_string()).is_err()); + } + + #[test] + fn rejects_invalid_timing_statements() { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Invalid").unwrap(); + let go = module.input("go", bit).unwrap(); + let y = module.output("y", bit).unwrap(); + assert_eq!( + module + .process(vec![Statement::WaitEvent { terms: Vec::new() }]) + .unwrap_err(), + BuildError::EmptyEventControl + ); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + assert_eq!( + module + .comb_process(vec![Statement::Delay { amount: one }]) + .unwrap_err(), + BuildError::UnsupportedCombStatement + ); + // A combinational process drives its targets like an assignment. + let read_go = module.read(go).unwrap(); + let y_target = module.whole(y).unwrap(); + module + .comb_process(vec![Statement::Assign { + target: y_target, + value: read_go, + }]) + .unwrap(); + assert!(matches!( + module.assign(y_target, read_go), + Err(BuildError::OverlappingDrivers { .. }) + )); + assert!(matches!( + module.process(vec![Statement::Nonblocking { + target: y_target, + value: one, + }]), + Err(BuildError::ProcessDriverConflict { .. }) + )); + } + + #[test] + fn a_combinational_process_may_overwrite_part_of_its_own_target() { + let byte = ValueType::bits(8).unwrap(); + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Override").unwrap(); + let a = module.input("a", byte).unwrap(); + let low = module.input("low", bit).unwrap(); + let y = module.output("y", byte).unwrap(); + let read_a = module.read(a).unwrap(); + let read_low = module.read(low).unwrap(); + let whole = module.whole(y).unwrap(); + let first = module.slice(y, 0, 1).unwrap(); + module + .comb_process(vec![ + Statement::Assign { + target: whole, + value: read_a, + }, + Statement::Assign { + target: first, + value: read_low, + }, + ]) + .unwrap(); + let artifact = module.finish(); + FrontendArtifact::from_json(&artifact.to_json().unwrap()).unwrap(); + } + #[test] fn rejects_partial_register_target() { let mut module = ModuleBuilder::new("Counter").unwrap(); diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 366e7817e60..9e0c51e10fd 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -105,6 +105,8 @@ pub(crate) struct LoweredSvModule { pub instances: Vec, /// Variables that denote a package variable, with its package and name. package_variables: Vec<(SourceVarId, String, String)>, + /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. + event_copies: Vec<(SourceVarId, SourceVarId)>, } #[derive(Clone)] @@ -1245,6 +1247,8 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( parameter_types: HashMap::default(), instances: Vec::new(), package_variables: Vec::new(), + // The foreign module's own combinational blocks carry its copies. + event_copies: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -1944,6 +1948,7 @@ fn lower_module_with_overrides( eval_apply_ff_blocks, reset_clock_map, parallel_ff_parts, + event_vars, ), mut runtime_event_sites, mut runtime_errors, @@ -1965,7 +1970,7 @@ fn lower_module_with_overrides( std::mem::take(&mut pm.extern_functions), ) }; - mark_ff_event_domains(module, &mut variables, &name_to_id); + mark_ff_event_domains(&event_vars, &mut variables); let (initial_values, processes) = lower_initial_processes( module, &mut variables, @@ -2070,6 +2075,9 @@ fn lower_module_with_overrides( reset_clock_map, processes, package_bindings: HashMap::default(), + counter_slots: Vec::new(), + wait_sites: Vec::new(), + nba_sites: Vec::new(), }, variables, port_order, @@ -2078,44 +2086,22 @@ fn lower_module_with_overrides( parameter_types, instances, package_variables, + event_copies: event_vars.copies, }) } fn mark_ff_event_domains( - module: &sv::ir::Module, + event_vars: &FfEventVars, variables: &mut HashMap, - name_to_id: &HashMap, ) { - for process in module.ff_processes() { - let Some(clock) = clock_event_from_ff_process(process) else { - continue; - }; - if let Some(id) = name_to_id.get(clock.signal()).copied() - && let Some(variable) = variables.get_mut(&id) - { - variable.domain_kind = match clock.edge() { - sv::ir::FfEdge::Pos => DomainKind::ClockPosedge, - sv::ir::FfEdge::Neg => DomainKind::ClockNegedge, + for (id, kind) in event_vars.kinds() { + if let Some(variable) = variables.get_mut(&id) { + variable.domain_kind = kind; + variable.type_kind = match kind { + DomainKind::ResetAsyncHigh => PortTypeKind::ResetAsyncHigh, + DomainKind::ResetAsyncLow => PortTypeKind::ResetAsyncLow, + _ => PortTypeKind::Clock, }; - variable.type_kind = PortTypeKind::Clock; - } - for event in process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - { - if let Some(id) = name_to_id.get(event.signal()).copied() - && let Some(variable) = variables.get_mut(&id) - { - variable.domain_kind = match event.edge() { - sv::ir::FfEdge::Pos => DomainKind::ResetAsyncHigh, - sv::ir::FfEdge::Neg => DomainKind::ResetAsyncLow, - }; - variable.type_kind = match event.edge() { - sv::ir::FfEdge::Pos => PortTypeKind::ResetAsyncHigh, - sv::ir::FfEdge::Neg => PortTypeKind::ResetAsyncLow, - }; - } } } } @@ -2441,8 +2427,28 @@ pub(crate) fn attach_instance_glue( None, ), })?; + let (mut comb_blocks, mut arena) = (comb_blocks, arena); + push_event_copies(&lowered.event_copies, &mut comb_blocks, &mut arena)?; module.comb_boundaries = comb_boundaries(&comb_blocks); module.comb_blocks = comb_blocks; + // Signals a kernel or an imperative combinational unit may store twice + // between two runtime checks get counters; assembly uses them only for + // the ones a flip-flop domain or wait watches. + let mut candidates = Vec::new(); + for process in &module.processes { + candidates.extend(celox_frontend_core::watch::multi_store_candidates( + &process.kernel, + |address| (address.region == STABLE_REGION).then_some(address.var_id), + )); + } + for path in &module.comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &path.target { + candidates.extend(celox_frontend_core::watch::multi_store_candidates( + unit, + |address| Some(*address), + )); + } + } module.arena = arena; // Combinational event sites follow the flip-flop ones, including the // events run-time loops emit. @@ -2511,6 +2517,8 @@ pub(crate) fn attach_instance_glue( arena: glue.2, }); } + module.counter_slots = + celox_frontend_core::watch::declare_counter_slots(&mut module.variables, candidates); Ok(()) } @@ -2967,6 +2975,46 @@ fn lower_comb_processes( Ok((comb_blocks, arena, created, observers, sites)) } +/// The continuous assignments `copy = signal` of the hidden event copies of +/// [`FfEventVars`]: a whole-variable copy, which clock-domain unification +/// keeps in the signal's domain unless the copy is sensed at the other edge. +fn push_event_copies( + copies: &[(SourceVarId, SourceVarId)], + comb_blocks: &mut Vec>, + arena: &mut SLTNodeArena, +) -> Result<(), ParserError> { + for &(copy, signal) in copies { + let access = BitAccess::new(0, 0); + let expr = arena + .alloc(SLTNode::Input { + variable: signal, + signed: false, + index: Vec::new(), + access, + }) + .map_err(|error| { + ParserError::illegal_context( + "systemverilog always_ff event copy", + error.to_string(), + None, + ) + })?; + comb_blocks.push(LogicPath { + target: LogicPathTarget::Var(VarAtomBase::new(copy, 0, 0)), + sources: std::iter::once(VarAtomBase::new(signal, 0, 0)).collect(), + previous_sources: HashSet::default(), + address_sources: HashSet::default(), + local_inputs: Vec::new(), + order_before: HashSet::default(), + comb_capture_enable_sites: Vec::new(), + comb_capture_enable_always: false, + pre_lower_nodes: Vec::new(), + expr, + }); + } + Ok(()) +} + /// The bit boundaries at which combinational processes write or statically /// read each variable. Flattening splits paths at these boundaries (and at /// those propagated through ports), so bit-disjoint dependencies on one @@ -6198,8 +6246,89 @@ type SvFfBlocks = ( TriggerSet, Vec>, >, + FfEventVars, ); +/// The variables `always_ff` event controls are sensed on. +/// +/// A variable carries one domain kind, the edge and role of its event, so a +/// signal is sensed on itself at one edge and role, and at any other on a +/// hidden copy of the signal: `negedge clk` beside `posedge clk`, or +/// `posedge rst` as a clock beside `negedge rst` as an asynchronous reset. +/// Each copy is a whole-variable continuous assignment of the signal, so it +/// changes in the same time step as the signal and is a clock derived from +/// it; only domains sensed on a copy pay for it. +/// +/// The signal itself keeps the first of rising clock, falling clock, active +/// high reset, active low reset that it is sensed as, independent of the +/// order of the processes: a clock port stays in the domain of the rising +/// clock that drives it, and `Simulator::tick` of the signal is its rising +/// edge whenever a process uses that. +#[derive(Clone, Default)] +pub(crate) struct FfEventVars { + /// Per signal, the domain kinds it is sensed at and their variables. + sensed: HashMap>, + /// The `(copy, signal)` pairs of the hidden copies, in creation order. + copies: Vec<(SourceVarId, SourceVarId)>, +} + +impl FfEventVars { + /// Sense each signal of `events` on itself at its first kind in + /// priority order. + fn new(events: impl Iterator) -> Self { + let priority = |kind: DomainKind| match kind { + DomainKind::ClockPosedge => 0, + DomainKind::ClockNegedge => 1, + DomainKind::ResetAsyncHigh => 2, + DomainKind::ResetAsyncLow => 3, + DomainKind::Other => 4, + }; + let mut primary = HashMap::::default(); + for (signal, kind) in events { + primary + .entry(signal) + .and_modify(|primary| { + if priority(kind) < priority(*primary) { + *primary = kind; + } + }) + .or_insert(kind); + } + Self { + sensed: primary + .into_iter() + .map(|(signal, kind)| (signal, vec![(kind, signal)])) + .collect(), + copies: Vec::new(), + } + } + + /// The variable on which `signal` is sensed as `kind`. + fn sensed( + &mut self, + pm: &mut procedural::ProcModule<'_>, + signal: SourceVarId, + kind: DomainKind, + ) -> SourceVarId { + let sensed = self.sensed.entry(signal).or_default(); + if let Some(&(_, var)) = sensed.iter().find(|(sensed_kind, _)| *sensed_kind == kind) { + return var; + } + let copy = pm.event_copy(signal, kind); + self.copies.push((copy, signal)); + sensed.push((kind, copy)); + copy + } + + /// Every sensed variable with its domain kind. + fn kinds(&self) -> impl Iterator + '_ { + self.sensed + .values() + .flatten() + .map(|&(kind, var)| (var, kind)) + } +} + fn lower_ff_processes( module: &sv::ir::Module, pm: &mut procedural::ProcModule<'_>, @@ -6210,71 +6339,58 @@ fn lower_ff_processes( let mut apply_ff_blocks = HashMap::default(); let mut eval_apply_ff_blocks = HashMap::default(); let mut reset_clock_map = HashMap::default(); - let mut clock_edges = HashMap::default(); - let mut reset_edges = HashMap::default(); - let random_seeds = process_random_seeds(module); - for (index, process) in module.ff_processes().iter().enumerate() { + // Every event of every process, as (signal, domain kind): the clock, then + // the resets. + let mut process_events = Vec::new(); + for process in module.ff_processes() { let clock = clock_event_from_ff_process(process) .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; - let clock_id = pm - .id(clock.signal()) - .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; - if pm - .variables - .get(&clock_id) - .is_some_and(|variable| variable.width != 1) - { - return Err(sv::AnalyzerError::Unsupported( - "multi-bit always_ff event signal".to_string(), - )); - } - if reset_edges.contains_key(&clock_id) { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock/reset-edge polarities for one signal".to_string(), - )); - } - if clock_edges - .insert(clock_id, clock.edge()) - .is_some_and(|edge| edge != clock.edge()) - { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock-edge polarities for one signal".to_string(), - )); - } - for reset in process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - { - let reset_id = pm.id(reset.signal()).ok_or_else(|| { + let event_id = |event: &sv::ir::FfEvent| { + let id = pm.id(event.signal()).ok_or_else(|| { sv::AnalyzerError::Unsupported("always_ff event control".to_string()) })?; if pm .variables - .get(&reset_id) + .get(&id) .is_some_and(|variable| variable.width != 1) { return Err(sv::AnalyzerError::Unsupported( "multi-bit always_ff event signal".to_string(), )); } - if clock_edges.contains_key(&reset_id) { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock/reset-edge polarities for one signal".to_string(), - )); - } - if reset_edges - .insert(reset_id, reset.edge()) - .is_some_and(|edge| edge != reset.edge()) - { - return Err(sv::AnalyzerError::Unsupported( - "mixed reset-edge polarities for one signal".to_string(), - )); - } + Ok(id) + }; + let clock_kind = match clock.edge() { + sv::ir::FfEdge::Pos => DomainKind::ClockPosedge, + sv::ir::FfEdge::Neg => DomainKind::ClockNegedge, + }; + let mut events = vec![(event_id(clock)?, clock_kind)]; + for reset in process + .events() + .iter() + .filter(|event| event.signal() != clock.signal()) + { + let reset_kind = match reset.edge() { + sv::ir::FfEdge::Pos => DomainKind::ResetAsyncHigh, + sv::ir::FfEdge::Neg => DomainKind::ResetAsyncLow, + }; + events.push((event_id(reset)?, reset_kind)); } - let trigger_set = trigger_set_from_ff_process(process, pm.name_to_id) - .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; + process_events.push(events); + } + let mut event_vars = FfEventVars::new(process_events.iter().flatten().copied()); + + let random_seeds = process_random_seeds(module); + for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { + let mut events = events + .into_iter() + .map(|(signal, kind)| event_vars.sensed(pm, signal, kind)); + let mut trigger_set = TriggerSet { + clock: events.next().expect("a process has a clock event"), + resets: Vec::new(), + }; + trigger_set.resets.extend(events); // A reset shared by several clock domains is associated with the // first; the association only names a clock for the reset signal. for reset in &trigger_set.resets { @@ -6321,6 +6437,7 @@ fn lower_ff_processes( eval_apply_ff_blocks, reset_clock_map, parallel_ff_parts, + event_vars, )) } @@ -6405,24 +6522,6 @@ fn expr_uses_ident_as_condition(expr: &sv::ir::Expr, name: &str) -> bool { } } -fn trigger_set_from_ff_process( - process: &sv::ir::FfProcess, - name_to_id: &HashMap, -) -> Option> { - let clock = clock_event_from_ff_process(process)?; - let clock_id = *name_to_id.get(clock.signal())?; - let resets = process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - .filter_map(|event| name_to_id.get(event.signal()).copied()) - .collect(); - Some(TriggerSet { - clock: clock_id, - resets, - }) -} - fn seal_builder(mut builder: SIRBuilder) -> ExecutionUnit { builder.seal_block(SIRTerminator::Return); let (blocks, register_map, _) = builder.drain(); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index f8178cc7e65..c0b2e9ad58d 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -523,6 +523,41 @@ impl<'a> ProcModule<'a> { (id, name) } + /// A hidden one-bit copy of the event signal `signal`, sensed as `kind`. + /// It has no name a SystemVerilog identifier can denote, and is not + /// addressable by path. + pub fn event_copy(&mut self, signal: SourceVarId, kind: DomainKind) -> SourceVarId { + let source = &self.variables[&signal]; + let suffix = match kind { + DomainKind::ClockPosedge => "posedge", + DomainKind::ClockNegedge => "negedge", + DomainKind::ResetAsyncHigh => "reset_high", + DomainKind::ResetAsyncLow => "reset_low", + DomainKind::Other => "event", + }; + let mut path = source.path.clone(); + if let Some(last) = path.last_mut() { + last.push('@'); + last.push_str(suffix); + } + let variable = SvVariable { + path, + width: 1, + signed: false, + is_4state: source.is_4state, + packed_ranges: vec![(0, 0)], + array_dims: Vec::new(), + domain_kind: kind, + kind: VariableKind::Variable, + type_kind: source.type_kind, + source: None, + hidden: true, + }; + let id = next_var_id(&mut self.next_id); + self.variables.insert(id, variable); + id + } + pub fn subroutine(&self, name: &str) -> Option<&sv::ir::Subroutine> { self.subroutines.get(name) } diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 7fd70c05f77..1c01f52e657 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -562,6 +562,9 @@ pub(crate) fn project_module_with_ids( .collect(), processes: Vec::new(), package_bindings: HashMap::default(), + counter_slots: Vec::new(), + wait_sites: Vec::new(), + nba_sites: Vec::new(), }, ids, )) diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index 94cc55260ca..bb7910a0fa6 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -1909,6 +1909,31 @@ impl NativeSimulationHandle { .map_err(|e| Error::from_reason(format!("{}", e))) } + /// Advance until `end_time` taking at most `max_steps` steps. Returns + /// false, at the time of the last step, when the steps ran out first. + #[napi] + pub fn run_until_bounded(&mut self, end_time: f64, max_steps: f64) -> Result { + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + sim.run_until_bounded(end_time as u64, max_steps as u64) + .map_err(|e| Error::from_reason(format!("{}", e))) + } + + /// Report that the host wrote the state through the shared memory: the + /// next step settles the current time when a process may see the writes + /// or an event signal changed. + #[napi] + pub fn note_host_writes(&mut self) -> Result<()> { + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + sim.note_raw_writes(); + Ok(()) + } + /// Advance to the next event. Returns the new time, or null if no events. #[napi] pub fn step(&mut self) -> Result> { diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index fb82fb3e8b0..20f1aea095c 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -5,6 +5,23 @@ use num_bigint::BigUint; pub use crate::SimulatorErrorCode; use crate::{AbsoluteAddr, MemoryLayout, RuntimeEventBuffer, SignalRef}; +/// The event IDs marked in a memory image's triggered bits, one bit per +/// event, least significant bit first. Read a word at a time: few bits are +/// set. +pub fn triggered_bits_from_bytes(bytes: &[u8]) -> bit_set::BitSet { + let mut bits = bit_set::BitSet::with_capacity(bytes.len() * 8); + for (index, chunk) in bytes.chunks(8).enumerate() { + let mut word = [0u8; 8]; + word[..chunk.len()].copy_from_slice(chunk); + let mut word = u64::from_le_bytes(word); + while word != 0 { + bits.insert(index * 64 + word.trailing_zeros() as usize); + word &= word - 1; + } + } + bits +} + /// Marker trait for backend-specific event handles. /// /// An event handle is an opaque reference to a compiled clock or @@ -172,3 +189,19 @@ pub trait SimBackend { } } } + +#[cfg(test)] +mod tests { + use super::triggered_bits_from_bytes; + + #[test] + fn triggered_bits_follow_the_bytes_least_significant_bit_first() { + let mut bytes = vec![0u8; 11]; + bytes[0] = 0b101; + bytes[7] = 0x80; + bytes[10] = 0x01; + let bits: Vec<_> = triggered_bits_from_bytes(&bytes).iter().collect(); + assert_eq!(bits, [0, 2, 63, 80]); + assert!(triggered_bits_from_bytes(&[]).is_empty()); + } +} diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index e3b6a58eb10..dcd1b21421f 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -34,6 +34,7 @@ use crate::{ AbsoluteAddr, SignalRef, SimulatorErrorCode, backend::{EventHandle, SimBackend}, simulation::{SimulationExecutor, event_level, stable_edge}, + timing::Halt, }; /// The kernels of one event domain. @@ -461,6 +462,24 @@ impl DerivedTickPlan { scratch: &mut DerivedTickScratch, settle: bool, ) -> Result<(), SimulatorErrorCode> + where + X: SimulationExecutor, + X::Backend: SimBackend, + { + match self.tick_domains(executor, scratch, settle) { + // An RTL `$finish` ends only a timed simulation, which does not + // tick; a tick leaves it to the host. + Ok(()) | Err(Halt::Finish) => Ok(()), + Err(Halt::Error(error)) => Err(error), + } + } + + fn tick_domains( + &self, + executor: &mut X, + scratch: &mut DerivedTickScratch, + settle: bool, + ) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -487,7 +506,7 @@ impl DerivedTickPlan { executor: &mut X, scratch: &mut DerivedTickScratch, settle: bool, - ) -> Result<(), SimulatorErrorCode> + ) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -519,7 +538,7 @@ impl DerivedTickPlan { executor: &mut X, scratch: &mut DerivedTickScratch, settle: bool, - ) -> Result<(), SimulatorErrorCode> + ) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -584,7 +603,7 @@ impl DerivedTickPlan { executor: &mut X, settle: bool, ready: &[usize], - ) -> Result<(), SimulatorErrorCode> + ) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -638,7 +657,7 @@ impl DerivedTickPlan { executor: &mut X, scratch: &mut DerivedTickScratch, phase: Phase, - ) -> Result<(), SimulatorErrorCode> + ) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -707,7 +726,7 @@ fn fire<'a, X, E>( executor: &mut X, settle: bool, domains: impl Iterator> + Clone, -) -> Result<(), SimulatorErrorCode> +) -> Result<(), Halt> where X: SimulationExecutor, X::Backend: SimBackend, @@ -762,23 +781,23 @@ impl SimulationExecutor for BackendExecutor<'_, B> { self.0 } - fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { - self.0.eval_comb() + fn eval_comb(&mut self) -> Result<(), Halt> { + Ok(self.0.eval_comb()?) } - fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), SimulatorErrorCode> { - self.0.eval_apply_ff_at(event) + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + Ok(self.0.eval_apply_ff_at(event)?) } - fn eval_comb_apply_ff_at(&mut self, event: B::Event) -> Result<(), SimulatorErrorCode> { - self.0.eval_comb_apply_ff_at(event) + fn eval_comb_apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + Ok(self.0.eval_comb_apply_ff_at(event)?) } - fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), SimulatorErrorCode> { - self.0.eval_only_ff_at(event) + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + Ok(self.0.eval_only_ff_at(event)?) } - fn apply_ff_at(&mut self, event: B::Event) -> Result<(), SimulatorErrorCode> { - self.0.apply_ff_at(event) + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + Ok(self.0.apply_ff_at(event)?) } } diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 6148f30249c..c7a251be978 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -10,6 +10,7 @@ pub mod scheduler; mod simulation; mod state_file; mod testbench; +pub mod timing; mod vcd; pub use derived_tick::{ @@ -23,13 +24,17 @@ pub use reflection::{ SignalDirection, }; pub use simulation::{ - EventInfo, ProcessRefs, ScheduleParts, SimulationExecutor, SimulationSnapshot, SimulationState, + EventInfo, ScheduleParts, SimulationExecutor, SimulationSnapshot, SimulationState, }; pub use state_file::{ - ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject, - StateRole, format_state_value, + BaselineRecord, NbaRecord, ProcessRecord, ScheduleRecord, ScheduledEvent, StateDifference, + StateFile, StateFileError, StateObject, StateRole, WaiterRecord, format_state_value, }; pub use testbench::bind_testbench_program; +pub use timing::{ + CountedDomainRefs, CountedRefs, Halt, HostWatch, NbaSiteRefs, NbaUpdate, ProcessRefs, + ProcessState, TermRefs, Waiter, Waiters, +}; pub use vcd::{VcdExternalSignalDesc, VcdSignalDesc, VcdStatistics, VcdWriter}; pub type AbsoluteAddr = celox_design::StateAddr; diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index d7a1a061cad..dfcd34780ff 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -1,15 +1,27 @@ use std::{cmp::Reverse, collections::BinaryHeap}; use bit_set::BitSet; -use celox_design::{DomainKind, ProcessStatus}; +use celox_design::{CounterKind, DomainKind, ProcessStatus}; use fxhash::FxHashMap; use crate::{ AbsoluteAddr, SignalRef, SimulatorErrorCode, backend::{EventHandle, SimBackend}, scheduler::{ClockDef, Scheduler, SimEvent}, + timing::{ + Baseline, CountedDomainRefs, Halt, NbaUpdate, ProcessRefs, ProcessState, StateView, Value, + copy_planes, encode_planes, kind_index, occurs, planes, planes_equal, planes_occur, read, + }, }; +/// Kernel returns a round may spend on `Yield` and nonblocking staging +/// before the runtime reports a process that never suspends. +const SLOT_RETURN_BUDGET: u64 = 1 << 24; + +/// Rounds one time slot may run before the runtime reports processes that +/// keep resuming at that time, such as `forever #0`. +const SLOT_ROUND_BUDGET: u64 = 1 << 20; + /// Backend execution hooks needed by the timed simulation engine. /// /// The facade implements this contract to retain policy such as runtime-event @@ -19,31 +31,33 @@ pub trait SimulationExecutor { fn backend(&self) -> &Self::Backend; fn backend_mut(&mut self) -> &mut Self::Backend; - fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode>; - fn eval_apply_ff_at( - &mut self, - event: ::Event, - ) -> Result<(), SimulatorErrorCode>; - fn eval_only_ff_at( - &mut self, - event: ::Event, - ) -> Result<(), SimulatorErrorCode>; + fn eval_comb(&mut self) -> Result<(), Halt>; + fn eval_apply_ff_at(&mut self, event: ::Event) + -> Result<(), Halt>; + fn eval_only_ff_at(&mut self, event: ::Event) -> Result<(), Halt>; /// Settle combinational logic, then evaluate and commit one domain. fn eval_comb_apply_ff_at( &mut self, event: ::Event, - ) -> Result<(), SimulatorErrorCode> { + ) -> Result<(), Halt> { self.eval_comb()?; self.eval_apply_ff_at(event) } - fn apply_ff_at( - &mut self, - event: ::Event, - ) -> Result<(), SimulatorErrorCode>; - fn run_process(&mut self, index: usize) -> Result<(), SimulatorErrorCode> { - self.backend_mut().run_process(index) + fn apply_ff_at(&mut self, event: ::Event) -> Result<(), Halt>; + fn run_process(&mut self, index: usize) -> Result<(), Halt> { + Ok(self.backend_mut().run_process(index)?) + } + + /// Values the host wrote to signals that a wait watches since the last + /// call, in write order (see [`crate::HostWatch`]). + fn take_host_writes(&mut self) -> Vec<(SignalRef, Value)> { + Vec::new() } + /// The design finished the simulation: further evaluation must not + /// change its state. + fn freeze(&mut self) {} + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -68,13 +82,6 @@ pub trait SimulationExecutor { fn finish_timed_step(&mut self, _timestamp: u64) {} } -/// Control slots of one process kernel, resolved to signals of the backend. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ProcessRefs { - pub status: SignalRef, - pub delay: SignalRef, -} - /// A process waiting for simulation time to reach `time`. Ordered so that a /// max-heap pops the earliest time first and, within one time, the process /// that was declared first. @@ -164,14 +171,131 @@ pub struct SimulationState { signal_index_by_id: Vec, processes: Vec, process_wakeups: BinaryHeap, + /// Counted signals and the domains their counters trigger. + counted: Vec, + counted_by_offset: FxHashMap, + /// Whether any process has a nonblocking site with a pending flag. + has_pending_nba_sites: bool, + process_state: ProcessState, + /// The host changed state that the next step must settle at the + /// current time: an event signal, or a signal a wait watches. + host_pending: bool, /// A process requested the end of the simulation. finished: bool, /// Per event ID, the event IDs of clocks computed combinationally from /// the event's signal. Empty when the design has none. combinational_derived: Vec>, + /// Buffers of the round in progress, kept between rounds. + scratch: Option>, + /// The design has process kernels or counted signals. Without either, a + /// round is exactly the batch step and skips every process check. + timed: bool, + /// Rounds and process-phase passes one time slot may run, and kernel + /// returns one round may spend, before the slot is reported as not + /// settling. + round_budget: u64, + return_budget: u64, + /// Rounds and process-phase passes the current time slot has run. + slot_passes: u64, +} + +/// Bookkeeping of one round of a time slot. +#[derive(Default)] +struct Round { + /// Event ids whose trigger survives the settling filter. + scheduled_trigger_ids: BitSet, + track_stable_edges: bool, + /// Event ids a counter triggered; they bypass the stable-edge test of + /// cascaded domains, since a counted pulse may end at its old value. + counted_triggered: BitSet, + /// Domains evaluated before an inactive region, in evaluation order, + /// with the working image of an evaluation that a later one of the + /// same domain superseded (IEEE 1800-2023 4.5: their nonblocking + /// assignments wait for the NBA region). + deferred: Vec<(usize, Option>)>, + /// Kernels ran in this round, so pending nonblocking flags may be set. + kernels_ran: bool, + nba_published: bool, + /// Event-signal values scheduled or written by processes, not yet + /// marked. + transitions: Vec<(usize, bool)>, + /// Event-signal values before and after a process run. + before: Vec, + after: Vec, + /// Event ids a pulse of several publications triggered; like counted + /// triggers they survive settling and bypass the stable-edge test. + occurrences: BitSet, + /// A domain published several evaluations and `transitions` records + /// the event signals they changed. + publishing: bool, + /// Event ids whose level change gates combinationally derived clocks, + /// not yet judged. + gating_sources: Vec, + /// Derived clocks whose edge was judged at their source's change; they + /// bypass the stable-edge test of cascaded domains. + edge_approved: BitSet, + /// The latest value of each event signal among the transitions marked + /// since the baseline (`last_clock_values`) was last taken, valid where + /// the stamp equals `generation`: a value written in one wave of the + /// active region is the previous value of the next wave's write. + latest: Vec<(u32, bool)>, + generation: u32, +} + +impl Round { + /// Start a scan of transitions over `events` event ids against a new + /// baseline. + fn begin_scan(&mut self, events: usize) { + if self.latest.len() < events { + self.latest.resize(events, (0, false)); + } + self.generation = self.generation.wrapping_add(1); + if self.generation == 0 { + // Stamps of an earlier wrap must not match. + self.latest.fill((0, false)); + self.generation = 1; + } + } + + /// The value event `id` had before this transition: its latest value in + /// the scan, or `baseline`; records `value` as its latest. + fn previous(&mut self, id: usize, value: bool, baseline: impl FnOnce() -> bool) -> bool { + let (stamp, latest) = std::mem::replace(&mut self.latest[id], (self.generation, value)); + if stamp == self.generation { + latest + } else { + baseline() + } + } +} + +impl Round { + /// Start a round, keeping the buffers of earlier ones. + fn reset(&mut self, track_stable_edges: bool) { + self.scheduled_trigger_ids.make_empty(); + self.track_stable_edges = track_stable_edges; + self.counted_triggered.make_empty(); + self.occurrences.make_empty(); + self.publishing = false; + self.gating_sources.clear(); + self.edge_approved.make_empty(); + self.deferred.clear(); + self.kernels_ran = false; + self.nba_published = false; + self.transitions.clear(); + } } impl SimulationState { + /// Bound the work of one time slot: `rounds` rounds and passes of the + /// process phase, and `returns` kernel returns per round, before a step + /// reports processes that keep resuming at that time. The defaults are + /// 2^20 and 2^24. + pub fn set_slot_budgets(&mut self, rounds: u64, returns: u64) { + self.round_budget = rounds; + self.return_budget = returns; + } + /// Declare, per event ID, the clocks computed combinationally from the /// event's signal. A change of the signal gives them their edges at the /// same instant: they are judged from the state before it and evaluate @@ -240,6 +364,10 @@ impl SimulationState { } } + let has_processes = !processes.is_empty(); + let has_pending_nba_sites = processes + .iter() + .any(|process| process.nba_sites.iter().any(|site| site.pending.is_some())); Self { scheduler: Scheduler::new(), periodic_events: FxHashMap::default(), @@ -253,11 +381,40 @@ impl SimulationState { .map(|process| Reverse((0, process))) .collect(), processes, + counted: Vec::new(), + counted_by_offset: FxHashMap::default(), + has_pending_nba_sites, + process_state: ProcessState::default(), + host_pending: false, finished: false, combinational_derived: Vec::new(), + scratch: None, + timed: has_processes, + round_budget: SLOT_ROUND_BUDGET, + return_budget: SLOT_RETURN_BUDGET, + slot_passes: 0, } } + /// Count the occurrences of `counted` signals, whose counters trigger + /// the listed domains instead of edge detection by value. + pub fn with_counted(mut self, backend: &B, counted: Vec) -> Self { + self.counted_by_offset = counted + .iter() + .enumerate() + .map(|(index, counted)| (counted.refs.signal.offset, index)) + .collect(); + self.process_state.domain_counters = counted + .iter() + .map(|counted| { + CounterKind::ALL.map(|kind| backend.get_as::(counted.refs.counter(kind))) + }) + .collect(); + self.timed |= !counted.is_empty(); + self.counted = counted; + self + } + pub fn add_clock( &mut self, event: B::Event, @@ -297,13 +454,82 @@ impl SimulationState { self.scheduler.push(event); } + /// Settle host writes at the current time, then advance to the next time + /// with scheduled events or processes and run it. Returns that time, the + /// current time when only host writes were settled, or `None` when + /// nothing was to do. pub fn step(&mut self, executor: &mut E) -> Result, SimulatorErrorCode> where E: SimulationExecutor, { - let Some(current_time) = self.next_event_time() else { - return Ok(None); - }; + self.step_until(executor, u64::MAX) + } + + /// Like [`Self::step`], but run no time after `limit`: settle host + /// writes at the current time if it is not after `limit`, and advance + /// only to a time up to `limit`. Returns `None` when nothing was run. + pub fn step_until( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result, SimulatorErrorCode> + where + E: SimulationExecutor, + { + match self.step_time(executor, limit) { + Ok(time) => Ok(time), + Err(Halt::Finish) => { + // The waveform records the state at the finish. + executor.finish_timed_step(self.scheduler.time); + self.finish(executor); + Ok(Some(self.scheduler.time)) + } + Err(Halt::Error(error)) => Err(error), + } + } + + /// End the simulation where it is. + pub fn finish(&mut self, executor: &mut E) + where + E: SimulationExecutor, + { + self.finished = true; + executor.freeze(); + } + + /// Settle host writes at the current time, then run the next time with + /// work; nothing after `limit` runs. Host writes do not hold a step at + /// the current time: the step goes on to the next event. + fn step_time(&mut self, executor: &mut E, limit: u64) -> Result, Halt> + where + E: SimulationExecutor, + { + let mut settled = None; + loop { + let Some(current_time) = self.next_event_time() else { + return Ok(settled); + }; + if current_time > limit { + return Ok(settled); + } + // Host writes alone: settle them, then go on to the next time. + let host_only = self.host_pending && self.next_work_time() != Some(current_time); + self.run_time(executor, current_time)?; + if !host_only { + return Ok(Some(current_time)); + } + settled = Some(current_time); + } + } + + /// Run the time slot `current_time`: its scheduled events, the + /// processes due then, and the rounds they cause. + fn run_time(&mut self, executor: &mut E, current_time: u64) -> Result<(), Halt> + where + E: SimulationExecutor, + { + self.host_pending = false; + self.slot_passes = 0; let events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() @@ -313,18 +539,51 @@ impl SimulationState { Vec::new() }; let ready = self.take_ready_processes(current_time); - self.step_round(executor, current_time, events_to_process, ready)?; - // A process that waited for zero time resumes in a later round of - // this time, after the previous round's edges have been handled. - while !self.finished { + self.step_round(executor, current_time, events_to_process, ready, true)?; + // A process that waited for zero time, or that the round woke, + // resumes in a later round of this time, after the previous round's + // edges have been handled. + loop { let ready = self.take_ready_processes(current_time); - if ready.is_empty() { + if ready.is_empty() && self.process_state.ready.is_empty() { break; } - self.step_round(executor, current_time, Vec::new(), ready)?; + self.charge_pass()?; + self.step_round(executor, current_time, Vec::new(), ready, false)?; } executor.finish_timed_step(current_time); - Ok(Some(current_time)) + Ok(()) + } + + /// Count a round or a pass of the process phase against the slot's + /// budget, so that processes resuming at one time forever end the step + /// with an error instead of hanging it. + fn charge_pass(&mut self) -> Result<(), Halt> { + self.slot_passes += 1; + self.charge(self.slot_passes, None) + } + + fn charge(&self, returns: u64, process: Option) -> Result<(), Halt> { + let budget = if process.is_some() { + self.return_budget + } else { + self.round_budget + }; + if returns <= budget { + return Ok(()); + } + Err(Halt::Error(SimulatorErrorCode::Runtime { + message: match process { + Some(process) => { + format!("process {process} does not suspend within one time slot") + } + None => format!( + "time {} does not settle: processes keep resuming", + self.scheduler.time + ), + }, + signals: Vec::new(), + })) } /// Remove the processes waiting for `time`, in declaration order. @@ -340,41 +599,753 @@ impl SimulationState { ready } - /// Run `ready` processes in order until each suspends or ends. A process - /// that waits for zero time is queued for the next round of this time. - fn run_processes( + /// Run process `process` once and file it where it resumes. Returns + /// whether it resumes at once (a queued nonblocking assignment or a + /// yield), in which case the caller checks the state before running it + /// again: the return separates the writes before and after it. + fn run_process( &mut self, executor: &mut E, current_time: u64, - ready: Vec, - ) -> Result<(), SimulatorErrorCode> + process: usize, + returns: &mut u64, + ) -> Result where E: SimulationExecutor, { - for process in ready { + { executor.run_process(process)?; - let refs = self.processes[process]; - let status: u8 = executor.backend().get_as(refs.status); + let status: u8 = executor.backend().get_as(self.processes[process].status); + let delay = || -> u64 { executor.backend().get_as(self.processes[process].delay) }; 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(), - } - })?; - self.process_wakeups.push(Reverse((time, process))); + let delay = delay(); + self.wake_after(current_time, delay, process)?; + } + Some(ProcessStatus::InactiveDelay) => { + let delay = delay(); + if delay == 0 { + self.process_state.inactive.insert(process); + } else { + self.wake_after(current_time, delay, process)?; + } } Some(ProcessStatus::Done) => {} - Some(ProcessStatus::Finish) => { - self.finished = true; + Some(ProcessStatus::Finish) => return Err(Halt::Finish), + Some(ProcessStatus::Wait | ProcessStatus::Pending) => { + let site = delay() as usize; + self.register_waiter(executor.backend(), process, site)?; + } + Some(ProcessStatus::Nba) => { + let site = delay() as usize; + self.queue_nba(executor.backend_mut(), process, site)?; + *returns += 1; + self.charge(*returns, Some(process))?; + return Ok(true); + } + Some(ProcessStatus::Yield) => { + *returns += 1; + self.charge(*returns, Some(process))?; + return Ok(true); + } + None => return Err(SimulatorErrorCode::InternalError.into()), + } + Ok(false) + } + } + + fn wake_after(&mut self, current_time: u64, delay: u64, process: usize) -> Result<(), Halt> { + let time = current_time.checked_add(delay).ok_or_else(|| { + Halt::Error(SimulatorErrorCode::Runtime { + message: format!("process {process} delay overflows simulation time"), + signals: Vec::new(), + }) + })?; + self.process_wakeups.push(Reverse((time, process))); + Ok(()) + } + + fn site_error(process: usize, site: usize) -> Halt { + Halt::Error(SimulatorErrorCode::Runtime { + message: format!("process {process} reported unknown site {site}"), + signals: Vec::new(), + }) + } + + /// Process `process` waits at its wait site `site`: remember what each + /// term compares against from now on. + fn register_waiter(&mut self, backend: &B, process: usize, site: usize) -> Result<(), Halt> { + let terms = self.processes[process] + .wait_sites + .get(site) + .ok_or_else(|| Self::site_error(process, site))?; + let driven = terms.iter().any(|term| term.driven); + self.process_state + .waiters + .register(process, driven, |waiter| { + // Re-arming at the same site reuses the baselines' storage. + let reuse = waiter.site == site && waiter.baselines.len() == terms.len(); + waiter.site = site; + if !reuse { + waiter.baselines.clear(); + waiter + .baselines + .extend(terms.iter().map(|_| Baseline::Value(Value::default()))); + } + for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { + match term.counter { + Some(counter) => { + *baseline = Baseline::Counter { + seen: backend.get_as(counter), + value: read(backend, term.signal), + } + } + None => match planes(backend, term.signal) { + Some(image) => { + if let Baseline::Raw(raw) = baseline { + copy_planes(raw, image, term.signal.width); + } else { + let mut raw = Vec::with_capacity(image.len()); + copy_planes(&mut raw, image, term.signal.width); + *baseline = Baseline::Raw(raw); + } + } + None => *baseline = Baseline::Value(read(backend, term.signal)), + }, + } + } + }); + Ok(()) + } + + /// Move the value staged at nonblocking site `site` of `process` into + /// the ordered queue. + fn queue_nba(&mut self, backend: &mut B, process: usize, site: usize) -> Result<(), Halt> { + let refs = *self.processes[process] + .nba_sites + .get(site) + .ok_or_else(|| Self::site_error(process, site))?; + if let Some(pending) = refs.pending { + // The flag is set: the kernel reached the site again before the + // NBA region and returned before staging over the earlier value. + backend.set(pending, 0u8); + } + let offset = refs + .offset + .map_or(0, |offset| backend.get_as::(offset) as usize); + self.process_state.nba_queue.push(NbaUpdate { + target: refs.target, + lsb: refs.lsb + offset, + width: refs.width, + value: read(backend, refs.value), + }); + Ok(()) + } + + /// Write `signal` on behalf of the runtime, counting a counted signal's + /// occurrences and showing the value to the waits on it. + #[inline] + fn write_signal(&mut self, backend: &mut B, signal: SignalRef, write: impl FnOnce(&mut B)) { + if self.counted.is_empty() && self.process_state.waiters.is_empty() { + write(backend); + return; + } + match self.counted_by_offset.get(&signal.offset).copied() { + Some(counted) => { + let old = read(backend, signal); + write(backend); + let new = read(backend, signal); + self.counted[counted].refs.bump(backend, &old, &new); + } + None => write(backend), + } + if !self.process_state.waiters.is_empty() { + self.observe(backend, Some(signal)); + } + } + + /// Test the waits against the current state, or only their terms on + /// signal `only` after a write of it. Woken processes become ready. + #[inline] + fn observe(&mut self, backend: &B, only: Option) { + self.check_waits(backend, only, false); + } + + /// Like [`Self::observe`], at a point where only design code wrote + /// state: terms on signals that only the host and the scheduler write + /// cannot have changed. + #[inline] + fn observe_driven(&mut self, backend: &B) { + if !self.process_state.waiters.none_driven() { + self.check_waits(backend, None, true); + } + } + + fn check_waits(&mut self, backend: &B, only: Option, driven_only: bool) { + let processes = &self.processes; + let state = StateView::new(backend); + let ProcessState { waiters, ready, .. } = &mut self.process_state; + waiters.retain(driven_only, |process, waiter| { + let terms = &processes[process].wait_sites[waiter.site]; + let mut wake = false; + for (index, term) in terms.iter().enumerate() { + if only.is_some_and(|signal| signal != term.signal) || (driven_only && !term.driven) + { + continue; + } + let baseline = &mut waiter.baselines[index]; + wake |= match baseline { + Baseline::Counter { seen, value } => { + let counted = term + .counter + .is_some_and(|counter| backend.get_as::(counter) != *seen); + let now = read(backend, term.signal); + let changed = occurs(term.kind, value, &now); + *value = now; + counted || changed + } + Baseline::Raw(last) => { + let now = state.planes(term.signal).expect("a plain signal"); + Self::advance(term.kind, last, now, term.signal.width) + } + Baseline::Value(last) => match state.planes(term.signal) { + // A baseline loaded from a state file. + Some(now) => { + let mut raw = encode_planes(last, term.signal.width, now.len()); + let hit = Self::advance(term.kind, &mut raw, now, term.signal.width); + *baseline = Baseline::Raw(raw); + hit + } + None => { + let now = read(backend, term.signal); + let hit = occurs(term.kind, last, &now); + *last = now; + hit + } + }, + }; + } + if wake { + ready.insert(process); + } + !wake + }); + } + + /// Whether the change from the image `last` to `now` is an occurrence of + /// `kind`; `last` becomes `now`. + #[inline] + fn advance(kind: CounterKind, last: &mut Vec, now: &[u8], width: usize) -> bool { + if planes_equal(last, now, width) { + return false; + } + let hit = planes_occur(kind, last, now, width); + copy_planes(last, now, width); + hit + } + + /// Show the waits one value the host wrote to `signal`. + fn observe_host_write(&mut self, signal: SignalRef, value: &Value) { + let processes = &self.processes; + let ProcessState { waiters, ready, .. } = &mut self.process_state; + waiters.retain(false, |process, waiter| { + let terms = &processes[process].wait_sites[waiter.site]; + let mut wake = false; + for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { + if term.signal != signal { + continue; + } + match baseline { + // Counters are bumped by the write itself. + Baseline::Counter { .. } => {} + Baseline::Raw(last) => { + let now = encode_planes(value, signal.width, last.len()); + wake |= Self::advance(term.kind, last, &now, signal.width); + } + Baseline::Value(last) => { + wake |= occurs(term.kind, last, value); + *last = value.clone(); + } + } + } + if wake { + ready.insert(process); + } + !wake + }); + } + + /// Mark the domains whose counters moved since they last triggered. + fn mark_counted_domains(&mut self, backend: &mut B, round: &mut Round) { + for (index, counted) in self.counted.iter().enumerate() { + for &(id, kind) in &counted.domains { + let value: u32 = backend.get_as(counted.refs.counter(kind)); + let seen = &mut self.process_state.domain_counters[index][kind_index(kind)]; + if value != *seen { + *seen = value; + backend.mark_triggered_bit(id); + round.scheduled_trigger_ids.insert(id); + round.counted_triggered.insert(id); + round.track_stable_edges = true; + } + } + } + } + + /// Mark the domains a scheduled or process-driven value of an event + /// signal triggers, against the values of the last settled round. + #[inline] + fn mark_scheduled_edges(&self, backend: &mut B, round: &mut Round, values: &[(usize, bool)]) { + for &(id, is_nonzero) in values { + round.track_stable_edges = true; + // A signal written again compares with its preceding value. + let was_nonzero = + round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); + if was_nonzero != is_nonzero + && self + .combinational_derived + .get(id) + .is_some_and(|derived| !derived.is_empty()) + { + round.gating_sources.push(id); + } + let triggered = match self.domain_kinds[id] { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + !was_nonzero && is_nonzero + } + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + was_nonzero && !is_nonzero + } + _ => !was_nonzero && is_nonzero, + }; + if triggered { + round.scheduled_trigger_ids.insert(id); + backend.mark_triggered_bit(id); + } + } + } + + /// Settle combinational logic after the round's sources changed, and + /// keep the triggers the round considers stable. + #[inline] + fn settle_marked(&mut self, executor: &mut E, round: &mut Round) -> Result<(), Halt> + where + E: SimulationExecutor, + { + executor.eval_comb()?; + if round.track_stable_edges { + // Combinational settling before an active scheduled source domain + // commits may expose transient derived-clock edges. In that case, + // keep only the source event and rediscover stable edges after the + // commit. If the source edge is inactive, preserve derived edges + // while filtering out the scheduled signal's own transition. + if round.scheduled_trigger_ids.is_empty() { + self.replace_triggers_with_stable_edges(executor.backend_mut()); + } else { + executor.backend_mut().clear_triggered_bits(); + for id in round.scheduled_trigger_ids.iter() { + executor.backend_mut().mark_triggered_bit(id); + } + } + // Derived clocks judged at an earlier settle of the round keep + // their edge until their domain evaluates; their baseline + // already moved. + for id in round.edge_approved.iter() { + executor.backend_mut().mark_triggered_bit(id); + } + } + if !round.gating_sources.is_empty() { + self.judge_derived_edges(executor.backend_mut(), round); + } + if !self.counted.is_empty() { + self.mark_counted_domains(executor.backend_mut(), round); + } + Ok(()) + } + + /// Clocks computed from a changed scheduled or process-driven signal, + /// such as `clk & enable`, change at the same instant, in the active + /// region before any nonblocking update (IEEE 1800-2023 4.4.2, 4.5): + /// their edges are judged now, from the state before any domain commits, + /// and their domains evaluate together with the source's. Their levels + /// at this instant become the baseline for the rounds after the commit, + /// where a gate the commit moves (an enable register rising with the + /// edge) gives a further edge, as the update events of the NBA region do. + fn judge_derived_edges(&mut self, backend: &mut B, round: &mut Round) { + for source in std::mem::take(&mut round.gating_sources) { + for &id in self.combinational_derived[source].iter() { + if self.stable_edge_triggered(backend, id) { + backend.mark_triggered_bit(id); + round.edge_approved.insert(id); + } + let Some((signal, _, _)) = self.topo_signals.get(self.signal_index_by_id[id]) + else { + continue; + }; + if event_level(backend, *signal) != 0 { + self.last_clock_values.insert(id); + } else { + self.last_clock_values.remove(id); + } + } + } + } + + fn event_values(&self, backend: &B, values: &mut Vec) { + values.clear(); + values.extend( + self.topo_signals + .iter() + .map(|(signal, _, _)| event_level(backend, *signal)), + ); + } + + /// Run the ready processes in declaration order, including those they + /// wake, recording the event signals each one changes. + fn run_ready( + &mut self, + executor: &mut E, + current_time: u64, + round: &mut Round, + returns: &mut u64, + ) -> Result + where + E: SimulationExecutor, + { + if self.process_state.ready.is_empty() { + return Ok(false); + } + self.event_values(executor.backend(), &mut round.before); + while let Some(process) = self.process_state.ready.pop_first() { + loop { + let again = self.run_process(executor, current_time, process, returns)?; + // Each run is a separate update of the event signals, so a + // pulse across two runs is an edge. + self.record_transitions(executor.backend(), round); + // Before the next run, its edges must be seen. After the last + // one, the check following the settle sees them: a settle + // does not write what processes write. + if again || !self.process_state.ready.is_empty() { + self.observe_driven(executor.backend()); + } + if !again { break; } - None => return Err(SimulatorErrorCode::InternalError), } } - Ok(()) + Ok(true) + } + + /// Record the event signals that changed since `round.before`. + fn record_transitions(&self, backend: &B, round: &mut Round) { + self.event_values(backend, &mut round.after); + for (((_, id, _), &old), &new) in self + .topo_signals + .iter() + .zip(&round.before) + .zip(&round.after) + { + if *id != usize::MAX && old != new { + round.transitions.push((*id, new != 0)); + } + } + std::mem::swap(&mut round.before, &mut round.after); + } + + /// Evaluate the triggered domains before an inactive region runs. Their + /// nonblocking assignments stay in the working state until the NBA + /// region. + fn evaluate_before_inactive( + &mut self, + executor: &mut E, + current_time: u64, + round: &mut Round, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let marked = executor.backend().get_triggered_bits(); + executor.backend_mut().clear_triggered_bits(); + let mut evaluated = BitSet::new(); + let mut unsplit = Vec::new(); + for id in marked.iter() { + let info = self.event_info[id]; + if info.canonical_id == usize::MAX || evaluated.contains(info.canonical_id) { + continue; + } + if info.is_cascaded + && !round.counted_triggered.contains(id) + && !round.edge_approved.contains(id) + && !self.stable_edge_triggered(executor.backend(), id) + { + continue; + } + evaluated.insert(info.canonical_id); + if info.eval_only_event.is_none() { + // Without a separate evaluation unit the domain cannot + // publish later; it evaluates with the remaining domains. + unsplit.push(id); + continue; + } + round.edge_approved.remove(id); + self.evaluate_deferred(executor, current_time, round, info)?; + } + // The edges are consumed: later rounds compare against the values + // they were evaluated at. + self.synchronize_event_values(executor.backend()); + round.begin_scan(self.domain_kinds.len()); + round.scheduled_trigger_ids.make_empty(); + round.counted_triggered.make_empty(); + for id in unsplit { + // The edge stays approved: the new baseline no longer shows it. + executor.backend_mut().mark_triggered_bit(id); + round.scheduled_trigger_ids.insert(id); + round.edge_approved.insert(id); + } + Ok(()) + } + + fn evaluate_deferred( + &mut self, + executor: &mut E, + current_time: u64, + round: &mut Round, + info: EventInfo, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + self.supersede(executor.backend(), round, info.canonical_id); + let Some(event) = info.eval_only_event else { + return Err(SimulatorErrorCode::InternalError.into()); + }; + executor.stage_external_event(info.eval_ff_event.unwrap_or(event), current_time)?; + executor.eval_only_ff_at(event)?; + round.deferred.push((info.canonical_id, None)); + Ok(()) + } + + /// A domain with an unpublished evaluation is evaluated again: keep the + /// earlier evaluation's working state for the NBA region. + fn supersede(&self, backend: &B, round: &mut Round, canonical: usize) { + if let Some((_, image)) = round + .deferred + .iter_mut() + .rev() + .find(|(id, image)| *id == canonical && image.is_none()) + { + *image = Some(working_image(backend)); + } + } + + /// Publish the queued and flagged nonblocking assignments of process + /// kernels (the NBA region, IEEE 1800-2023 4.5). + fn publish_nba(&mut self, executor: &mut E, round: &mut Round) -> bool + where + E: SimulationExecutor, + { + if round.nba_published { + return false; + } + round.nba_published = true; + let flagged = round.kernels_ran && self.has_pending_nba_sites; + if self.process_state.nba_queue.is_empty() && !flagged { + return false; + } + let mut updates = std::mem::take(&mut self.process_state.nba_queue); + if flagged { + let backend = executor.backend_mut(); + for process in &self.processes { + for site in &process.nba_sites { + let Some(pending) = site.pending else { + continue; + }; + if backend.get_as::(pending) == 0 { + continue; + } + backend.set(pending, 0u8); + let offset = site + .offset + .map_or(0, |offset| backend.get_as::(offset) as usize); + updates.push(NbaUpdate { + target: site.target, + lsb: site.lsb + offset, + width: site.width, + value: read(backend, site.value), + }); + } + } + } + if updates.is_empty() { + return false; + } + // Several updates may pulse an event signal: each is an update the + // event domains see, not only the final value. + let several = updates.len() > 1; + if several { + self.event_values(executor.backend(), &mut round.before); + round.transitions.clear(); + } + for update in updates { + let backend = executor.backend_mut(); + let merged = update.merge_into(&read(backend, update.target)); + let target = update.target; + self.write_signal(backend, target, |backend| { + if target.is_4state { + backend.set_four_state(target, merged.0, merged.1); + } else { + backend.set_wide(target, merged.0); + } + }); + if several { + self.record_transitions(executor.backend(), round); + } + } + if several { + let transitions = std::mem::take(&mut round.transitions); + self.mark_occurrences(executor.backend_mut(), round, &transitions); + round.transitions = transitions; + round.transitions.clear(); + } + round.track_stable_edges = true; + true + } + + /// Apply the domains evaluated before an inactive region. + fn apply_deferred(&mut self, executor: &mut E, round: &mut Round) -> Result, Halt> + where + E: SimulationExecutor, + { + let deferred = std::mem::take(&mut round.deferred); + if deferred.is_empty() { + return Ok(Vec::new()); + } + let superseded = deferred.iter().any(|(_, image)| image.is_some()); + if superseded { + // A domain publishes several evaluations, each an update of its + // outputs: waits and event domains see each one. + self.event_values(executor.backend(), &mut round.before); + round.transitions.clear(); + let live = working_image(executor.backend()); + for (id, image) in &deferred { + if let Some(image) = image { + restore_working_image(executor.backend_mut(), image); + if let Some(event) = self.event_info[*id].apply_event { + executor.apply_ff_at(event)?; + } + self.record_transitions(executor.backend(), round); + self.observe_driven(executor.backend()); + } + } + restore_working_image(executor.backend_mut(), &live); + } + let mut applied = Vec::new(); + for (id, image) in deferred { + if image.is_none() { + if let Some(event) = self.event_info[id].apply_event { + executor.apply_ff_at(event)?; + } + applied.push(id); + } + } + // The domains' last evaluations may still publish with the NBA + // region: their edges are marked once that is done. + round.publishing = superseded; + Ok(applied) + } + + /// After the NBA region of a round in which a domain published several + /// evaluations: see the last publication and mark the domains the + /// edges among all of them trigger. + fn finish_publications(&self, backend: &mut B, round: &mut Round) { + if !std::mem::take(&mut round.publishing) { + return; + } + self.record_transitions(backend, round); + let transitions = std::mem::take(&mut round.transitions); + self.mark_occurrences(backend, round, &transitions); + round.transitions = transitions; + round.transitions.clear(); + } + + /// Mark the domains that edges among `transitions` trigger, even if the + /// signals end at their old values, and keep them marked through the + /// settles of this round. + fn mark_occurrences(&self, backend: &mut B, round: &mut Round, transitions: &[(usize, bool)]) { + for &(id, is_nonzero) in transitions { + let was_nonzero = + round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); + let triggered = match self.domain_kinds[id] { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + !was_nonzero && is_nonzero + } + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + was_nonzero && !is_nonzero + } + _ => was_nonzero != is_nonzero, + }; + if triggered { + round.occurrences.insert(id); + round.scheduled_trigger_ids.insert(id); + round.track_stable_edges = true; + backend.mark_triggered_bit(id); + } + } + } + + /// The process phase of a round: the active and inactive regions before + /// any domain publishes (IEEE 1800-2023 4.5). Without ready processes, + /// waits or counted signals this is one settle, the batch step's. + fn process_phase( + &mut self, + executor: &mut E, + current_time: u64, + round: &mut Round, + mut entry: bool, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let mut returns = 0; + let mut first = true; + loop { + self.charge_pass()?; + // 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. + let ran = self.run_ready(executor, current_time, round, &mut returns)?; + round.kernels_ran |= ran; + if first || ran { + let transitions = std::mem::take(&mut round.transitions); + self.mark_scheduled_edges(executor.backend_mut(), round, &transitions); + round.transitions = transitions; + round.transitions.clear(); + self.settle_marked(executor, round)?; + first = false; + } + if entry { + // Scheduled and host values, including raw writes of the + // host's view of the state, and what the settle derived. + entry = false; + if !self.process_state.waiters.is_empty() { + self.observe(executor.backend(), None); + } + } else { + self.observe_driven(executor.backend()); + } + if !self.process_state.ready.is_empty() { + continue; + } + if self.process_state.inactive.is_empty() { + return Ok(()); + } + // The active region is empty: the domains it triggered evaluate + // before the inactive region's processes resume. + self.evaluate_before_inactive(executor, current_time, round)?; + let inactive = std::mem::take(&mut self.process_state.inactive); + self.process_state.ready.extend(inactive); + } } /// Whether a process requested the end of the simulation. @@ -392,23 +1363,71 @@ impl SimulationState { where E: SimulationExecutor, { - self.step_round(executor, time, Vec::new(), Vec::new())?; - executor.finish_timed_step(time); - Ok(Some(time)) + self.slot_passes = 0; + match self.step_round(executor, time, Vec::new(), Vec::new(), true) { + Ok(()) => { + executor.finish_timed_step(time); + Ok(Some(time)) + } + Err(Halt::Finish) => { + executor.finish_timed_step(time); + self.finish(executor); + Ok(Some(self.scheduler.time)) + } + Err(Halt::Error(error)) => Err(error), + } } - /// Apply `events_to_process`, run `ready_processes`, and settle the + /// The host changed state since the last step: note whether the next + /// step must settle the current time first because an event signal + /// changed or a process may be woken. + pub fn note_host_writes(&mut self, backend: &B, logged: bool) { + if self.finished { + return; + } + // With waiting processes or counted signals, a write may reach a + // waited or counted signal through combinational logic that has not + // settled yet; only settling the current time tells. Processes that + // finished or wait for a time do not see it. + if logged || !self.process_state.waiters.is_empty() || !self.counted.is_empty() { + self.host_pending = true; + return; + } + // Otherwise only an event signal's change needs the current time. + for (signal, id, _) in &self.topo_signals { + if *id != usize::MAX + && (event_level(backend, *signal) != 0) != self.last_clock_values.contains(*id) + { + self.host_pending = true; + return; + } + } + } + + /// Apply `events_to_process`, run the ready processes, and settle the /// edges they cause. + /// + /// A round is the batch step of a time slot with a process phase in + /// front of the flip-flop domains (IEEE 1800-2023 4.5): processes run + /// in the active region, the domains they and the scheduled values + /// trigger evaluate, zero-delay processes run in the inactive region, + /// and only then are nonblocking assignments published. A round + /// without ready processes and counted signals does exactly the batch + /// step. fn step_round( &mut self, executor: &mut E, current_time: u64, events_to_process: Vec>, ready_processes: Vec, - ) -> Result<(), SimulatorErrorCode> + entry: bool, + ) -> Result<(), Halt> where E: SimulationExecutor, { + if !self.timed { + return self.batch_round(executor, current_time, events_to_process); + } self.scheduler.time = current_time; // Keep periodic provenance private so the public SimEvent shape stays @@ -439,33 +1458,335 @@ impl SimulationState { "periodic event sidecar fell behind the scheduler" ); + let timed = self.timed; + if timed { + // Host writes the waits must see one at a time. + for (signal, value) in executor.take_host_writes() { + self.observe_host_write(signal, &value); + } + } + let num_events = executor.backend().num_events(); - for event in &events_to_process { - executor.backend_mut().set(event.signal, event.next_val); + for (index, event) in events_to_process.iter().enumerate() { + let signal = event.signal; + let value = event.next_val; + if !timed { + executor.backend_mut().set(signal, value); + continue; + } + if let Some(&counted) = self.counted_by_offset.get(&signal.offset) { + let backend = executor.backend_mut(); + let old = read(backend, signal); + backend.set(signal, value); + let new = read(backend, signal); + self.counted[counted].refs.bump(backend, &old, &new); + } else { + executor.backend_mut().set(signal, value); + } + // A signal the batch writes again pulses: its waits see each + // value. Otherwise one check after the batch sees the edge. + if !self.process_state.waiters.is_empty() + && events_to_process[index + 1..] + .iter() + .any(|later| later.signal == signal) + { + self.observe(executor.backend(), Some(signal)); + } + } + if timed && !self.process_state.waiters.is_empty() && !events_to_process.is_empty() { + // The scheduled values wake their processes before the process + // phase runs. + self.observe(executor.backend(), None); } - // 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. - let mut process_driven = Vec::new(); - if !ready_processes.is_empty() { - let before: Vec = self - .topo_signals - .iter() - .map(|(signal, _, _)| event_level(executor.backend(), *signal)) - .collect(); - self.run_processes(executor, current_time, ready_processes)?; - for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { - if *id == usize::MAX { + let mut round = self.scratch.take().unwrap_or_default(); + round.reset(events_to_process.is_empty()); + round.begin_scan(self.domain_kinds.len()); + if timed { + self.process_state.ready.extend(ready_processes); + } + executor.backend_mut().clear_triggered_bits(); + // 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. + round + .transitions + .extend(events_to_process.iter().filter_map(|event| { + self.signal_to_id + .get(&event.signal) + .map(|&id| (id, event.next_val != 0)) + })); + + if timed { + // The check after the batch already saw every signal. + let entry = entry && events_to_process.is_empty(); + self.process_phase(executor, current_time, &mut round, entry)?; + } else { + let transitions = std::mem::take(&mut round.transitions); + self.mark_scheduled_edges(executor.backend_mut(), &mut round, &transitions); + round.transitions = transitions; + self.settle_marked(executor, &mut round)?; + } + + let mut triggered_domains = BitSet::with_capacity(num_events); + let mut discovered_in_this_step = BitSet::with_capacity(num_events); + let mut comb_already_done = false; + let mut deferred_pending = !round.deferred.is_empty(); + loop { + let mut any_new_outer_loop_trigger = false; + let mut newly_triggered = Vec::new(); + + loop { + let mut any_new_sequential_trigger = false; + let marked_bits = executor.backend().get_triggered_bits(); + executor.backend_mut().clear_triggered_bits(); + + let mut can_use_eval_apply = + !deferred_pending && triggered_domains.is_empty() && marked_bits.count() == 1; + if can_use_eval_apply { + let single_id = marked_bits.iter().next().expect("one marked trigger"); + let info = self.event_info[single_id]; + can_use_eval_apply = !info.is_cascaded; + if can_use_eval_apply { + if let Some(event) = info.eval_ff_event { + discovered_in_this_step.insert(single_id); + triggered_domains.insert(info.canonical_id); + any_new_outer_loop_trigger = true; + executor.stage_external_event(event, current_time)?; + executor.eval_apply_ff_at(event)?; + executor.fire_external_event(event, current_time)?; + if timed { + self.publish_nba(executor, &mut round); + } + executor.eval_comb()?; + if round.track_stable_edges { + self.replace_triggers_with_stable_edges(executor.backend_mut()); + // Pulses of the publications end where they + // started; the filter cannot see them. + for id in round.occurrences.iter() { + executor.backend_mut().mark_triggered_bit(id); + } + } + if !self.counted.is_empty() { + self.mark_counted_domains(executor.backend_mut(), &mut round); + } + if timed { + // Each update is seen by the waits on it + // (IEEE 1800-2023 4.5). + self.observe_driven(executor.backend()); + } + comb_already_done = true; + break; + } + } + } + + for id in marked_bits.iter() { + if discovered_in_this_step.contains(id) { + continue; + } + let info = self.event_info[id]; + if triggered_domains.contains(info.canonical_id) { + continue; + } + // Native trigger bits can be coarse hints raised by a + // working-region write before its commit. A derived clock + // must have the requested stable edge before its FFs run. + if info.is_cascaded + && !round.counted_triggered.contains(id) + && !round.occurrences.contains(id) + && !round.edge_approved.contains(id) + && !self.stable_edge_triggered(executor.backend(), id) + { + continue; + } + discovered_in_this_step.insert(id); + triggered_domains.insert(info.canonical_id); + any_new_sequential_trigger = true; + newly_triggered.push(info.canonical_id); + + if !round.deferred.is_empty() { + self.supersede(executor.backend(), &mut round, info.canonical_id); + } + if let Some(event) = info.eval_only_event { + executor.stage_external_event( + info.eval_ff_event.unwrap_or(event), + current_time, + )?; + executor.eval_only_ff_at(event)?; + } else if let Some(event) = info.eval_ff_event { + executor.stage_external_event(event, current_time)?; + executor.eval_apply_ff_at(event)?; + } else { + unreachable!( + "FF trigger discovered without a corresponding execution unit" + ); + } + } + + if !any_new_sequential_trigger { + break; + } + } + + let mut published = false; + if deferred_pending { + deferred_pending = false; + // Domains evaluated before an inactive region that did not + // trigger again publish with this NBA region. + for id in self.apply_deferred(executor, &mut round)? { + if !newly_triggered.contains(&id) + && let Some(event) = self.event_info[id].eval_ff_event + { + executor.fire_external_event(event, current_time)?; + } + } + published = true; + } + + if newly_triggered.is_empty() && !any_new_outer_loop_trigger { + if published { + self.finish_publications(executor.backend_mut(), &mut round); + self.observe_driven(executor.backend()); + } + // The NBA region still publishes the processes' assignments, + // which may trigger further domains. + if (timed && self.publish_nba(executor, &mut round)) || published { + self.settle_marked(executor, &mut round)?; continue; } - let value = event_level(executor.backend(), *signal); - if value != before { - process_driven.push((*id, value != 0)); + break; + } + + for id in &newly_triggered { + if let Some(event) = self.event_info[*id].apply_event { + executor.apply_ff_at(event)?; + } + } + if round.publishing { + self.finish_publications(executor.backend_mut(), &mut round); + self.observe_driven(executor.backend()); + } + for id in &newly_triggered { + if let Some(event) = self.event_info[*id].eval_ff_event { + executor.fire_external_event(event, current_time)?; + } + } + if timed { + self.publish_nba(executor, &mut round); + } + + if comb_already_done { + comb_already_done = false; + } else { + executor.eval_comb()?; + if round.track_stable_edges { + self.replace_triggers_with_stable_edges(executor.backend_mut()); + for id in round.occurrences.iter() { + executor.backend_mut().mark_triggered_bit(id); + } + } + if !self.counted.is_empty() { + self.mark_counted_domains(executor.backend_mut(), &mut round); + } + if timed { + // A combinational value between two waves of domains is + // an update the waits see (IEEE 1800-2023 4.5). + self.observe_driven(executor.backend()); } } } + for (signal, id, _) in &self.topo_signals { + if *id == usize::MAX { + continue; + } + if event_level(executor.backend(), *signal) != 0 { + self.last_clock_values.insert(*id); + } else { + self.last_clock_values.remove(*id); + } + } + + // Processes the published values wake run in the next round. + if timed { + self.observe_driven(executor.backend()); + } + + for event in periodic_events_to_process { + let event_id = event.event_ref.id(); + if let Some(Some(clock)) = self.scheduler.clocks.get(event_id) { + // Keep the extra odd-period tick in the high phase, matching + // the process/testbench clock model. + // A clock needs at least one time unit in each phase. + let period = clock.period.max(2); + let half = (period / 2) + ((period & 1) & u64::from(event.next_val != 0)); + let time = current_time.checked_add(half).ok_or_else(|| { + Halt::Error(SimulatorErrorCode::Runtime { + message: format!("event {event_id} overflows simulation time"), + signals: Vec::new(), + }) + })?; + self.push_periodic_event(SimEvent { + time, + event_ref: event.event_ref, + signal: event.signal, + next_val: 1 - event.next_val, + }); + } + } + + self.scratch = Some(round); + Ok(()) + } + + /// The round of a design without processes and counted signals: the + /// batch step as it was before process rounds, kept apart from + /// [`Self::step_round`] so that such designs run its code unchanged. + fn batch_round( + &mut self, + executor: &mut E, + current_time: u64, + events_to_process: Vec>, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + self.scheduler.time = current_time; + + // Keep periodic provenance private so the public SimEvent shape stays + // stable. Consume matching sidecar counts before fallible work so an + // execution error cannot leave a stale periodic marker behind. + let mut periodic_events_to_process: Vec> = Vec::new(); + for event in &events_to_process { + let key = PeriodicEventKey::from_event(event); + let mut remove_key = false; + if let Some(count) = self.periodic_events.get_mut(&key) { + periodic_events_to_process.push(SimEvent { + time: event.time, + event_ref: event.event_ref, + signal: event.signal, + next_val: event.next_val, + }); + *count -= 1; + remove_key = *count == 0; + } + if remove_key { + self.periodic_events.remove(&key); + } + } + debug_assert!( + self.periodic_events + .keys() + .all(|event| event.time > current_time), + "periodic event sidecar fell behind the scheduler" + ); + + let num_events = executor.backend().num_events(); + for event in &events_to_process { + executor.backend_mut().set(event.signal, event.next_val); + } + let mut triggered_domains = BitSet::with_capacity(num_events); let mut discovered_in_this_step = BitSet::with_capacity(num_events); let mut scheduled_trigger_ids = BitSet::with_capacity(num_events); @@ -475,14 +1796,11 @@ impl SimulationState { let mut track_stable_edges = events_to_process.is_empty(); executor.backend_mut().clear_triggered_bits(); - let scheduled = events_to_process - .iter() - .filter_map(|event| { - self.signal_to_id - .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) - }) - .chain(process_driven); + let scheduled = events_to_process.iter().filter_map(|event| { + self.signal_to_id + .get(&event.signal) + .map(|&id| (id, event.next_val != 0)) + }); // Scheduled signals that changed level and gate derived clocks. let mut gating_sources = Vec::new(); for (id, is_nonzero) in scheduled { @@ -678,13 +1996,12 @@ impl SimulationState { // A clock needs at least one time unit in each phase. let period = clock.period.max(2); let half = (period / 2) + ((period & 1) & u64::from(event.next_val != 0)); - let time = - current_time - .checked_add(half) - .ok_or_else(|| SimulatorErrorCode::Runtime { - message: format!("event {event_id} overflows simulation time"), - signals: Vec::new(), - })?; + let time = current_time.checked_add(half).ok_or_else(|| { + Halt::Error(SimulatorErrorCode::Runtime { + message: format!("event {event_id} overflows simulation time"), + signals: Vec::new(), + }) + })?; self.push_periodic_event(SimEvent { time, event_ref: event.event_ref, @@ -711,6 +2028,21 @@ impl SimulationState { if self.finished { return None; } + // Host writes are work of the current time. + if self.host_pending { + return Some(self.scheduler.time); + } + self.next_work_time() + } + + /// The next time with scheduled events or processes to run. + fn next_work_time(&self) -> Option { + if self.finished { + return None; + } + if !self.process_state.ready.is_empty() { + return Some(self.scheduler.time); + } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); match (self.scheduler.next_event_time(), process) { (Some(event), Some(process)) => Some(event.min(process)), @@ -738,6 +2070,8 @@ impl SimulationState { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + process_state: self.process_state.clone(), + host_pending: self.host_pending, finished: self.finished, } } @@ -771,6 +2105,8 @@ impl SimulationState { self.last_clock_values .clone_from(&snapshot.last_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); + self.process_state.clone_from(&snapshot.process_state); + self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; Ok(()) } @@ -791,6 +2127,11 @@ pub struct ScheduleParts { pub high_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, + /// Waiting and ready processes, queued nonblocking assignments and the + /// counter values counted domains last triggered on. + pub process_state: ProcessState, + /// The host changed state the next step settles at the current time. + pub host_pending: bool, /// A process requested the end of the simulation. pub finished: bool, } @@ -834,6 +2175,8 @@ impl SimulationState { wakeups.sort_unstable(); wakeups }, + process_state: self.process_state.clone(), + host_pending: self.host_pending, finished: self.finished, } } @@ -865,6 +2208,8 @@ impl SimulationState { .into_iter() .map(|(process, time)| Reverse((time, process))) .collect(); + self.process_state = parts.process_state; + self.host_pending = parts.host_pending; self.finished = parts.finished; } } @@ -877,6 +2222,8 @@ pub struct SimulationSnapshot { periodic_events: FxHashMap, last_clock_values: BitSet, process_wakeups: BinaryHeap, + process_state: ProcessState, + host_pending: bool, finished: bool, } @@ -889,6 +2236,8 @@ impl Clone for SimulationSnapshot { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + process_state: self.process_state.clone(), + host_pending: self.host_pending, finished: self.finished, } } @@ -900,3 +2249,20 @@ impl SimulationSnapshot { self.time } } + +/// The working and sparse working state: the next-state values of +/// evaluated but unpublished flip-flop domains. +fn working_image(backend: &B) -> Vec { + let layout = backend.layout(); + let range = layout.working_base_offset..layout.triggered_bits_offset; + let (ptr, len) = backend.memory_as_ptr(); + assert!(range.end <= len, "working state exceeds the memory image"); + // Safety: the backend exposes `len` readable bytes at `ptr`. + let memory = unsafe { std::slice::from_raw_parts(ptr, len) }; + memory[range].to_vec() +} + +fn restore_working_image(backend: &mut B, image: &[u8]) { + let offset = backend.layout().working_base_offset; + backend.write_memory(offset, image); +} diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index af5e4737441..0a7b177353f 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -19,14 +19,32 @@ //! 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 +//! processes (version 2): +//! wakeup count u32, then per wakeup: process str | time u64 +//! waiter count u32, then per waiter: +//! process str | site u64 | baseline count u32, then per baseline: +//! 0 u8 | counter u32 | value bytes | mask bytes, or +//! 1 u8 | value bytes | mask bytes +//! ready count u32, then per process: process str +//! inactive count u32, then per process: process str +//! update count u32, then per update: +//! target str | lsb u64 | width u64 | value bytes | mask bytes +//! counted count u32, then per signal: signal str | 3 × counter u32 +//! write count u32, then per host write: signal str | value bytes | mask bytes +//! host pending u8 | finished u8 //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 +//! bytes: byte length u32 | little-endian bytes //! ``` +//! +//! Version 1 files, which have no process section, still load. A file whose +//! processes have nothing to record is written as version 1, which older +//! builds read too. 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 +95,69 @@ pub struct ScheduleRecord { pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. pub high_events: Vec, + /// Scheduling state of the design's processes. + pub processes: ProcessRecord, +} + +/// Scheduling state of process kernels, by name. A process is named by the +/// path of its status slot, a signal by its state object path. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ProcessRecord { + /// Suspended processes and the time each resumes at. + pub wakeups: Vec<(String, u64)>, + /// Processes suspended at a wait. + pub waiters: Vec, + /// Processes ready in the active region of the current time. + pub ready: Vec, + /// Processes resuming in the inactive region of the current time. + pub inactive: Vec, + /// Queued nonblocking assignments, in issue order. + pub nba_queue: Vec, + /// Counter values each counted domain last triggered on, by counted + /// signal, in changes/rises/falls order. + pub domain_counters: Vec<(String, [u32; 3])>, + /// Values the host wrote to waited signals that the next step has yet + /// to show the waits, in write order: signal, value and mask bytes. + pub host_writes: Vec<(String, Vec, Vec)>, + /// The host changed state the next step settles at the current time. + pub host_pending: bool, + /// A process finished the simulation. + pub finished: bool, +} + +/// A process suspended at a wait. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WaiterRecord { + pub process: String, + /// Index of the wait site among the process's sites. + pub site: u64, + /// What each term of the site compares against. + pub baselines: Vec, +} + +/// What one term of a waiting process compares against. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BaselineRecord { + /// A counted signal's counter value when the wait began, and its value + /// at the last check as little-endian bytes. + Counter { + seen: u32, + value: Vec, + mask: Vec, + }, + /// The signal's value at the last check, as little-endian bytes. + Value { value: Vec, mask: Vec }, +} + +/// A queued nonblocking assignment. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NbaRecord { + pub target: String, + pub lsb: u64, + pub width: u64, + /// Little-endian bytes of the assigned value and its unknown bits. + pub value: Vec, + pub mask: Vec, } /// Contents of a state file. @@ -119,7 +200,12 @@ impl StateFile { pub fn write_to(&self, mut writer: impl Write) -> io::Result<()> { let w = &mut writer; w.write_all(MAGIC)?; - put_u16(w, VERSION)?; + let processes = self + .schedule + .as_ref() + .map(|schedule| &schedule.processes) + .filter(|processes| **processes != ProcessRecord::default()); + put_u16(w, if processes.is_some() { VERSION } else { 1 })?; let mut flags = 0; if self.four_state { flags |= FLAG_FOUR_STATE; @@ -168,6 +254,9 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } + if let Some(processes) = processes { + put_processes(w, processes)?; + } } Ok(()) } @@ -180,7 +269,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,12 +322,18 @@ impl StateFile { let high_events = (0..get_u32(r)?) .map(|_| get_str(r)) .collect::>()?; + let processes = if version >= 2 { + get_processes(r)? + } else { + ProcessRecord::default() + }; Some(ScheduleRecord { time, clocks, events, periodic, high_events, + processes, }) } else { None @@ -349,6 +444,153 @@ fn put_event(w: &mut impl Write, event: &ScheduledEvent) -> io::Result<()> { w.write_all(&[event.value]) } +fn put_bytes(w: &mut impl Write, bytes: &[u8]) -> io::Result<()> { + put_len(w, bytes.len())?; + w.write_all(bytes) +} + +fn put_names(w: &mut impl Write, names: &[String]) -> io::Result<()> { + put_len(w, names.len())?; + names.iter().try_for_each(|name| put_str(w, name)) +} + +fn put_processes(w: &mut impl Write, processes: &ProcessRecord) -> io::Result<()> { + put_len(w, processes.wakeups.len())?; + for (process, time) in &processes.wakeups { + put_str(w, process)?; + put_u64(w, *time)?; + } + put_len(w, processes.waiters.len())?; + for waiter in &processes.waiters { + put_str(w, &waiter.process)?; + put_u64(w, waiter.site)?; + put_len(w, waiter.baselines.len())?; + for baseline in &waiter.baselines { + match baseline { + BaselineRecord::Counter { seen, value, mask } => { + w.write_all(&[0])?; + w.write_all(&seen.to_le_bytes())?; + put_bytes(w, value)?; + put_bytes(w, mask)?; + } + BaselineRecord::Value { value, mask } => { + w.write_all(&[1])?; + put_bytes(w, value)?; + put_bytes(w, mask)?; + } + } + } + } + put_names(w, &processes.ready)?; + put_names(w, &processes.inactive)?; + put_len(w, processes.nba_queue.len())?; + for update in &processes.nba_queue { + put_str(w, &update.target)?; + put_u64(w, update.lsb)?; + put_u64(w, update.width)?; + put_bytes(w, &update.value)?; + put_bytes(w, &update.mask)?; + } + put_len(w, processes.domain_counters.len())?; + for (signal, counters) in &processes.domain_counters { + put_str(w, signal)?; + for counter in counters { + w.write_all(&counter.to_le_bytes())?; + } + } + put_len(w, processes.host_writes.len())?; + for (signal, value, mask) in &processes.host_writes { + put_str(w, signal)?; + put_bytes(w, value)?; + put_bytes(w, mask)?; + } + w.write_all(&[processes.host_pending as u8, processes.finished as u8]) +} + +fn get_flag(r: &mut impl Read) -> Result { + let mut flag = [0; 1]; + r.read_exact(&mut flag)?; + match flag[0] { + 0 => Ok(false), + 1 => Ok(true), + other => Err(StateFileError::Malformed(format!("flag {other}"))), + } +} + +fn get_len_bytes(r: &mut impl Read) -> Result, StateFileError> { + let len = get_u32(r)? as usize; + Ok(get_bytes(r, len)?) +} + +fn get_names(r: &mut impl Read) -> Result, StateFileError> { + (0..get_u32(r)?).map(|_| get_str(r)).collect() +} + +fn get_processes(r: &mut impl Read) -> Result { + let wakeups = (0..get_u32(r)?) + .map(|_| Ok((get_str(r)?, get_u64(r)?))) + .collect::>()?; + let waiters = (0..get_u32(r)?) + .map(|_| { + let process = get_str(r)?; + let site = get_u64(r)?; + let baselines = (0..get_u32(r)?) + .map(|_| { + let mut tag = [0; 1]; + r.read_exact(&mut tag)?; + match tag[0] { + 0 => Ok(BaselineRecord::Counter { + seen: get_u32(r)?, + value: get_len_bytes(r)?, + mask: get_len_bytes(r)?, + }), + 1 => Ok(BaselineRecord::Value { + value: get_len_bytes(r)?, + mask: get_len_bytes(r)?, + }), + other => Err(StateFileError::Malformed(format!("baseline {other}"))), + } + }) + .collect::>()?; + Ok(WaiterRecord { + process, + site, + baselines, + }) + }) + .collect::>()?; + let ready = get_names(r)?; + let inactive = get_names(r)?; + let nba_queue = (0..get_u32(r)?) + .map(|_| { + Ok(NbaRecord { + target: get_str(r)?, + lsb: get_u64(r)?, + width: get_u64(r)?, + value: get_len_bytes(r)?, + mask: get_len_bytes(r)?, + }) + }) + .collect::>()?; + let domain_counters = (0..get_u32(r)?) + .map(|_| Ok((get_str(r)?, [get_u32(r)?, get_u32(r)?, get_u32(r)?]))) + .collect::>()?; + let host_writes = (0..get_u32(r)?) + .map(|_| Ok((get_str(r)?, get_len_bytes(r)?, get_len_bytes(r)?))) + .collect::>()?; + Ok(ProcessRecord { + wakeups, + waiters, + ready, + inactive, + nba_queue, + domain_counters, + host_writes, + host_pending: get_flag(r)?, + finished: get_flag(r)?, + }) +} + fn get_u16(r: &mut impl Read) -> io::Result { let mut bytes = [0; 2]; r.read_exact(&mut bytes)?; @@ -440,10 +682,55 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], + processes: ProcessRecord { + wakeups: vec![("$process[0].status".into(), 20)], + waiters: vec![WaiterRecord { + process: "$process[1].status".into(), + site: 2, + baselines: vec![ + BaselineRecord::Counter { + seen: 7, + value: vec![2], + mask: vec![0], + }, + BaselineRecord::Value { + value: vec![1], + mask: vec![0], + }, + ], + }], + ready: vec!["$process[2].status".into()], + inactive: vec!["$process[3].status".into()], + nba_queue: vec![NbaRecord { + target: "q".into(), + lsb: 2, + width: 3, + value: vec![5], + mask: vec![2], + }], + domain_counters: vec![("clk".into(), [1, 2, 3])], + host_writes: vec![("go".into(), vec![1], vec![])], + host_pending: true, + finished: false, + }, }), } } + #[test] + fn files_without_process_state_are_version_1() { + let mut file = sample(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(bytes[8..10], 2u16.to_le_bytes()); + file.schedule.as_mut().unwrap().processes = ProcessRecord::default(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + // Version 1 ends after the high events. + assert_eq!(bytes[8..10], 1u16.to_le_bytes()); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + #[test] fn round_trips() { let file = sample(); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs new file mode 100644 index 00000000000..f0e3888890e --- /dev/null +++ b/crates/celox-runtime/src/timing.rs @@ -0,0 +1,617 @@ +//! Process waits, counted signals and nonblocking assignments of process +//! kernels. +//! +//! Most watched signals change at most once between two points at which the +//! runtime checks them, so a wait compares values: it remembers the value +//! of each of its signals when it began and tests every later value against +//! the edge it waits for (IEEE 1800-2023 9.4.2, Table 9-2). A *counted* +//! signal may change several times without a check in between; the code +//! that writes it counts each occurrence, and a wait on it compares +//! counters instead. + +use celox_design::CounterKind; +use fxhash::{FxHashMap, FxHashSet}; +use num_bigint::BigUint; + +use crate::{SignalRef, SimulatorErrorCode, backend::SimBackend}; + +/// Why a simulation stopped executing before completing the work it was +/// given: the design finished the simulation, or an error occurred. +#[derive(Debug, Clone, PartialEq)] +pub enum Halt { + /// `$finish`: the simulation ends where it is (IEEE 1800-2023 20.2). + Finish, + Error(SimulatorErrorCode), +} + +impl From for Halt { + fn from(error: SimulatorErrorCode) -> Self { + Self::Error(error) + } +} + +/// A four-state value: payload and unknown-bit mask. +pub type Value = (BigUint, BigUint); + +pub(crate) fn read(backend: &B, signal: SignalRef) -> Value { + if signal.is_4state { + backend.get_four_state(signal) + } else { + (backend.get(signal), BigUint::default()) + } +} + +/// Whether the change from `old` to `new` is an occurrence of `kind`. +pub fn occurs(kind: CounterKind, old: &Value, new: &Value) -> bool { + if kind == CounterKind::Changes { + return old != new; + } + let bit = |value: &Value| (value.0.bit(0), value.1.bit(0)); + edge(kind, bit(old), bit(new)) +} + +/// Whether a least significant bit changing from `old` to `new`, each a +/// value and an unknown flag, is an edge of `kind`. +#[inline] +fn edge( + kind: CounterKind, + (old_value, old_unknown): (bool, bool), + (new_value, new_unknown): (bool, bool), +) -> bool { + if (old_value, old_unknown) == (new_value, new_unknown) { + return false; + } + let (from, to) = if kind == CounterKind::Rises { + (false, true) + } else { + (true, false) + }; + // Table 9-2: a positive edge leaves 0 or reaches 1, a negative edge + // leaves 1 or reaches 0. + (!old_unknown && old_value == from) || (!new_unknown && new_value == to) +} + +/// Occurrence counters of a counted signal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CountedRefs { + pub signal: SignalRef, + pub changes: SignalRef, + pub rises: SignalRef, + pub falls: SignalRef, +} + +impl CountedRefs { + pub fn counter(&self, kind: CounterKind) -> SignalRef { + match kind { + CounterKind::Changes => self.changes, + CounterKind::Rises => self.rises, + CounterKind::Falls => self.falls, + } + } + + /// Count the occurrences of a change from `old` to `new`. + pub fn bump(&self, backend: &mut B, old: &Value, new: &Value) { + for kind in CounterKind::ALL { + if occurs(kind, old, new) { + let counter = self.counter(kind); + let value: u32 = backend.get_as(counter); + backend.set(counter, value.wrapping_add(1)); + } + } + } +} + +/// Host writes the runtime must observe one at a time: writes of counted +/// signals bump their counters, and writes of signals a wait watches are +/// logged for the waits to examine. Empty unless a timed simulation with +/// such signals is attached, so ordinary writes pay one emptiness check. +#[derive(Clone, Debug, Default)] +pub struct HostWatch { + counted: FxHashMap, + waited: FxHashSet, + log: Vec<(SignalRef, Value)>, +} + +impl HostWatch { + pub fn new(counted: impl IntoIterator, waited: FxHashSet) -> Self { + Self { + counted: counted + .into_iter() + .map(|refs| (refs.signal.offset, refs)) + .collect(), + waited, + log: Vec::new(), + } + } + + pub fn is_empty(&self) -> bool { + self.counted.is_empty() && self.waited.is_empty() + } + + /// Run `write`, which writes `signal` in `backend`, and observe it. + pub fn write( + &mut self, + backend: &mut B, + signal: SignalRef, + write: impl FnOnce(&mut B), + ) { + let counted = self.counted.get(&signal.offset).copied(); + let waited = self.waited.contains(&signal.offset); + if counted.is_none() && !waited { + write(backend); + return; + } + let old = read(backend, signal); + write(backend); + let new = read(backend, signal); + if let Some(counted) = counted { + counted.bump(backend, &old, &new); + } + if waited && old != new { + self.log.push((signal, new)); + } + } + + /// The logged values of waited signals, in write order. + pub fn log(&self) -> &[(SignalRef, Value)] { + &self.log + } + + /// Replace the log, as when returning to a saved state. + pub fn set_log(&mut self, log: Vec<(SignalRef, Value)>) { + self.log = log; + } + + /// Take the logged values of waited signals, in write order. + pub fn take_log(&mut self) -> Vec<(SignalRef, Value)> { + std::mem::take(&mut self.log) + } + + pub fn has_log(&self) -> bool { + !self.log.is_empty() + } +} + +/// One term of a wait site. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TermRefs { + pub signal: SignalRef, + pub kind: CounterKind, + /// The counter of `kind`, if the signal is counted. + pub counter: Option, + /// Design code may write the signal. Otherwise only the host and the + /// scheduler do, and the runtime checks the term only where they write. + pub driven: bool, +} + +/// A nonblocking assignment site. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NbaSiteRefs { + pub target: SignalRef, + pub lsb: usize, + pub width: usize, + pub value: SignalRef, + pub offset: Option, + pub pending: Option, +} + +/// Control slots and sites of one process kernel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProcessRefs { + pub status: SignalRef, + pub delay: SignalRef, + /// Wait sites by local index: their terms. + pub wait_sites: Vec>, + /// Nonblocking sites by local index. + pub nba_sites: Vec, +} + +impl ProcessRefs { + /// A process without wait or nonblocking sites. + pub fn new(status: SignalRef, delay: SignalRef) -> Self { + Self { + status, + delay, + wait_sites: Vec::new(), + nba_sites: Vec::new(), + } + } +} + +/// A counted signal and the canonical event domains its counters trigger. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CountedDomainRefs { + pub refs: CountedRefs, + /// Event ids and the counter that triggers each. + pub domains: Vec<(usize, CounterKind)>, +} + +/// What one term of a waiting process compares against. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Baseline { + /// The counter's value when the wait began, and the signal's value at + /// the last check. Only kernels and combinational process units count a + /// signal's writes, so a write the counter misses, such as one of a + /// continuous assignment to other bits, shows as a change of value. + Counter { seen: u32, value: Value }, + /// The signal's value at the last check. + Value(Value), + /// The signal's state at the last check, as the bytes of its planes + /// (see [`planes`]) with the bits above its width cleared. Checks + /// compare it with the state in place. + Raw(Vec), +} + +/// The state of a signal without unpacked dimensions: the bytes of its +/// value plane followed, for a four-state signal in a four-state layout, by +/// those of its mask plane. `None` for an unpacked array. +pub fn planes(backend: &B, signal: SignalRef) -> Option<&[u8]> { + StateView::new(backend).planes(signal) +} + +/// The state image of a backend, read without going through the backend +/// for every signal. +pub struct StateView<'a> { + memory: &'a [u8], + four_state: bool, +} + +impl<'a> StateView<'a> { + pub fn new(backend: &'a B) -> Self { + let (ptr, size) = backend.memory_as_ptr(); + Self { + // Safety: the backend exposes `size` readable bytes at `ptr` for + // as long as it is borrowed. + memory: unsafe { std::slice::from_raw_parts(ptr, size) }, + four_state: backend.layout().four_state, + } + } + + /// See [`planes`]. + pub fn planes(&self, signal: SignalRef) -> Option<&'a [u8]> { + if signal.array_layout.is_some() { + return None; + } + let bytes = signal.width.div_ceil(8); + let len = if self.four_state && signal.is_4state { + 2 * bytes + } else { + bytes + }; + Some(&self.memory[signal.offset..signal.offset + len]) + } +} + +#[inline] +fn top_mask(width: usize) -> u8 { + 0xff >> ((8 - width % 8) % 8) +} + +/// Whether two plane images of a `width`-bit signal hold the same state. +#[inline] +pub fn planes_equal(left: &[u8], right: &[u8], width: usize) -> bool { + let bytes = width.div_ceil(8).max(1); + let top = top_mask(width); + if left.len() != right.len() { + return false; + } + // Images are a few bytes: compare them in place. + let mut position = 0; + for (left, right) in left.iter().zip(right) { + let mask = if position == bytes - 1 { top } else { 0xff }; + if (left ^ right) & mask != 0 { + return false; + } + position = if position == bytes - 1 { + 0 + } else { + position + 1 + }; + } + true +} + +/// Copy a plane image, clearing the bits above `width`. +#[inline] +pub fn copy_planes(target: &mut Vec, source: &[u8], width: usize) { + let bytes = width.div_ceil(8).max(1); + let top = top_mask(width); + if target.len() != source.len() { + target.clear(); + target.resize(source.len(), 0); + } + let mut position = 0; + for (target, source) in target.iter_mut().zip(source) { + *target = if position == bytes - 1 { + source & top + } else { + *source + }; + position = if position == bytes - 1 { + 0 + } else { + position + 1 + }; + } +} + +/// The plane image of `value` for a `width`-bit signal whose image is +/// `len` bytes long. +pub fn encode_planes(value: &Value, width: usize, len: usize) -> Vec { + let bytes = width.div_ceil(8).max(1); + let plane = |number: &BigUint| { + let mut data = number.to_bytes_le(); + data.resize(bytes, 0); + data + }; + let mut image = plane(&value.0); + if len > bytes { + image.extend(plane(&value.1)); + } + let mut masked = Vec::with_capacity(len); + copy_planes(&mut masked, &image, width); + masked +} + +/// Whether the change from plane image `old` to `new` of a `width`-bit +/// signal is an occurrence of `kind` (Table 9-2 on the least significant +/// bit). +#[inline] +pub fn planes_occur(kind: CounterKind, old: &[u8], new: &[u8], width: usize) -> bool { + if kind == CounterKind::Changes { + return !planes_equal(old, new, width); + } + let bytes = width.div_ceil(8).max(1); + let lsb = |image: &[u8]| { + ( + image[0] & 1 != 0, + image.get(bytes).is_some_and(|mask| mask & 1 != 0), + ) + }; + edge(kind, lsb(old), lsb(new)) +} + +/// A process suspended at a wait. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Waiter { + pub site: usize, + pub baselines: Vec, +} + +/// The processes suspended at a wait, by process index. A slot keeps its +/// storage while its process runs, so suspending again reuses it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Waiters { + slots: Vec, + waiting: Vec, + /// Whether a slot's site has a term on a driven signal. + driven: Vec, + count: usize, + driven_count: usize, +} + +impl Waiters { + pub fn is_empty(&self) -> bool { + self.count == 0 + } + + pub fn len(&self) -> usize { + self.count + } + + /// Whether no waiting process has a term on a driven signal. + pub fn none_driven(&self) -> bool { + self.driven_count == 0 + } + + fn slot(&mut self, process: usize) -> &mut Waiter { + if process >= self.slots.len() { + self.slots.resize_with(process + 1, Waiter::default); + self.waiting.resize(process + 1, false); + self.driven.resize(process + 1, false); + } + &mut self.slots[process] + } + + /// Process `process` waits at a site with a term on a driven signal if + /// `driven`; `fill` sets its site and baselines in the slot's previous + /// storage. + pub fn register(&mut self, process: usize, driven: bool, fill: impl FnOnce(&mut Waiter)) { + fill(self.slot(process)); + self.remove(process); + self.waiting[process] = true; + self.driven[process] = driven; + self.count += 1; + self.driven_count += usize::from(driven); + } + + /// Process `process` waits as `waiter`. + pub fn insert(&mut self, process: usize, driven: bool, waiter: Waiter) { + self.register(process, driven, |slot| *slot = waiter); + } + + /// Process `process` no longer waits. + pub fn remove(&mut self, process: usize) { + if self.waiting.get(process).copied().unwrap_or(false) { + self.waiting[process] = false; + self.count -= 1; + self.driven_count -= usize::from(self.driven[process]); + } + } + + /// The waiting processes in index order. + pub fn iter(&self) -> impl Iterator { + self.slots + .iter() + .enumerate() + .filter(|(process, _)| self.waiting[*process]) + } + + /// Keep the waiting processes for which `keep` holds, in index order. + /// Keep the waiting processes for which `keep` holds, in index order; + /// with `driven_only`, consider only those with a term on a driven + /// signal. + #[inline] + pub fn retain(&mut self, driven_only: bool, mut keep: impl FnMut(usize, &mut Waiter) -> bool) { + for process in 0..self.slots.len() { + if self.waiting[process] + && (!driven_only || self.driven[process]) + && !keep(process, &mut self.slots[process]) + { + self.remove(process); + } + } + } + + /// The waiting processes in index order, for updating their baselines. + pub fn iter_mut(&mut self) -> impl Iterator { + let waiting = &self.waiting; + self.slots + .iter_mut() + .enumerate() + .filter(move |(process, _)| waiting[*process]) + } +} + +/// A nonblocking assignment waiting for the NBA region. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NbaUpdate { + pub target: SignalRef, + /// Bit position of the assigned range in the target. + pub lsb: usize, + pub width: usize, + pub value: Value, +} + +impl NbaUpdate { + /// Write the update into the target's value. + pub fn merge_into(&self, target: &Value) -> Value { + let width = self.target.width; + let range = ((BigUint::from(1u8) << self.width) - 1u8) << self.lsb; + let all = (BigUint::from(1u8) << width) - 1u8; + let keep = &all ^ (&range & &all); + let place = + |old: &BigUint, new: &BigUint| ((old & &keep) | ((new << self.lsb) & &range)) & &all; + ( + place(&target.0, &self.value.0), + place(&target.1, &self.value.1), + ) + } +} + +/// Mutable process scheduling state beyond the delay queue: who waits for +/// what, the inactive and post-NBA queues, and the queued nonblocking +/// assignments. All of it is empty in a design without process kernels. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProcessState { + /// Processes suspended at a wait. + pub waiters: Waiters, + /// Processes ready to run in the active region of the current time. + pub ready: std::collections::BTreeSet, + /// Processes that resume in the inactive region (`#0`). + pub inactive: std::collections::BTreeSet, + /// Queued nonblocking assignments, in issue order. + pub nba_queue: Vec, + /// Counter values each counted domain last triggered on, by counted + /// signal index and kind. + pub domain_counters: Vec<[u32; 3]>, +} + +pub(crate) fn kind_index(kind: CounterKind) -> usize { + match kind { + CounterKind::Changes => 0, + CounterKind::Rises => 1, + CounterKind::Falls => 2, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plane_images_ignore_bits_above_the_width() { + // A 4-bit four-state signal: value 0b0101 and mask 0b0010, with + // garbage above bit 3 in both planes. + let memory = [0b1111_0101, 0b1010_0010]; + let mut image = Vec::new(); + copy_planes(&mut image, &memory, 4); + assert_eq!(image, [0b0101, 0b0010]); + assert!(planes_equal(&image, &memory, 4)); + assert_eq!( + encode_planes(&(BigUint::from(5u8), BigUint::from(2u8)), 4, 2), + image + ); + assert!(!planes_equal(&image, &[0b0101, 0b0011], 4)); + // 0 with an unknown bit 1 -> 1: no edge on the least significant bit, + // but a change. + assert!(!planes_occur(CounterKind::Rises, &image, &[0b0101, 0], 4)); + assert!(planes_occur(CounterKind::Changes, &image, &[0b0101, 0], 4)); + assert!(planes_occur( + CounterKind::Falls, + &image, + &[0b0100, 0b0010], + 4 + )); + } + + fn v(value: u8, mask: u8) -> Value { + (BigUint::from(value), BigUint::from(mask)) + } + + #[test] + fn edges_follow_table_9_2() { + // (old, new, posedge, negedge); 2 = x, 3 = z share the mask bit. + let x = v(0, 1); + let z = v(1, 1); + let zero = v(0, 0); + let one = v(1, 0); + for (old, new, rise, fall) in [ + (&zero, &one, true, false), + (&zero, &x, true, false), + (&zero, &z, true, false), + (&x, &one, true, false), + (&z, &one, true, false), + (&one, &zero, false, true), + (&one, &x, false, true), + (&one, &z, false, true), + (&x, &zero, false, true), + (&z, &zero, false, true), + (&x, &z, false, false), + (&one, &one, false, false), + ] { + assert_eq!( + occurs(CounterKind::Rises, old, new), + rise, + "{old:?} -> {new:?}" + ); + assert_eq!( + occurs(CounterKind::Falls, old, new), + fall, + "{old:?} -> {new:?}" + ); + } + assert!(occurs(CounterKind::Changes, &x, &z)); + assert!(!occurs(CounterKind::Changes, &x, &x)); + } + + #[test] + fn nba_updates_merge_their_range() { + let target = SignalRef { + offset: 0, + width: 8, + is_4state: true, + array_layout: None, + }; + let update = NbaUpdate { + target, + lsb: 2, + width: 3, + value: v(0b101, 0b010), + }; + assert_eq!( + update.merge_into(&v(0xff, 0x00)), + v(0b1111_0111, 0b0000_1000) + ); + } +} diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index b2bc2c7a56c..67765df9e85 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -137,7 +137,6 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ 440, ), ("wildcard port connection", 442), - ("mixed clock-edge polarities for one signal", 443), ("delayed continuous assignment", 444), ("duplicate internal signal", 445), ("streaming concatenation", 447), @@ -150,7 +149,6 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("undriven net declaration", 460), ("non-integer module parameter override", 461), ("always_ff event expression", 464), - ("mixed reset-edge polarities for one signal", 471), ("package net", 1146), ]; diff --git a/crates/celox-test-suite/README.md b/crates/celox-test-suite/README.md index 237d2d45acc..d5444a25a2a 100644 --- a/crates/celox-test-suite/README.md +++ b/crates/celox-test-suite/README.md @@ -268,6 +268,15 @@ after the first `run_until`, or generate it in the design. For the same reason the design does not call `$finish` at time zero, and the target of the first `run_until` does not read the design. +Within a time slot the standard orders regions, not processes (IEEE 1800-2023 +4.5): a process woken by `@(posedge clk)` runs in the active region of that +edge, before the edge's nonblocking assignments publish, so it reads flip-flop +outputs from before the edge. Its blocking writes, however, race with the +flip-flops that the same edge triggers. A shared case must not depend on that +race: a process that drives a flip-flop input at the edge uses a nonblocking +assignment or a delay, and a check of the race's outcome belongs to no +shared case. + After that, reads, output collection and `eval` settle processes due at the current timestamp without advancing time. External scripted adapters use an Icarus read/write synchronization callback or a Verilator clocking event diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index e4bbab47695..c7817aab5be 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -517,3 +517,94 @@ (assert_eq known 0xa) (assert_eq partial (fourstate 0xd 0x5)) (assert_eq unset (fourstate 0xf 0xf))) + +; Processes at the rising and the falling edge of one clock, here a divided +; clock `q`, each evaluate against the state before their edge +; (IEEE 1800-2023 9.4.2, 10.4.2). +(case always_ff_at_both_edges_of_one_clock + (source "both_edges.sv" #" + module Top(input logic clk, output logic [7:0] rise, fall, at_rise, at_fall); + logic q = 1'b0; + logic [7:0] r = 8'd0, f = 8'd0, ar = 8'd0, af = 8'd0; + always_ff @(posedge clk) q <= ~q; + always_ff @(negedge q) begin f <= f + 8'd1; af <= r; end + always_ff @(posedge q) begin r <= r + 8'd1; ar <= f; end + assign rise = r; + assign fall = f; + assign at_rise = ar; + assign at_fall = af; + endmodule + "#) + (top Top) + (for k (list 1 2 3) + (tick clk) + (assert_eq rise k) + (assert_eq fall (- k 1)) + (assert_eq at_rise (- k 1)) + (tick clk) + (assert_eq fall k) + (assert_eq at_fall k))) + +; A child senses both edges of its clock port; its rising-edge register +; samples the parent's before the parent's rising edge commits. +(case always_ff_at_both_edges_of_a_child_clock_port + (source "both_edges_child.sv" #" + module Child(input logic c, input logic [7:0] p, + output logic [7:0] sampled, falls); + logic [7:0] s = 8'd0, f = 8'd0; + always_ff @(negedge c) f <= f + 8'd1; + always_ff @(posedge c) s <= p; + assign sampled = s; + assign falls = f; + endmodule + module Top(input logic clk, output logic [7:0] parent, sampled, falls); + logic q = 1'b0; + logic [7:0] p = 8'd0; + always_ff @(posedge clk) q <= ~q; + always_ff @(posedge q) p <= p + 8'd1; + Child u(.c(q), .p(p), .sampled(sampled), .falls(falls)); + assign parent = p; + endmodule + "#) + (top Top) + (for k (list 1 2 3) + (tick clk) + (assert_eq parent k) + (assert_eq sampled (- k 1)) + (assert_eq falls (- k 1)) + (tick clk) + (assert_eq falls k))) + +; One asynchronous reset `r` sensed active high and active low, and also as a +; clock at both edges. +(case always_ff_reset_at_both_edges_and_as_a_clock + (source "both_edges_reset.sv" #" + module Top(input logic clk, d, output logic [7:0] high, low, rises, falls); + logic r = 1'b0; + logic [7:0] h = 8'd0, l = 8'd0, ri = 8'd0, fa = 8'd0; + always_ff @(posedge clk) r <= d; + always_ff @(posedge clk or posedge r) if (r) h <= 8'd0; else h <= h + 8'd1; + always_ff @(posedge clk or negedge r) if (!r) l <= 8'd0; else l <= l + 8'd1; + always_ff @(posedge r) ri <= ri + 8'd1; + always_ff @(negedge r) fa <= fa + 8'd1; + assign high = h; + assign low = l; + assign rises = ri; + assign falls = fa; + endmodule + "#) + (top Top) + (for (value h l ri fa) + (list + (0 1 0 0 0) + (1 0 0 1 0) + (1 0 1 1 0) + (1 0 2 1 0) + (0 0 0 1 1) + (0 1 0 1 1)) + (modify (set d value)) + (tick clk) + (assert_eq high h) + (assert_eq low l) + (assert_eq rises ri) + (assert_eq falls fa))) diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 07e553f1b28..9a7393c1c66 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -107,6 +107,50 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { }) }); } + + // Benchmark 3: Simulation::step of SystemVerilog counters at the rising + // edge only, half at each edge of `clk`, and half at the falling edge of + // a copy of `clk`. + #[cfg(feature = "systemverilog")] + for (name, falling) in [ + ("sv_simulation_step_posedge_x20000", "posedge clk"), + ("sv_simulation_step_both_edges_x20000", "negedge clk"), + ("sv_simulation_step_negedge_copy_x20000", "negedge c"), + ] { + let source = format!( + "module Top #(parameter int N = 1000) (input logic clk, input logic rst, + output logic [31:0] cnt [N]); + logic c; + assign c = clk; + for (genvar i = 0; i < N; i++) begin : g + if (i % 2 == 0) begin : rise + always_ff @(posedge clk or posedge rst) + if (rst) cnt[i] <= 0; else cnt[i] <= cnt[i] + 1; + end else begin : fall + always_ff @({falling} or posedge rst) + if (rst) cnt[i] <= 0; else cnt[i] <= cnt[i] + 1; + end + end + endmodule" + ); + let path = std::path::Path::new("overhead.sv"); + let mut sim = Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top") + .build() + .unwrap(); + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + sim.add_clock("clk", 10, 10); + + c.bench_function(name, |b| { + b.iter(|| { + for _ in 0..20000 { + sim.step().unwrap(); + } + }) + }); + } } criterion_group!(benches, benchmark_simulation_overhead); diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 2158ddf7968..800b6911d7b 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1985,22 +1985,15 @@ impl SimBackend for InterpBackend { } fn get_triggered_bits(&self) -> bit_set::BitSet { - let mut bits = bit_set::BitSet::with_capacity(self.num_events()); let base_ptr = self.memory.as_ptr() as *const u8; - let triggered_bits_ptr = unsafe { base_ptr.add(self.layout.triggered_bits_offset) }; - let total_size = self.layout.triggered_bits_total_size; - - for i in 0..total_size { - let byte = unsafe { *triggered_bits_ptr.add(i) }; - if byte != 0 { - for j in 0..8 { - if (byte & (1 << j)) != 0 { - bits.insert(i * 8 + j); - } - } - } - } - bits + // Safety: the triggered bits lie within the memory image. + let bytes = unsafe { + std::slice::from_raw_parts( + base_ptr.add(self.layout.triggered_bits_offset), + self.layout.triggered_bits_total_size, + ) + }; + celox_runtime::backend::triggered_bits_from_bytes(bytes) } } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 58f4cadbccf..2267bf7793f 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -392,6 +392,9 @@ pub(crate) struct NativeRuntimeSchema { /// Ordered so that the encoded image does not depend on hash order. pub(crate) live_signals: std::collections::BTreeSet, pub(crate) processes: Vec>, + pub(crate) watches: Vec>, + pub(crate) wait_sites: Vec>, + pub(crate) nba_sites: Vec>, } /// Pointer-free native compiler artifact which can be attached to the @@ -493,6 +496,9 @@ impl NativeProgramImage { dead_store_policy: self.runtime_schema.dead_store_policy, live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), + watches: self.runtime_schema.watches.clone(), + wait_sites: self.runtime_schema.wait_sites.clone(), + nba_sites: self.runtime_schema.nba_sites.clone(), }, testbench: self.testbench.clone(), } @@ -2269,6 +2275,9 @@ fn compile_program( .copied() .collect(), processes: sir.runtime().runtime_schema.processes.clone(), + watches: sir.runtime().runtime_schema.watches.clone(), + wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), + nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), }, layout: layout.clone(), native_memory_size, @@ -3272,15 +3281,6 @@ impl super::super::SimBackend for NativeBackend { fn get_triggered_bits(&self) -> BitSet { let offset = self.compiled.layout.triggered_bits_offset; let size = self.compiled.layout.triggered_bits_total_size; - let bytes = self.mem_bytes(); - let mut bs = BitSet::with_capacity(size * 8); - for i in 0..size * 8 { - let byte_idx = offset + i / 8; - let bit_idx = i % 8; - if bytes[byte_idx] & (1 << bit_idx) != 0 { - bs.insert(i); - } - } - bs + celox_runtime::backend::triggered_bits_from_bytes(&self.mem_bytes()[offset..offset + size]) } } 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/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index 2b3f4a7c4d6..3808249cd3a 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -1291,22 +1291,15 @@ impl JitBackend { /// Reads back the triggered bits bitset and returns it as a BitSet. pub fn get_triggered_bits(&self) -> bit_set::BitSet { - let mut bits = bit_set::BitSet::with_capacity(self.num_events()); let base_ptr = self.memory.as_ptr() as *const u8; - let triggered_bits_ptr = unsafe { base_ptr.add(self.shared.layout.triggered_bits_offset) }; - let total_size = self.shared.layout.triggered_bits_total_size; - - for i in 0..total_size { - let byte = unsafe { *triggered_bits_ptr.add(i) }; - if byte != 0 { - for j in 0..8 { - if (byte & (1 << j)) != 0 { - bits.insert(i * 8 + j); - } - } - } - } - bits + // Safety: the triggered bits lie within the memory image. + let bytes = unsafe { + std::slice::from_raw_parts( + base_ptr.add(self.shared.layout.triggered_bits_offset), + self.shared.layout.triggered_bits_total_size, + ) + }; + celox_runtime::backend::triggered_bits_from_bytes(bytes) } } diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 6bcabd3d8e0..c2fc78eb488 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -741,22 +741,10 @@ impl WasmBackend { } pub fn get_triggered_bits(&self) -> bit_set::BitSet { - let mut bits = bit_set::BitSet::with_capacity(self.num_events()); let mem = self.memory.data(&self.store); let offset = self.layout.triggered_bits_offset; let size = self.layout.triggered_bits_total_size; - - for i in 0..size { - let byte = mem[offset + i]; - if byte != 0 { - for j in 0..8 { - if (byte & (1 << j)) != 0 { - bits.insert(i * 8 + j); - } - } - } - } - bits + celox_runtime::backend::triggered_bits_from_bytes(&mem[offset..offset + size]) } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 8928b0bd845..5ca35239a4c 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -36,9 +36,10 @@ pub use celox_frontend_sdk as frontend_sdk; pub use celox_frontend_sdk::FrontendArtifact; pub use celox_frontend_veryl::{FrontendDiagnostic, LoweringPhase, ParserError}; pub use celox_runtime::{ - DesignReflection, ReflectionScope, ReflectionScopeId, ReflectionSignal, ReflectionSignalId, - ScheduleRecord, ScheduledEvent, SignalDirection, StateDifference, StateFile, StateFileError, - StateObject, StateRole, format_state_value, + BaselineRecord, DesignReflection, NbaRecord, ProcessRecord, ReflectionScope, ReflectionScopeId, + ReflectionSignal, ReflectionSignalId, ScheduleRecord, ScheduledEvent, SignalDirection, + StateDifference, StateFile, StateFileError, StateObject, StateRole, WaiterRecord, + format_state_value, }; pub use celox_slt::scheduler::SchedulerError; pub use celox_state_layout::STATE_HEADER_SIZE; @@ -103,15 +104,26 @@ mod host_api { pub struct IOContext<'a, B: SimBackend = DefaultBackend> { pub(crate) backend: &'a mut B, + /// Writes a timed simulation observes one at a time; empty + /// otherwise. + pub(crate) watch: &'a mut celox_runtime::HostWatch, } impl<'a, B: SimBackend> IOContext<'a, B> { + fn write(&mut self, signal: crate::SignalRef, write: impl FnOnce(&mut B)) { + if self.watch.is_empty() { + write(self.backend); + } else { + self.watch.write(self.backend, signal, write); + } + } + pub fn set(&mut self, signal: crate::SignalRef, val: T) { - self.backend.set(signal, val); + self.write(signal, |backend| backend.set(signal, val)); } pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) { - self.backend.set_wide(signal, val); + self.write(signal, |backend| backend.set_wide(signal, val)); } pub fn set_four_state( @@ -120,7 +132,7 @@ mod host_api { val: crate::BigUint, mask: crate::BigUint, ) { - self.backend.set_four_state(signal, val, mask); + self.write(signal, |backend| backend.set_four_state(signal, val, mask)); } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 0b794623087..a1203f1c1ef 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -7,7 +7,8 @@ use crate::{ }, }; use celox_runtime::{ - EventInfo, ProcessRefs, SimulationExecutor, SimulationSnapshot, SimulationState, + CountedDomainRefs, CountedRefs, EventInfo, Halt, HostWatch, NbaSiteRefs, ProcessRefs, + SimulationExecutor, SimulationSnapshot, SimulationState, TermRefs, }; /// Saved state of a [`Simulation`], created by [`Simulation::checkpoint`]: @@ -15,6 +16,9 @@ use celox_runtime::{ pub struct SimulationCheckpoint { simulator: Checkpoint, schedule: SimulationSnapshot, + /// Host writes of waited signals the next step has yet to show the + /// waits. + host_writes: Vec<(SignalRef, celox_runtime::timing::Value)>, } impl Clone for SimulationCheckpoint { @@ -22,6 +26,7 @@ impl Clone for SimulationCheckpoint { Self { simulator: self.simulator.clone(), schedule: self.schedule.clone(), + host_writes: self.host_writes.clone(), } } } @@ -76,30 +81,49 @@ impl SimulationExecutor for Simulator { &mut self.backend } - fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { - self.eval_comb_checked() + #[inline] + fn eval_comb(&mut self) -> Result<(), Halt> { + self.eval_comb_checked()?; + self.runtime_finish() } - fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - self.eval_apply_ff_at_checked(event) + #[inline] + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + self.eval_apply_ff_at_checked(event)?; + self.runtime_finish() } - fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - self.eval_only_ff_at_checked(event) + #[inline] + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + self.eval_only_ff_at_checked(event)?; + self.runtime_finish() } - fn eval_comb_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - self.eval_comb_apply_ff_at_checked(event) + #[inline] + fn eval_comb_apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + self.eval_comb_apply_ff_at_checked(event)?; + self.runtime_finish() } - fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - self.apply_ff_at_checked(event) + #[inline] + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), Halt> { + self.apply_ff_at_checked(event)?; + self.runtime_finish() } - fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + fn run_process(&mut self, index: usize) -> Result<(), Halt> { self.backend .run_process(index) - .map_err(|e| self.decorate_runtime_error(e)) + .map_err(|e| self.decorate_runtime_error(e))?; + self.runtime_finish() + } + + fn take_host_writes(&mut self) -> Vec<(SignalRef, celox_runtime::timing::Value)> { + self.host_watch.take_log() + } + + fn freeze(&mut self) { + self.frozen = true; } fn stage_external_event( @@ -136,6 +160,22 @@ impl SimulationExecutor for Simulator { } } +impl Simulator { + /// A `$finish` the design's flip-flop or combinational code executed + /// ends a timed simulation (IEEE 1800-2023 20.2). + #[inline] + fn runtime_finish(&mut self) -> Result<(), Halt> { + if !self.finish_sites { + return Ok(()); + } + if self.take_runtime_finish() { + Err(Halt::Finish) + } else { + Ok(()) + } + } +} + // ── Backend-specific constructors ─────────────────────────────────── impl Simulation { @@ -243,16 +283,70 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul } } - let processes = simulator - .program - .runtime_schema - .processes + let schema = &simulator.program.runtime_schema; + let resolve = |addr: &crate::AbsoluteAddr| simulator.backend.resolve_signal(addr); + let counted: Vec = schema + .watches .iter() - .map(|slots| ProcessRefs { - status: simulator.backend.resolve_signal(&slots.status), - delay: simulator.backend.resolve_signal(&slots.delay), + .filter_map(|watch| { + Some(CountedDomainRefs { + refs: CountedRefs { + signal: resolve(&watch.signal), + changes: resolve(&watch.changes?), + rises: resolve(&watch.rises?), + falls: resolve(&watch.falls?), + }, + domains: watch + .domains + .iter() + .filter_map(|(event, kind)| { + Some((simulator.backend.resolve_event_opt(event)?.id(), *kind)) + }) + .collect(), + }) }) .collect(); + // Signals design code writes; the rest only the host and the scheduler + // write. + let driven: crate::HashSet = + schema.rtl_writes.iter().map(|atom| atom.id).collect(); + let counter_of = |signal: SignalRef, kind| { + counted + .iter() + .find(|counted| counted.refs.signal == signal) + .map(|counted| counted.refs.counter(kind)) + }; + let mut processes: Vec = schema + .processes + .iter() + .map(|slots| ProcessRefs::new(resolve(&slots.status), resolve(&slots.delay))) + .collect(); + for site in &schema.wait_sites { + let terms = site + .terms + .iter() + .map(|(address, kind)| { + let signal = resolve(address); + TermRefs { + signal, + kind: *kind, + counter: counter_of(signal, *kind), + driven: driven.contains(address), + } + }) + .collect(); + processes[site.process].wait_sites.push(terms); + } + for site in &schema.nba_sites { + processes[site.process].nba_sites.push(NbaSiteRefs { + target: resolve(&site.target), + lsb: site.lsb, + width: site.width, + value: resolve(&site.value), + offset: site.offset.as_ref().map(resolve), + pending: site.pending.as_ref().map(resolve), + }); + } let mut state = SimulationState::new( &simulator.backend, @@ -260,7 +354,8 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul domain_kinds, event_info, processes, - ); + ) + .with_counted(&simulator.backend, counted); let events = &simulator.program.design.events; if !events.combinational_derived.is_empty() { let derived = simulator @@ -283,9 +378,41 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul state } +/// Host writes a timed simulation of `simulator` observes one at a time: +/// those of counted signals and of signals a wait watches. +fn host_watch(simulator: &Simulator) -> HostWatch { + let schema = &simulator.program.runtime_schema; + let resolve = |addr: &crate::AbsoluteAddr| simulator.backend.resolve_signal(addr); + HostWatch::new( + schema.watches.iter().filter_map(|watch| { + Some(CountedRefs { + signal: resolve(&watch.signal), + changes: resolve(&watch.changes?), + rises: resolve(&watch.rises?), + falls: resolve(&watch.falls?), + }) + }), + schema + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|(signal, _)| resolve(signal).offset)) + .collect(), + ) +} + impl Simulation { - pub(crate) fn new(simulator: Simulator) -> Self { + pub(crate) fn new(mut simulator: Simulator) -> Self { let state = simulation_state(&simulator); + simulator.host_watch = host_watch(&simulator); + // Only a timed simulation ends at an RTL `$finish`; a bare + // `Simulator`, ticks included, leaves that to the host. + simulator.finish_sites = simulator + .program + .runtime_schema + .runtime_event_sites + .iter() + .any(|site| matches!(site.kind, crate::ir::RuntimeEventKind::Finish)); + simulator.skip_runtime_finish(); Self { simulator, state } } @@ -299,18 +426,20 @@ impl Simulation { Ok(SimulationCheckpoint { simulator: self.simulator.checkpoint()?, schedule: self.state.snapshot(), + host_writes: self.simulator.host_watch.log().to_vec(), }) } /// Save the value of every state object by path, together with the /// simulation time, clocks and pending events by name. pub fn save_state(&mut self) -> Result { - if self.has_processes() { - return Err(StateError::Processes); - } let mut file = self.simulator.save_state()?; + // Settling for the file may have executed a `$finish`. + self.sync_finish(); let parts = self.state.export_schedule(&self.simulator.backend); - file.schedule = Some(self.simulator.name_schedule(parts)); + let mut record = self.simulator.name_schedule(parts); + record.processes.host_writes = self.simulator.name_host_writes(); + file.schedule = Some(record); Ok(file) } @@ -318,14 +447,16 @@ impl Simulation { /// clocks and pending events. See [`Simulator::load_state`] for how /// objects are matched. pub fn load_state(&mut self, file: &celox_runtime::StateFile) -> Result<(), StateError> { - if self.has_processes() { - return Err(StateError::Processes); - } let record = file.schedule.as_ref().ok_or(StateError::MissingSchedule)?; self.simulator.check_vcd_rewind(record.time)?; let parts = self.simulator.resolve_schedule(record)?; + let host_writes = self + .simulator + .resolve_host_writes(&record.processes.host_writes)?; self.simulator.load_state(file)?; self.state.import_schedule(parts); + self.simulator.host_watch.set_log(host_writes); + self.simulator.frozen = self.state.is_finished(); Ok(()) } @@ -347,17 +478,32 @@ impl Simulation { .filter(|local| local.addr() == event.addr()) }) .map_err(|_| CheckpointError::DesignMismatch)?; - self.simulator.restore(&checkpoint.simulator) + self.simulator.restore(&checkpoint.simulator)?; + self.simulator + .host_watch + .set_log(checkpoint.host_writes.clone()); + Ok(()) + } + + /// A `$finish` that flip-flop or combinational code executed outside a + /// step, during a direct settle, read or dump, ends the simulation too. + fn sync_finish(&mut self) { + if !self.state.is_finished() && self.simulator.take_runtime_finish() { + self.state.finish(&mut self.simulator); + } } /// Captures the current state of all signals and writes them to the VCD file. pub fn dump(&mut self, timestamp: u64) { self.simulator.dump(timestamp); + self.sync_finish(); } /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { - self.simulator.try_dump(timestamp) + let result = self.simulator.try_dump(timestamp); + self.sync_finish(); + result } /// See [`Simulator::switch_vcd`]. @@ -376,15 +522,27 @@ impl Simulation { /// Retrieves the current value of a variable using a pre-resolved [`SignalRef`] handle. pub fn get(&mut self, signal: SignalRef) -> num_bigint::BigUint { - self.simulator.get(signal) + let value = self.simulator.get(signal); + self.sync_finish(); + value } /// Modifies internal state via a callback and re-stabilizes combinational logic. + /// + /// A write that changes an event signal, and any write while a process + /// waits or a signal is counted, is an update of the current time: the + /// next [`Self::step`] or [`Self::run_until`] settles it at that time, + /// then advances. pub fn modify(&mut self, f: F) -> Result<(), RuntimeErrorCode> where F: FnOnce(&mut crate::IOContext), { - self.simulator.modify(f) + let result = self.simulator.modify(f); + self.sync_finish(); + result?; + let logged = self.simulator.host_watch.has_log(); + self.state.note_host_writes(&self.simulator.backend, logged); + Ok(()) } /// Register a clock signal and its period, enqueuing the first edge. @@ -415,11 +573,19 @@ impl Simulation { } /// Advance time to the next scheduled event and process all events at that time. - /// Returns the new simulation time, or None if no events are scheduled. + /// Host writes since the last step are settled at the current time first. + /// Returns the new simulation time, the current time when only host + /// writes were settled, or None if nothing was to do. pub fn step(&mut self) -> Result, RuntimeErrorCode> { self.state.step(&mut self.simulator) } + /// [`Self::step`] that, after settling host writes at the current time, + /// does not advance past `end_time`. + fn step_until(&mut self, end_time: u64) -> Result, RuntimeErrorCode> { + self.state.step_until(&mut self.simulator, end_time) + } + /// Advance time and run until `end_time` (inclusive). /// Targets earlier than the current time leave time and state unchanged. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { @@ -433,7 +599,7 @@ impl Simulation { if next_time > end_time { break; } - self.step()?; + self.step_until(end_time)?; } if self.state.is_finished() { return Ok(()); @@ -443,8 +609,30 @@ impl Simulation { Ok(()) } - fn has_processes(&self) -> bool { - !self.simulator.program.runtime_schema.processes.is_empty() + /// Like [`Self::run_until`], but takes at most `max_steps` steps. + /// Returns `false`, with the simulation at the time of its last step, + /// when another step would be needed to reach `end_time`. + pub fn run_until_bounded( + &mut self, + end_time: u64, + max_steps: u64, + ) -> Result { + if end_time < self.state.time() { + return Ok(true); + } + let mut steps = 0; + while let Some(next_time) = self.state.next_event_time() { + if next_time > end_time { + break; + } + if steps >= max_steps { + return Ok(false); + } + self.step_until(end_time)?; + steps += 1; + } + self.run_until(end_time)?; + Ok(true) } /// Whether a process of the design requested the end of the simulation. @@ -478,7 +666,9 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { - self.simulator.eval_comb() + let result = self.simulator.eval_comb(); + self.sync_finish(); + result } /// Returns a raw pointer to the backend memory and its total size in bytes. @@ -491,6 +681,14 @@ impl Simulation { self.simulator.memory_as_mut_ptr() } + /// The host wrote the state through [`Self::memory_as_mut_ptr`]. Like + /// [`Self::modify`], the next step then settles the current time when the + /// writes may wake a process or changed an event signal. Waits and + /// counters see the values the writes left, not each write. + pub fn note_raw_writes(&mut self) { + self.state.note_host_writes(&self.simulator.backend, false); + } + /// Returns an opaque owner that keeps the backend memory allocation alive. pub fn memory_owner(&self) -> Option> { self.simulator.memory_owner() @@ -1187,3 +1385,6 @@ endmodule } } } + +#[cfg(all(test, feature = "host-runtime"))] +mod runtime_core_tests; diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs new file mode 100644 index 00000000000..5592ebb5a7f --- /dev/null +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -0,0 +1,1793 @@ +//! The event-driven process phase of the timed scheduler on every backend: +//! waits, counted signals, the inactive and NBA regions, finish and +//! checkpoints. Designs are built with the frontend SDK, whose processes are +//! lowered by `ProcessKernelBuilder`. + +use celox_frontend_sdk::{ + BinaryOp, Constant, Edge, EventEdge, EventTerm, ExprId, FrontendArtifact, ModuleBuilder, + SignalId, Statement, UnaryOp, ValueType, +}; + +use super::Simulation; +use crate::{SimBackend, Simulator, SimulatorBuilder}; + +/// Run `$body` with `$sim` bound to a timed simulation of `$builder` on +/// every backend, including a native program image that went through its +/// container. +macro_rules! on_every_backend { + ($builder:expr, $top:expr, |$sim:ident| $body:block) => {{ + fn run(mut $sim: Simulation) $body + run(Simulation::new($builder.build_interpreter().unwrap())); + run(Simulation::new($builder.build_cranelift().unwrap())); + run(Simulation::new($builder.build_wasm().unwrap())); + run(Simulation::new($builder.build_tiered().unwrap())); + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + { + run(Simulation::new($builder.build_native().unwrap())); + let image = $builder.compile_native().unwrap().into_program_image(); + let image = crate::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + run(Simulation::new( + Simulator::from_sources(Vec::new(), $top) + .emit_triggers() + .build_native_from_image(image) + .unwrap(), + )); + } + }}; +} + +/// A flat SDK module under construction. +struct Design { + module: ModuleBuilder, + four_state: bool, +} + +impl Design { + fn new(name: &str, four_state: bool) -> Self { + Self { + module: ModuleBuilder::new(name).unwrap(), + four_state, + } + } + + fn ty(&self, width: usize) -> ValueType { + ValueType::new(width, false, self.four_state).unwrap() + } + + /// An internal signal starting at `initial`. + fn internal(&mut self, name: &str, width: usize, initial: u64) -> SignalId { + let ty = self.ty(width); + let signal = self.module.internal(name, ty).unwrap(); + self.init(signal, width, initial); + signal + } + + fn output(&mut self, name: &str, width: usize, initial: u64) -> SignalId { + let ty = self.ty(width); + let signal = self.module.output(name, ty).unwrap(); + self.init(signal, width, initial); + signal + } + + fn input(&mut self, name: &str, width: usize) -> SignalId { + let ty = self.ty(width); + self.module.input(name, ty).unwrap() + } + + fn init(&mut self, signal: SignalId, width: usize, value: u64) { + self.module + .set_initial(signal, Constant::two_state(value, width).unwrap()) + .unwrap(); + } + + fn constant(&mut self, value: u64, width: usize) -> ExprId { + self.module + .constant(Constant::two_state(value, width).unwrap()) + } + + fn read(&mut self, signal: SignalId) -> ExprId { + self.module.read(signal).unwrap() + } + + fn width(&self, signal: SignalId) -> usize { + self.module.whole(signal).unwrap().width() + } + + /// `signal = value;` + fn set(&mut self, signal: SignalId, value: u64) -> Statement { + let width = self.width(signal); + let value = self.constant(value, width); + self.assign(signal, value) + } + + fn assign(&mut self, signal: SignalId, value: ExprId) -> Statement { + Statement::Assign { + target: self.module.whole(signal).unwrap(), + value, + } + } + + /// `signal <= value;` + fn nonblocking(&mut self, signal: SignalId, value: ExprId) -> Statement { + Statement::Nonblocking { + target: self.module.whole(signal).unwrap(), + value, + } + } + + fn plus_one(&mut self, signal: SignalId) -> ExprId { + let width = self.width(signal); + let current = self.read(signal); + let one = self.constant(1, width); + let ty = self.ty(width); + self.module.binary(BinaryOp::Add, current, one, ty).unwrap() + } + + /// `signal = signal + 1;` + fn increment(&mut self, signal: SignalId) -> Statement { + let next = self.plus_one(signal); + self.assign(signal, next) + } + + fn delay(&mut self, amount: u64) -> Statement { + Statement::Delay { + amount: self.constant(amount, 8), + } + } + + /// `#amount` with the IEEE inactive-region meaning of `#0`. + fn inactive_delay(&mut self, amount: u64) -> Statement { + Statement::InactiveDelay { + amount: self.constant(amount, 8), + } + } + + /// `always_ff @(edge clock) target <= next;` + fn register(&mut self, target: SignalId, next: ExprId, clock: SignalId, edge: Edge) { + let target = self.module.whole(target).unwrap(); + self.module + .register(target, next, clock, edge, None, None) + .unwrap(); + } + + /// `always_ff @(posedge clock) target <= target + 1;` + fn counter(&mut self, target: SignalId, clock: SignalId) { + let next = self.plus_one(target); + self.register(target, next, clock, Edge::Posedge); + } + + fn finish(self) -> FrontendArtifact { + self.module.finish() + } +} + +fn wait(signal: SignalId, edge: EventEdge) -> Statement { + Statement::WaitEvent { + terms: vec![EventTerm::new(signal, edge)], + } +} + +fn builder(artifact: &FrontendArtifact, four_state: bool) -> SimulatorBuilder<'static, Simulator> { + Simulator::from_frontend(artifact.clone()) + .four_state(four_state) + .emit_triggers() +} + +fn value(sim: &mut Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + let value = sim.get(signal); + u64::try_from(value).unwrap() +} + +/// A process writes 0→1→0 to `clk` without suspending: `@(posedge clk)` +/// and the flip-flops of `clk` see the pulse exactly once. +fn pulse(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Pulse", four_state); + let clk = d.internal("clk", 1, 0); + let waits = d.output("waits", 8, 0); + let ffs = d.output("ffs", 8, 0); + d.counter(ffs, clk); + let body = vec![d.delay(1), d.set(clk, 1), d.set(clk, 0)]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(waits)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn a_pulse_within_one_process_run_wakes_posedge_once() { + for four_state in [false, true] { + let artifact = pulse(four_state); + on_every_backend!(builder(&artifact, four_state), "Pulse", |sim| { + sim.run_until(0).unwrap(); + assert_eq!(value(&mut sim, "waits"), 0); + sim.run_until(5).unwrap(); + assert_eq!(value(&mut sim, "clk"), 0); + assert_eq!(value(&mut sim, "waits"), 1, "the wait sees the pulse once"); + assert_eq!( + value(&mut sim, "ffs"), + 1, + "the flip-flop sees the pulse once" + ); + }); + } +} + +/// `clk` rises twice in one time slot, separated by `#0`: the flip-flop +/// domain evaluates twice before the NBA region and both updates publish +/// in order. +fn repeated_edges(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Repeated", four_state); + let clk = d.internal("clk", 1, 0); + let data = d.internal("data", 8, 0); + let q = d.output("q", 8, 0); + let wakes = d.output("wakes", 8, 0); + let read = d.read(data); + d.register(q, read, clk, Edge::Posedge); + let body = vec![ + d.delay(1), + d.set(data, 1), + d.set(clk, 1), + d.inactive_delay(0), + d.set(clk, 0), + d.set(data, 2), + d.inactive_delay(0), + d.set(clk, 1), + d.inactive_delay(0), + d.set(clk, 0), + ]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(wakes)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn repeated_edges_in_one_slot_trigger_a_domain_repeatedly() { + for four_state in [false, true] { + let artifact = repeated_edges(four_state); + on_every_backend!(builder(&artifact, four_state), "Repeated", |sim| { + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 2); + // Both evaluations publish, the later one last. + assert_eq!(value(&mut sim, "q"), 2); + }); + } +} + +/// Host writes of an input clock trigger its flip-flops and wake a +/// process waiting on it at the current time. +fn host_clock(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("HostClock", four_state); + let clk = d.input("clk", 1); + let ffs = d.output("ffs", 8, 0); + let waits = d.output("waits", 8, 0); + d.counter(ffs, clk); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(waits)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn host_writes_trigger_registers_and_wake_waits() { + for four_state in [false, true] { + let artifact = host_clock(four_state); + on_every_backend!(builder(&artifact, four_state), "HostClock", |sim| { + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.run_until(0).unwrap(); + for edge in 1..=3u64 { + sim.modify(|io| io.set(clk, 1u8)).unwrap(); + sim.run_until(2 * edge - 1).unwrap(); + assert_eq!(value(&mut sim, "ffs"), edge); + assert_eq!(value(&mut sim, "waits"), edge); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.run_until(2 * edge).unwrap(); + assert_eq!(value(&mut sim, "ffs"), edge); + } + // A pulse inside one host update wakes the wait as well. + sim.modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(); + sim.run_until(10).unwrap(); + assert_eq!(value(&mut sim, "waits"), 4); + }); + } +} + +/// `wait (ready)` blocks until another process sets `ready` and passes at +/// once when it already holds. +fn level(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Level", four_state); + let ready = d.internal("ready", 1, 0); + let first = d.output("first", 8, 0); + let second = d.output("second", 8, 0); + let condition = d.read(ready); + let body = vec![Statement::WaitLevel { condition }, d.set(first, 1)]; + d.module.process(body).unwrap(); + let body = vec![d.delay(3), d.set(ready, 1)]; + d.module.process(body).unwrap(); + let body = vec![ + d.delay(5), + Statement::WaitLevel { condition }, + d.set(second, 1), + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn level_waits_block_until_their_condition_holds() { + for four_state in [false, true] { + let artifact = level(four_state); + on_every_backend!(builder(&artifact, four_state), "Level", |sim| { + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "first"), 0); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "first"), 1); + sim.run_until(4).unwrap(); + assert_eq!(value(&mut sim, "second"), 0); + sim.run_until(5).unwrap(); + assert_eq!(value(&mut sim, "second"), 1); + assert_eq!(sim.next_event_time(), None); + }); + } +} + +/// IEEE 1800-2023 4.5: the domains an edge triggers evaluate before an +/// inactive-region `#0` resumes, and nonblocking assignments publish only +/// after the inactive region; a zero `Delay` resumes after them. +fn zero_delays(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("ZeroDelays", four_state); + let clk = d.internal("clk", 1, 0); + let data = d.internal("data", 8, 3); + let q = d.output("q", 8, 0); + let x = d.internal("x", 8, 0); + let y = d.internal("y", 8, 0); + let inactive_seen = d.output("inactive_seen", 8, 9); + let post_nba_seen = d.output("post_nba_seen", 8, 9); + let read = d.read(data); + d.register(q, read, clk, Edge::Posedge); + let body = vec![ + d.delay(1), + d.set(clk, 1), + d.inactive_delay(0), + d.set(data, 5), + ]; + d.module.process(body).unwrap(); + let one = d.constant(1, 8); + let read_x = d.read(x); + let read_y = d.read(y); + let body = vec![ + d.delay(1), + d.nonblocking(x, one), + d.inactive_delay(0), + d.assign(inactive_seen, read_x), + ]; + d.module.process(body).unwrap(); + let body = vec![ + d.delay(1), + d.nonblocking(y, one), + d.delay(0), + d.assign(post_nba_seen, read_y), + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn zero_delays_order_against_flip_flops_and_nonblocking_assignments() { + for four_state in [false, true] { + let artifact = zero_delays(four_state); + on_every_backend!(builder(&artifact, four_state), "ZeroDelays", |sim| { + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 3, "the domain evaluated before #0"); + assert_eq!( + value(&mut sim, "inactive_seen"), + 0, + "#0 runs before the NBA region" + ); + assert_eq!( + value(&mut sim, "post_nba_seen"), + 1, + "a zero Delay runs after it" + ); + assert_eq!(value(&mut sim, "x"), 1); + }); + } +} + +/// Two nonblocking assignments to one watched destination in one slot +/// publish in order, each as its own update; so do three executions of a +/// single-site assignment. +fn nonblocking(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Nonblocking", four_state); + let q = d.output("q", 8, 0); + let r = d.output("r", 8, 0); + let i = d.internal("i", 8, 0); + let q_changes = d.output("q_changes", 8, 0); + let r_changes = d.output("r_changes", 8, 0); + let one = d.constant(1, 8); + let zero = d.constant(0, 8); + let body = vec![d.delay(1), d.nonblocking(q, one), d.nonblocking(q, zero)]; + d.module.process(body).unwrap(); + let read_i = d.read(i); + let three = d.constant(3, 8); + let ty = d.ty(1); + let below = d + .module + .binary(BinaryOp::LessUnsigned, read_i, three, ty) + .unwrap(); + let loop_body = vec![d.nonblocking(r, read_i), d.increment(i)]; + let body = vec![ + d.delay(2), + Statement::While { + condition: below, + body: loop_body, + }, + ]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(q, EventEdge::Change), d.increment(q_changes)], + }]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(r, EventEdge::Change), d.increment(r_changes)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn nonblocking_assignments_publish_in_order() { + for four_state in [false, true] { + let artifact = nonblocking(four_state); + on_every_backend!(builder(&artifact, four_state), "Nonblocking", |sim| { + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 0); + assert_eq!( + value(&mut sim, "q_changes"), + 1, + "q was 1 between the updates" + ); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "r"), 2, "the last assignment wins"); + assert_eq!(value(&mut sim, "r_changes"), 1); + }); + } +} + +/// A process writes `a`, finishes and would write it again; a register +/// counts clock edges. Nothing changes after the finish. +fn finishing(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Finishing", four_state); + let clk = d.input("clk", 1); + let a = d.output("a", 8, 0); + let edges = d.output("edges", 8, 0); + d.counter(edges, clk); + let body = vec![d.delay(4), d.set(a, 1), Statement::Finish, d.set(a, 2)]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn finish_freezes_the_simulation() { + for four_state in [false, true] { + let artifact = finishing(four_state); + on_every_backend!(builder(&artifact, four_state), "Finishing", |sim| { + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.add_clock("clk", 2, 1); + sim.run_until(20).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 4); + assert_eq!(value(&mut sim, "a"), 1); + // Edges at 1 and 3; the one at 5 is after the finish. + assert_eq!(value(&mut sim, "edges"), 2); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 7u8)).unwrap(); + sim.eval_comb().unwrap(); + assert_eq!(value(&mut sim, "a"), 1, "host writes are ignored"); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.next_event_time(), None); + }); + } +} + +/// A process waiting on `go` survives a checkpoint: restoring returns it to +/// waiting, and the next edge wakes it again. +fn waiting(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Waiting", four_state); + let go = d.input("go", 1); + let wakes = d.output("wakes", 8, 0); + let body = vec![Statement::Forever { + body: vec![wait(go, EventEdge::Posedge), d.increment(wakes)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn checkpoints_restore_a_waiting_process() { + for four_state in [false, true] { + let artifact = waiting(four_state); + on_every_backend!(builder(&artifact, four_state), "Waiting", |sim| { + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.run_until(1).unwrap(); + let saved = sim.checkpoint().unwrap(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 1); + sim.restore(&saved).unwrap(); + assert_eq!(sim.time(), 1); + assert_eq!(value(&mut sim, "wakes"), 0); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 0, "restored waiting, not woken"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 1); + }); + } +} + +#[test] +fn state_files_carry_waiting_processes_across_backends() { + // Saved on the interpreter, loaded into every backend. + let artifact = waiting(true); + let mut source = Simulation::new(builder(&artifact, true).build_interpreter().unwrap()); + let go = source.signal("go"); + source.modify(|io| io.set(go, 0u8)).unwrap(); + source.run_until(1).unwrap(); + source.modify(|io| io.set(go, 1u8)).unwrap(); + source.run_until(2).unwrap(); + source.modify(|io| io.set(go, 0u8)).unwrap(); + source.run_until(3).unwrap(); + let file = source.save_state().unwrap(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); + STATE.with(|state| *state.borrow_mut() = Some(file)); + on_every_backend!(builder(&artifact, true), "Waiting", |sim| { + let file = STATE.with(|state| state.borrow().clone().unwrap()); + sim.load_state(&file).unwrap(); + assert_eq!(sim.time(), 3); + assert_eq!(value(&mut sim, "wakes"), 1); + sim.run_until(4).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 1); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + sim.run_until(5).unwrap(); + assert_eq!( + value(&mut sim, "wakes"), + 2, + "the loaded process still waits" + ); + }); +} + +thread_local! { + static STATE: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// IEEE 1800-2023 4.5: a process woken by `@(posedge clk)` runs in the +/// active region of that edge, before the edge's NBA region, so it reads the +/// flip-flop output from before the edge. +fn edge_order(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("EdgeOrder", four_state); + let clk = d.input("clk", 1); + let q = d.output("q", 8, 0); + let seen = d.output("seen", 8, 99); + d.counter(q, clk); + let read = d.read(q); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.assign(seen, read)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn edge_woken_processes_read_flip_flops_before_the_edge_publishes() { + for four_state in [false, true] { + let artifact = edge_order(four_state); + on_every_backend!(builder(&artifact, four_state), "EdgeOrder", |sim| { + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.add_clock("clk", 10, 5); + for edge in 1..=4u64 { + sim.run_until(10 * edge - 5).unwrap(); + assert_eq!(value(&mut sim, "q"), edge); + assert_eq!(value(&mut sim, "seen"), edge - 1); + } + }); + } +} + +/// A combinational process writes `y = 0; if (a) y = 1;`. With `a` steady, +/// settling again and reading does not re-run it, so `@(posedge y)` and the +/// flip-flops of `y` are not woken; a change of another input re-runs it and +/// the 1→0→1 pulse is an edge (IEEE 1800-2023 9.2.2.2). +fn comb_pulse(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("CombPulse", four_state); + let a = d.input("a", 1); + let b = d.input("b", 1); + let y = d.output("y", 1, 0); + let z = d.output("z", 1, 0); + let ffs = d.output("ffs", 8, 0); + let waits = d.output("waits", 8, 0); + let read_a = d.read(a); + let read_b = d.read(b); + let body = vec![ + d.set(y, 0), + Statement::If { + condition: read_a, + then_body: vec![d.set(y, 1)], + else_body: Vec::new(), + }, + d.assign(z, read_b), + ]; + d.module.comb_process(body).unwrap(); + d.counter(ffs, y); + let body = vec![Statement::Forever { + body: vec![wait(y, EventEdge::Posedge), d.increment(waits)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn comb_processes_pulse_only_when_an_input_changes() { + for four_state in [false, true] { + let artifact = comb_pulse(four_state); + on_every_backend!(builder(&artifact, four_state), "CombPulse", |sim| { + let a = sim.signal("a"); + let b = sim.signal("b"); + sim.modify(|io| { + io.set(a, 0u8); + io.set(b, 0u8); + }) + .unwrap(); + sim.run_until(0).unwrap(); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "y"), 1); + assert_eq!(value(&mut sim, "ffs"), 1); + assert_eq!(value(&mut sim, "waits"), 1); + // Steady inputs: settles and reads do not re-run the process. + for time in 2..6 { + sim.eval_comb().unwrap(); + assert_eq!(value(&mut sim, "y"), 1); + sim.run_until(time).unwrap(); + } + assert_eq!(value(&mut sim, "ffs"), 1, "no spurious edge"); + assert_eq!(value(&mut sim, "waits"), 1, "no spurious wakeup"); + sim.modify(|io| io.set(b, 1u8)).unwrap(); + sim.run_until(6).unwrap(); + assert_eq!(value(&mut sim, "z"), 1); + assert_eq!(value(&mut sim, "ffs"), 2, "the re-run pulses y"); + assert_eq!(value(&mut sim, "waits"), 2); + }); + } +} + +#[cfg(feature = "systemverilog")] +mod systemverilog { + use super::*; + + /// An imperative SystemVerilog combinational unit (one calling + /// `$urandom`) keeps its default-then-override writes; it is gated on + /// its inputs, so a steady input never pulses `y`. + const SOURCE: &str = r#" +module Top(input logic a, b, output logic y, output logic [31:0] r, output logic [7:0] n); + always_comb begin + y = 1'b0; + if (a) y = 1'b1; + r = b ? $urandom(7) : 32'd0; + end + initial n = 8'd0; + always_ff @(posedge y) n <= n + 8'd1; +endmodule +"#; + + #[test] + fn imperative_comb_units_pulse_only_when_an_input_changes() { + for four_state in [false, true] { + let build = || { + Simulator::from_sv_sources( + vec![(SOURCE, std::path::Path::new("comb_pulse.sv"))], + "Top", + ) + .four_state(four_state) + .emit_triggers() + }; + on_every_backend!(build(), "Top", |sim| { + let a = sim.signal("a"); + let b = sim.signal("b"); + sim.modify(|io| { + io.set(a, 0u8); + io.set(b, 0u8); + }) + .unwrap(); + sim.run_until(0).unwrap(); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "n"), 1); + for time in 2..6 { + sim.eval_comb().unwrap(); + assert_eq!(value(&mut sim, "y"), 1); + sim.run_until(time).unwrap(); + } + assert_eq!(value(&mut sim, "n"), 1, "no spurious edge"); + sim.modify(|io| io.set(b, 1u8)).unwrap(); + sim.run_until(6).unwrap(); + assert_eq!(value(&mut sim, "n"), 2, "the re-run pulses y"); + }); + } + } +} + +/// Records the entry points a timed step calls on a simulator. +struct Recording<'a, B: SimBackend> { + sim: &'a mut Simulator, + calls: Vec<&'static str>, +} + +impl celox_runtime::SimulationExecutor for Recording<'_, 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<(), celox_runtime::Halt> { + self.calls.push("comb"); + celox_runtime::SimulationExecutor::eval_comb(self.sim) + } + + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), celox_runtime::Halt> { + self.calls.push("eval_apply"); + celox_runtime::SimulationExecutor::eval_apply_ff_at(self.sim, event) + } + + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), celox_runtime::Halt> { + self.calls.push("eval_only"); + celox_runtime::SimulationExecutor::eval_only_ff_at(self.sim, event) + } + + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), celox_runtime::Halt> { + self.calls.push("apply"); + celox_runtime::SimulationExecutor::apply_ff_at(self.sim, event) + } + + fn run_process(&mut self, index: usize) -> Result<(), celox_runtime::Halt> { + self.calls.push("process"); + celox_runtime::SimulationExecutor::run_process(self.sim, index) + } +} + +/// Two registers on `clk`, a combinational output, and with `testbench` +/// a process that counts rising edges of `clk` and one that sleeps. +fn rtl(testbench: bool) -> FrontendArtifact { + let mut d = Design::new("Rtl", false); + let clk = d.input("clk", 1); + let a = d.output("a", 8, 0); + let b = d.output("b", 8, 0); + let sum = d.output("sum", 8, 0); + d.counter(a, clk); + let read_a = d.read(a); + d.register(b, read_a, clk, Edge::Posedge); + let read_b = d.read(b); + let ty = d.ty(8); + let added = d.module.binary(BinaryOp::Add, read_a, read_b, ty).unwrap(); + let target = d.module.whole(sum).unwrap(); + d.module.assign(target, added).unwrap(); + if testbench { + let edges = d.output("edges", 8, 0); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(edges)], + }]; + d.module.process(body).unwrap(); + let body = vec![d.inactive_delay(200)]; + d.module.process(body).unwrap(); + } + d.finish() +} + +fn recorded_steps(mut sim: Simulation, steps: usize) -> Vec> { + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(1).unwrap(); + (0..steps) + .map(|_| { + let mut recording = Recording { + sim: &mut sim.simulator, + calls: Vec::new(), + }; + sim.state.step(&mut recording).unwrap(); + recording.calls + }) + .collect() +} + +#[test] +fn processes_leave_the_flip_flop_path_of_a_time_slot_unchanged() { + let check = |threads: usize| { + let build = |testbench| { + builder(&rtl(testbench), false) + .threads(threads) + .build_native() + .unwrap() + }; + let plain = recorded_steps(Simulation::new(build(false)), 4); + let timed = recorded_steps(Simulation::new(build(true)), 4); + // Rising and falling edges of a plain design: one settle, the fused + // evaluate-and-apply of the domain, and the settle after it. + assert_eq!(plain[0], ["comb", "eval_apply", "comb"]); + assert_eq!(plain[1], ["comb"]); + // With a waiting testbench process, the rising edge additionally runs + // the woken process in front of the same flip-flop path; no extra + // settle or split evaluation. + for (plain, timed) in plain.iter().zip(&timed).step_by(2) { + let mut expected = vec!["process"]; + expected.extend(plain); + assert_eq!(timed, &expected); + } + for (plain, timed) in plain.iter().zip(&timed).skip(1).step_by(2) { + assert_eq!(timed, plain, "a falling edge wakes nothing"); + } + }; + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + for threads in [1, 4] { + check(threads); + } +} + +/// A domain evaluated twice before the NBA region publishes 1 and then 0 +/// to `q`: a process waiting for any change of `q` sees the pulse although +/// `q` ends at its old value. +fn republished(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Republished", four_state); + let clk = d.internal("clk", 1, 0); + let data = d.internal("data", 1, 0); + let q = d.output("q", 1, 0); + let changes = d.output("changes", 8, 0); + let read = d.read(data); + d.register(q, read, clk, Edge::Posedge); + let body = vec![ + d.delay(1), + d.set(data, 1), + d.set(clk, 1), + d.inactive_delay(0), + d.set(clk, 0), + d.set(data, 0), + d.inactive_delay(0), + d.set(clk, 1), + ]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(q, EventEdge::Change), d.increment(changes)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn every_publication_of_a_domain_is_an_update() { + for four_state in [false, true] { + let artifact = republished(four_state); + on_every_backend!(builder(&artifact, four_state), "Republished", |sim| { + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 0); + assert_eq!( + value(&mut sim, "changes"), + 1, + "q was 1 between the publications" + ); + }); + } +} + +/// A queued nonblocking assignment returns to the runtime between the two +/// writes of `clk`; the pulse is still an edge for waits and registers. +fn pulse_around_nba(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("PulseAroundNba", four_state); + let clk = d.internal("clk", 1, 0); + let r = d.internal("r", 8, 0); + let waits = d.output("waits", 8, 0); + let ffs = d.output("ffs", 8, 0); + d.counter(ffs, clk); + let one = d.constant(1, 8); + let two = d.constant(2, 8); + // Two sites assign `r`, so both go through the queue. + let body = vec![ + d.delay(1), + d.set(clk, 1), + d.nonblocking(r, one), + d.set(clk, 0), + d.nonblocking(r, two), + ]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(waits)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn a_pulse_around_a_queued_nonblocking_assignment_is_an_edge() { + for four_state in [false, true] { + let artifact = pulse_around_nba(four_state); + on_every_backend!(builder(&artifact, four_state), "PulseAroundNba", |sim| { + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "r"), 2); + assert_eq!(value(&mut sim, "waits"), 1); + assert_eq!(value(&mut sim, "ffs"), 1); + }); + } +} + +#[test] +fn host_write_pulses_survive_checkpoints_and_state_files() { + // A pulse written by the host and saved before the step that shows it + // to the waits. + let artifact = waiting(false); + on_every_backend!(builder(&artifact, false), "Waiting", |sim| { + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.run_until(1).unwrap(); + sim.modify(|io| { + io.set(go, 1u8); + io.set(go, 0u8); + }) + .unwrap(); + let saved = sim.checkpoint().unwrap(); + let file = sim.save_state().unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 1); + sim.restore(&saved).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!( + value(&mut sim, "wakes"), + 1, + "restored with the pending pulse" + ); + sim.load_state(&file).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 0); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "wakes"), 1, "loaded with the pending pulse"); + }); +} + +#[test] +fn loading_a_finished_state_freezes_the_simulation() { + let artifact = finishing(false); + on_every_backend!(builder(&artifact, false), "Finishing", |sim| { + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + let start = sim.save_state().unwrap(); + sim.run_until(10).unwrap(); + assert!(sim.is_finished()); + let finished = sim.save_state().unwrap(); + sim.load_state(&start).unwrap(); + assert!(!sim.is_finished()); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 5u8)).unwrap(); + assert_eq!( + value(&mut sim, "a"), + 5, + "an unfinished state accepts writes" + ); + sim.load_state(&finished).unwrap(); + assert!(sim.is_finished()); + sim.modify(|io| io.set(a, 7u8)).unwrap(); + assert_eq!(value(&mut sim, "a"), 1, "a finished state is frozen"); + }); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn finish_during_a_direct_settle_ends_the_simulation() { + const SOURCE: &str = r#" +module Top(input logic go, output logic [7:0] y); + always_comb begin + y = go ? 8'd1 : 8'd0; + if (go) $finish; + end +endmodule +"#; + let build = || { + Simulator::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") + .emit_triggers() + }; + on_every_backend!(build(), "Top", |sim| { + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.eval_comb().unwrap(); + assert!(!sim.is_finished()); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + sim.eval_comb().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.next_event_time(), None); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + assert_eq!(value(&mut sim, "y"), 1, "frozen at the finish"); + }); +} + +/// Two outputs of a domain evaluated twice publish 1 then 0 together; a +/// domain on the negative edge of the first sees its pulse although the +/// transitions of the two signals interleave. +fn interleaved(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("Interleaved", four_state); + let clk = d.internal("clk", 1, 0); + let data = d.internal("data", 1, 0); + let qa = d.output("qa", 1, 0); + let qb = d.output("qb", 1, 0); + let falls = d.output("falls", 8, 0); + let rises = d.output("rises", 8, 0); + for q in [qa, qb] { + let read = d.read(data); + d.register(q, read, clk, Edge::Posedge); + } + let next = d.plus_one(falls); + d.register(falls, next, qa, Edge::Negedge); + d.counter(rises, qb); + let body = vec![ + d.delay(1), + d.set(data, 1), + d.set(clk, 1), + d.inactive_delay(0), + d.set(clk, 0), + d.set(data, 0), + d.inactive_delay(0), + d.set(clk, 1), + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn interleaved_publications_keep_each_signals_edges() { + for four_state in [false, true] { + let artifact = interleaved(four_state); + on_every_backend!(builder(&artifact, four_state), "Interleaved", |sim| { + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "qa"), 0); + assert_eq!(value(&mut sim, "rises"), 1); + assert_eq!(value(&mut sim, "falls"), 1, "qa fell after its pulse"); + }); + } +} + +#[test] +fn state_files_reject_queued_assignments_outside_their_target() { + let artifact = nonblocking(false); + let mut sim = Simulation::new(builder(&artifact, false).build_interpreter().unwrap()); + sim.run_until(0).unwrap(); + let mut file = sim.save_state().unwrap(); + file.schedule + .as_mut() + .unwrap() + .processes + .nba_queue + .push(celox_runtime::NbaRecord { + target: "q".into(), + lsb: 4, + width: u64::MAX, + value: vec![1], + mask: Vec::new(), + }); + assert!(matches!( + sim.load_state(&file), + Err(crate::StateError::Mismatch(_)) + )); +} + +/// Two processes write a high clock low and then high again in one slot: +/// the second write is a positive edge although the clock ends where it +/// started. +fn low_then_high(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("LowThenHigh", four_state); + let clk = d.internal("clk", 1, 1); + let ffs = d.output("ffs", 8, 0); + d.counter(ffs, clk); + let body = vec![d.delay(1), d.set(clk, 0)]; + d.module.process(body).unwrap(); + let body = vec![d.delay(1), d.set(clk, 1)]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn a_signal_written_again_compares_with_its_preceding_value() { + for four_state in [false, true] { + let artifact = low_then_high(four_state); + on_every_backend!(builder(&artifact, four_state), "LowThenHigh", |sim| { + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "clk"), 1); + assert_eq!(value(&mut sim, "ffs"), 1); + }); + } +} + +/// `clk <= 1; clk <= 0;` from a low clock pulses it in the NBA region. +fn nba_pulse(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("NbaPulse", four_state); + let clk = d.internal("clk", 1, 0); + let ffs = d.output("ffs", 8, 0); + d.counter(ffs, clk); + let one = d.constant(1, 1); + let zero = d.constant(0, 1); + let body = vec![ + d.delay(1), + d.nonblocking(clk, one), + d.nonblocking(clk, zero), + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn queued_nonblocking_pulses_trigger_flip_flops() { + for four_state in [false, true] { + let artifact = nba_pulse(four_state); + on_every_backend!(builder(&artifact, four_state), "NbaPulse", |sim| { + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "clk"), 0); + assert_eq!(value(&mut sim, "ffs"), 1); + }); + } +} + +/// A combinational process overwrites part of what it assigned. +fn comb_override(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("CombOverride", four_state); + let a = d.input("a", 8); + let low = d.input("low", 1); + let y = d.output("y", 8, 0); + let read_a = d.read(a); + let read_low = d.read(low); + let first = d.module.slice(y, 0, 1).unwrap(); + let body = vec![ + d.assign(y, read_a), + Statement::Assign { + target: first, + value: read_low, + }, + ]; + d.module.comb_process(body).unwrap(); + d.finish() +} + +#[test] +fn comb_processes_may_overwrite_their_own_targets() { + for four_state in [false, true] { + let artifact = comb_override(four_state); + on_every_backend!(builder(&artifact, four_state), "CombOverride", |sim| { + let a = sim.signal("a"); + let low = sim.signal("low"); + sim.modify(|io| { + io.set(a, 0xf0u8); + io.set(low, 1u8); + }) + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "y"), 0xf1); + }); + } +} + +#[test] +fn the_waveform_records_the_finish() { + let artifact = finishing(false); + let path = std::env::temp_dir().join(format!("celox-finish-{}.vcd", std::process::id())); + let mut sim = Simulation::new( + builder(&artifact, false) + .vcd(&path) + .build_interpreter() + .unwrap(), + ); + let clk = sim.signal("clk"); + sim.modify(|io| io.set(clk, 0u8)).unwrap(); + sim.add_clock("clk", 2, 1); + sim.run_until(20).unwrap(); + assert!(sim.is_finished()); + sim.flush_vcd().unwrap(); + let vcd = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).ok(); + let last = vcd.lines().rfind(|line| line.starts_with('#')); + assert_eq!(last, Some("#4"), "{vcd}"); +} + +#[test] +fn state_files_reject_baselines_of_the_wrong_kind() { + let artifact = waiting(false); + let mut sim = Simulation::new(builder(&artifact, false).build_interpreter().unwrap()); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.run_until(1).unwrap(); + let mut file = sim.save_state().unwrap(); + let waiters = &mut file.schedule.as_mut().unwrap().processes.waiters; + assert_eq!(waiters.len(), 1); + // `go` is not counted: its wait compares values. + waiters[0].baselines = vec![celox_runtime::BaselineRecord::Counter { + seen: 0, + value: vec![0], + mask: vec![0], + }]; + assert!(matches!( + sim.load_state(&file), + Err(crate::StateError::Mismatch(_)) + )); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn saving_state_after_a_finishing_write_records_the_finish() { + const SOURCE: &str = r#" +module Top(input logic go, output logic [7:0] y); + always_comb begin + y = go ? 8'd1 : 8'd0; + if (go) $finish; + end +endmodule +"#; + let mut sim = Simulation::new( + Simulator::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") + .emit_triggers() + .build_interpreter() + .unwrap(), + ); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.run_until(0).unwrap(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let file = sim.save_state().unwrap(); + assert!(sim.is_finished()); + assert!(file.schedule.unwrap().processes.finished); +} + +/// `y = a & b` is read only by a wait: dead store elimination keeps its +/// store, so the wait still sees `y` rise. +fn wait_on_comb(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("WaitOnComb", four_state); + let a = d.input("a", 1); + let b = d.input("b", 1); + let ty = d.ty(1); + let y = d.module.internal("y", ty).unwrap(); + let hits = d.output("hits", 8, 0); + let (read_a, read_b) = (d.read(a), d.read(b)); + let and = d.module.binary(BinaryOp::And, read_a, read_b, ty).unwrap(); + let target = d.module.whole(y).unwrap(); + d.module.assign(target, and).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(y, EventEdge::Posedge), d.increment(hits)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn dead_store_elimination_keeps_signals_a_wait_watches() { + for four_state in [false, true] { + let artifact = wait_on_comb(four_state); + let optimized = || builder(&artifact, four_state).opt_level(crate::OptLevel::O2); + on_every_backend!(optimized(), "WaitOnComb", |sim| { + let (a, b) = (sim.signal("a"), sim.signal("b")); + sim.modify(|io| { + io.set(a, 0u8); + io.set(b, 1u8); + }) + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "hits"), 0); + for (time, hits) in [(2, 1), (4, 2)] { + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(time).unwrap(); + assert_eq!(value(&mut sim, "hits"), hits); + sim.modify(|io| io.set(a, 0u8)).unwrap(); + sim.run_until(time + 1).unwrap(); + } + }); + } +} + +/// A scheduled `clk` edge triggers one domain, and the process it wakes +/// pulses `p` with two nonblocking assignments: the domain of `p` sees the +/// pulse although only one domain evaluated in front of it. +fn nba_pulse_after_one_domain(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("NbaPulseOneDomain", four_state); + let clk = d.input("clk", 1); + let p = d.internal("p", 1, 0); + let a_count = d.output("a_count", 8, 0); + let b_count = d.output("b_count", 8, 0); + d.counter(a_count, clk); + d.counter(b_count, p); + let one = d.constant(1, 1); + let zero = d.constant(0, 1); + let body = vec![Statement::Forever { + body: vec![ + wait(clk, EventEdge::Posedge), + d.nonblocking(p, one), + d.nonblocking(p, zero), + ], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn nonblocking_pulses_after_a_single_domain_trigger_their_domain() { + for four_state in [false, true] { + let artifact = nba_pulse_after_one_domain(four_state); + on_every_backend!(builder(&artifact, four_state), "NbaPulseOneDomain", |sim| { + sim.schedule("clk", 0, 0).unwrap(); + sim.run_until(0).unwrap(); + for edge in 1..=3u64 { + sim.schedule("clk", 2 * edge - 1, 1).unwrap(); + sim.schedule("clk", 2 * edge, 0).unwrap(); + sim.run_until(2 * edge).unwrap(); + assert_eq!(value(&mut sim, "a_count"), edge); + assert_eq!(value(&mut sim, "p"), 0); + assert_eq!(value(&mut sim, "b_count"), edge, "edge {edge}"); + } + }); + } +} + +/// `s` falls in one wave of the active region and rises again in the next, +/// written by the process the fall woke: the domain of `s` sees the rise. +fn pulse_across_waves(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("PulseAcrossWaves", four_state); + let s = d.internal("s", 1, 1); + let rises = d.output("rises", 8, 0); + d.counter(rises, s); + let body = vec![d.delay(1), d.set(s, 0)]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(s, EventEdge::Negedge), d.set(s, 1)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn a_pulse_across_two_waves_of_a_slot_is_an_edge() { + for four_state in [false, true] { + let artifact = pulse_across_waves(four_state); + on_every_backend!(builder(&artifact, four_state), "PulseAcrossWaves", |sim| { + sim.run_until(0).unwrap(); + assert_eq!(value(&mut sim, "rises"), 0); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "s"), 1); + assert_eq!(value(&mut sim, "rises"), 1); + }); + } +} + +/// Processes that keep resuming at one time, through `#0`, by waking each +/// other or in a loop without a timing control, exhaust the slot's budget +/// instead of hanging a step. +fn zero_time_loops(four_state: bool) -> [FrontendArtifact; 3] { + let mut d = Design::new("InactiveLoop", four_state); + let body = vec![ + d.delay(1), + Statement::Forever { + body: vec![d.inactive_delay(0)], + }, + ]; + d.module.process(body).unwrap(); + let inactive = d.finish(); + + let mut d = Design::new("PingPong", four_state); + let ping = d.internal("ping", 1, 0); + let pong = d.internal("pong", 1, 0); + let (read_ping, read_pong) = (d.read(ping), d.read(pong)); + let ty = d.ty(1); + let not_ping = d.module.unary(UnaryOp::BitNot, read_ping, ty).unwrap(); + let not_pong = d.module.unary(UnaryOp::BitNot, read_pong, ty).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(ping, EventEdge::Change), d.assign(pong, not_pong)], + }]; + d.module.process(body).unwrap(); + let body = vec![Statement::Forever { + body: vec![wait(pong, EventEdge::Change), d.assign(ping, not_ping)], + }]; + d.module.process(body).unwrap(); + let body = vec![d.delay(1), d.set(ping, 1)]; + d.module.process(body).unwrap(); + let ping_pong = d.finish(); + + let mut d = Design::new("Spin", four_state); + let count = d.output("count", 8, 0); + let body = vec![ + d.delay(1), + Statement::Forever { + body: vec![d.increment(count)], + }, + ]; + d.module.process(body).unwrap(); + [inactive, ping_pong, d.finish()] +} + +#[test] +fn zero_time_loops_exhaust_the_slot_budget() { + for four_state in [false, true] { + for (artifact, top) in + zero_time_loops(four_state) + .into_iter() + .zip(["InactiveLoop", "PingPong", "Spin"]) + { + on_every_backend!(builder(&artifact, four_state), top, |sim| { + sim.state.set_slot_budgets(256, 2); + sim.run_until(0).unwrap(); + let error = sim.run_until(5).unwrap_err(); + assert!( + matches!( + &error, + crate::RuntimeErrorCode::Runtime { message, .. } + if message.contains("does not settle") + || message.contains("does not suspend") + ), + "{error}" + ); + assert_eq!(sim.time(), 1); + }); + } + } +} + +/// A process waiting on an input wakes at the time the host writes the +/// input through the raw memory view, as the TypeScript DUT does, once +/// the host reports the write. +fn raw_go(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("RawGo", four_state); + let go = d.input("go", 1); + let done = d.output("done", 8, 0); + let body = vec![wait(go, EventEdge::Posedge), d.set(done, 1)]; + d.module.process(body).unwrap(); + d.finish() +} + +/// Write `value` to `signal` through the raw memory view. +fn write_raw(sim: &mut Simulation, signal: crate::SignalRef, value: u8) { + let four_state = sim.layout().four_state && signal.is_4state; + let bytes = signal.width.div_ceil(8); + let (pointer, size) = sim.memory_as_mut_ptr(); + assert!(signal.offset + 2 * bytes <= size); + // Safety: the view holds `size` writable bytes. + unsafe { + *pointer.add(signal.offset) = value; + if four_state { + *pointer.add(signal.offset + bytes) = 0; + } + } +} + +#[test] +fn raw_host_writes_wake_waits_at_the_current_time() { + for four_state in [false, true] { + let artifact = raw_go(four_state); + on_every_backend!(builder(&artifact, four_state), "RawGo", |sim| { + let go = sim.signal("go"); + write_raw(&mut sim, go, 0); + sim.note_raw_writes(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "done"), 0); + write_raw(&mut sim, go, 1); + sim.note_raw_writes(); + assert_eq!(sim.next_event_time(), Some(3)); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "done"), 1); + }); + } +} + +/// `v[1] = a` drives one bit of `v`, a combinational process copies it to +/// `v[0]`: the process reads the bit it does not write, so it runs again +/// when `a` changes (IEEE 1800-2023 9.2.2.2.1). +fn comb_reads_unwritten_bits(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("CombBits", four_state); + let a = d.input("a", 1); + let ty = d.ty(2); + let v = d.module.internal("v", ty).unwrap(); + let y = d.output("y", 2, 0); + let high = d.module.slice(v, 1, 1).unwrap(); + let read_a = d.read(a); + d.module.assign(high, read_a).unwrap(); + let low = d.module.slice(v, 0, 1).unwrap(); + let read_v = d.read(v); + let bit = d.module.expr_slice(read_v, 1, 1).unwrap(); + d.module + .comb_process(vec![Statement::Assign { + target: low, + value: bit, + }]) + .unwrap(); + let read_v = d.read(v); + let whole_y = d.module.whole(y).unwrap(); + d.module.assign(whole_y, read_v).unwrap(); + d.finish() +} + +#[test] +fn comb_processes_rerun_on_bits_they_do_not_write() { + for four_state in [false, true] { + let artifact = comb_reads_unwritten_bits(four_state); + on_every_backend!(builder(&artifact, four_state), "CombBits", |sim| { + let a = sim.signal("a"); + for (time, input, expected) in [(1, 0u8, 0u64), (2, 1, 3), (3, 0, 0), (4, 1, 3)] { + sim.modify(|io| io.set(a, input)).unwrap(); + sim.run_until(time).unwrap(); + assert_eq!(value(&mut sim, "y"), expected, "a = {input}"); + } + }); + } +} + +/// `gclk = clk & en` clocks a counter, and a process waits on `clk`: the +/// woken process makes a second wave of the active region, or with `#0` +/// an inactive region, before the gated domain evaluates. The domain still +/// sees every edge. +fn gated_clock_with_process(four_state: bool, inactive: bool) -> FrontendArtifact { + let mut d = Design::new("GatedClock", four_state); + let clk = d.input("clk", 1); + let en = d.input("en", 1); + let ty = d.ty(1); + let gclk = d.module.internal("gclk", ty).unwrap(); + let (read_clk, read_en) = (d.read(clk), d.read(en)); + let and = d + .module + .binary(BinaryOp::And, read_clk, read_en, ty) + .unwrap(); + let target = d.module.whole(gclk).unwrap(); + d.module.assign(target, and).unwrap(); + let count = d.output("count", 8, 0); + d.counter(count, gclk); + let ticks = d.output("ticks", 8, 0); + d.counter(ticks, clk); + let wakes = d.output("wakes", 8, 0); + let mut body = vec![wait(clk, EventEdge::Posedge)]; + if inactive { + body.push(d.inactive_delay(0)); + } + body.push(d.increment(wakes)); + d.module.process(vec![Statement::Forever { body }]).unwrap(); + d.finish() +} + +#[test] +fn gated_clocks_see_their_edges_with_processes() { + for four_state in [false, true] { + for inactive in [false, true] { + let artifact = gated_clock_with_process(four_state, inactive); + on_every_backend!(builder(&artifact, four_state), "GatedClock", |sim| { + let en = sim.signal("en"); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.schedule("clk", 0, 0).unwrap(); + sim.run_until(0).unwrap(); + for edge in 1..=3u64 { + sim.schedule("clk", 2 * edge - 1, 1).unwrap(); + sim.schedule("clk", 2 * edge, 0).unwrap(); + sim.run_until(2 * edge).unwrap(); + assert_eq!(value(&mut sim, "ticks"), edge); + assert_eq!(value(&mut sim, "wakes"), edge); + assert_eq!(value(&mut sim, "count"), edge, "edge {edge}"); + } + }); + } + } +} + +/// A process that has finished, or one waiting on a clock, does not keep +/// host writes from advancing time: each step settles them at the current +/// time and goes on to the next event. +fn host_writes_with_processes(four_state: bool, waiting: bool) -> FrontendArtifact { + let mut d = Design::new("HostSteps", four_state); + let clk = d.input("clk", 1); + let din = d.input("d", 8); + let q = d.output("q", 8, 0); + let read = d.read(din); + let target = d.module.whole(q).unwrap(); + d.module.assign(target, read).unwrap(); + let ticks = d.output("ticks", 8, 0); + d.counter(ticks, clk); + let done = d.output("done", 1, 0); + let body = vec![d.delay(5), d.set(done, 1)]; + d.module.process(body).unwrap(); + if waiting { + let rises = d.output("rises", 8, 0); + let body = vec![Statement::Forever { + body: vec![wait(clk, EventEdge::Posedge), d.increment(rises)], + }]; + d.module.process(body).unwrap(); + } + d.finish() +} + +#[test] +fn host_writes_do_not_hold_steps_at_the_current_time() { + for four_state in [false, true] { + for waiting in [false, true] { + let artifact = host_writes_with_processes(four_state, waiting); + on_every_backend!(builder(&artifact, four_state), "HostSteps", |sim| { + for (time, level) in [(10, 1), (20, 0), (30, 1)] { + sim.schedule("clk", time, level).unwrap(); + } + sim.run_until(6).unwrap(); + assert_eq!(value(&mut sim, "done"), 1); + let din = sim.signal("d"); + for (index, time) in [10u64, 20, 30].into_iter().enumerate() { + sim.modify(|io| io.set(din, index as u8 + 1)).unwrap(); + assert_eq!(sim.step().unwrap(), Some(time)); + assert_eq!(value(&mut sim, "q"), index as u64 + 1); + } + }); + } + } +} + +/// `v` is counted, since a process stores `v[0]` twice, and a wait watches +/// it; `v[1]` is driven combinationally from an input. The wait sees the +/// changes the uncounted writer makes too. +fn counted_with_comb_writer(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("CountedComb", four_state); + let a = d.input("a", 1); + let ty = d.ty(2); + let v = d.module.internal("v", ty).unwrap(); + let high = d.module.slice(v, 1, 1).unwrap(); + let read_a = d.read(a); + d.module.assign(high, read_a).unwrap(); + let changes = d.output("changes", 8, 0); + let body = vec![Statement::Forever { + body: vec![wait(v, EventEdge::Change), d.increment(changes)], + }]; + d.module.process(body).unwrap(); + let low = d.module.slice(v, 0, 1).unwrap(); + let (one, zero) = (d.constant(1, 1), d.constant(0, 1)); + let body = vec![ + Statement::Assign { + target: low, + value: one, + }, + Statement::Assign { + target: low, + value: zero, + }, + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn waits_on_counted_signals_see_uncounted_writers() { + for four_state in [false, true] { + let artifact = counted_with_comb_writer(four_state); + on_every_backend!(builder(&artifact, four_state), "CountedComb", |sim| { + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 0u8)).unwrap(); + sim.run_until(1).unwrap(); + let base = value(&mut sim, "changes"); + assert!(base >= 1, "the pulse of v[0] is a change"); + for (time, input, changes) in [(2, 1u8, base + 1), (4, 0, base + 2)] { + sim.modify(|io| io.set(a, input)).unwrap(); + // Saving settles the write; the loaded wait still compares + // with the value it saw before it. + let file = sim.save_state().unwrap(); + sim.load_state(&file).unwrap(); + sim.run_until(time).unwrap(); + assert_eq!(value(&mut sim, "changes"), changes, "a = {input}"); + } + }); + } +} + +/// `a` toggles on `clk`, `b <= a` on `posedge a`, and `y = a & ~b`: when +/// `a` first rises, `y` is high between the two domains' publications and +/// low at the end of the slot. A process waiting on `posedge y` sees the +/// pulse like the flip-flop clocked by `y` does. +fn comb_pulse_between_waves(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("CombPulse", four_state); + let clk = d.input("clk", 1); + let a = d.internal("a", 1, 0); + let b = d.internal("b", 1, 0); + let ty = d.ty(1); + let y = d.module.internal("y", ty).unwrap(); + let read_a = d.read(a); + let not_a = d.module.unary(UnaryOp::BitNot, read_a, ty).unwrap(); + d.register(a, not_a, clk, Edge::Posedge); + let read_a = d.read(a); + d.register(b, read_a, a, Edge::Posedge); + let (read_a, read_b) = (d.read(a), d.read(b)); + let not_b = d.module.unary(UnaryOp::BitNot, read_b, ty).unwrap(); + let and = d.module.binary(BinaryOp::And, read_a, not_b, ty).unwrap(); + let target = d.module.whole(y).unwrap(); + d.module.assign(target, and).unwrap(); + let ffs = d.output("ffs", 8, 0); + d.counter(ffs, y); + let wakes = d.output("wakes", 8, 0); + let body = vec![Statement::Forever { + body: vec![wait(y, EventEdge::Posedge), d.increment(wakes)], + }]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn waits_see_combinational_pulses_between_flip_flop_waves() { + for four_state in [false, true] { + let artifact = comb_pulse_between_waves(four_state); + on_every_backend!(builder(&artifact, four_state), "CombPulse", |sim| { + sim.schedule("clk", 0, 0).unwrap(); + for edge in 1..=4u64 { + sim.schedule("clk", 2 * edge - 1, 1).unwrap(); + sim.schedule("clk", 2 * edge, 0).unwrap(); + } + sim.run_until(8).unwrap(); + assert_eq!(value(&mut sim, "ffs"), 1); + assert_eq!(value(&mut sim, "wakes"), 1); + }); + } +} + +/// A loop that may not suspend yields only every 2^16 iterations: a long +/// finite loop finishes within a return budget of two. +fn long_loop(four_state: bool) -> FrontendArtifact { + let mut d = Design::new("LongLoop", four_state); + let i = d.output("i", 32, 0); + let done = d.output("done", 1, 0); + let read = d.read(i); + let limit = d.constant(1 << 17, 32); + let ty = d.ty(1); + let condition = d + .module + .binary(BinaryOp::LessUnsigned, read, limit, ty) + .unwrap(); + let body = vec![ + d.delay(1), + Statement::While { + condition, + body: vec![d.increment(i)], + }, + d.set(done, 1), + ]; + d.module.process(body).unwrap(); + d.finish() +} + +#[test] +fn long_finite_loops_yield_rarely() { + for four_state in [false, true] { + let artifact = long_loop(four_state); + on_every_backend!(builder(&artifact, four_state), "LongLoop", |sim| { + sim.state.set_slot_budgets(256, 2); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "i"), 1 << 17); + assert_eq!(value(&mut sim, "done"), 1); + }); + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 8c7393b161a..c84171fb151 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -123,6 +123,17 @@ mod host { derived_ticks: celox_runtime::DerivedTickPlans, /// Boxed, so that taking it out for a tick moves one pointer. derived_scratch: Option>, + /// The design finished a timed simulation (`$finish`). Evaluation, + /// host writes and waveform dumps no longer change anything. + pub(crate) frozen: bool, + /// Host writes a timed simulation observes one at a time. + pub(crate) host_watch: celox_runtime::HostWatch, + /// Runtime-event sequence up to which a timed simulation looked for + /// `$finish` records. + pub(crate) finish_scan_seq: u64, + /// Whether a timed simulation runs the design and it has a `$finish` + /// runtime event site. + pub(crate) finish_sites: bool, } /// Why [`Simulator::try_dump`] failed. @@ -711,6 +722,10 @@ mod host { tick_timing_eval_comb_ns: 0, derived_ticks, derived_scratch: Some(Box::new(derived_scratch)), + frozen: false, + host_watch: Default::default(), + finish_scan_seq: 0, + finish_sites: false, }; sim.comb_observer_snapshots = sim.snapshot_all_comb_observers(); sim @@ -965,6 +980,36 @@ mod host { } } + /// Whether the design wrote a `$finish` record since the last call. + pub(crate) fn take_runtime_finish(&mut self) -> bool { + if !self.finish_sites { + return false; + } + let write_seq = self.runtime_event_write_seq(); + if write_seq == self.finish_scan_seq { + return false; + } + let events = self.peek_backend_runtime_events_from(self.finish_scan_seq); + self.finish_scan_seq = write_seq; + let sites = &self.program.runtime_schema.runtime_event_sites; + events.iter().any(|event| { + matches!( + event, + RawRuntimeEvent::Event { site_id, .. } + if sites.get(*site_id).is_some_and(|site| { + matches!(site.kind, RuntimeEventKind::Finish) + }) + ) + }) + } + + /// Start looking for `$finish` records at the current sequence. + pub(crate) fn skip_runtime_finish(&mut self) { + if self.finish_sites { + self.finish_scan_seq = self.runtime_event_write_seq(); + } + } + fn runtime_event_write_seq(&self) -> u64 { if let Some(buffer) = self.backend.runtime_event_buffer() { buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire) @@ -1047,6 +1092,9 @@ mod host { /// VCD file. Fails if combinational evaluation or writing fails, or /// if `timestamp` is earlier than the last dumped timestamp. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), DumpError> { + if self.frozen { + return Ok(()); + } if self.dirty { self.eval_comb_checked().map_err(DumpError::Runtime)?; self.dirty = false; @@ -1142,8 +1190,12 @@ mod host { where F: FnOnce(&mut IOContext), { + if self.frozen { + return Ok(()); + } let mut ctx = IOContext { backend: &mut self.backend, + watch: &mut self.host_watch, }; f(&mut ctx); self.dirty = true; @@ -1160,6 +1212,9 @@ mod host { } pub(crate) fn eval_comb_checked(&mut self) -> Result<(), RuntimeErrorCode> { + if self.frozen { + return Ok(()); + } let (result, events) = self.eval_comb_capturing_events(); let fatal_status = matches!( &result, @@ -1803,6 +1858,11 @@ mod host { pub fn named_events(&self) -> Vec> { let mut result = Vec::new(); for (id, addr) in self.backend.id_to_addr_slice().iter().enumerate() { + // A hidden event, such as the copy of a clock sensed at its + // other edge, has no name to list. + if !self.event_is_named(addr) { + continue; + } let name = self.program.get_path(addr); if let Some(ev) = self.backend.resolve_event_opt(addr) { result.push(NamedEvent { @@ -1815,6 +1875,19 @@ mod host { result } + /// Whether the event at `addr` is a variable a path names. + fn event_is_named(&self, addr: &crate::ir::AbsoluteAddr) -> bool { + self.program + .design + .instance(addr.instance_id) + .is_some_and(|instance| { + self.program + .design + .variable(addr) + .is_some_and(|variable| instance.resolves_path_to(&variable.path, *addr)) + }) + } + /// Triggers a clock/event by its numeric ID. /// /// # Errors diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index e4159342014..e766ce119df 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -95,6 +95,8 @@ pub struct Checkpoint { testbench_strings: celox_testbench::TestbenchStrings, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, + /// Whether the design had finished a timed simulation. + frozen: bool, } impl Checkpoint { @@ -146,6 +148,7 @@ impl Simulator { testbench_strings: self.testbench_strings.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, + frozen: self.frozen, }) } @@ -158,6 +161,7 @@ impl Simulator { pub fn restore(&mut self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { self.validate_restore(checkpoint)?; let fingerprint = self.state_fingerprint(); + self.frozen = checkpoint.frozen; checkpoint .image .restore_into(&mut self.backend, fingerprint)?; diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index faf5e1714de..5e3c705175c 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -12,8 +12,10 @@ use std::sync::Arc; use crate::HashMap; use celox_runtime::scheduler::SimEvent; +use celox_runtime::timing::Baseline; use celox_runtime::{ - ScheduleParts, ScheduleRecord, ScheduledEvent, StateFile, StateObject, StateRole, + BaselineRecord, NbaRecord, ProcessRecord, ProcessState, ScheduleParts, ScheduleRecord, + ScheduledEvent, StateFile, StateObject, StateRole, WaiterRecord, }; use num_bigint::BigUint; @@ -34,9 +36,9 @@ pub enum StateError { MissingSchedule, #[error("evaluating combinational logic failed: {0}")] Runtime(RuntimeErrorCode), - /// A suspended process is not a named state object, so a state file - /// cannot record where it resumes. - #[error("state files are not supported for simulations with processes")] + /// Not returned: state files record suspended processes. Kept so that + /// matching code keeps compiling. + #[error("the state of the simulation's processes could not be recorded")] Processes, #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] TestbenchStrings, @@ -367,6 +369,7 @@ impl Simulator { signal: signal_path(event), value: event.next_val, }; + let processes = self.name_processes(&parts, &signal_paths); ScheduleRecord { time: parts.time, clocks: parts @@ -381,9 +384,345 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), + processes, } } + /// The status slot of each process, by which a state file names it. + fn process_statuses(&self) -> Vec { + self.program + .runtime_schema + .processes + .iter() + .map(|slots| self.backend.resolve_signal(&slots.status)) + .collect() + } + + /// The signal of each counted signal, in counter order. + fn counted_signals(&self) -> Vec { + self.program + .runtime_schema + .watches + .iter() + .map(|watch| self.backend.resolve_signal(&watch.signal)) + .collect() + } + + fn name_processes( + &self, + parts: &ScheduleParts, + signal_paths: &HashMap, + ) -> ProcessRecord { + let path = |signal: SignalRef| { + signal_paths + .get(&signal.offset) + .cloned() + .unwrap_or_default() + }; + let statuses = self.process_statuses(); + let process = |index: usize| path(statuses[index]); + let state = &parts.process_state; + ProcessRecord { + wakeups: parts + .process_wakeups + .iter() + .map(|&(index, time)| (process(index), time)) + .collect(), + waiters: state + .waiters + .iter() + .map(|(index, waiter)| { + // The widths of the site's term signals split a plane + // image into its value and mask. + let widths: Vec = self + .program + .runtime_schema + .wait_sites + .iter() + .filter(|site| site.process == index) + .nth(waiter.site) + .map(|site| { + site.terms + .iter() + .map(|(signal, _)| self.backend.resolve_signal(signal).width) + .collect() + }) + .unwrap_or_default(); + WaiterRecord { + process: process(index), + site: waiter.site as u64, + baselines: waiter + .baselines + .iter() + .enumerate() + .map(|(term, baseline)| match baseline { + Baseline::Counter { + seen, + value: (value, mask), + } => BaselineRecord::Counter { + seen: *seen, + value: value.to_bytes_le(), + mask: mask.to_bytes_le(), + }, + Baseline::Value((value, mask)) => BaselineRecord::Value { + value: value.to_bytes_le(), + mask: mask.to_bytes_le(), + }, + Baseline::Raw(image) => { + let bytes = widths + .get(term) + .map_or(image.len(), |width| width.div_ceil(8).max(1)) + .min(image.len()); + BaselineRecord::Value { + value: image[..bytes].to_vec(), + mask: image[bytes..].to_vec(), + } + } + }) + .collect(), + } + }) + .collect(), + ready: state.ready.iter().map(|&index| process(index)).collect(), + inactive: state.inactive.iter().map(|&index| process(index)).collect(), + nba_queue: state + .nba_queue + .iter() + .map(|update| NbaRecord { + target: path(update.target), + lsb: update.lsb as u64, + width: update.width as u64, + value: update.value.0.to_bytes_le(), + mask: update.value.1.to_bytes_le(), + }) + .collect(), + domain_counters: self + .counted_signals() + .into_iter() + .zip(&state.domain_counters) + .map(|(signal, counters)| (path(signal), *counters)) + .collect(), + host_writes: Vec::new(), + host_pending: parts.host_pending, + finished: parts.finished, + } + } + + /// The host writes a timed simulation has yet to show its waits, by + /// signal path. + pub(crate) fn name_host_writes(&self) -> Vec<(String, Vec, Vec)> { + let schema = self.state_schema(); + self.host_watch + .log() + .iter() + .filter_map(|(signal, (value, mask))| { + let object = schema + .objects + .iter() + .find(|object| object.signal.offset == signal.offset)?; + Some((object.path.clone(), value.to_bytes_le(), mask.to_bytes_le())) + }) + .collect() + } + + /// Resolve logged host writes, or the signal names this design does not + /// declare. + pub(crate) fn resolve_host_writes( + &self, + writes: &[(String, Vec, Vec)], + ) -> Result, StateError> { + let schema = self.state_schema(); + let mut unknown = Vec::new(); + let resolved = writes + .iter() + .filter_map(|(path, value, mask)| { + let object = schema.objects.iter().find(|object| &object.path == path); + if object.is_none() { + unknown.push(path.clone()); + } + Some(( + object?.signal, + (BigUint::from_bytes_le(value), BigUint::from_bytes_le(mask)), + )) + }) + .collect(); + if unknown.is_empty() { + Ok(resolved) + } else { + Err(StateError::Mismatch(StateMismatch { + unknown_names: unknown, + ..Default::default() + })) + } + } + + /// Resolve the process section of a schedule, or the names and sites + /// this design does not declare. + fn resolve_processes( + &self, + record: &ProcessRecord, + signals: &HashMap, + ) -> Result<(Vec<(usize, u64)>, ProcessState), Vec> { + let statuses = self.process_statuses(); + let processes: HashMap = statuses + .iter() + .enumerate() + .filter_map(|(index, status)| { + let path = signals + .iter() + .find(|(_, signal)| signal.offset == status.offset)? + .0; + Some((path.clone(), index)) + }) + .collect(); + let mut unknown: Vec = record + .wakeups + .iter() + .map(|(name, _)| name) + .chain(&record.ready) + .chain(&record.inactive) + .chain(record.waiters.iter().map(|waiter| &waiter.process)) + .filter(|name| !processes.contains_key(*name)) + .cloned() + .collect(); + let process = |name: &String| processes.get(name).copied(); + let wakeups: Vec<_> = record + .wakeups + .iter() + .filter_map(|(name, time)| Some((process(name)?, *time))) + .collect(); + let ready = record.ready.iter().filter_map(process).collect(); + let inactive = record.inactive.iter().filter_map(process).collect(); + let mut waiters = celox_runtime::timing::Waiters::default(); + for waiter in &record.waiters { + let Some(index) = process(&waiter.process) else { + continue; + }; + let sites = self + .program + .runtime_schema + .wait_sites + .iter() + .filter(|site| site.process == index) + .collect::>(); + let site = usize::try_from(waiter.site).ok(); + // Each baseline has the kind of its term: a counter for a + // counted signal, a value otherwise. + let counted = |signal: &crate::AbsoluteAddr| { + self.program + .runtime_schema + .watches + .iter() + .any(|watch| watch.signal == *signal) + }; + if !site.and_then(|site| sites.get(site)).is_some_and(|site| { + site.terms.len() == waiter.baselines.len() + && site + .terms + .iter() + .zip(&waiter.baselines) + .all(|((signal, _), baseline)| { + counted(signal) == matches!(baseline, BaselineRecord::Counter { .. }) + }) + }) { + unknown.push(format!("{} wait site {}", waiter.process, waiter.site)); + continue; + } + let driven = self + .program + .runtime_schema + .wait_sites + .iter() + .filter(|site| site.process == index) + .nth(site.unwrap_or_default()) + .is_some_and(|site| { + site.terms.iter().any(|(signal, _)| { + self.program + .runtime_schema + .rtl_writes + .iter() + .any(|atom| atom.id == *signal) + }) + }); + waiters.insert( + index, + driven, + celox_runtime::timing::Waiter { + site: site.unwrap_or_default(), + baselines: waiter + .baselines + .iter() + .map(|baseline| match baseline { + BaselineRecord::Counter { seen, value, mask } => Baseline::Counter { + seen: *seen, + value: ( + BigUint::from_bytes_le(value), + BigUint::from_bytes_le(mask), + ), + }, + BaselineRecord::Value { value, mask } => Baseline::Value(( + BigUint::from_bytes_le(value), + BigUint::from_bytes_le(mask), + )), + }) + .collect(), + }, + ); + } + let mut nba_queue = Vec::new(); + for update in &record.nba_queue { + match signals.get(&update.target) { + // A queued assignment covers a nonempty range of its target. + Some(&target) + if update.width == 0 + || update + .lsb + .checked_add(update.width) + .is_none_or(|end| end > target.width as u64) => + { + unknown.push(format!( + "{} [{} +: {}]", + update.target, update.lsb, update.width + )); + } + Some(&target) => nba_queue.push(celox_runtime::NbaUpdate { + target, + lsb: update.lsb as usize, + width: update.width as usize, + value: ( + BigUint::from_bytes_le(&update.value), + BigUint::from_bytes_le(&update.mask), + ), + }), + None => unknown.push(update.target.clone()), + } + } + let counted = self.counted_signals(); + let mut domain_counters = vec![[0; 3]; counted.len()]; + for (name, counters) in &record.domain_counters { + let index = signals + .get(name) + .and_then(|signal| counted.iter().position(|counted| counted == signal)); + match index { + Some(index) => domain_counters[index] = *counters, + None => unknown.push(name.clone()), + } + } + if !unknown.is_empty() { + return Err(unknown); + } + Ok(( + wakeups, + ProcessState { + waiters, + ready, + inactive, + nba_queue, + domain_counters, + }, + )) + } + /// Resolve a named schedule into this design's handles. Fails with the /// names the design does not declare. pub(crate) fn resolve_schedule( @@ -420,6 +759,10 @@ impl Simulator { ) .cloned() .collect(); + let processes = self.resolve_processes(&record.processes, &signals); + if let Err(names) = &processes { + unknown.extend(names.iter().cloned()); + } if !unknown.is_empty() { unknown.sort(); unknown.dedup(); @@ -428,6 +771,7 @@ impl Simulator { ..Default::default() })); } + let (process_wakeups, process_state) = processes.expect("checked above"); let resolve = |event: &ScheduledEvent| SimEvent { time: event.time, event_ref: events[&event.event], @@ -448,9 +792,10 @@ impl Simulator { .map(|(event, count)| (resolve(event), *count)) .collect(), high_events: record.high_events.iter().map(|name| events[name]).collect(), - // State files are rejected for designs with processes. - process_wakeups: Vec::new(), - finished: false, + process_wakeups, + process_state, + host_pending: record.processes.host_pending, + finished: record.processes.finished, }) } } diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs new file mode 100644 index 00000000000..2e14eda8b01 --- /dev/null +++ b/crates/celox/tests/both_clock_edges.rs @@ -0,0 +1,395 @@ +//! `always_ff` processes sensed at both edges of one signal (#443). +//! +//! A signal carries one domain kind, so the frontend senses every further +//! edge or role of a signal on a hidden whole-variable copy of it, which runs +//! as a clock derived from the signal. These tests drive the timed +//! `Simulation` and check that each process runs at the edges IEEE 1800-2023 +//! 9.4.2 defines, evaluating against the state before the edge (4.4.2, +//! 10.4.2), and that the copy is invisible. +//! +//! Event-based `Simulator` tests with explicit edges belong here too, once the +//! `Simulator` can drive a falling edge: a `tick` is the rising edge only and +//! does not run falling-edge domains. + +#![cfg(feature = "systemverilog")] + +use celox::{BigUint, OptLevel, Simulation}; + +fn build(source: &str, four_state: bool) -> Simulation { + build_with(source, four_state, OptLevel::O1) +} + +fn build_with(source: &str, four_state: bool, opt_level: OptLevel) -> Simulation { + let path = std::path::Path::new("both_clock_edges.sv"); + Simulation::from_sv_sources(vec![(source, path)], "Top") + .four_state(four_state) + .opt_level(opt_level) + .build() + .unwrap() +} + +fn get(sim: &mut Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() +} + +/// Pulses `rst` high at time 0 with `clk` low, then applies `cycles` clock +/// periods of 10 (rising at 10, 20, ...; falling 5 later) and returns the +/// values of `outputs` after every edge, rising edge first. +fn run(sim: &mut Simulation, cycles: u64, outputs: &[&str]) -> Vec> { + sim.schedule("clk", 0, 0).unwrap(); + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + let mut observed = Vec::new(); + for cycle in 0..cycles { + for (offset, level) in [(10, 1), (15, 0)] { + sim.schedule("clk", cycle * 10 + offset, level).unwrap(); + sim.step().unwrap(); + observed.push(outputs.iter().map(|name| get(sim, name)).collect()); + } + } + observed +} + +/// `rise` and `fall` count the edges of `clk`; `at_fall` samples `rise` at +/// each falling edge and `at_rise` samples `fall` at each rising edge. +fn expected_counters(cycles: u64) -> Vec> { + (1..=cycles) + .flat_map(|k| [vec![k, k - 1, k - 1, k - 1], vec![k, k, k, k - 1]]) + .collect() +} + +const COUNTERS: [&str; 4] = ["rise", "fall", "at_fall", "at_rise"]; + +fn counters_source(negedge_first: bool) -> String { + let rise = "always_ff @(posedge clk or posedge rst) + if (rst) begin rise <= 0; at_rise <= 0; end + else begin rise <= rise + 1; at_rise <= fall; end"; + let fall = "always_ff @(negedge clk or posedge rst) + if (rst) begin fall <= 0; at_fall <= 0; end + else begin fall <= fall + 1; at_fall <= rise; end"; + let (first, second) = if negedge_first { + (fall, rise) + } else { + (rise, fall) + }; + format!( + "module Top(input logic clk, input logic rst, + output logic [7:0] rise, output logic [7:0] fall, + output logic [7:0] at_fall, output logic [7:0] at_rise); + {first} + {second} + endmodule" + ) +} + +#[test] +fn processes_at_both_edges_of_one_clock() { + for negedge_first in [false, true] { + for four_state in [false, true] { + for opt_level in [OptLevel::O0, OptLevel::O1, OptLevel::O2] { + let mut sim = build_with(&counters_source(negedge_first), four_state, opt_level); + assert_eq!( + run(&mut sim, 4, &COUNTERS), + expected_counters(4), + "negedge first: {negedge_first}, four-state: {four_state}, {opt_level:?}" + ); + } + } + } +} + +/// A child module senses both edges of its clock port, the falling edge in +/// its first process. The child's rising-edge register `c` samples the +/// parent's register `p` before the parent's rising edge commits, and the +/// falling edge runs on its own. +#[test] +fn both_edges_of_a_child_clock_port() { + let source = "module Child(input logic clk, input logic rst, input logic [7:0] p, + output logic [7:0] c, output logic [7:0] f); + always_ff @(negedge clk or posedge rst) if (rst) f <= 0; else f <= f + 1; + always_ff @(posedge clk or posedge rst) if (rst) c <= 0; else c <= p; + endmodule + module Top(input logic clk, input logic rst, + output logic [7:0] p, output logic [7:0] c, output logic [7:0] f); + always_ff @(posedge clk or posedge rst) if (rst) p <= 0; else p <= p + 1; + Child u(.clk(clk), .rst(rst), .p(p), .c(c), .f(f)); + endmodule"; + let expected: Vec> = (1..=4) + .flat_map(|k| [vec![k, k - 1, k - 1], vec![k, k - 1, k]]) + .collect(); + for four_state in [false, true] { + let mut sim = build(source, four_state); + assert_eq!( + run(&mut sim, 4, &["p", "c", "f"]), + expected, + "four-state: {four_state}" + ); + } +} + +/// Both edges reached through whole-variable copies of `clk`, and both edges +/// of one copy. +#[test] +fn both_edges_through_clock_copies() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] rise, output logic [7:0] fall, + output logic [7:0] at_fall, output logic [7:0] at_rise); + logic c1, c2; + assign c1 = clk; + assign c2 = c1; + always_ff @(posedge c2 or posedge rst) if (rst) rise <= 0; else rise <= rise + 1; + always_ff @(negedge c2 or posedge rst) if (rst) fall <= 0; else fall <= fall + 1; + always_ff @(negedge c1 or posedge rst) if (rst) at_fall <= 0; else at_fall <= rise; + always_ff @(posedge clk or posedge rst) if (rst) at_rise <= 0; else at_rise <= fall; + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + assert_eq!( + run(&mut sim, 4, &COUNTERS), + expected_counters(4), + "four-state: {four_state}" + ); + } +} + +/// One asynchronous reset sensed active high by one process and active low by +/// another. +#[test] +fn a_reset_at_both_edges() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] high, output logic [7:0] low); + always_ff @(posedge clk or posedge rst) if (rst) high <= 0; else high <= high + 1; + always_ff @(posedge clk or negedge rst) if (!rst) low <= 0; else low <= low + 1; + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + let mut observed = Vec::new(); + let mut time = 0; + let mut edge = |sim: &mut Simulation, port: &str, level: u64| { + sim.schedule(port, time, level).unwrap(); + sim.step().unwrap(); + time += 5; + (get(sim, "high"), get(sim, "low")) + }; + // `rst` high clears `high`; its fall clears `low`. + edge(&mut sim, "clk", 0); + observed.push(edge(&mut sim, "rst", 1)); + for _ in 0..2 { + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + observed.push(edge(&mut sim, "rst", 0)); + for _ in 0..2 { + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + observed.push(edge(&mut sim, "rst", 1)); + observed.push(edge(&mut sim, "clk", 1)); + // Before `rst` first falls, `low` is unknown, and stays unknown when + // incremented. + let low = |count: u64| if four_state { 0xff } else { count }; + assert_eq!( + observed, + vec![ + (0, low(0)), + (0, low(1)), + (0, low(2)), + (0, 0), + (1, 0), + (2, 0), + (0, 0), + (0, 1), + ], + "four-state: {four_state}" + ); + } +} + +/// One signal as the asynchronous reset of one process and the clock of +/// others, at the same and at the opposite edge. +#[test] +fn a_signal_as_reset_and_as_clock() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] cnt, output logic [7:0] rises, output logic [7:0] falls); + always_ff @(posedge clk or posedge rst) if (rst) cnt <= 0; else cnt <= cnt + 1; + always_ff @(posedge rst) rises <= rises + 1; + always_ff @(negedge rst) falls <= falls + 1; + initial begin rises = 0; falls = 0; end + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + let mut time = 0; + let mut edge = |sim: &mut Simulation, port: &str, level: u64| { + sim.schedule(port, time, level).unwrap(); + sim.step().unwrap(); + time += 5; + (get(sim, "cnt"), get(sim, "rises"), get(sim, "falls")) + }; + edge(&mut sim, "clk", 0); + // A four-state `rst` starts unknown, and its move to 0 is a negedge + // (IEEE 1800-2023 Table 9-2); a two-state one starts at 0. + let (_, _, initial_falls) = edge(&mut sim, "rst", 0); + assert_eq!( + initial_falls, + u64::from(four_state), + "four-state: {four_state}" + ); + let mut observed = Vec::new(); + for _ in 0..2 { + observed.push(edge(&mut sim, "rst", 1)); + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + observed.push(edge(&mut sim, "rst", 0)); + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + let f = initial_falls; + assert_eq!( + observed, + vec![ + (0, 1, f), + (0, 1, f), + (0, 1, f + 1), + (1, 1, f + 1), + (0, 2, f + 1), + (0, 2, f + 1), + (0, 2, f + 2), + (1, 2, f + 2), + ], + "four-state: {four_state}" + ); + } +} + +/// Drives `d` through `levels` (value, unknown mask) and pulses `clk` after +/// each, so that the register `q` takes each level in turn, starting from +/// unknown. Returns the outputs `pos` and `neg` after each level. +fn register_edges(source: &str, levels: &[(u8, u8)]) -> Vec<(u64, u64)> { + let mut sim = build(source, true); + let d = sim.signal("d"); + sim.schedule("clk", 0, 0).unwrap(); + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + let mut time = 10; + let mut observed = Vec::new(); + for &(value, mask) in levels { + sim.modify(|io| io.set_four_state(d, BigUint::from(value), BigUint::from(mask))) + .unwrap(); + sim.schedule("clk", time, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("clk", time + 5, 0).unwrap(); + sim.step().unwrap(); + time += 10; + observed.push((get(&mut sim, "pos"), get(&mut sim, "neg"))); + } + observed +} + +fn register_source(posedge: bool, negedge: bool) -> String { + let pos = if posedge { + "always_ff @(posedge q or posedge rst) if (rst) pos <= 0; else pos <= pos + 1;" + } else { + "assign pos = 0;" + }; + let neg = if negedge { + "always_ff @(negedge q or posedge rst) if (rst) neg <= 0; else neg <= neg + 1;" + } else { + "assign neg = 0;" + }; + format!( + "module Top(input logic clk, input logic rst, input logic d, + output logic [7:0] pos, output logic [7:0] neg); + logic q; + always_ff @(posedge clk) q <= d; + {pos} + {neg} + endmodule" + ) +} + +const LOW: (u8, u8) = (0, 0); +const HIGH: (u8, u8) = (1, 0); +const X: (u8, u8) = (1, 1); +const Z: (u8, u8) = (0, 1); + +/// Both edges of a register that takes unknown and high-impedance values. +#[test] +fn both_edges_of_a_register_through_unknown_values() { + // `q` starts unknown. + let levels = [LOW, HIGH, LOW, X, LOW]; + assert_eq!( + register_edges(®ister_source(true, true), &levels), + vec![ + (0, 1), // x -> 0: negedge + (1, 1), // 0 -> 1: posedge + (1, 2), // 1 -> 0: negedge + (2, 2), // 0 -> x: posedge + (2, 3), // x -> 0: negedge + ] + ); + // Through every transition between 0, 1, x, and z, each process runs + // exactly when it runs in a design that senses only its edge of `q`. + let levels = [HIGH, X, HIGH, Z, HIGH, LOW, Z, LOW, X, Z, X, LOW, HIGH]; + let both = register_edges(®ister_source(true, true), &levels); + let pos = register_edges(®ister_source(true, false), &levels); + let neg = register_edges(®ister_source(false, true), &levels); + assert_eq!( + both, + pos.iter() + .zip(&neg) + .map(|(&(pos, _), &(_, neg))| (pos, neg)) + .collect::>() + ); +} + +/// The hidden copy is no signal, event, or trace variable of the design. +#[test] +fn the_edge_copy_is_hidden() { + let dir = tempfile::tempdir().unwrap(); + let vcd = dir.path().join("wave.vcd"); + let path = std::path::Path::new("both_clock_edges.sv"); + let source = counters_source(false); + let mut sim = Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top") + .vcd(&vcd) + .build() + .unwrap(); + let names: Vec<_> = sim + .named_signals() + .into_iter() + .map(|signal| signal.name) + .collect(); + assert!(names.iter().all(|name| !name.contains('@')), "{names:?}"); + assert!(names.iter().any(|name| name == "clk"), "{names:?}"); + let events: Vec<_> = sim + .named_events() + .into_iter() + .map(|event| event.name) + .collect(); + assert_eq!( + events.iter().filter(|name| name.contains("clk")).count(), + 1, + "{events:?}" + ); + assert!(events.iter().all(|name| !name.contains('@')), "{events:?}"); + let hierarchy = sim.named_hierarchy(); + assert!( + hierarchy + .signals + .iter() + .all(|signal| !signal.name.contains('@')), + "hierarchy lists a hidden copy" + ); + run(&mut sim, 2, &COUNTERS); + sim.dump(100); + sim.flush_vcd().unwrap(); + let wave = std::fs::read_to_string(&vcd).unwrap(); + assert!(!wave.contains('@'), "{wave}"); + assert!(wave.contains(" clk "), "{wave}"); + let addr = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sim.signal("clk@negedge"))); + assert!(addr.is_err(), "the copy resolves by name"); +} diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index f74e969ba81..bf0318df3a6 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -70,4 +70,16 @@ sv_backends! { fn declaration_initializers_keep_unknown_bits(sim) { @case "procedural::declaration_initializers_keep_unknown_bits"; } + + fn always_ff_at_both_edges_of_one_clock(sim) { + @case "procedural::always_ff_at_both_edges_of_one_clock"; + } + + fn always_ff_at_both_edges_of_a_child_clock_port(sim) { + @case "procedural::always_ff_at_both_edges_of_a_child_clock_port"; + } + + fn always_ff_reset_at_both_edges_and_as_a_clock(sim) { + @case "procedural::always_ff_reset_at_both_edges_and_as_a_clock"; + } } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 53159dee475..437920ea798 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5486,15 +5486,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { module Top(input logic a, output wire y); assign #5 y = a; endmodule "#, ), - ( - "mixed clock-edge polarities for one signal", - r#" - module Top(input logic clk, a, b, output logic qa, qb); - always_ff @(posedge clk) qa <= a; - always_ff @(negedge clk) qb <= b; - endmodule - "#, - ), ( "streaming concatenation", r#" @@ -5732,39 +5723,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "mixed reset-edge polarities for one signal", - r#" - module Top(input logic clk1, clk2, rst, d, output logic q1, q2); - always_ff @(posedge clk1 or posedge rst) - if (rst) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or negedge rst) - if (!rst) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), - ( - "mixed clock/reset-edge polarities for one signal", - r#" - module Top(input logic sig, clk2, rst2, d, output logic q1, q2); - always_ff @(posedge sig or posedge rst2) - if (rst2) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or negedge sig) - if (!sig) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), - ( - "mixed clock/reset-edge polarities for one signal", - r#" - module Top(input logic sig, clk2, rst2, d, output logic q1, q2); - always_ff @(posedge sig or posedge rst2) - if (rst2) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or posedge sig) - if (sig) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), ( "unsupported function formal data type", r#" @@ -8493,3 +8451,78 @@ fn commits_ff_output_actuals_whose_index_calls_a_function() { assert_eq!(sim.get_as::(bits), 4); } } + +/// The designs once rejected for sensing one signal at two edges or in two +/// roles (#443, #471) run each process at its own edge. +#[test] +fn runs_processes_sensing_one_signal_at_two_edges_or_roles() { + const BOTH_EDGES: &str = "module Top(input logic clk, a, b, output logic qa, qb); + always_ff @(posedge clk) qa <= a; + always_ff @(negedge clk) qb <= b; + endmodule"; + // The source, its data inputs (driven to 1), the scheduled event levels in + // order, and the outputs with their values afterwards. + type Case<'a> = ( + &'a str, + &'a [&'a str], + &'a [(&'a str, u64)], + [(&'a str, u64); 2], + ); + let cases: [Case; 4] = [ + ( + BOTH_EDGES, + &["a", "b"], + &[("clk", 1)], + [("qa", 1), ("qb", 0)], + ), + ( + BOTH_EDGES, + &["a", "b"], + &[("clk", 1), ("clk", 0)], + [("qa", 1), ("qb", 1)], + ), + ( + "module Top(input logic clk1, clk2, rst, d, output logic q1, q2); + always_ff @(posedge clk1 or posedge rst) + if (rst) q1 <= 1'b0; else q1 <= d; + always_ff @(posedge clk2 or negedge rst) + if (!rst) q2 <= 1'b0; else q2 <= d; + endmodule", + &["d"], + // `q2` loads at `clk2` while `rst` is high, then `rst` falls; + // `q1` loads at `clk1` once `rst` is low. + &[("rst", 1), ("clk2", 1), ("rst", 0), ("clk1", 1)], + [("q1", 1), ("q2", 0)], + ), + ( + "module Top(input logic sig, clk2, rst2, d, output logic q1, q2); + always_ff @(posedge sig or posedge rst2) + if (rst2) q1 <= 1'b0; else q1 <= d; + always_ff @(posedge clk2 or negedge sig) + if (!sig) q2 <= 1'b0; else q2 <= d; + endmodule", + &["d"], + &[("sig", 1), ("clk2", 1), ("sig", 0)], + [("q1", 1), ("q2", 0)], + ), + ]; + for (source, inputs, stimulus, expected) in cases { + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("both_edges.sv"))], "Top") + .build() + .unwrap(); + for input in inputs { + let signal = sim.signal(input); + sim.modify(|io| io.set(signal, 1u8)).unwrap(); + } + for (index, &(port, level)) in stimulus.iter().enumerate() { + sim.schedule(port, index as u64 * 10 + 10, level).unwrap(); + sim.step().unwrap(); + } + let observed = expected.map(|(name, _)| { + let signal = sim.signal(name); + (name, u64::try_from(sim.get(signal)).unwrap()) + }); + assert_eq!(observed, expected, "{source}"); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 417df5e169a..7c90eb8dde2 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -6,9 +6,9 @@ use celox_test_suite::{Backend, CompilationRejected, Design, Result, SignalPath} struct CeloxBackend(Simulator); /// A timed case: the design's own processes and clocks run in a -/// [`Simulation`]. The runtime does not yet resume the processes a host write -/// wakes until time advances, and offers no four-state read; the cases that -/// need either are excluded in `timing.rs`. +/// [`Simulation`]. A host write is settled at the current time by the next +/// run operation. A timed simulation offers no four-state read; the cases +/// that need it are excluded in `timing.rs`. struct TimedBackend { sim: Simulation, four_state: bool, diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 14536b199d6..0793fea43ac 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -157,6 +157,5 @@ timed_cases! { #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn cross_file_package_initializers_keep_static_clock_baseline = "timing::cross_file_package_initializers_keep_static_clock_baseline"; fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; - #[ignore = "a host write to a clock does not trigger its flip-flops in a timed Simulation"] fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; } diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 8cf5452eb97..42b300da623 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -267,14 +267,26 @@ fn checkpoint_restores_a_suspended_process() { } #[test] -fn state_files_reject_processes() { +fn state_files_record_suspended_processes() { let mut sim = Simulation::from_frontend(clocked_counter()) .build() .unwrap(); - assert!(matches!( - sim.save_state(), - Err(celox::StateError::Processes) - )); + sim.run_until(52).unwrap(); + let file = sim.save_state().unwrap(); + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + + let mut restored = Simulation::from_frontend(clocked_counter()) + .build() + .unwrap(); + restored.load_state(&file).unwrap(); + assert_eq!(restored.time(), 52); + let count = restored.signal("count"); + assert_eq!(restored.get(count), 5u8.into()); + // The clock process resumes where it was suspended. + restored.run_until(100).unwrap(); + assert_eq!(restored.get(count), 10u8.into()); } #[test] diff --git a/crates/celox/tests/vcd.rs b/crates/celox/tests/vcd.rs index ef85a06d05a..0bbd3f71f5e 100644 --- a/crates/celox/tests/vcd.rs +++ b/crates/celox/tests/vcd.rs @@ -558,6 +558,12 @@ mod activity { if step == 2 { let rst = sim.signal("rst"); sim.modify(|io| io.set(rst, 1u8)).unwrap(); + // The next step settles the write at the current time, and + // the waveform records it there. + let (ptr, size) = sim.memory_as_ptr(); + reference + .dump(sim.time(), unsafe { std::slice::from_raw_parts(ptr, size) }) + .unwrap(); } let time = sim.step().unwrap().unwrap(); sim.dump(time); diff --git a/docs/guide/checkpoints.md b/docs/guide/checkpoints.md index ed39059b143..e1b762c5d19 100644 --- a/docs/guide/checkpoints.md +++ b/docs/guide/checkpoints.md @@ -131,7 +131,8 @@ with the same width. If any is missing, nothing is changed and the error lists the differences. Combinational signals are recomputed after loading, so they need not match; their saved values only seed combinational loops declared with `true_loop`, which settle back into the saved state. A `Simulation` state file also records the time, clocks and -pending events by name. +pending events by name, and where the design's processes are suspended or +waiting. The `celox` command line tool inspects state files: diff --git a/docs/guide/external-frontends.md b/docs/guide/external-frontends.md index cce58382da4..c6a5b53dc4e 100644 --- a/docs/guide/external-frontends.md +++ b/docs/guide/external-frontends.md @@ -128,9 +128,13 @@ in order: | Statement | Behavior | |---|---| | `Assign` | Blocking assignment. Later statements read the new value; other logic sees it once the process suspends. | +| `Nonblocking` | Nonblocking assignment: the value is evaluated now and assigned in the NBA region of the current time. | | `If` | Branch on a condition. A condition with unknown bits counts as false. | | `While` / `Forever` | Repeat a body while a condition holds, or forever. | -| `Delay` | Suspend for an amount of time units, at most 64 bits wide. | +| `Delay` | Suspend for an amount of time units, at most 64 bits wide. A zero delay resumes after the nonblocking assignments of the time are published. | +| `InactiveDelay` | Like `Delay`, with SystemVerilog's `#0`: a zero delay resumes in the inactive region, before nonblocking assignments are published. | +| `WaitEvent` | Suspend until one of its terms occurs: any change, a positive or a negative edge of a signal (`@(...)`). | +| `WaitLevel` | Suspend until a condition is nonzero (`wait (...)`); continue at once if it already is. | | `Finish` | End the simulation. | ```rust @@ -144,30 +148,56 @@ module.process(vec![Statement::Forever { Statement::Assign { target: module.whole(clk)?, value: toggled }, ], }])?; + +// always @(posedge clk) count = count + 1; +module.process(vec![Statement::Forever { + body: vec![ + Statement::WaitEvent { terms: vec![EventTerm::new(clk, EventEdge::Posedge)] }, + Statement::Assign { target: module.whole(count)?, value: next_count }, + ], +}])?; ``` +`ModuleBuilder::comb_process` adds a combinational process such as +`always_comb`: assignments and conditionals that run at time zero and again +whenever a signal they read, and do not write, changes. Each write is visible +as it happens, so `y = 0; if (a) y = 1;` pulses `y` when an input change re-runs +the process; settling again with steady inputs does not re-run it. + Processes run only in a timed `Simulation`. Each one is compiled into a -resumable kernel that the simulation scheduler resumes when its delay expires. -Processes that resume at the same time run in declaration order. A process -sees the state settled at the previous time. The clock and reset edges it -causes trigger registers at the current time, like a scheduled event. A zero -delay resumes the process later at the same time, after the other processes -have run and the registers their edges trigger have settled, so a pulse -separated by a zero delay is still an edge. +resumable kernel that the simulation scheduler resumes when its delay expires +or its wait is satisfied. Processes that resume at the same time run in +declaration order. A time slot follows the regions of IEEE 1800-2023 4.5: +processes, including those an edge wakes, run in the active region before the +registers of that edge publish their nonblocking assignments, so a process +woken by `@(posedge clk)` reads the register outputs from before the edge. +Zero-delay `InactiveDelay` processes run after the active region, and +nonblocking assignments publish only when both are empty. A process that +drives a register's input at the same edge races with the register, as in +SystemVerilog. + +Every write a process makes counts: a pulse such as `clk = 1; clk = 0;` +without a suspension in between triggers `@(posedge clk)` and the registers of +`clk` once, and two nonblocking assignments to one signal in one time slot +publish in order. A host write through `Simulation::modify`, through the +raw memory view reported with `Simulation::note_raw_writes`, or through a +TypeScript DUT input, is an update of the current time: the next `step` or +`run_until` settles it at that time, then advances. A process may write output and internal signals that no continuous assignment or register drives. Several processes may write the same signal. Checkpoints -capture suspended processes, but state files are not yet supported for a -simulation with processes. A Veryl native testbench cannot instantiate an -artifact with processes. +and state files capture suspended and waiting processes. A Veryl native +testbench cannot instantiate an artifact with processes. ## Artifact format limits Format version 1 accepts one flattened module. It supports typed signals, constants, combinational expressions and assignments, edge-triggered registers, asynchronous reset, synchronous enable, and initial values. Format version 2 -adds processes. The builder writes version 1 for an artifact without processes, -so consumers that read only version 1 still accept it. A frontend must lower +adds processes, and version 3 their nonblocking assignments, inactive delays, +waits and combinational processes. The builder writes the oldest version that +can carry the artifact, so consumers that read only an earlier version still +accept it. A frontend must lower hierarchy, memories, latches, custom primitives, and bidirectional signals before calling the SDK builder. diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 23af8333ba1..4a1702b0063 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -76,7 +76,7 @@ synthesis and is tested at the design level. | Interfaces | interfaces with parameters, `localparam`s, `typedef`s, variables and nets, logic (`assign`, `always_comb`, `always_ff`, generate) and functions; interface instances and instance arrays, also inside generate blocks; interface ports with or without a modport, generic `interface` and `interface.mp` ports, and arrays of interface ports; modport `input` / `output` members and imported functions; access to members, parameters and functions through an instance or port (`h[i].m`, `h.P`, `h.f(...)`) | | Continuous logic | `assign`, `wire w = expr;` | | Combinational processes | `always_comb`, `always @*`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | -| Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains | +| Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | | Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate assertions | | Functions | `function` and `task` (without timing) with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | @@ -136,8 +136,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: descending ([#438](https://github.com/celox-sim/celox/issues/438)), internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs, strings and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a - plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists, and both edges of one clock ([#443](https://github.com/celox-sim/celox/issues/443)) or one - reset ([#471](https://github.com/celox-sim/celox/issues/471)) across processes. + plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. - Combinational processes: nonblocking assignments inside `always_comb` ([#453](https://github.com/celox-sim/celox/issues/453)). - Loops: a procedural loop unrolls at most 10,000 iterations; a combinational diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index 435461057e2..53ee498b4f3 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -144,10 +144,10 @@ try { ### Timeout Guard for runUntil -Pass `{ maxSteps }` to `runUntil()` to enable step counting. Without it, the fast Rust path is used with no overhead: +Pass `{ maxSteps }` to `runUntil()` to bound the number of steps. Both forms run in the Rust scheduler: ```typescript -// Fast Rust path (no overhead) +// Unbounded sim.runUntil(10000); // Guarded: throws SimulationTimeoutError if budget is exceeded diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index a995791e480..9a414b2ff7c 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -178,28 +178,87 @@ its boundaries. ### Process kernels -A procedural process with delays is compiled into a process kernel: one SIR -execution unit that runs the process from its last suspension point to the -next. Each process owns three hidden two-state state objects: +A procedural process is compiled into a process kernel: one SIR execution unit +that runs the process from its last suspension point to the next. Each process +owns three hidden two-state state objects: - a resume slot, which the kernel's entry block dispatches on with a `Switch` (two levels beyond 255 suspension points); -- a status slot, in which the kernel reports a delay, the end of the process, - or `$finish` before it returns; -- a delay slot, which holds the wait amount. +- a status slot, in which the kernel reports how it returned: a delay, an + inactive-region delay, a wait, a still-pending wait, a staged nonblocking + assignment, a yield, the end of the process, or `$finish`; +- a delay slot, which holds the wait amount, or the index of the wait or + nonblocking site. A suspension stores these slots and returns, so no backend needs a new terminator. Kernels are never merged with each other or with a phase, and every backend compiles each one as its own function, invoked through -`SimBackend::run_process`. - -The timed scheduler keeps a queue of process wakeups next to its event queue. -At each time it applies the scheduled values, then runs the processes that -resume at that time in declaration order. It detects the clock edges they cause -by comparing event signals before and after, and then settles as for scheduled -events. Processes that waited for zero time resume in a further round at the -same time, which repeats the edge detection and settling. Because the slots are ordinary state, a checkpoint captures suspended -processes. The optimizer does not yet optimize kernels, but it treats their +`SimBackend::run_process`. `ProcessKernelBuilder` is the frontend interface: +`delay`, `inactive_delay`, `yield_now`, `suspend_wait` with `wake_if` and +`wait_level`, `nonblocking` and `finish`. + +#### Watched and counted signals + +A wait names its terms: a signal and the occurrence it waits for (any change, +a positive or a negative edge, IEEE 1800-2023 9.4.2 Table 9-2). Most signals +change at most once between two points at which the runtime checks them: a +scheduled or host write, a flip-flop publication, a continuous assignment +settling, or a kernel storing it once between suspensions. For these the +runtime keeps the value each waiting process last saw and compares, and +flip-flop domains keep today's edge detection. + +A signal is *counted* when a unit may store it twice without a check in +between, so an intermediate value would otherwise be lost: a kernel storing it +twice between two suspensions or inside a loop without one, or an imperative +combinational unit storing it twice on one path (`y = 0; if (a) y = 1;`). +Frontends report such candidates with counter objects +(`watch::multi_store_candidates`, `CounterSlots`); assembly counts only the +candidates a flip-flop domain or a wait watches. It then rewrites exactly the +stores to them in kernels and combinational process units with +`watch::emit_watched`, which bumps changes/rises/falls counters around each +store in plain SIR. A counted domain triggers when its counter moves, and a +wait on a counted signal compares counters. Combinational process units run +only when an input changed (IEEE 1800-2023 9.2.2.2), so settling again never +repeats an intermediate write. Nothing else in the design changes. + +#### Time slots + +A time slot is a sequence of rounds. A round is the batch step described above +with a process phase in front of the flip-flop domains, following the regions +of IEEE 1800-2023 4.5: + +1. apply the scheduled values of the time; +2. run the ready processes in declaration order, including those they wake, + then settle once (the batch step's settle) and wake the processes the + settled values satisfy; when only inactive-region (`#0`) processes remain, + evaluate the domains triggered so far first and keep their nonblocking + assignments for the NBA region; +3. evaluate and publish the triggered domains as in the batch step, and + publish the processes' nonblocking assignments with them; +4. wake the processes the published values satisfy; they, and processes that + waited for a zero `Delay`, run in the next round of the same time. + +A process woken by an edge therefore runs before that edge's domains publish: +it reads flip-flop outputs from before the edge, and a process that drives a +flip-flop input at the same edge races with the flip-flop, as in +SystemVerilog. A round without ready processes, waiting processes or counted +signals does exactly the batch step, with the fused evaluate-and-apply and +parallel units. A domain evaluated twice before its nonblocking assignments +publish keeps the earlier evaluation's working state, and both publish in +order. Nonblocking assignments of kernels go through an ordered queue, or a +single pending value per site when the frontend knows that nothing else +assigns the destination. + +`$finish`, from a kernel or from flip-flop or combinational code, ends a timed +simulation where it is: the scheduler propagates it as a control result, and +the simulator freezes so that evaluation, host writes and dumps change +nothing. A host write is an update of the current time; the next step settles +it at that time, then advances, so host writes never hold the simulation at +one time. Checkpoints, state files and exported schedules carry +the waiting processes with what each compares against, the ready and inactive +processes, the queued nonblocking assignments and the counter values counted +domains last triggered on; the slots and counters themselves are ordinary +state. The 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. diff --git a/docs/ja/guide/checkpoints.md b/docs/ja/guide/checkpoints.md index 15c26a775c5..addac63cba6 100644 --- a/docs/ja/guide/checkpoints.md +++ b/docs/ja/guide/checkpoints.md @@ -116,7 +116,7 @@ other.load_state(&file)?; 足りないものがあると何も変更せず、エラーに差分の一覧が入ります。 組み合わせ回路の信号は読み込み後に計算し直すので、一致している必要はありません。 保存された値は、`true_loop` で宣言した組み合わせ回路のループの初期値としてだけ使われ、ループは保存時の状態に落ち着きます。 -`Simulation` の状態ファイルには、時刻、クロック、予約済みのイベントも名前で記録されます。 +`Simulation` の状態ファイルには、時刻、クロック、予約済みのイベントも名前で記録されます。設計の process がどこで suspend しているか、何を待っているかも記録されます。 状態ファイルは `celox` コマンドで確認できます。 diff --git a/docs/ja/guide/external-frontends.md b/docs/ja/guide/external-frontends.md index 56c75432a36..d1d0b66b663 100644 --- a/docs/ja/guide/external-frontends.md +++ b/docs/ja/guide/external-frontends.md @@ -128,9 +128,13 @@ Celox artifact JSON も parse しません。build 可能な addon と load test | 文 | 動作 | |---|---| | `Assign` | blocking 代入。後続の文は新しい値を読み、他の logic は process が suspend した後に新しい値を見ます。 | +| `Nonblocking` | nonblocking 代入。値はその場で評価し、現在時刻の NBA region で代入します。 | | `If` | 条件で分岐します。不定 bit を含む条件は偽として扱います。 | | `While` / `Forever` | 条件が成り立つ間、または永久に body を繰り返します。 | -| `Delay` | 指定した時間単位だけ suspend します。量は 64 bit 以下です。 | +| `Delay` | 指定した時間単位だけ suspend します。量は 64 bit 以下です。0 の delay は、その時刻の nonblocking 代入が反映された後で再開します。 | +| `InactiveDelay` | `Delay` と同様ですが、SystemVerilog の `#0` と同じく 0 の delay は inactive region、つまり nonblocking 代入の反映より前に再開します。 | +| `WaitEvent` | term のどれかが起きるまで suspend します。term は signal の任意の変化、立ち上がり edge、立ち下がり edge です(`@(...)`)。 | +| `WaitLevel` | 条件が非 0 になるまで suspend します(`wait (...)`)。既に成り立っていればそのまま進みます。 | | `Finish` | simulation を終了します。 | ```rust @@ -144,30 +148,54 @@ module.process(vec![Statement::Forever { Statement::Assign { target: module.whole(clk)?, value: toggled }, ], }])?; + +// always @(posedge clk) count = count + 1; +module.process(vec![Statement::Forever { + body: vec![ + Statement::WaitEvent { terms: vec![EventTerm::new(clk, EventEdge::Posedge)] }, + Statement::Assign { target: module.whole(count)?, value: next_count }, + ], +}])?; ``` +`ModuleBuilder::comb_process` は `always_comb` のような組み合わせ process を +追加します。代入と条件分岐だけからなり、時刻 0 と、読む(書かない)signal が +変化したときに実行されます。書き込みはその都度見えるので、`y = 0; if (a) y = 1;` +は入力の変化で再実行されたときに `y` に pulse を出します。入力が変わらないまま +settle し直しても再実行はされません。 + process は時刻付きの `Simulation` でだけ実行されます。各 process は再開可能な -kernel に compile され、delay が満了すると simulation の scheduler が再開 -します。同じ時刻に再開する process は宣言順に実行されます。process が見るのは前の時刻で -settle した state です。process が起こした clock や reset の edge は、 -schedule された event と同様にその時刻の register を trigger します。0 の delay -を置くと、process は同じ時刻のうちに、他の process が実行され、その edge が -trigger した register が settle した後で再開します。そのため 0 の delay で区切った -pulse も edge になります。 +kernel に compile され、delay の満了や wait の成立で simulation の scheduler が +再開します。同じ時刻に再開する process は宣言順に実行されます。time slot は +IEEE 1800-2023 4.5 の region に従います。edge で起こされた process も含めて +process は active region で実行され、その edge の register が nonblocking 代入を +反映する前に動きます。そのため `@(posedge clk)` で起きた process は edge 前の +register 出力を読みます。0 の `InactiveDelay` の process は active region の後に +実行され、nonblocking 代入は両方が空になってから反映されます。同じ edge で +register の入力を駆動する process は、SystemVerilog と同じく register と race +します。 + +process の書き込みはすべて数えられます。suspend を挟まない `clk = 1; clk = 0;` +のような pulse も `@(posedge clk)` と `clk` の register を 1 回 trigger し、1 つの +time slot で同じ signal へ行う 2 つの nonblocking 代入は順に反映されます。 +`Simulation::modify`、`Simulation::note_raw_writes` で報告した raw memory view +への書き込み、TypeScript DUT の input への書き込みは、いずれも現在時刻の更新です。 +次の `step` や `run_until` はそれを現在時刻で settle してから時刻を進めます。 process が書けるのは、continuous assignment や register が駆動していない output と internal signal です。同じ signal を複数の process が書いても -構いません。checkpoint は suspend 中の process を保存しますが、process を -持つ simulation の state file にはまだ対応していません。process を持つ -artifact は Veryl native testbench から instantiate できません。 +構いません。checkpoint と state file は suspend 中や wait 中の process を +保存します。process を持つ artifact は Veryl native testbench から +instantiate できません。 ## artifact format の制限 format version 1 が受け取るのは平坦化済みの1 module です。型付き signal、 constant、組み合わせ式と代入、edge-triggered register、非同期 reset、同期 -enable、初期値を扱えます。format version 2 で process が加わりました。 -process を持たない artifact は builder が version 1 として書き出すので、 -version 1 しか読まない consumer もそのまま受け取れます。hierarchy、memory、 +enable、初期値を扱えます。format version 2 で process が、version 3 で +その nonblocking 代入、inactive delay、wait と組み合わせ process が加わりました。 +builder は artifact を表せる最も古い version で書き出すので、それより前の +version しか読まない consumer もそのまま受け取れます。hierarchy、memory、 latch、custom primitive、bidirectional signal は SDK builder を呼ぶ前に frontend 側で lower してください。 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index f564c966a54..dc176b63d4a 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -62,7 +62,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | -| 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット | +| 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | | initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しない) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、タイミング制御のない `task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | @@ -102,8 +102,7 @@ package・interface の手続きは宣言元の時間単位と精度を保持し - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、0 起点の降順でない 多次元 packed 範囲([#438](https://github.com/celox-sim/celox/issues/438))、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、文字列、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ - オペランド([#464](https://github.com/celox-sim/celox/issues/464))、プロセスをまたいだ同一クロック([#443](https://github.com/celox-sim/celox/issues/443))・同一リセット - ([#471](https://github.com/celox-sim/celox/issues/471))の両エッジの使用。 + オペランド([#464](https://github.com/celox-sim/celox/issues/464))。 - 組み合わせ回路のプロセス:`always_comb` 内のノンブロッキング代入([#453](https://github.com/celox-sim/celox/issues/453))。 - ループ:手続き的なループの展開は 10,000 回までです。反復回数が実行時に決まる組み合わせ 回路のループは、カウンタ形式の `for` である必要があります。loop-generate は 10,000 回を diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 790fa5272ef..08e05c0c2c2 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -140,10 +140,10 @@ try { ### runUntil のタイムアウトガード -`runUntil()` に `{ maxSteps }` を渡すとステップカウントが有効になります。指定しない場合は高速な Rust パスがそのまま使われ、オーバーヘッドはありません: +`runUntil()` に `{ maxSteps }` を渡すとステップ数に上限を設けられます。どちらの形も Rust のスケジューラで実行されます: ```typescript -// 高速 Rust パス (オーバーヘッドなし) +// 上限なし sim.runUntil(10000); // ガード付き: 上限を超えると SimulationTimeoutError をスロー diff --git a/packages/celox/src/dut.ts b/packages/celox/src/dut.ts index 0897640f7b5..fc682b9ce05 100644 --- a/packages/celox/src/dut.ts +++ b/packages/celox/src/dut.ts @@ -29,6 +29,11 @@ import { isFourStateValue } from "./types.js"; */ export interface DirtyState { dirty: boolean; + /** + * An input was written since the timed scheduler last heard of it; a + * combinational settle for a read does not clear it. + */ + written?: boolean; disposed?: boolean; } @@ -479,6 +484,7 @@ function defineSignalProperty( } state.dirty = true; + state.written = true; }, enumerable: true, @@ -854,6 +860,7 @@ function createArrayDut( if (is4state) storage.write(index, true, 0n); } state.dirty = true; + state.written = true; }, }; } diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index bacb9fdf732..240513de9a3 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -45,6 +45,8 @@ export interface RawNapiSimulationHandle { addClock(eventId: number, period: number, initialDelay: number): void; schedule(eventId: number, time: number, value: number): void; runUntil(endTime: number): void; + runUntilBounded?(endTime: number, maxSteps: number): boolean; + noteHostWrites?(): void; step(): number | null; time(): number; nextEventTime(): number | null; @@ -860,6 +862,15 @@ export function wrapDirectSimulationHandle( runUntil(endTime: number): void { raw.runUntil(endTime); }, + runUntilBounded(endTime: number, maxSteps: number): boolean { + if (!raw.runUntilBounded) { + throw new Error("This simulation does not support bounded runs"); + } + return raw.runUntilBounded(endTime, maxSteps); + }, + noteHostWrites(): void { + raw.noteHostWrites?.(); + }, step(): number | null { return raw.step(); }, diff --git a/packages/celox/src/simulation.test.ts b/packages/celox/src/simulation.test.ts index 2aa2937e6a4..5432fcf232e 100644 --- a/packages/celox/src/simulation.test.ts +++ b/packages/celox/src/simulation.test.ts @@ -65,6 +65,19 @@ function createMockNative(opts?: { view.setUint8(4, view.getUint8(2)); currentTime = endTime; }), + runUntilBounded: vi + .fn() + .mockImplementation((endTime: number, maxSteps: number) => { + let steps = 0; + while (nextScheduledTime != null && nextScheduledTime <= endTime) { + if (steps >= maxSteps) return false; + handle.step(); + steps++; + } + handle.runUntil(endTime); + return true; + }), + noteHostWrites: vi.fn(), step: vi.fn().mockImplementation(processNextEvent), time: vi.fn().mockImplementation(() => currentTime), nextEventTime: vi.fn().mockImplementation(() => nextScheduledTime), @@ -280,6 +293,65 @@ describe("Simulation", () => { }).toThrow("Native simulator binding not loaded"); }); + test("input writes reach the scheduler before it advances", () => { + const mock = createMockNative(); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + const order: string[] = []; + vi.mocked(mock.handle.noteHostWrites!).mockImplementation(() => { + order.push("note"); + }); + + sim.runUntil(10); + expect(mock.handle.noteHostWrites).not.toHaveBeenCalled(); + vi.mocked(mock.handle.runUntil).mockImplementationOnce(() => { + order.push("run"); + }); + + // A read settles the inputs but does not report them. + sim.dut.d = 0x42n; + expect(sim.dut.q).toBe(0x42n); + sim.runUntil(20); + expect(order).toEqual(["note", "run"]); + + // Each write is reported once, before the step that sees it. + sim.dut.d = 1n; + sim.step(); + sim.step(); + sim.nextEventTime(); + expect(mock.handle.noteHostWrites).toHaveBeenCalledTimes(2); + sim.dut.d = 2n; + sim.nextEventTime(); + expect(mock.handle.noteHostWrites).toHaveBeenCalledTimes(3); + }); + + test("bounded runUntil at the current time settles host writes", () => { + const mock = createMockNative(); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + let pending = false; + vi.mocked(mock.handle.noteHostWrites!).mockImplementation(() => { + pending = true; + }); + vi.mocked(mock.handle.nextEventTime).mockImplementation(() => + pending ? mock.handle.time() : null, + ); + vi.mocked(mock.handle.runUntilBounded!).mockImplementation(() => { + pending = false; + return true; + }); + + sim.runUntil(sim.time(), { maxSteps: 5 }); + expect(mock.handle.runUntilBounded).not.toHaveBeenCalled(); + + sim.dut.d = 3n; + sim.runUntil(sim.time(), { maxSteps: 5 }); + expect(mock.handle.noteHostWrites).toHaveBeenCalledTimes(1); + expect(mock.handle.runUntilBounded).toHaveBeenCalledWith(sim.time(), 5); + }); + test("runUntil with maxSteps: fast path when omitted", () => { const mock = createMockNative(); const sim = Simulation.create(TopModule, { diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index f17b2af5354..f575986cd10 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -437,43 +437,41 @@ export class Simulation

> { * Run the simulation until the given time. * Processes all scheduled events up to and including `endTime`. * - * When `maxSteps` is provided, steps are counted in TS and a - * `SimulationTimeoutError` is thrown if the budget is exhausted before - * reaching `endTime`. Without `maxSteps` the fast Rust path is used. + * When `maxSteps` is provided, the Rust run loop takes at most that many + * steps and a `SimulationTimeoutError` is thrown if the budget is + * exhausted before reaching `endTime`. */ runUntil(endTime: number, opts?: { maxSteps?: number }): void { this.ensureAlive(); // A skipped run must preserve pending input changes for lazy evaluation. if (endTime < this._handle.time()) return; if (opts?.maxSteps == null) { + this.noteHostWrites(); this._handle.runUntil(endTime); this._state.dirty = false; return; } const max = opts.maxSteps; - let steps = 0; + if (!this._handle.runUntilBounded) { + throw new Error("This simulation does not support bounded runs"); + } + // Host writes are work of the current time, also at the target. + this.noteHostWrites(); if (this._handle.time() >= endTime) { - return; + // Nothing is due at the target: keep pending inputs for lazy + // evaluation. + const next = this._handle.nextEventTime(); + if (next == null || next > endTime) return; } - while (true) { - const nextEventTime = this._handle.nextEventTime(); - if (nextEventTime == null || nextEventTime > endTime) break; - if (steps >= max) { - throw new SimulationTimeoutError( - `runUntil: exceeded ${max} steps at time ${this._handle.time()} (target ${endTime})`, - this._handle.time(), - steps, - ); - } - const t = this._handle.step(); - if (t == null) break; - this._state.dirty = false; - steps++; + if (!this._handle.runUntilBounded(endTime, max)) { + // A step took the pending inputs unless none was allowed. + if (max > 0) this._state.dirty = false; + throw new SimulationTimeoutError( + `runUntil: exceeded ${max} steps at time ${this._handle.time()} (target ${endTime})`, + this._handle.time(), + max, + ); } - // Match the native fast path: after all events due by endTime have been - // processed, advance the clock exactly to endTime without consuming a - // later event, and perform the native path's final dump. - this._handle.runUntil(endTime); this._state.dirty = false; } @@ -484,6 +482,7 @@ export class Simulation

> { */ step(): number | null { this.ensureAlive(); + this.noteHostWrites(); const t = this._handle.step(); this._state.dirty = false; return t; @@ -502,6 +501,7 @@ export class Simulation

> { */ nextEventTime(): number | null { this.ensureAlive(); + this.noteHostWrites(); return this._handle.nextEventTime(); } @@ -525,6 +525,7 @@ export class Simulation

> { const max = opts?.maxSteps ?? this._defaultMaxSteps ?? 100_000; let steps = 0; while (!condition()) { + this.noteHostWrites(); // An exhausted queue is a normal completion, even when the budget is // already spent. Preserve that behavior instead of reporting a timeout. if (steps >= max && this._handle.nextEventTime() != null) { @@ -695,6 +696,7 @@ export class Simulation

> { if (!this._handle.checkpoint) { throw new Error("This simulation does not support checkpoints"); } + this.noteHostWrites(); return new SimulationCheckpoint(this._handle.checkpoint()); } @@ -712,6 +714,7 @@ export class Simulation

> { this._handle.restore(checkpoint._native); this.syncClocks(); this._state.dirty = false; + this._state.written = false; } /** @@ -736,6 +739,7 @@ export class Simulation

> { if (!this._handle.saveState) { throw new Error("This simulation does not support state files"); } + this.noteHostWrites(); const bytes = this._handle.saveState(); this._state.dirty = false; return bytes; @@ -757,6 +761,7 @@ export class Simulation

> { this._handle.loadState(bytes); this.syncClocks(); this._state.dirty = false; + this._state.written = false; } /** Release native resources. */ @@ -774,6 +779,17 @@ export class Simulation

> { // Internal // ----------------------------------------------------------------------- + /** + * Report the DUT's input writes to the timed scheduler, which settles the + * current time first when a process may see them or a clock changed. + */ + private noteHostWrites(): void { + if (this._state.written) { + this._state.written = false; + this._handle.noteHostWrites?.(); + } + } + /** Rebuild the clock registry from the clocks the handle now runs. */ private syncClocks(): void { const periods = this._handle.clockPeriods?.(); diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 738911221f2..278c5291b36 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -199,6 +199,17 @@ export interface NativeSimulationHandle { addClock(eventId: number, period: number, initialDelay: number): void; schedule(eventId: number, time: number, value: number): void; runUntil(endTime: number): void; + /** + * Advance until `endTime` taking at most `maxSteps` steps; `false` when + * the steps ran out first, at the time of the last step. + */ + runUntilBounded?(endTime: number, maxSteps: number): boolean; + /** + * Report that the host wrote the shared memory: the next step settles the + * current time when a process may see the writes or an event signal + * changed. + */ + noteHostWrites?(): void; step(): number | null; time(): number; nextEventTime(): number | null;