diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index ad65391ccce..1de57c16f22 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -230,6 +230,13 @@ pub enum ProcessStatus { /// It ran no statement, so no state other than its own wait bookkeeping /// changed. Pending, + /// Resume after the number of rising edges stored in + /// [`ProcessSlots::delay`] of the process clock whose index is stored in + /// [`ProcessSlots::clock`]. The runtime generates those edges: the clock + /// toggles every half period from the first wait on it, and the process + /// resumes one period after the last counted edge, before the edge that + /// follows. + WaitClock, /// An event occurred while sampling queued drives; resume its body after the batch. Ready, /// Resume this process immediately, charging the current time-slot budget. @@ -247,6 +254,7 @@ impl ProcessStatus { Self::Finish => 3, Self::Wait => 4, Self::Pending => 5, + Self::WaitClock => 6, Self::Ready => 11, Self::Yield => 10, } @@ -260,6 +268,7 @@ impl ProcessStatus { 3 => Some(Self::Finish), 4 => Some(Self::Wait), 5 => Some(Self::Pending), + 6 => Some(Self::WaitClock), 11 => Some(Self::Ready), 10 => Some(Self::Yield), _ => None, @@ -267,18 +276,42 @@ impl ProcessStatus { } } +/// A clock a process waits on with [`ProcessStatus::WaitClock`]: the clock +/// signal of a sequential domain, and the period of the edges the runtime +/// generates for it (at least two time units). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessClock { + pub signal: A, + pub period: u64, +} + +impl ProcessClock { + pub fn map(self, map: impl FnOnce(A) -> B) -> ProcessClock { + ProcessClock { + signal: map(self.signal), + period: self.period, + } + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to /// find where it stopped; before returning it stores the next resume point, -/// a [`ProcessStatus`] code in `status` and, for a delay, the number of time -/// units in `delay`. All three are ordinary two-state state objects, so -/// checkpoints capture a suspended process. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// a [`ProcessStatus`] code in `status` and, for a delay or a clock wait, the +/// number of time units or edges in `delay`; a clock wait also stores the +/// index into `clocks` in `clock`. The slots are ordinary two-state state +/// objects, so checkpoints capture a suspended process. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { pub resume: A, pub status: A, pub delay: A, + pub clock: A, + /// The clocks the process may wait on, in the order its kernel numbers + /// them. + #[serde(default = "Vec::new")] + pub clocks: Vec>, } impl ProcessSlots { @@ -287,11 +320,18 @@ impl ProcessSlots { resume: map(self.resume), status: map(self.status), delay: map(self.delay), + clock: map(self.clock), + clocks: self + .clocks + .into_iter() + .map(|clock| clock.map(&mut map)) + .collect(), } } + /// The control slots, without the clock signals. pub fn iter(&self) -> impl Iterator { - [&self.resume, &self.status, &self.delay].into_iter() + [&self.resume, &self.status, &self.delay, &self.clock].into_iter() } } @@ -299,6 +339,8 @@ impl ProcessSlots { pub const PROCESS_STATUS_WIDTH: usize = 8; /// Width of [`ProcessSlots::delay`]. pub const PROCESS_DELAY_WIDTH: usize = 64; +/// Width of [`ProcessSlots::clock`]. +pub const PROCESS_CLOCK_WIDTH: usize = 32; pub const PROCESS_EVENT_COUNTER_WIDTH: usize = 32; @@ -348,6 +390,8 @@ pub struct RuntimeSchema { /// derived from the other state, so state files recompute rather than /// compare them. pub comb_writes: HashSet, + /// Combinational execution reads a clock, so both phases must settle. + pub clock_phase_sensitive_comb: bool, /// Dead store elimination policy the program was compiled with. Together /// with `live_signals` and the design it decides which combinationally /// written state the host may observe. @@ -357,7 +401,7 @@ pub struct RuntimeSchema { /// Control slots of the process kernels, in kernel order. pub processes: Vec>, pub process_event_counters: Vec>, - /// FF evaluation domains that publish blocking stores into active state. + /// FF domains with blocking stores or finish effects in the active region. pub active_ff_events: HashSet, } @@ -371,6 +415,7 @@ impl Default for RuntimeSchema { testbench_read_roots: HashSet::default(), rtl_writes: HashSet::default(), comb_writes: HashSet::default(), + clock_phase_sensitive_comb: false, dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index fa6aa699207..5f10bab6c9f 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -16,8 +16,8 @@ //! suspension methods where the source suspends. use celox_design::{ - PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase, - STABLE_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, + RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BinaryOp, BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, @@ -43,6 +43,8 @@ pub const MAX_PROCESS_SUSPENSIONS: usize = (1 << PROCESS_RESUME_WIDTH) - 1; pub enum ProcessKernelError { #[error("a process has more than {MAX_PROCESS_SUSPENSIONS} suspension points")] TooManySuspensions, + #[error("a process waits on clock {0}, which its slots do not list")] + UnknownClock(u32), } /// Builder of one process kernel. @@ -140,6 +142,29 @@ impl ProcessKernelBuilder { Ok(()) } + /// Suspend until `count` rising edges of the process clock `clock` (an + /// index into the slots' clock list) have passed, and continue at a new + /// resume point one period after the last of them. `count` is an + /// unsigned two-state register of [`PROCESS_DELAY_WIDTH`] bits; a count + /// of zero continues at once. + pub fn wait_clock(&mut self, clock: u32, count: RegisterId) -> Result<(), ProcessKernelError> { + if clock as usize >= self.slots.clocks.len() { + return Err(ProcessKernelError::UnknownClock(clock)); + } + let point = self.resume_blocks.len(); + if point > MAX_PROCESS_SUSPENSIONS { + return Err(ProcessKernelError::TooManySuspensions); + } + self.store(self.slots.delay, PROCESS_DELAY_WIDTH, count); + self.store_constant(self.slots.clock, PROCESS_CLOCK_WIDTH, u64::from(clock)); + self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); + self.end(ProcessStatus::WaitClock); + let resume = self.builder.new_block(); + self.resume_blocks.push(resume); + self.builder.switch_to_block(resume); + Ok(()) + } + /// Suspend until a condition the kernel evaluates holds, and continue at /// a new resume point. The caller lowers the condition at that point /// and ends it with [`Self::wake_if`]; the runtime resumes the process diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index b6c5231d2e3..187743ff56a 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -2,8 +2,9 @@ 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, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, + ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, + VariableMetadata, WORKING_REGION, }; use celox_frontend_sdk::{ ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice, @@ -1034,6 +1035,7 @@ fn lower_registers( fn lower_statements( artifact: &FrontendArtifact, kernel: &mut ProcessKernelBuilder, + clocks: &[SignalId], statements: &[Statement], ) -> Result { for statement in statements { @@ -1075,7 +1077,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(artifact, kernel, clocks, body)? { let builder = kernel.builder(); let target = *join.get_or_insert_with(|| builder.new_block()); builder.seal_block(SIRTerminator::Jump(target, Vec::new())); @@ -1100,7 +1102,7 @@ fn lower_statements( false_block: (exit, Vec::new()), }); builder.switch_to_block(body_block); - if lower_statements(artifact, kernel, body)? { + if lower_statements(artifact, kernel, clocks, body)? { kernel .builder() .seal_block(SIRTerminator::Jump(header, Vec::new())); @@ -1112,7 +1114,7 @@ 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)? { + if lower_statements(artifact, kernel, clocks, body)? { kernel .builder() .seal_block(SIRTerminator::Jump(header, Vec::new())); @@ -1129,6 +1131,20 @@ fn lower_statements( )?; kernel.delay(amount)?; } + Statement::ClockCycles { clock, count } => { + let index = clocks + .iter() + .position(|c| c == clock) + .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))?; + let count = coerce_sir_expression( + artifact, + *count, + ValueType::bits(PROCESS_DELAY_WIDTH)?, + kernel.builder(), + &mut cache, + )?; + kernel.wait_clock(index as u32, count)?; + } Statement::Finish => { kernel.finish(); return Ok(false); @@ -1176,13 +1192,28 @@ fn lower_processes( .enumerate() .map(|(index, process)| { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; + let mut clocks = Vec::new(); + celox_frontend_sdk::collect_process_clocks(process.body(), &mut clocks); let slots = ProcessSlots { resume: declare(name("resume"), PROCESS_RESUME_WIDTH), status: declare(name("status"), PROCESS_STATUS_WIDTH), delay: declare(name("delay"), PROCESS_DELAY_WIDTH), + clock: declare(name("clock"), PROCESS_CLOCK_WIDTH), + clocks: clocks + .iter() + .map(|clock| { + Ok(ProcessClock { + signal: source_id(*clock), + period: artifact + .clock_period(*clock) + .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))? + .max(2), + }) + }) + .collect::, FrontendArtifactError>>()?, }; - let mut kernel = ProcessKernelBuilder::new(slots); - lower_statements(artifact, &mut kernel, process.body())?; + let mut kernel = ProcessKernelBuilder::new(slots.clone()); + lower_statements(artifact, &mut kernel, &clocks, process.body())?; Ok(SymbolicProcess { kernel: kernel.build(), slots, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f9e88f448e8..56ca734f8bd 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1440,6 +1440,7 @@ pub fn schedule_symbolic_rtl( testbench_read_roots: process_read_roots, rtl_writes, comb_writes: Default::default(), + clock_phase_sensitive_comb: false, dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, @@ -2273,7 +2274,10 @@ fn relocate_units( &runtime_event_site_map, &extern_function_map, ), - slots: process.slots.map(|var_id| bindings.locate(*id, var_id)), + slots: process + .slots + .clone() + .map(|var_id| bindings.locate(*id, var_id)), }, )); } diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs index 8b83123dc8d..7788bf5a355 100644 --- a/crates/celox-frontend-sdk/src/lib.rs +++ b/crates/celox-frontend-sdk/src/lib.rs @@ -13,9 +13,9 @@ use thiserror::Error; /// Current JSON interchange version of [`FrontendArtifact`]. /// -/// 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; +/// Version 2 adds [`Process`]es; version 3 adds [`Statement::ClockCycles`]. +/// Artifacts use the oldest version that can represent their statements. +pub const ARTIFACT_FORMAT_VERSION: u32 = 3; /// Oldest JSON interchange version [`FrontendArtifact::from_json`] accepts. pub const MIN_ARTIFACT_FORMAT_VERSION: u32 = 1; @@ -474,6 +474,13 @@ pub enum Statement { /// amount count as zero; a zero delay resumes at the same time, after /// the other processes and the registers their edges trigger. Delay { amount: ExprId }, + /// Suspend the process until `count` rising edges of `clock` have + /// passed. The runtime generates the edges of a clock from the first + /// wait on it, with the period set by [`ModuleBuilder::clock_period`], + /// and resumes the process one period after the last counted edge, + /// before the edge that follows. Unknown bits of the count count as + /// zero; a zero count continues at once. + ClockCycles { clock: SignalId, count: ExprId }, /// End the simulation. Finish, } @@ -509,6 +516,9 @@ pub struct FrontendArtifact { port_order: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] processes: Vec, + /// Periods of the clocks processes wait on, in time units. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + clock_periods: Vec<(SignalId, u64)>, } impl FrontendArtifact { @@ -523,10 +533,25 @@ impl FrontendArtifact { /// Decode and version-check an artifact produced by an external frontend. pub fn from_json(json: &str) -> Result { + #[derive(Deserialize)] + struct Header { + format_version: u32, + } + let header: Header = serde_json::from_str(json)?; + if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION).contains(&header.format_version) + { + return Err(ArtifactJsonError::UnsupportedVersion { + expected: ARTIFACT_FORMAT_VERSION, + actual: header.format_version, + }); + } 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()) + let mut clocks = Vec::new(); + for process in &artifact.processes { + collect_process_clocks(&process.body, &mut clocks); + } + if (artifact.format_version < 2 && !artifact.processes.is_empty()) + || (artifact.format_version < 3 && !clocks.is_empty()) { return Err(ArtifactJsonError::UnsupportedVersion { expected: ARTIFACT_FORMAT_VERSION, @@ -850,6 +875,67 @@ impl FrontendArtifact { for process in &self.processes { self.validate_statements(&process.body, &driver_ranges)?; } + // The same requirements as `ModuleBuilder::clock_period` and + // `ModuleBuilder::process` put on the clocks processes wait on. + let mut declared_clocks = std::collections::BTreeSet::new(); + for (clock, period) in &self.clock_periods { + if !declared_clocks.insert(clock.index()) { + let name = self + .signal(*clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(); + return Err(BuildError::DuplicateClockPeriod { name }); + } + let signal = self + .signal(*clock) + .ok_or(BuildError::UnknownSignal(clock.index()))?; + if signal.value_type.width() != 1 { + return Err(BuildError::InvalidControlWidth { + name: signal.name.clone(), + }); + } + if *period < 2 { + return Err(BuildError::InvalidClockPeriod { period: *period }); + } + } + for process in &self.processes { + let mut clocks = Vec::new(); + collect_process_clocks(&process.body, &mut clocks); + for clock in clocks { + let mut targets = Vec::new(); + for process in &self.processes { + collect_process_targets(&process.body, &mut targets); + } + if driver_ranges.contains_key(&clock) + || targets.iter().any(|target| target.signal == clock) + { + return Err(BuildError::DrivenProcessClock { + name: self + .signal(clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(), + }); + } + let known = self + .clock_periods + .iter() + .any(|(signal, _)| *signal == clock) + && self + .registers + .iter() + .any(|register| register.clock == clock); + if !known { + let name = self + .signal(clock) + .ok_or(BuildError::UnknownSignal(clock.index()))? + .name + .clone(); + return Err(BuildError::UnknownProcessClock { name }); + } + } + } let mut ordered_ports = FxHashMap::default(); for signal in &self.port_order { let signal = self @@ -906,6 +992,14 @@ impl FrontendArtifact { &self.processes } + /// The period of `clock` for [`Statement::ClockCycles`], if set. + pub fn clock_period(&self, clock: SignalId) -> Option { + self.clock_periods + .iter() + .find(|(signal, _)| *signal == clock) + .map(|(_, period)| *period) + } + fn validate_statements( &self, statements: &[Statement], @@ -955,6 +1049,14 @@ pub enum BuildError { }, #[error("control signal `{name}` must be one bit wide")] InvalidControlWidth { name: String }, + #[error("a clock period must be at least two time units, not {period}")] + InvalidClockPeriod { period: u64 }, + #[error("duplicate process-clock period for `{name}`")] + DuplicateClockPeriod { name: String }, + #[error("clock `{name}` needs a period and a register it clocks before a process waits on it")] + UnknownProcessClock { name: String }, + #[error("process clock `{name}` also has a continuous, register or process driver")] + DrivenProcessClock { name: String }, #[error("register target `{name}` must cover the complete signal")] PartialRegisterTarget { name: String }, #[error("module name must not be empty")] @@ -1014,6 +1116,7 @@ pub struct ModuleBuilder { driver_ranges: FxHashMap>, port_order: Vec, processes: Vec, + clock_periods: Vec<(SignalId, u64)>, } impl ModuleBuilder { @@ -1033,6 +1136,7 @@ impl ModuleBuilder { driver_ranges: FxHashMap::default(), port_order: Vec::new(), processes: Vec::new(), + clock_periods: Vec::new(), }) } @@ -1366,6 +1470,36 @@ impl ModuleBuilder { &|expression| self.expressions.get(expression.index() as usize), &self.driver_ranges, )?; + let mut clocks = Vec::new(); + collect_process_clocks(&body, &mut clocks); + let mut targets = Vec::new(); + collect_process_targets(&body, &mut targets); + for process in &self.processes { + collect_process_targets(&process.body, &mut targets); + collect_process_clocks(&process.body, &mut clocks); + } + for clock in clocks { + if self.driver_ranges.contains_key(&clock) + || targets.iter().any(|target| target.signal == clock) + { + return Err(BuildError::DrivenProcessClock { + name: self.signal_info(clock)?.name.clone(), + }); + } + let known = self + .clock_periods + .iter() + .any(|(signal, _)| *signal == clock) + && self + .registers + .iter() + .any(|register| register.clock == clock); + if !known { + return Err(BuildError::UnknownProcessClock { + name: self.signal_info(clock)?.name.clone(), + }); + } + } self.processes.push(Process { body }); Ok(()) } @@ -1375,7 +1509,15 @@ impl ModuleBuilder { format_version: if self.processes.is_empty() { MIN_ARTIFACT_FORMAT_VERSION } else { - ARTIFACT_FORMAT_VERSION + let mut clocks = Vec::new(); + for process in &self.processes { + collect_process_clocks(&process.body, &mut clocks); + } + if clocks.is_empty() { + 2 + } else { + ARTIFACT_FORMAT_VERSION + } }, module_name: self.name, signals: self.signals, @@ -1384,9 +1526,31 @@ impl ModuleBuilder { registers: self.registers, port_order: self.port_order, processes: self.processes, + clock_periods: self.clock_periods, } } + /// Set the period, in time units, of the edges the runtime generates + /// for `clock` when a process waits on it with + /// [`Statement::ClockCycles`]. The clock must clock a register, and + /// the period is at least two. + pub fn clock_period(&mut self, clock: SignalId, period: u64) -> Result<(), BuildError> { + let signal = self.signal_info(clock)?; + if signal.value_type.width() != 1 { + return Err(BuildError::InvalidControlWidth { + name: signal.name.clone(), + }); + } + if period < 2 { + return Err(BuildError::InvalidClockPeriod { period }); + } + match self.clock_periods.iter_mut().find(|(s, _)| *s == clock) { + Some(entry) => entry.1 = period, + None => self.clock_periods.push((clock, period)), + } + Ok(()) + } + fn signal_info(&self, signal: SignalId) -> Result<&Signal, BuildError> { self.signals .get(signal.index() as usize) @@ -1430,6 +1594,13 @@ impl ModuleBuilder { fn record_driver_target(&mut self, target: SignalSlice) -> Result<(), BuildError> { let signal_name = self.signal_info(target.signal)?.name.clone(); + let mut process_clocks = Vec::new(); + for process in &self.processes { + collect_process_clocks(&process.body, &mut process_clocks); + } + if process_clocks.contains(&target.signal) { + return Err(BuildError::DrivenProcessClock { name: signal_name }); + } let mut process_targets = Vec::new(); for process in &self.processes { collect_process_targets(&process.body, &mut process_targets); @@ -1473,7 +1644,32 @@ fn collect_process_targets(statements: &[Statement], targets: &mut Vec { collect_process_targets(body, targets); } - Statement::Delay { .. } | Statement::Finish => {} + Statement::Delay { .. } | Statement::ClockCycles { .. } | Statement::Finish => {} + } + } +} + +/// The clocks the statements wait on, in order of first use. +pub fn collect_process_clocks(statements: &[Statement], clocks: &mut Vec) { + for statement in statements { + match statement { + Statement::ClockCycles { clock, .. } => { + if !clocks.contains(clock) { + clocks.push(*clock); + } + } + Statement::If { + then_body, + else_body, + .. + } => { + collect_process_clocks(then_body, clocks); + collect_process_clocks(else_body, clocks); + } + Statement::While { body, .. } | Statement::Forever { body } => { + collect_process_clocks(body, clocks); + } + Statement::Assign { .. } | Statement::Delay { .. } | Statement::Finish => {} } } } @@ -1552,6 +1748,13 @@ fn validate_statements<'a>( return Err(BuildError::DelayTooWide { width }); } } + Statement::ClockCycles { clock, count } => { + signal(*clock).ok_or(BuildError::UnknownSignal(clock.index()))?; + let width = expression_type(*count)?.width(); + if width > MAX_DELAY_WIDTH { + return Err(BuildError::DelayTooWide { width }); + } + } Statement::Finish => {} } } @@ -1899,6 +2102,113 @@ mod tests { )); } + fn module_for_driven_clock() -> Result<(), BuildError> { + let bit = ValueType::bits(1)?; + let mut module = ModuleBuilder::new("Driven")?; + let clk = module.internal("clk", bit)?; + let q = module.output("q", bit)?; + let one = module.constant(Constant::two_state(1u8, 1)?); + let target = module.whole(q)?; + module.register(target, one, clk, Edge::Posedge, None, None)?; + module.clock_period(clk, 4)?; + let target = module.whole(clk)?; + module.assign(target, one)?; + module.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + } + + #[test] + fn revalidates_process_clocks_from_json() { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("ProcessClocks").unwrap(); + let clock = module.internal("clock", bit).unwrap(); + let count = module.output("count", bit).unwrap(); + let toggled = module.read(count).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, toggled, bit).unwrap(); + let target = module.whole(count).unwrap(); + module + .register(target, toggled, clock, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clock, 4).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + module + .process(vec![Statement::ClockCycles { clock, count: one }]) + .unwrap(); + let artifact = module.finish(); + assert_eq!(artifact.format_version(), 3); + let json = serde_json::to_value(&artifact).unwrap(); + let mut old_version = json.clone(); + old_version["format_version"] = 2.into(); + assert!(matches!( + FrontendArtifact::from_json(&old_version.to_string()), + Err(ArtifactJsonError::UnsupportedVersion { actual: 2, .. }) + )); + let mut future = json.clone(); + future["format_version"] = 4.into(); + future["processes"][0]["body"][0] = serde_json::json!({"FutureStatement": {}}); + assert!(matches!( + FrontendArtifact::from_json(&future.to_string()), + Err(ArtifactJsonError::UnsupportedVersion { actual: 4, .. }) + )); + // Validate both builder orderings and the deserialization trust boundary. + let driven = module_for_driven_clock(); + assert!(matches!(driven, Err(BuildError::DrivenProcessClock { .. }))); + let mut late_driver = json.clone(); + late_driver["assignments"] = serde_json::json!([{ "target": {"signal": clock, "lsb": 0, "width": 1}, "value": toggled }]); + assert!(matches!( + FrontendArtifact::from_json(&late_driver.to_string()), + Err(ArtifactJsonError::InvalidArtifact( + BuildError::DrivenProcessClock { .. } + )) + )); + let mut later = ModuleBuilder::new("LaterDriver").unwrap(); + let clk = later.internal("clk", bit).unwrap(); + let q = later.output("q", bit).unwrap(); + let one = later.constant(Constant::two_state(1u8, 1).unwrap()); + let target = later.whole(q).unwrap(); + later + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + later.clock_period(clk, 4).unwrap(); + later + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let target = later.whole(clk).unwrap(); + assert!(matches!( + later.assign(target, one), + Err(BuildError::DrivenProcessClock { .. }) + )); + + // Without its period, the clock clocks nothing. + let mut unknown = json.clone(); + unknown["clock_periods"] = serde_json::json!([]); + let error = FrontendArtifact::from_json(&unknown.to_string()).unwrap_err(); + assert!( + matches!( + error, + ArtifactJsonError::InvalidArtifact(BuildError::UnknownProcessClock { .. }) + ), + "{error:?}" + ); + + // A period below two cannot have distinct edges. + let mut short = json.clone(); + short["clock_periods"][0][1] = 1.into(); + let error = FrontendArtifact::from_json(&short.to_string()).unwrap_err(); + assert!( + matches!( + error, + ArtifactJsonError::InvalidArtifact(BuildError::InvalidClockPeriod { period: 1 }) + ), + "{error:?}" + ); + } + #[test] fn rejects_input_driver_targets_in_builder_and_json() { let bit = ValueType::bits(1).unwrap(); diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 2070a5892e5..bb5d5179bd4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -11,9 +11,10 @@ use std::path::Path; use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, - InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, - PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind, - RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, + InitialStateData, InitialStateValue, ModuleId, PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, + PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, + RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, + WORKING_REGION, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -3660,6 +3661,8 @@ fn lower_initial_processes( resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), + clock: declare("clock", PROCESS_CLOCK_WIDTH), + clocks: Vec::new(), } }) .collect(); @@ -3708,7 +3711,7 @@ fn lower_initial_processes( Ok(SymbolicProcess { kernel: ff::Ff::new(&mut pm).lower_initial_kernel( process.body(), - slots, + slots.clone(), activation, )?, slots, diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index fb82fb3e8b0..67c22bc7753 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -53,7 +53,13 @@ pub trait SimBackend { if count == 0 { return (0, Ok(())); } - (1, self.eval_comb_apply_ff_at(event)) + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } } /// Evaluate FF domain without applying (for cascaded clocks). diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 616e4ddd1f2..d34c3ab9d33 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -18,7 +18,8 @@ pub use reflection::{ SignalDirection, }; pub use simulation::{ - EventInfo, ProcessRefs, ScheduleParts, SimulationExecutor, SimulationSnapshot, SimulationState, + EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ScheduleParts, SimulationExecutor, + SimulationSnapshot, SimulationState, }; pub use state_file::{ ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 805a5d38a00..089b675d6d6 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -62,6 +62,33 @@ pub trait SimulationExecutor { self.backend_mut().run_process(index) } + /// Run up to `count` rising edges of `event` as fused ticks: each one + /// evaluates the combinational logic and then the sequential domain, + /// without toggling the clock signal. Returns how many completed before + /// a runtime event or an error forced a return to the host. + fn tick_many( + &mut self, + event: ::Event, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + if count == 0 { + return (0, Ok(())); + } + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } + } + + /// Whether clock waits may be served by fused ticks, which skip the + /// clock signal's own edges and the host's per-edge hooks. + fn fused_ticks_allowed(&self) -> bool { + false + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -86,11 +113,92 @@ pub trait SimulationExecutor { fn finish_timed_step(&mut self, _timestamp: u64) {} } +/// A clock a process may wait on, resolved to the backend. +#[derive(Debug)] +pub struct ProcessClockRef { + pub event: B::Event, + pub signal: SignalRef, + pub period: u64, +} + +impl Clone for ProcessClockRef { + fn clone(&self) -> Self { + Self { + event: self.event, + signal: self.signal, + period: self.period, + } + } +} + /// Control slots of one process kernel, resolved to signals of the backend. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ProcessRefs { +#[derive(Debug)] +pub struct ProcessRefs { pub status: SignalRef, pub delay: SignalRef, + pub clock: SignalRef, + pub clocks: Vec>, +} + +impl Clone for ProcessRefs { + fn clone(&self) -> Self { + Self { + status: self.status, + delay: self.delay, + clock: self.clock, + clocks: self.clocks.clone(), + } + } +} + +/// A process clock some process has waited on: the runtime generates its +/// edges from then on. A rising edge is due at `next_edge` while a process +/// waits; the falling edge of the last rising edge that was applied to the +/// signal is pending at `falling_edge`. +#[derive(Debug)] +struct TickClock { + event: B::Event, + signal: SignalRef, + period: u64, + next_edge: u64, + falling_edge: Option, + /// Last level actually driven by this generator, independent of the + /// edge-detection baseline retained until publication succeeds. + driven_value: Option, +} + +impl Clone for TickClock { + fn clone(&self) -> Self { + Self { + event: self.event, + signal: self.signal, + period: self.period, + next_edge: self.next_edge, + falling_edge: self.falling_edge, + driven_value: self.driven_value, + } + } +} + +/// A process waiting for `remaining` more rising edges of the process clock +/// with event id `clock`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ClockWait { + clock: usize, + remaining: u64, +} + +/// The state of one process clock, for schedules expressed by name. +#[derive(Debug)] +pub struct ProcessClockState { + pub event: B::Event, + pub signal: SignalRef, + pub period: u64, + pub next_edge: u64, + pub falling_edge: Option, + /// Last generator drive; `None` before its first drive. Retain this + /// across failed rounds independently of the sampled event baseline. + pub driven_value: Option, } /// A process waiting for simulation time to reach `time`. Ordered so that a @@ -151,6 +259,12 @@ impl PeriodicEventKey { /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, + round_published_domains: BitSet, + round_triggered_domains: BitSet, + scheduled_clock_drives: BitSet, + scheduled_clock_time: u64, + round_triggers_discovered: bool, + round_new_rising: BitSet, periodic_events: FxHashMap, last_clock_values: BitSet, pending_host_edges: BTreeMap, @@ -160,13 +274,21 @@ pub struct SimulationState { event_info: Vec>, signal_to_id: FxHashMap, signal_index_by_id: Vec, - processes: Vec, + processes: Vec>, process_event_counters: Vec<(usize, SignalRef, SignalRef)>, active_ff_domains: BitSet, process_wakeups: BinaryHeap, /// Processes suspended at an event or level wait, which their kernels /// re-check whenever the state may have changed. waiting: BTreeSet, + /// Process clocks that have been waited on, by event id. + tick_clocks: BTreeMap>, + /// Processes waiting for rising edges of a process clock. + clock_waits: BTreeMap, + /// Processes that ran to their end. + done: BTreeSet, + /// Rising edges of process clocks so far. + ticks: u64, sampled_ready: BTreeSet, inactive: BTreeSet, /// A process requested the end of the simulation. @@ -196,11 +318,22 @@ fn sample_event_signal(backend: &B, signal: SignalRef) -> (bool, } } +/// The error of a process clock whose next edge lies beyond simulation time. +fn clock_overflow(clock: usize) -> SimulatorErrorCode { + SimulatorErrorCode::Runtime { + message: format!("process clock {clock} overflows simulation time"), + signals: Vec::new(), + } +} + impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.pending_host_edges.clear(); self.sample_event_values(backend); + for clock in self.tick_clocks.values_mut() { + clock.driven_value = None; + } } fn sample_event_values(&mut self, backend: &B) { @@ -220,13 +353,29 @@ impl SimulationState { } } + fn pending_generated_baseline(&self, id: usize) -> Option<(bool, bool)> { + let driven = self.tick_clocks.get(&id)?.driven_value?; + let baseline = ( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + ); + (baseline != (driven, false)).then_some(baseline) + } + /// Retain FF occurrences observed by a host evaluation until the scheduler runs. pub fn capture_host_edges(&mut self, backend: &B) { if self.finished { return; } + // A failed generated round owns its unpublished source edge. Host + // settling must neither dispatch it nor consume its retry baseline. + let generated_baselines: Vec<_> = self + .tick_clocks + .keys() + .filter_map(|&id| self.pending_generated_baseline(id).map(|value| (id, value))) + .collect(); for (_, id, _) in &self.topo_signals { - if *id == usize::MAX { + if *id == usize::MAX || self.pending_generated_baseline(*id).is_some() { continue; } let info = &self.event_info[*id]; @@ -239,6 +388,18 @@ impl SimulationState { } } self.sample_event_values(backend); + for (id, (value, unknown)) in generated_baselines { + if value { + self.last_clock_values.insert(id); + } else { + self.last_clock_values.remove(id); + } + if unknown { + self.unknown_clock_values.insert(id); + } else { + self.unknown_clock_values.remove(id); + } + } } fn stable_edge_triggered(&self, backend: &B, id: usize) -> bool { @@ -290,7 +451,7 @@ impl SimulationState { topo_signals: Vec<(SignalRef, usize, usize)>, domain_kinds: Vec>, event_info: Vec>, - processes: Vec, + processes: Vec>, ) -> Self { let mut last_clock_values = BitSet::with_capacity(backend.num_events()); let mut unknown_clock_values = BitSet::with_capacity(backend.num_events()); @@ -329,13 +490,32 @@ impl SimulationState { process_event_counters: Vec::new(), active_ff_domains: BitSet::new(), waiting: BTreeSet::new(), + tick_clocks: BTreeMap::new(), + clock_waits: BTreeMap::new(), + done: BTreeSet::new(), + ticks: 0, sampled_ready: BTreeSet::new(), inactive: BTreeSet::new(), finished: false, + round_published_domains: BitSet::new(), + round_triggered_domains: BitSet::new(), + scheduled_clock_drives: BitSet::new(), + scheduled_clock_time: 0, + round_triggers_discovered: false, + round_new_rising: BitSet::new(), finish_round: false, } } + /// Rising edges of process clocks the simulation has run so far. + pub fn ticks(&self) -> u64 { + self.ticks + } + + fn clock_has_waiters(&self, clock: usize) -> bool { + self.clock_waits.values().any(|wait| wait.clock == clock) + } + pub fn add_clock( &mut self, event: B::Event, @@ -423,7 +603,7 @@ impl SimulationState { return Ok(()); } for &process in &self.waiting { - let refs = self.processes[process]; + let refs = &self.processes[process]; let status = ProcessStatus::from_code(executor.backend().get_as(refs.status)); if !matches!(status, Some(ProcessStatus::Wait | ProcessStatus::Pending)) && !(probe && status == Some(ProcessStatus::Ready)) @@ -448,14 +628,83 @@ impl SimulationState { Ok(()) } + /// Clock signals changed outside a scheduler round through retained memory. + pub fn escaped_host_clock_writes(&self, backend: &B) -> Vec { + self.processes + .iter() + .flat_map(|process| &process.clocks) + .filter_map(|clock| { + let id = clock.event.id(); + let expected = self + .tick_clocks + .get(&id) + .and_then(|clock| clock.driven_value) + .map(|value| (value, false)) + .unwrap_or(( + self.last_clock_values.contains(id), + self.unknown_clock_values.contains(id), + )); + (expected != sample_event_signal(backend, clock.signal)).then_some(clock.signal) + }) + .collect() + } + + fn record_generated_clock_drive(&mut self, event: &SimEvent) { + if let Some(clock) = self.tick_clocks.get_mut(&event.event_ref.id()) + && clock.signal == event.signal + { + clock.driven_value = Some(event.next_val & 1 != 0); + } + } + + /// A generated process clock owns its signal, including before its first wait. + pub fn validate_host_write(&self, signal: SignalRef) -> Result<(), SimulatorErrorCode> { + if let Some(clock) = self + .processes + .iter() + .flat_map(|process| &process.clocks) + .find(|clock| clock.signal == signal) + { + return Err(SimulatorErrorCode::Runtime { + message: format!( + "process clock {} is driven by a direct host write", + clock.event.id() + ), + signals: Vec::new(), + }); + } + Ok(()) + } + pub fn step(&mut self, executor: &mut E) -> Result, SimulatorErrorCode> where E: SimulationExecutor, { + self.step_until(executor, u64::MAX) + } + + /// [`Self::step`], where a run of fused clock ticks stops before + /// `limit`: the time the step reaches is at most `limit`. + pub fn step_until( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result, SimulatorErrorCode> + where + E: SimulationExecutor, + { + for (id, clock) in &self.tick_clocks { + if self.clock_has_waiters(*id) || clock.falling_edge.is_some() { + self.check_clock_generator(*id)?; + } + } let Some(current_time) = self.next_event_time() else { return Ok(None); }; - let events_to_process = if self.scheduler.next_event_time() == Some(current_time) { + if current_time > limit { + return Ok(None); + } + let mut events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() .map(|(_, events)| events) @@ -463,54 +712,386 @@ impl SimulationState { } else { Vec::new() }; + // A process owns its generated clock even before its first wait. + // Retain consumed scheduled-drive provenance across timestamps. + self.scheduled_clock_time = current_time; + for event in &events_to_process { + self.scheduled_clock_drives.insert(event.event_ref.id()); + if let Some(id) = self.signal_to_id.get(&event.signal) { + self.scheduled_clock_drives.insert(*id); + } + } + let mut falling = Vec::new(); + for (id, clock) in &self.tick_clocks { + if clock.falling_edge == Some(current_time) { + falling.push(*id); + events_to_process.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 0, + }); + } + } + let rising: Vec = self + .tick_clocks + .iter() + .filter(|(id, clock)| { + let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); + let pending_rise = high + && (!self.last_clock_values.contains(**id) + || self.unknown_clock_values.contains(**id)); + (!events_to_process.is_empty() || pending_rise) + && !falling.contains(*id) + && clock.next_edge == current_time + && self.clock_has_waiters(**id) + && (!high || pending_rise) + }) + .map(|(id, _)| *id) + .collect(); + let mut generated_events = Vec::new(); + for id in &rising { + let clock = &self.tick_clocks[id]; + generated_events.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + }); + } let ready = self.take_ready_processes(current_time); let mut delta_rounds = 0; - self.step_round( + let result = self.step_round( executor, current_time, events_to_process, + generated_events, ready, true, &mut delta_rounds, - )?; - self.run_remaining_rounds(executor, current_time, &mut delta_rounds)?; - executor.finish_timed_step(current_time); - Ok(Some(current_time)) + ); + self.finish_clock_round(current_time, rising, &falling, result)?; + self.run_remaining_rounds(executor, current_time, limit, &mut delta_rounds)?; + executor.finish_timed_step(self.scheduler.time); + // Fused ticks may have moved the time on. + Ok(Some(self.scheduler.time)) } - /// Run the further rounds of `current_time`: a process that waited for - /// zero time resumes in a later round, after the previous round's edges - /// have been handled, and the settled state may wake a process waiting - /// for an event or a condition. A round in which no process ran changes - /// nothing and ends the time. + /// Run the further rounds of `current_time`: the rising edges of the + /// process clocks that are due once the processes have run; a process + /// that waited for zero time resumes in a later round, after the + /// previous round's edges have been handled; and the settled state may + /// wake a process waiting for an event or a condition. A round in which + /// no process ran changes nothing and ends the time. When every live + /// process waits on the one clock that is due and nothing else is + /// pending, its edges run as fused ticks up to `limit` instead. fn run_remaining_rounds( &mut self, executor: &mut E, current_time: u64, + limit: u64, delta_rounds: &mut usize, ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { while !self.finished { + let due: Vec = self + .tick_clocks + .iter() + .filter(|(id, clock)| { + clock.next_edge == current_time && self.clock_has_waiters(**id) + }) + .map(|(id, _)| *id) + .collect(); + if let [clock] = due[..] + && self.fused_ticks(executor, clock, current_time, limit)? + { + // Time moved on; the processes that resume run in the next step. + return Ok(()); + } + let fired = !due.is_empty(); + if fired { + self.fire_edges(executor, current_time, &due, delta_rounds)?; + } let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.waiting.is_empty() { + if fired { + // The edges may have released waits that resume now. + continue; + } break; } - if !self.step_round( + let result = self.step_round( executor, current_time, Vec::new(), + Vec::new(), ready, false, delta_rounds, - )? { + ); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(current_time, Vec::new(), &[], result)?; + if !progressed && !fired { break; } } Ok(()) } + /// Apply the rising edges of the process clocks `due` at `time`, count + /// them against the processes waiting on them, and schedule the + /// resumptions and falling edges. + fn fire_edges( + &mut self, + executor: &mut E, + time: u64, + due: &[usize], + delta_rounds: &mut usize, + ) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + for id in due { + time.checked_add(self.tick_clocks[id].period) + .ok_or_else(|| clock_overflow(*id))?; + } + // A clock that is high when its edge is due (the host or a previous + // run left it so) falls first, in a round of its own: the rising + // edge that counts is then a real one. + let mut events = Vec::with_capacity(due.len()); + let mut rising = Vec::with_capacity(due.len()); + let mut falling = Vec::new(); + for id in due { + let clock = &self.tick_clocks[id]; + let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); + events.push(SimEvent { + time, + event_ref: clock.event, + signal: clock.signal, + next_val: u8::from(!high), + }); + if !high { + rising.push(*id); + } else { + falling.push(*id); + } + } + for id in &falling { + self.tick_clocks + .get_mut(id) + .expect("a normalizing clock") + .falling_edge = Some(time); + } + let result = self.step_round( + executor, + time, + events, + Vec::new(), + Vec::new(), + true, + delta_rounds, + ); + self.finish_clock_round(time, rising, &falling, result) + } + + fn finish_clock_round( + &mut self, + time: u64, + rising: Vec, + falling: &[usize], + result: Result, + ) -> Result<(), SimulatorErrorCode> { + let rising: BTreeSet<_> = rising + .into_iter() + .chain(self.round_new_rising.iter()) + .collect(); + let committed = rising + .into_iter() + .filter(|id| { + (result.is_ok() && !self.finished) + || self + .round_published_domains + .contains(self.event_info[*id].canonical_id) + }) + .collect(); + self.credit_rising_edges(time, committed)?; + if result.is_ok() + || (self.round_triggers_discovered + && self + .round_triggered_domains + .is_subset(&self.round_published_domains)) + { + for id in falling { + self.tick_clocks + .get_mut(id) + .expect("a pending process-clock fall") + .falling_edge = None; + self.last_clock_values.remove(*id); + } + } + result.map(|_| ()) + } + + fn credit_rising_edges( + &mut self, + time: u64, + rising: Vec, + ) -> Result<(), SimulatorErrorCode> { + for id in rising { + let clock = self.tick_clocks.get_mut(&id).expect("a due process clock"); + let next_edge = time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(id))?; + self.ticks += 1; + clock.next_edge = next_edge; + clock.falling_edge = Some(next_edge - clock.period / 2); + let resume_at = clock.next_edge; + self.last_clock_values.insert(id); + self.count_edges(id, 1, resume_at); + } + Ok(()) + } + + /// Credit `edges` rising edges of `clock` to the processes waiting on + /// it; those whose wait is over resume at `resume_at`. + fn count_edges(&mut self, clock: usize, edges: u64, resume_at: u64) { + let released: Vec = self + .clock_waits + .iter_mut() + .filter(|(_, wait)| wait.clock == clock) + .filter_map(|(process, wait)| { + wait.remaining = wait.remaining.saturating_sub(edges); + (wait.remaining == 0).then_some(*process) + }) + .collect(); + for process in released { + self.clock_waits.remove(&process); + self.process_wakeups.push(Reverse((resume_at, process))); + } + } + + /// When every live process waits on `clock`, no other event or + /// resumption is pending, and the host allows it, run the edges every + /// process waits for as fused ticks, as many as the first resumption + /// needs and `limit` permits. Returns whether that happened. + fn fused_ticks( + &mut self, + executor: &mut E, + clock: usize, + time: u64, + limit: u64, + ) -> Result + where + E: SimulationExecutor, + { + // The fused kernel runs the waited-on clock's domain alone: a design + // whose registers drive another clock or reset needs the scheduler's + // rounds, and a clock that is high now needs its normalizing fall. + if time > limit + || !executor.fused_ticks_allowed() + || self.domain_kinds[clock] != Some(DomainKind::ClockPosedge) + || !self.inactive.is_empty() + || !self.waiting.is_empty() + || !self.process_wakeups.is_empty() + || self.scheduler.next_event_time().is_some() + || self + .tick_clocks + .values() + .any(|clock| clock.falling_edge.is_some()) + || self.clock_waits.values().any(|wait| wait.clock != clock) + || self.clock_waits.len() + self.done.len() != self.processes.len() + || self.event_info.iter().any(|info| info.is_cascaded) + || sample_event_signal(executor.backend(), self.tick_clocks[&clock].signal) + != (false, false) + { + return Ok(false); + } + let Some(needed) = self.clock_waits.values().map(|wait| wait.remaining).min() else { + return Ok(false); + }; + let (event, signal, period) = { + let clock = &self.tick_clocks[&clock]; + (clock.event, clock.signal, clock.period) + }; + // Edges at `time`, `time + period`, ...: the last one stays at or + // before `limit`. + let count = needed.min(limit.saturating_sub(time) / period + 1); + if count == 0 { + return Ok(false); + } + // If the batch's resumption cannot be represented, execute normal + // bounded edges instead. They diagnose the offending edge before it + // mutates the backend, retaining the valid earlier progress. + if count + .checked_mul(period) + .and_then(|span| time.checked_add(span)) + .is_none() + { + return Ok(false); + } + // Combinational next-state logic samples the rising level of the clock. + executor.backend_mut().set(signal, 1u8); + self.tick_clocks.get_mut(&clock).unwrap().driven_value = Some(true); + let (completed, result) = executor.tick_many(event, count); + if completed == 0 { + executor.backend_mut().set(signal, 0u8); + self.tick_clocks.get_mut(&clock).unwrap().driven_value = Some(false); + } + if completed > count || (completed == 0 && result.is_ok()) { + return Err(SimulatorErrorCode::Runtime { + message: "the backend made invalid progress on fused clock ticks".into(), + signals: Vec::new(), + }); + } + // The edges the backend completed count, also before an error, so + // the schedule agrees with the state it left. + if completed != 0 { + self.ticks += completed; + self.scheduler.time = time + (completed - 1) * period; + let next_edge = completed + .checked_mul(period) + .and_then(|span| time.checked_add(span)) + .ok_or_else(|| clock_overflow(clock))?; + let tick_clock = self + .tick_clocks + .get_mut(&clock) + .expect("a due process clock"); + tick_clock.next_edge = next_edge; + tick_clock.falling_edge = Some(next_edge - period / 2); + self.last_clock_values.insert(clock); + self.count_edges(clock, completed, next_edge); + } + result?; + // The processes that resume read the state settled after the last + // edge. + executor.eval_comb()?; + Ok(true) + } + + fn check_clock_generator(&self, id: usize) -> Result<(), SimulatorErrorCode> { + if self.scheduler.clocks.get(id).is_some_and(Option::is_some) { + return Err(SimulatorErrorCode::Runtime { + message: format!("process clock {id} is already driven by add_clock"), + signals: Vec::new(), + }); + } + if self.scheduled_clock_drives.contains(id) + || self + .scheduler + .event_queue + .iter() + .any(|event| event.event_ref.id() == id) + { + return Err(SimulatorErrorCode::Runtime { + message: format!("process clock {id} is already driven by schedule"), + signals: Vec::new(), + }); + } + Ok(()) + } + /// Whether a clock/reset differs from the last settled scheduler state. /// Host reads may have already cleared backend trigger bits. pub fn has_unsettled_edges(&self, backend: &B) -> bool { @@ -523,6 +1104,23 @@ impl SimulationState { }) } + /// Pending external clock/reset changes, excluding drives whose phase + /// belongs to a process clock. Those must retry with their scheduled batch. + pub fn has_unsettled_host_edges(&self, backend: &B) -> bool { + self.topo_signals.iter().any(|(signal, id, _)| { + *id != usize::MAX + && !self + .processes + .iter() + .flat_map(|process| &process.clocks) + .any(|clock| clock.signal == *signal) + && ( + self.last_clock_values.contains(*id), + self.unknown_clock_values.contains(*id), + ) != sample_event_signal(backend, *signal) + }) + } + /// Whether a pending transition activates its clock/reset domain. pub fn has_unsettled_active_edges(&self, backend: &B) -> bool { self.topo_signals @@ -543,7 +1141,23 @@ impl SimulationState { where E: SimulationExecutor, { - if self.finished || (self.waiting.is_empty() && self.pending_host_edges.is_empty()) { + self.poll_waiting_until(executor, u64::MAX) + } + + /// [`Self::poll_waiting`], where the fused clock ticks a woken process + /// may start stop before `limit`, as in [`Self::step_until`]. + pub fn poll_waiting_until( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result + where + E: SimulationExecutor, + { + if self.finished + || (self.waiting.is_empty() && self.pending_host_edges.is_empty()) + || self.scheduler.time > limit + { return Ok(false); } let time = self.scheduler.time; @@ -551,28 +1165,28 @@ impl SimulationState { .scheduler .next_event_time() .is_some_and(|next| next <= time) - || self - .process_wakeups - .peek() - .is_some_and(|Reverse((next, _))| *next <= time) - || !self.inactive.is_empty() { return Ok(false); } self.sample_waiting_events(executor)?; + let ready = self.take_ready_processes(time); let mut delta_rounds = 0; - if !self.step_round( + let result = self.step_round( executor, time, Vec::new(), Vec::new(), + ready, false, &mut delta_rounds, - )? { + ); + let progressed = result.as_ref().is_ok_and(|ran| *ran); + self.finish_clock_round(time, Vec::new(), &[], result)?; + if !progressed { return Ok(false); } - self.run_remaining_rounds(executor, time, &mut delta_rounds)?; - executor.finish_timed_step(time); + self.run_remaining_rounds(executor, time, limit, &mut delta_rounds)?; + executor.finish_timed_step(self.scheduler.time); Ok(true) } @@ -637,7 +1251,6 @@ impl SimulationState { ) }) .collect::>(); - // A previous delay amount is no longer live on resumption. executor .backend_mut() .set(self.processes[process].delay, 0u64); @@ -645,6 +1258,7 @@ impl SimulationState { self.sampled_ready.remove(&process); if executor.finish_requested(current_time) { self.finish_round = true; + self.finished = true; return Ok(true); } @@ -661,7 +1275,7 @@ impl SimulationState { executor.backend_mut().mark_triggered_bit(*id); } } - let refs = self.processes[process]; + let refs = &self.processes[process]; let status: u8 = executor.backend().get_as(refs.status); match ProcessStatus::from_code(status) { Some(ProcessStatus::Yield) => { @@ -699,11 +1313,13 @@ impl SimulationState { } Some(ProcessStatus::Done) => { self.waiting.remove(&process); + self.done.insert(process); any_ran = true; } Some(ProcessStatus::Finish) => { self.finish_round = true; self.waiting.remove(&process); + self.done.insert(process); self.finished = true; return Ok(true); } @@ -711,6 +1327,49 @@ impl SimulationState { self.waiting.insert(process); any_ran = true; } + Some(ProcessStatus::WaitClock) => { + let count: u64 = executor.backend().get_as(refs.delay); + let index: u32 = executor.backend().get_as(refs.clock); + let Some(clock) = refs.clocks.get(index as usize) else { + return Err(SimulatorErrorCode::InternalError); + }; + self.waiting.remove(&process); + if count == 0 { + // A zero-count wait does not yield to another process, + // but repeated immediate continuations must be bounded. + if let Err(error) = count_delta_pass(delta_rounds) { + self.process_wakeups.push(Reverse((current_time, process))); + for process in remaining { + self.process_wakeups.push(Reverse((current_time, process))); + } + return Err(error); + } + continue; + } else { + let id = clock.event.id(); + let tick_clock = + self.tick_clocks.entry(id).or_insert_with(|| TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period.max(2), + next_edge: current_time, + falling_edge: None, + driven_value: None, + }); + tick_clock.next_edge = tick_clock.next_edge.max(current_time); + self.clock_waits.insert( + process, + ClockWait { + clock: id, + remaining: count, + }, + ); + // Retain the activation before validation so + // retries cannot skip the failed suspension. + self.check_clock_generator(id)?; + } + any_ran = true; + } // The kernel found its wait condition unmet and ran // nothing; it stays waiting. Some(ProcessStatus::Pending) => {} @@ -751,21 +1410,31 @@ impl SimulationState { where E: SimulationExecutor, { - while self.next_event_time().is_some_and(|next| next < time) { - self.step(executor)?; + let mut settled_target = false; + while self.next_event_time().is_some_and(|next| next <= time) { + settled_target |= self.step_until(executor, time)? == Some(time); } if self.finished { return Ok(None); } - if self.scheduler.next_event_time() == Some(time) { - return self.step(executor); + if settled_target { + return Ok(Some(time)); } let ready = self.take_ready_processes(time); let mut delta_rounds = 0; - self.step_round(executor, time, Vec::new(), ready, true, &mut delta_rounds)?; + let result = self.step_round( + executor, + time, + Vec::new(), + Vec::new(), + ready, + true, + &mut delta_rounds, + ); + self.finish_clock_round(time, Vec::new(), &[], result)?; // A process the settled state woke may wait for zero time: the // rounds of this time are drained, as `step` drains them. - self.run_remaining_rounds(executor, time, &mut delta_rounds)?; + self.run_remaining_rounds(executor, time, time, &mut delta_rounds)?; executor.finish_timed_step(time); Ok(Some(time)) } @@ -774,11 +1443,13 @@ impl SimulationState { /// processes, and settle the edges they cause. Without `settle_idle`, /// a round with no event in which no process ran is skipped, and /// `false` is returned. + #[allow(clippy::too_many_arguments)] fn step_round( &mut self, executor: &mut E, current_time: u64, - events_to_process: Vec>, + mut events_to_process: Vec>, + mut generated_events: Vec>, ready_processes: Vec, settle_idle: bool, delta_rounds: &mut usize, @@ -787,6 +1458,10 @@ impl SimulationState { E: SimulationExecutor, { self.scheduler.time = current_time; + self.round_published_domains.make_empty(); + self.round_triggered_domains.make_empty(); + self.round_triggers_discovered = false; + self.round_new_rising.make_empty(); // Keep periodic provenance private so the public SimEvent shape stays // stable. Consume matching sidecar counts before fallible work so an @@ -852,6 +1527,7 @@ impl SimulationState { }; let before = sample_event_signal(executor.backend(), event.signal); executor.backend_mut().set(event.signal, event.next_val); + self.record_generated_clock_drive(event); let after = sample_event_signal(executor.backend(), event.signal); let mut blocking_source = false; if let Some(&id) = self.signal_to_id.get(&event.signal) @@ -912,6 +1588,7 @@ impl SimulationState { executor.backend_mut().clear_triggered_bits(); let counter_values = self.event_counter_values(executor.backend()); let mut process_driven = Vec::new(); + let mut process_settled = false; if !ready_processes.is_empty() || !self.waiting.is_empty() { let before: Vec<(bool, bool)> = self .topo_signals @@ -930,6 +1607,16 @@ impl SimulationState { { return Ok(false); } + // Discover combinationally derived edges before choosing the + // generated clocks that must share this publication round. + if progressed { + executor.eval_comb()?; + process_settled = true; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } + } for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { if *id == usize::MAX { continue; @@ -941,10 +1628,12 @@ impl SimulationState { } } - let mut triggered_domains = BitSet::with_capacity(num_events); - let mut discovered_in_this_step = BitSet::with_capacity(num_events); - // Counter-recorded kernel edges survive later blocking stores that - // restored the signal before the kernel returned. + if self.finished { + // Suppress generated edges queued before a ready process finished. + self.round_new_rising.make_empty(); + generated_events.clear(); + } + let mut edge_replays = host_replays; self.add_process_edge_replays( executor.backend(), @@ -952,7 +1641,66 @@ impl SimulationState { &mut edge_replays, &scheduled_edges, ); - let mut recorded_edges = self.counter_edges(executor.backend(), &counter_values); + let process_recorded_edges = self.counter_edges(executor.backend(), &counter_values); + + // Ready processes may activate a clock at this timestamp. Join it + // to existing source events before any coincident FF domain commits. + // With no other event, retain the later fused-tick path. + if !self.finished + && (!scheduled_edges.is_empty() + || !events_to_process.is_empty() + || !process_driven.is_empty() + || !generated_events.is_empty() + || !process_recorded_edges.is_empty() + || !executor.backend().get_triggered_bits().is_empty()) + { + for (id, clock) in &self.tick_clocks { + if clock.next_edge == current_time + && clock.falling_edge != Some(current_time) + && self.clock_has_waiters(*id) + && sample_event_signal(executor.backend(), clock.signal) != (true, false) + && !events_to_process + .iter() + .any(|event| event.signal == clock.signal && event.next_val == 0) + && !generated_events + .iter() + .any(|event| event.event_ref.id() == *id) + { + current_time + .checked_add(clock.period) + .ok_or_else(|| clock_overflow(*id))?; + generated_events.push(SimEvent { + time: current_time, + event_ref: clock.event, + signal: clock.signal, + next_val: 1, + }); + self.round_new_rising.insert(*id); + } + } + } + + // A completed clock wait resumes before the following generated + // rising edge. Apply that edge after the ready processes, then join + // it to scheduled triggers so coincident FF domains share one batch. + for event in &generated_events { + let id = event.event_ref.id(); + current_time + .checked_add(self.tick_clocks[&id].period) + .ok_or_else(|| clock_overflow(id))?; + } + for event in &generated_events { + process_settled = false; + executor.backend_mut().set(event.signal, event.next_val); + self.record_generated_clock_drive(event); + } + events_to_process.extend(generated_events); + + let mut triggered_domains = BitSet::with_capacity(num_events); + let mut discovered_in_this_step = BitSet::with_capacity(num_events); + // Counter-recorded kernel edges survive later blocking stores that + // restored the signal before the kernel returned. + let mut recorded_edges = process_recorded_edges; recorded_edges.union_with(&scheduled_edges); let mut scheduled_trigger_ids = recorded_edges.clone(); // An external drive may already have been combinationally evaluated @@ -979,7 +1727,9 @@ impl SimulationState { } } - executor.eval_comb()?; + if !process_settled { + executor.eval_comb()?; + } if executor.finish_requested(current_time) { self.finished = true; return Ok(true); @@ -1021,8 +1771,23 @@ impl SimulationState { let mut any_new_outer_loop_trigger = false; loop { - count_delta_pass(delta_rounds)?; let marked_bits = executor.backend().get_triggered_bits(); + // Discover the complete batch before any fallible sampling or FF + // execution can interrupt it. An empty set before discovery is + // not evidence that a generated falling edge was published. + for id in marked_bits.iter() { + let info = self.event_info[id]; + if !discovered_in_this_step.contains(id) + && !triggered_domains.contains(info.canonical_id) + && (!info.is_cascaded + || recorded_edges.contains(id) + || self.stable_edge_triggered(executor.backend(), id)) + { + self.round_triggered_domains.insert(info.canonical_id); + } + } + self.round_triggers_discovered = true; + count_delta_pass(delta_rounds)?; executor.backend_mut().clear_triggered_bits(); let mut can_use_eval_apply = self.processes.is_empty() @@ -1039,8 +1804,10 @@ impl SimulationState { discovered_in_this_step.insert(single_id); triggered_domains.insert(info.canonical_id); any_new_outer_loop_trigger = true; + self.round_triggered_domains.insert(info.canonical_id); executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; + self.record_domain_publication(executor.backend(), info.canonical_id); executor.fire_external_event(event, current_time)?; executor.eval_comb()?; if executor.finish_requested(current_time) { @@ -1080,6 +1847,7 @@ impl SimulationState { triggered_domains.insert(info.canonical_id); newly_triggered.push(info.canonical_id); + self.round_triggered_domains.insert(info.canonical_id); let before = self.event_counter_values(executor.backend()); if let Some(event) = info.eval_only_event { executor.stage_external_event( @@ -1090,6 +1858,7 @@ impl SimulationState { } else if let Some(event) = info.eval_ff_event { executor.stage_external_event(event, current_time)?; executor.eval_apply_ff_at(event)?; + self.record_domain_publication(executor.backend(), info.canonical_id); } else { unreachable!( "FF trigger discovered without a corresponding execution unit" @@ -1300,6 +2069,7 @@ impl SimulationState { for id in &newly_triggered { if let Some(event) = self.event_info[*id].apply_event { executor.apply_ff_at(event)?; + self.record_domain_publication(executor.backend(), *id); } } for id in &newly_triggered { @@ -1419,6 +2189,25 @@ impl SimulationState { Ok(true) } + fn record_domain_publication(&mut self, backend: &B, canonical: usize) { + self.round_published_domains.insert(canonical); + for (signal, id, _) in &self.topo_signals { + if *id != usize::MAX && self.event_info[*id].canonical_id == canonical { + let (value, unknown) = sample_event_signal(backend, *signal); + if unknown { + self.unknown_clock_values.insert(*id); + } else { + self.unknown_clock_values.remove(*id); + } + if value { + self.last_clock_values.insert(*id); + } else { + self.last_clock_values.remove(*id); + } + } + } + } + fn event_counter_values(&self, backend: &B) -> Vec<(u32, u32)> { self.process_event_counters .iter() @@ -1524,10 +2313,21 @@ impl SimulationState { } else { Some(self.scheduler.time) }; - match (self.scheduler.next_event_time(), process) { - (Some(event), Some(process)) => Some(event.min(process)), - (event, process) => event.or(process), - } + let clocks = self + .tick_clocks + .iter() + .flat_map(|(id, clock)| { + [ + self.clock_has_waiters(*id).then_some(clock.next_edge), + clock.falling_edge, + ] + }) + .flatten() + .min(); + [self.scheduler.next_event_time(), process, clocks] + .into_iter() + .flatten() + .min() } /// Periodic clocks as (event id, period). @@ -1553,8 +2353,14 @@ impl SimulationState { unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), + tick_clocks: self.tick_clocks.clone(), + clock_waits: self.clock_waits.clone(), + done: self.done.clone(), + ticks: self.ticks, sampled_ready: self.sampled_ready.clone(), inactive: self.inactive.clone(), + scheduled_clock_drives: self.scheduled_clock_drives.clone(), + scheduled_clock_time: self.scheduled_clock_time, finished: self.finished, } } @@ -1581,6 +2387,20 @@ impl SimulationState { }) }) .collect::>()?; + // Every translation happens before anything changes. + let tick_clocks = snapshot + .tick_clocks + .iter() + .map(|(id, clock)| { + Ok(( + *id, + TickClock { + event: remap(clock.event).ok_or(clock.event)?, + ..clock.clone() + }, + )) + }) + .collect::>()?; self.scheduler.time = snapshot.time; self.scheduler.clocks.clone_from(&snapshot.clocks); self.scheduler.event_queue = event_queue; @@ -1593,8 +2413,15 @@ impl SimulationState { .clone_from(&snapshot.unknown_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.waiting.clone_from(&snapshot.waiting); + self.tick_clocks = tick_clocks; + self.clock_waits.clone_from(&snapshot.clock_waits); + self.done.clone_from(&snapshot.done); + self.ticks = snapshot.ticks; self.sampled_ready.clone_from(&snapshot.sampled_ready); self.inactive.clone_from(&snapshot.inactive); + self.scheduled_clock_drives + .clone_from(&snapshot.scheduled_clock_drives); + self.scheduled_clock_time = snapshot.scheduled_clock_time; self.finished = snapshot.finished; Ok(()) } @@ -1620,6 +2447,18 @@ pub struct ScheduleParts { pub process_wakeups: Vec<(usize, u64)>, /// Processes waiting for an event or a condition, in ascending order. pub waiting_processes: Vec, + /// Process clocks that have been waited on. + pub process_clocks: Vec>, + /// Processes waiting for edges of a process clock: the process, the + /// clock's event, and the edges still to wait for. + pub clock_waits: Vec<(usize, B::Event, u64)>, + /// Processes that ran to their end, in ascending order. + pub done_processes: Vec, + /// Rising edges of process clocks so far. + pub ticks: u64, + /// Timestamp and one-shot clock drives already consumed at that time. + pub scheduled_clock_time: u64, + pub scheduled_clock_drives: Vec, pub inactive_processes: Vec, /// A process requested the end of the simulation. pub finished: bool, @@ -1681,6 +2520,31 @@ impl SimulationState { wakeups }, waiting_processes: self.waiting.iter().copied().collect(), + process_clocks: self + .tick_clocks + .values() + .map(|clock| ProcessClockState { + event: clock.event, + signal: clock.signal, + period: clock.period, + next_edge: clock.next_edge, + falling_edge: clock.falling_edge, + driven_value: clock.driven_value, + }) + .collect(), + clock_waits: self + .clock_waits + .iter() + .map(|(process, wait)| (*process, events[wait.clock], wait.remaining)) + .collect(), + done_processes: self.done.iter().copied().collect(), + ticks: self.ticks, + scheduled_clock_time: self.scheduled_clock_time, + scheduled_clock_drives: self + .scheduled_clock_drives + .iter() + .map(|id| events[id]) + .collect(), inactive_processes: self.inactive.iter().copied().collect(), finished: self.finished, } @@ -1723,6 +2587,44 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.waiting = parts.waiting_processes.into_iter().collect(); + self.tick_clocks = parts + .process_clocks + .into_iter() + .map(|clock| { + ( + clock.event.id(), + TickClock { + event: clock.event, + signal: clock.signal, + period: clock.period, + next_edge: clock.next_edge, + falling_edge: clock.falling_edge, + driven_value: clock.driven_value, + }, + ) + }) + .collect(); + self.clock_waits = parts + .clock_waits + .into_iter() + .map(|(process, event, remaining)| { + ( + process, + ClockWait { + clock: event.id(), + remaining, + }, + ) + }) + .collect(); + self.done = parts.done_processes.into_iter().collect(); + self.ticks = parts.ticks; + self.scheduled_clock_time = parts.scheduled_clock_time; + self.scheduled_clock_drives = parts + .scheduled_clock_drives + .into_iter() + .map(|event| event.id()) + .collect(); self.inactive = parts.inactive_processes.into_iter().collect(); self.finished = parts.finished; } @@ -1739,8 +2641,14 @@ pub struct SimulationSnapshot { unknown_clock_values: BitSet, process_wakeups: BinaryHeap, waiting: BTreeSet, + tick_clocks: BTreeMap>, + clock_waits: BTreeMap, + done: BTreeSet, + ticks: u64, sampled_ready: BTreeSet, inactive: BTreeSet, + scheduled_clock_drives: BitSet, + scheduled_clock_time: u64, finished: bool, } @@ -1756,8 +2664,14 @@ impl Clone for SimulationSnapshot { unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), waiting: self.waiting.clone(), + tick_clocks: self.tick_clocks.clone(), + clock_waits: self.clock_waits.clone(), + done: self.done.clone(), + ticks: self.ticks, sampled_ready: self.sampled_ready.clone(), inactive: self.inactive.clone(), + scheduled_clock_drives: self.scheduled_clock_drives.clone(), + scheduled_clock_time: self.scheduled_clock_time, finished: self.finished, } } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 10208e6d0ae..3c0e4dd22fe 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -197,9 +197,13 @@ impl SharedNativeCode { /// /// # Safety /// - /// The image's machine code must come from a trusted source. Structural - /// validation and the container checksum detect corruption, but do not - /// authenticate code before it is mapped executable and invoked. + /// The entire compiler-produced image, including its code and metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. + /// Supported API transformations, such as diagnostic path remapping, are + /// allowed. Structural validation and the container checksum do not + /// authenticate either code or metadata. + /// In particular, coherently rewritten ABI metadata cannot be checked + /// against the original compiler intent without external authentication. pub unsafe fn from_image(program_image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. unsafe { Self::from_image_with_dpi(program_image, &crate::DpiSymbols::default()) } @@ -388,6 +392,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) rtl_writes: HashSet>, /// Ordered so that the encoded image does not depend on hash order. pub(crate) comb_writes: std::collections::BTreeSet, + pub(crate) clock_phase_sensitive_comb: bool, pub(crate) dead_store_policy: celox_design::DeadStorePolicy, /// Ordered so that the encoded image does not depend on hash order. pub(crate) live_signals: std::collections::BTreeSet, @@ -408,6 +413,11 @@ pub struct NativeProgramImage { comb_unit_offsets: Vec, /// Entry offset of each process kernel. process_offsets: Vec, + /// Clock-control addresses and byte offsets used to compile each process kernel. + compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, + compiled_process_clock_lists: Vec>>, + compiled_clock_phase_sensitive_comb: bool, + compiled_native_tick_loop: bool, required_native_features: u8, event_map: HashMap, eval_only_event_map: HashMap, @@ -490,6 +500,7 @@ impl NativeProgramImage { testbench_read_roots: self.runtime_schema.testbench_read_roots.clone(), rtl_writes: self.runtime_schema.rtl_writes.clone(), comb_writes: self.runtime_schema.comb_writes.iter().copied().collect(), + clock_phase_sensitive_comb: self.runtime_schema.clock_phase_sensitive_comb, 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(), @@ -512,6 +523,9 @@ impl NativeProgramImage { self.reflection .validate() .map_err(|error| format!("invalid design reflection: {error}"))?; + if self.options.native_tick_loop != self.compiled_native_tick_loop { + return Err("native tick-loop eligibility differs from compiled image".into()); + } if self.code.is_empty() { return Err("code image is empty".into()); } @@ -556,6 +570,86 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } + if self.compiled_process_clocks.len() != self.runtime_schema.processes.len() + || self + .compiled_process_clocks + .iter() + .zip(&self.runtime_schema.processes) + .any(|((address, offset), process)| { + process.clock != *address || self.layout.offsets.get(address) != Some(offset) + }) + { + return Err( + "process clock control slots disagree with compiled kernel bindings".into(), + ); + } + let mut process_clock_periods = fxhash::FxHashMap::default(); + for process in &self.runtime_schema.processes { + if !self + .design + .state_objects + .get(&process.clock) + .is_some_and(|metadata| { + metadata.width == celox_design::PROCESS_CLOCK_WIDTH + && !metadata.is_4state + && metadata.array_dims.is_empty() + }) + { + return Err("a process clock control slot has an invalid state object".into()); + } + for clock in &process.clocks { + if clock.period < 2 + || !self.event_map.contains_key(&clock.signal) + || !self + .design + .state_objects + .get(&clock.signal) + .is_some_and(|metadata| { + metadata.width == 1 + && metadata.array_dims.is_empty() + && matches!( + metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + ) + }) + { + return Err("a process clock has an invalid event domain or period".into()); + } + if self + .runtime_schema + .rtl_writes + .iter() + .any(|write| { + let clock_bit=self.layout.offsets.get(&clock.signal).and_then(|offset|offset.checked_mul(8)); + let written=self.layout.offsets.get(&write.id).and_then(|offset|offset.checked_mul(8)).and_then(|base|Some((base.checked_add(write.access.lsb)?,base.checked_add(write.access.msb)?))); + matches!((clock_bit,written),(Some(clock),Some((first,last))) if first<=clock && clock<=last) + }) + { + return Err("a process clock is driven by design logic".into()); + } + let event = self.event_map[&clock.signal].id; + if let Some(previous) = process_clock_periods.insert(event, clock.period) + && previous != clock.period + { + return Err("process clocks for one event have conflicting periods".into()); + } + } + } + if self.compiled_process_clock_lists.len() != self.runtime_schema.processes.len() + || self + .compiled_process_clock_lists + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| compiled != &process.clocks) + { + return Err("process clock lists disagree with compiled kernel indices".into()); + } + if self.compiled_clock_phase_sensitive_comb + != self.runtime_schema.clock_phase_sensitive_comb + { + return Err("clock phase sensitivity disagrees with compiled kernels".into()); + } for counters in &self.runtime_schema.process_event_counters { if !self.event_map.contains_key(&counters.signal) { return Err("a process edge counter names an unknown event domain".into()); @@ -1808,6 +1902,23 @@ fn compile_program( let sir = laid_out; let layout = laid_out.layout(); let (compile_tasks, task_bindings) = collect_ff_compile_tasks(sir); + // Make the compiled ABI and serialized dispatch agree. Fallible phases + // must return to the host without crediting a failed loop iteration. + let mut effective_options = options.clone(); + effective_options.x86_options.native_tick_loop &= !sir + .sir + .eval_comb + .iter() + .chain(sir.sir.eval_apply_ffs.values().flatten()) + .chain( + compile_tasks + .iter() + .filter(|task| task.label == "eval_comb_apply_ff") + .flat_map(|task| task.units.iter().copied()), + ) + .flat_map(|unit| unit.blocks.values()) + .any(|block| matches!(block.terminator, celox_sir::SIRTerminator::Error(_))); + let options = &effective_options; let comb_blocks = sir .sir .eval_comb @@ -2261,6 +2372,25 @@ fn compile_program( comb_offset, comb_unit_offsets, process_offsets, + compiled_process_clocks: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| (process.clock, layout.offsets[&process.clock])) + .collect(), + compiled_process_clock_lists: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| process.clocks.clone()) + .collect(), + compiled_native_tick_loop: options.x86_options.native_tick_loop, + compiled_clock_phase_sensitive_comb: sir + .runtime() + .runtime_schema + .clock_phase_sensitive_comb, required_native_features, event_map, eval_only_event_map, @@ -2284,6 +2414,7 @@ fn compile_program( .iter() .copied() .collect(), + clock_phase_sensitive_comb: sir.runtime().runtime_schema.clock_phase_sensitive_comb, dead_store_policy: sir.runtime().runtime_schema.dead_store_policy, live_signals: sir .runtime() @@ -2479,9 +2610,9 @@ impl NativeBackend { /// /// # Safety /// - /// The image's machine code must come from a trusted compiler or image - /// container. Structural validation does not authenticate code before it - /// is mapped executable and invoked. + /// The entire compiler-produced image, including code and ABI metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. A successful + /// container checksum or structural validation does not authenticate it. pub unsafe fn from_image(image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. unsafe { Self::from_image_with_dpi(image, &crate::DpiSymbols::default()) } @@ -3033,7 +3164,11 @@ impl super::super::SimBackend for NativeBackend { if count == 0 { return (0, Ok(())); } - return (1, self.eval_comb_apply_ff_at(event)); + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } + let result = self.eval_apply_ff_at(event); + return (u64::from(result.is_ok()), result); } if self.compiled.options.native_tick_loop { let (executed, result) = self.call_func_many_timed(event.comb_apply_func, count); @@ -3047,11 +3182,17 @@ impl super::super::SimBackend for NativeBackend { } else if count == 0 { (0, Ok(())) } else { + if let Err(error) = self.eval_comb() { + return (0, Err(error)); + } if fused_sequential { self.lane_selectors .advance(super::super::lanes::LaneKernelSlot::Fused(event.id), 1); } - (1, self.call_func_timed(event.comb_apply_func)) + { + let result = self.eval_apply_ff_at(event); + (u64::from(result.is_ok()), result) + } } } @@ -3316,3 +3457,300 @@ impl super::super::SimBackend for NativeBackend { bs } } + +#[cfg(test)] +mod process_metadata_tests { + use super::super::image_file::NativeImageContainerError; + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn image() -> NativeProgramImage { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let clk2 = module.internal("clk2", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + module + .output("unrelated", ValueType::bits(32).unwrap()) + .unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let target = module.whole(q).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + let q2 = module.output("q2", bit).unwrap(); + let target2 = module.whole(q2).unwrap(); + module + .register(target2, one, clk2, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk2, 4).unwrap(); + module.clock_period(clk, 2).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: one, + }, + Statement::ClockCycles { + clock: clk2, + count: one, + }, + ]) + .unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + crate::Simulator::from_frontend(module.finish()) + .compile_native() + .unwrap() + .into_program_image() + } + + #[test] + fn process_clock_lists_match_the_compiled_indices() { + let original = image(); + original.to_container_bytes().unwrap(); + assert_eq!(original.runtime_schema.processes[0].clocks.len(), 2); + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clocks.swap(0, 1); + assert!(broken.to_container_bytes().is_err()); + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clocks[0] = + original.runtime_schema.processes[0].clocks[1]; + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn clock_phase_sensitivity_matches_compilation() { + let mut broken = image(); + broken.runtime_schema.clock_phase_sensitive_comb = + !broken.runtime_schema.clock_phase_sensitive_comb; + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn process_clock_control_cannot_name_an_unrelated_register() { + let original = image(); + original.to_container_bytes().unwrap(); + let clock = original.runtime_schema.processes[0].clock; + let unrelated = *original + .design + .state_objects + .iter() + .find(|(addr, metadata)| { + **addr != clock + && metadata.width == celox_design::PROCESS_CLOCK_WIDTH + && !original + .runtime_schema + .processes + .iter() + .any(|p| [p.resume, p.status, p.delay, p.clock].contains(addr)) + }) + .unwrap() + .0; + let mut broken = original.clone(); + broken.runtime_schema.processes[0].clock = unrelated; + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + + #[test] + fn process_clock_control_layout_matches_the_compiled_kernel() { + let mut broken = image(); + let process = &broken.runtime_schema.processes[0]; + broken + .layout + .offsets + .insert(process.clock, broken.layout.offsets[&process.resume]); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + + #[test] + fn process_clock_metadata_is_checked_before_image_attachment() { + let original = image(); + original.to_container_bytes().unwrap(); + for corruption in 0..5 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes[0]; + match corruption { + 0 => slots.clocks[0].signal = slots.delay, + 1 => slots.clocks[0].period = 1, + 2 => slots.clock = slots.status, + 4 => { + let signal = slots.clocks[0].signal; + broken + .runtime_schema + .rtl_writes + .insert(celox_design::VarAtomBase { + id: signal, + access: celox_design::BitAccess::new(0, 0), + }); + } + _ => { + let signal = *broken + .design + .state_objects + .iter() + .find(|(_, metadata)| { + metadata.width == 1 && metadata.kind == celox_design::DomainKind::Other + }) + .unwrap() + .0; + let event = broken.event_map[&slots.clocks[0].signal]; + broken.event_map.insert(signal, event); + slots.clocks[0].signal = signal; + } + } + assert!( + matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + ), + "accepted corruption {corruption}" + ); + } + } + + #[test] + fn aliased_rtl_storage_cannot_drive_a_process_clock() { + let mut broken = image(); + broken.to_container_bytes().unwrap(); + let clock = broken.runtime_schema.processes[0].clocks[0].signal; + let driver = broken + .runtime_schema + .rtl_writes + .iter() + .find(|write| write.id != clock) + .unwrap() + .id; + assert_ne!(driver, clock); + assert_ne!( + broken.layout.offsets[&driver], + broken.layout.offsets[&clock] + ); + broken + .layout + .offsets + .insert(clock, broken.layout.offsets[&driver]); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + + #[test] + fn process_clock_periods_must_agree_across_slot_tables() { + let mut broken = image(); + broken.to_container_bytes().unwrap(); + broken.runtime_schema.processes[1].clocks[0].period = 4; + assert!( + matches!(broken.to_container_bytes(), Err(NativeImageContainerError::InvalidImage(message)) if message.contains("conflicting periods")) + ); + } + + #[test] + fn native_loop_eligibility_cannot_be_changed_in_a_checksummed_image() { + let source = r#"module Top(clk:input clock,enable:output logic,v:output logic){ + assign v=if enable ? ~v : 1'd0; + always_ff(clk){enable=1;} + }"#; + let original = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .compile_native() + .unwrap() + .into_program_image(); + assert!(!original.options.native_tick_loop); + let pure = image(); + assert!(pure.options.native_tick_loop); + for original in [original, pure] { + let mut changed = original.clone(); + changed.options.native_tick_loop = !changed.options.native_tick_loop; + // Bypass the writer's validation and regenerate a valid payload + // checksum, exercising the reader's attachment boundary directly. + let mut bytes = original.to_container_bytes().unwrap(); + let trailer = bytes.len() - 32; + let payload = postcard::to_stdvec(&changed).unwrap(); + assert_eq!(payload.len(), trailer); + bytes[..trailer].copy_from_slice(&payload); + let checksum = payload.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3) + }); + bytes[trailer + 24..trailer + 32].copy_from_slice(&checksum.to_le_bytes()); + assert!( + matches!(NativeProgramImage::from_container_bytes(&bytes),Err(NativeImageContainerError::InvalidImage(message)) if message.contains("tick-loop")) + ); + } + } + + #[test] + fn default_native_loops_do_not_credit_a_failed_pre_edge_iteration() { + use crate::backend::SimBackend; + let source = r#"module Top(clk:input clock,enable:output logic,v:output logic){ + assign v=if enable ? ~v : 1'd0; + always_ff(clk){enable=1;} + }"#; + let mut sim = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_native() + .unwrap(); + let event = sim.event("clk"); + let bytes = sim + .backend + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = NativeProgramImage::from_container_bytes(&bytes).unwrap(); + // Safety: this round-trip image was compiled in this test. + let mut loaded = unsafe { NativeBackend::from_image(image) }.unwrap(); + for backend in [&mut sim.backend, &mut loaded] { + let (completed, result) = backend.eval_comb_apply_ff_many_at(event, 10); + assert_eq!(completed, 1); + assert!(result.is_ok()); + let (completed, result) = backend.eval_comb_apply_ff_many_at(event, 9); + assert_eq!(completed, 0); + assert!(result.is_err()); + } + } + + #[test] + fn lane_ticks_report_zero_progress_for_pre_edge_comb_failure() { + use crate::backend::SimBackend; + let source = r#"module Top(clk: input clock, ok: input logic, q: output logic, a: output logic, b: output logic, c: output logic, v: output logic) { + assign v = if ok ? 1'd0 : ~v; + always_ff(clk) { q=1; } + always_ff(clk) { a=1; } + always_ff(clk) { b=1; } + always_ff(clk) { c=1; } + }"#; + let mut sim = crate::Simulator::builder(source, "Top") + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .threads(4) + .parallel_partition(crate::ParallelPartition::Always) + .build_native() + .unwrap(); + let event = sim.event("clk"); + assert!(sim.backend.lane_event_kernel(event)); + let (completed, result) = sim.backend.eval_comb_apply_ff_many_at(event, 10); + assert_eq!(completed, 0); + assert!(result.is_err()); + assert_eq!(sim.backend.get_as::(sim.signal("q")), 0); + } +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 474e774d9cc..5ac0b03728e 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 = 18; +const CONTAINER_VERSION: u16 = 22; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; @@ -172,6 +172,10 @@ impl NativeProgramImage { } /// Decode a standalone container with no runtime prefix. + /// + /// Successful decoding checks structure and consistency, not authenticity. + /// Before attaching this image, the caller must establish trust in the + /// entire compiler-produced artifact, including its ABI metadata. pub fn from_container_bytes(bytes: &[u8]) -> Result { let appended = Self::discover_appended(bytes)?.ok_or(NativeImageContainerError::MissingTrailer)?; @@ -262,6 +266,46 @@ fn checksum(bytes: &[u8]) -> u64 { }) } +#[cfg(test)] +mod process_metadata_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + + fn image() -> NativeProgramImage { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let target = module.whole(q).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + crate::Simulator::from_frontend(module.finish()) + .compile_native() + .unwrap() + .into_program_image() + } + + #[test] + fn the_previous_process_schema_is_rejected_before_decoding() { + let mut bytes = image().to_container_bytes().unwrap(); + let version = bytes.len() - TRAILER_SIZE + 8; + bytes[version..version + 2].copy_from_slice(&(CONTAINER_VERSION - 1).to_le_bytes()); + assert!(matches!( + NativeProgramImage::from_container_bytes(&bytes), + Err(NativeImageContainerError::UnsupportedVersion(version)) if version == CONTAINER_VERSION - 1 + )); + } +} + #[cfg(test)] mod runtime_schema_version_tests { use super::*; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7dfdf72d48e..10ce330f3aa 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -54,8 +54,9 @@ impl NativeProgramInstance { /// /// # Safety /// - /// The image's machine code must come from a trusted source. Image - /// validation is structural and does not authenticate executable code. + /// The entire compiler-produced image, including code and ABI metadata, + /// must come from a trusted source and preserve its compiler-produced ABI. Image validation + /// is structural and does not authenticate either code or metadata. pub unsafe fn from_image(image: NativeProgramImage) -> Result { // Safety: upheld by this constructor's caller. let shared = Arc::new( @@ -82,8 +83,9 @@ impl NativeProgramInstance { /// /// # Safety /// - /// The appended machine code must come from a trusted source. The - /// container checksum is not an authenticity check. + /// The entire appended image, including its code and ABI metadata, must + /// come from a trusted source and preserve its compiler-produced ABI. The checksum + /// is not an authenticity check. pub unsafe fn from_attached_bytes(bytes: &[u8]) -> Result { let appended = NativeProgramImage::discover_appended(bytes)? .ok_or(NativeProgramLoadError::MissingImage)?; diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 26d36a20078..bd6934176b5 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -311,10 +311,10 @@ impl CompiledTier { count: u64, ) -> (u64, Result<(), SimulatorErrorCode>) { match self { - Self::Jit(jit) => (1, { + Self::Jit(jit) => { let event = jit.id_to_event_slice()[id]; - jit.eval_comb_apply_ff_at(event) - }), + jit.eval_comb_apply_ff_many_at(event, count) + } #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1268,12 +1268,9 @@ impl SimBackend for TieredBackend { match &mut self.phase { Phase::Interpreting(Some(interp)) => { self.interpreted_steps = self.interpreted_steps.saturating_add(1); - ( - 1, - interp.eval_comb_apply_ff_at(super::interp::InterpEventRef::from_parts( - event.addr(), - event.id(), - )), + interp.eval_comb_apply_ff_many_at( + super::interp::InterpEventRef::from_parts(event.addr(), event.id()), + count, ) } Phase::Compiled(compiled) => { diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 4ea9e6d5ead..c7329d1d065 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -446,6 +446,28 @@ pub struct UnoptimizedSir { impl UnoptimizedSir { pub(crate) fn new(sir: SirProgram, mut runtime: RuntimeProgram) -> Self { + runtime.runtime_schema.clock_phase_sensitive_comb = sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .any(|instruction| { + if let SIRInstruction::Load(_, address, _, _) = instruction { + runtime + .design + .state_objects + .get(&address.absolute_addr()) + .is_some_and(|metadata| { + matches!( + metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + ) + }) + } else { + false + } + }); runtime.runtime_schema.active_ff_events = sir.eval_only_ffs.iter() .filter(|(_, units)| units.iter().any(|unit| { // Design destinations are seeded in working storage. Internal diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index ebcbb546c6b..438d0896691 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -100,14 +100,22 @@ mod host_api { pub struct IOContext<'a, B: SimBackend = DefaultBackend> { pub(crate) backend: &'a mut B, + pub(crate) host_writes: &'a mut Vec, + pub(crate) host_clock_signals: &'a [crate::SignalRef], } impl<'a, B: SimBackend> IOContext<'a, B> { pub fn set(&mut self, signal: crate::SignalRef, val: T) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set(signal, val); } pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set_wide(signal, val); } @@ -117,6 +125,9 @@ mod host_api { val: crate::BigUint, mask: crate::BigUint, ) { + if self.host_clock_signals.contains(&signal) && !self.host_writes.contains(&signal) { + self.host_writes.push(signal); + } self.backend.set_four_state(signal, val, mask); } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index aa13ac61ac7..2301ca89e47 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -116,6 +116,41 @@ impl SimulationExecutor for Simulator { .map_err(|e| self.decorate_runtime_error(e)) } + fn tick_many(&mut self, event: B::Event, count: u64) -> (u64, Result<(), RuntimeErrorCode>) { + if count == 0 { + return (0, Ok(())); + } + if !self.program.runtime_schema.comb_observers.is_empty() { + if let Err(error) = self.eval_comb_checked() { + return (0, Err(error)); + } + let result = self.tick_deferred_comb(event); + return (u64::from(result.is_ok()), result); + } + // Every tick settles the combinational logic first, so a clean + // state needs no special case and the whole run stays in the + // backend's loop. + let (completed, result) = self.backend.eval_comb_apply_ff_many_at(event, count); + self.dirty = true; + ( + completed, + result.map_err(|error| self.decorate_runtime_error(error)), + ) + } + + fn fused_ticks_allowed(&self) -> bool { + self.vcd_writer.is_none() + && !self.components.has_scheduled_components() + && self.program.runtime_schema.comb_observers.is_empty() + && !self + .program + .runtime_schema + .runtime_event_sites + .iter() + .any(|site| matches!(site.kind, celox_design::RuntimeEventKind::Finish)) + && !self.program.runtime_schema.clock_phase_sensitive_comb + } + fn stage_external_event( &mut self, event: B::Event, @@ -265,6 +300,19 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul .map(|slots| ProcessRefs { status: simulator.backend.resolve_signal(&slots.status), delay: simulator.backend.resolve_signal(&slots.delay), + clock: simulator.backend.resolve_signal(&slots.clock), + clocks: slots + .clocks + .iter() + .map(|clock| celox_runtime::ProcessClockRef { + event: simulator + .backend + .resolve_event_opt(&clock.signal) + .expect("a process clock is the clock of a sequential domain"), + signal: simulator.backend.resolve_signal(&clock.signal), + period: clock.period, + }) + .collect(), }) .collect(); @@ -318,6 +366,14 @@ impl Simulation { /// Save the design state, simulation time, clocks and pending events. pub fn checkpoint(&self) -> Result, CheckpointError> { + if self.simulator.escaped_mutable_memory + && !self + .state + .escaped_host_clock_writes(&self.simulator.backend) + .is_empty() + { + return Err(CheckpointError::UntrackedHostClockWrite); + } Ok(SimulationCheckpoint { simulator: self.simulator.checkpoint()?, schedule: self.state.snapshot(), @@ -420,6 +476,19 @@ impl Simulation { self.simulator.signal(path) } + fn record_escaped_host_clock_writes(&mut self) { + if self.simulator.escaped_mutable_memory { + for signal in self + .state + .escaped_host_clock_writes(&self.simulator.backend) + { + if !self.simulator.pending_host_writes.contains(&signal) { + self.simulator.pending_host_writes.push(signal); + } + } + } + } + fn synchronize_runtime_finish(&mut self, was_dirty: bool) { if !self.simulator.dirty { self.pending_host_work = false; @@ -444,6 +513,7 @@ 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.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get(signal) @@ -459,6 +529,7 @@ impl Simulation { &mut self, signal: SignalRef, ) -> (num_bigint::BigUint, num_bigint::BigUint) { + self.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let value = if self.state.is_finished() { self.simulator.backend.get_four_state(signal) @@ -561,21 +632,21 @@ impl Simulation { if self.state.poll_waiting(&mut self.simulator)? { return Ok((!self.state.is_finished()).then_some(self.state.time())); } - if self.state.has_unsettled_edges(&self.simulator.backend) { + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); let active = self .state .has_unsettled_active_edges(&self.simulator.backend); let queued = self.state.next_event_time() == Some(time); if queued { - self.state.step(&mut self.simulator)?; - } else { - self.state.settle_at(&mut self.simulator, time)?; + let result = self.state.step(&mut self.simulator)?; + return Ok(result.filter(|_| !self.state.is_finished())); } + self.state.settle_at(&mut self.simulator, time)?; if self.state.is_finished() { return Ok(None); } - if active || queued { + if active { return Ok(Some(time)); } } @@ -596,7 +667,8 @@ impl Simulation { return Ok(()); } let time = self.state.time(); - if self.simulator.dirty + if !self.simulator.pending_host_writes.is_empty() + || self.simulator.dirty || !self.simulator.backend.get_triggered_bits().is_empty() || self.state.has_unsettled_edges(&self.simulator.backend) || self @@ -614,14 +686,14 @@ impl Simulation { .next_event_time() .is_some_and(|next| next <= time) { - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, time)?; drained = true; } if !drained { self.state.settle_at(&mut self.simulator, time)?; } } else { - self.state.poll_waiting(&mut self.simulator)?; + self.state.poll_waiting_until(&mut self.simulator, time)?; } Ok(()) } @@ -632,6 +704,14 @@ impl Simulation { if self.state.is_finished() { return Ok(()); } + self.record_escaped_host_clock_writes(); + let writes = self.simulator.take_host_writes(); + for &signal in &writes { + if let Err(error) = self.state.validate_host_write(signal) { + self.simulator.pending_host_writes = writes; + return Err(error); + } + } if self.simulator.dirty { self.eval_comb()?; } @@ -667,24 +747,24 @@ impl Simulation { if self.state.is_finished() { return Ok(None); } - if self.state.poll_waiting(&mut self.simulator)? { + if self.state.poll_waiting_until(&mut self.simulator, limit)? { return Ok((!self.state.is_finished()).then_some(self.state.time())); } - if self.state.has_unsettled_edges(&self.simulator.backend) { + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); let active = self .state .has_unsettled_active_edges(&self.simulator.backend); let queued = self.state.next_event_time() == Some(time); if queued { - self.state.step(&mut self.simulator)?; - } else { - self.state.settle_at(&mut self.simulator, time)?; + let result = self.state.step_until(&mut self.simulator, limit)?; + return Ok(result.filter(|_| !self.state.is_finished())); } + self.state.settle_at(&mut self.simulator, time)?; if self.state.is_finished() { return Ok(None); } - if active || queued { + if active { return Ok(Some(time)); } } @@ -693,14 +773,15 @@ impl Simulation { .next_event_time() .is_some_and(|time| time <= limit) { - self.state.step(&mut self.simulator) + self.state.step_until(&mut self.simulator, limit) } else { Ok(None) } } /// Advance time and run until `end_time` (inclusive). As for - /// [`Self::step`], processes that a host write woke resume first. + /// [`Self::step`], processes that a host write woke resume first. A time + /// before the current time leaves the simulation unchanged. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { if self.state.is_finished() { return Ok(()); @@ -709,11 +790,12 @@ impl Simulation { return Ok(()); } self.settle_host_writes()?; - self.state.poll_waiting(&mut self.simulator)?; - if self.state.has_unsettled_edges(&self.simulator.backend) { + self.state + .poll_waiting_until(&mut self.simulator, end_time)?; + if self.state.has_unsettled_host_edges(&self.simulator.backend) { let time = self.state.time(); if self.state.next_event_time() == Some(time) { - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, end_time)?; } else { self.state.settle_at(&mut self.simulator, time)?; } @@ -725,7 +807,7 @@ impl Simulation { if next_time > end_time { break; } - self.state.step(&mut self.simulator)?; + self.state.step_until(&mut self.simulator, end_time)?; } if self.state.is_finished() { return Ok(()); @@ -751,6 +833,12 @@ impl Simulation { self.state.time() } + /// Rising edges of the clocks processes wait on that the simulation has + /// run so far. + pub fn ticks(&self) -> u64 { + self.state.ticks() + } + /// Periodic clocks registered with [`Self::add_clock`] (or loaded with a /// state), as (event id, period). pub fn clock_periods(&self) -> Vec<(usize, u64)> { @@ -760,6 +848,7 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + self.record_escaped_host_clock_writes(); let was_dirty = self.simulator.dirty; let events = if self.state.is_finished() { self.simulator.drain_runtime_events_without_evaluation() @@ -782,6 +871,10 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + self.record_escaped_host_clock_writes(); + for &signal in &self.simulator.pending_host_writes { + self.state.validate_host_write(signal)?; + } self.simulator.eval_comb()?; if self.simulator.has_pending_runtime_finish() { self.state.finish(); @@ -1486,10 +1579,247 @@ mod wait_tests { } } +/// Clock waits of processes on every backend: fused where the backend +/// loops in generated code, one tick per call elsewhere. +#[cfg(all(test, feature = "host-runtime"))] +mod clock_wait_tests { + use celox_frontend_sdk::{ + BinaryOp, Constant, Edge, FrontendArtifact, ModuleBuilder, Statement, ValueType, + }; + + use super::Simulation; + use crate::{SimBackend, Simulator, SimulatorBuilder}; + + /// A counter clocked by a process clock; one process waits 1000 edges + /// and records the count, another waits 400 and then 5 more. + fn design(four_state: bool) -> FrontendArtifact { + let bit = ValueType::new(1, false, four_state).unwrap(); + let word = ValueType::new(16, false, four_state).unwrap(); + let mut module = ModuleBuilder::new("ClockWaits").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let count = module.output("count", word).unwrap(); + let late = module.output("late", word).unwrap(); + let early = module.output("early", word).unwrap(); + for signal in [count, late, early] { + module + .set_initial(signal, Constant::two_state(0u8, 16).unwrap()) + .unwrap(); + } + let count_expr = module.read(count).unwrap(); + let one = module.constant(Constant::two_state(1u8, 16).unwrap()); + let next = module.binary(BinaryOp::Add, count_expr, one, word).unwrap(); + let count_target = module.whole(count).unwrap(); + module + .register(count_target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let constant = |module: &mut ModuleBuilder, value: u64| { + module.constant(Constant::two_state(value, 64).unwrap()) + }; + let thousand = constant(&mut module, 1000); + let late_target = module.whole(late).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: thousand, + }, + Statement::Assign { + target: late_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + let four_hundred = constant(&mut module, 400); + let five = constant(&mut module, 5); + let early_target = module.whole(early).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: four_hundred, + }, + Statement::Assign { + target: early_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: five, + }, + ]) + .unwrap(); + module.finish() + } + + fn check(mut sim: Simulation) { + let count = sim.signal("count"); + let early = sim.signal("early"); + let late = sim.signal("late"); + sim.run_until(1601).unwrap(); + assert_eq!(sim.get(early), 400u16.into()); + assert_eq!(sim.get(count), 401u16.into()); + assert_eq!(sim.ticks(), 401); + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 4000); + assert_eq!(sim.get(late), 1000u16.into()); + assert_eq!(sim.get(count), 1000u16.into()); + assert_eq!(sim.ticks(), 1000); + } + + fn builder(four_state: bool) -> SimulatorBuilder<'static, Simulator> { + Simulator::from_frontend(design(four_state)) + .four_state(four_state) + .emit_triggers() + } + + fn check_all_backends(four_state: bool) { + check(Simulation::new( + builder(four_state).build_interpreter().unwrap(), + )); + check(Simulation::new( + builder(four_state).build_cranelift().unwrap(), + )); + check(Simulation::new(builder(four_state).build_wasm().unwrap())); + check(Simulation::new(builder(four_state).build_tiered().unwrap())); + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + check(Simulation::new(builder(four_state).build_native().unwrap())); + } + + #[test] + fn clock_waits_run_on_every_backend() { + check_all_backends(false); + } + + #[test] + fn four_state_clock_waits_run_on_every_backend() { + check_all_backends(true); + } + fn edge_design(edge: Edge) -> FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Edges").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let clock_value = module.read(clk).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let value = if edge == Edge::Posedge { + clock_value + } else { + one + }; + let target = module.whole(q).unwrap(); + module + .register(target, value, clk, edge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let three = module.constant(Constant::two_state(3u8, 8).unwrap()); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + module.finish() + } + + fn check_edge(mut sim: Simulation, edge: Edge) { + sim.run_until(0).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + sim.run_until(1).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.run_until(20).unwrap(); + assert_eq!(sim.time(), 12); + assert_eq!(sim.ticks(), 3); + assert!(sim.is_finished()); + } + + #[test] + fn clock_levels_and_falling_edges_agree_across_backends() { + for edge in [Edge::Posedge, Edge::Negedge] { + let builder = || Simulator::from_frontend(edge_design(edge)).emit_triggers(); + check_edge( + Simulation::new(builder().build_interpreter().unwrap()), + edge, + ); + check_edge(Simulation::new(builder().build_cranelift().unwrap()), edge); + check_edge(Simulation::new(builder().build_wasm().unwrap()), edge); + check_edge(Simulation::new(builder().build_tiered().unwrap()), edge); + check_edge(Simulation::new(builder().build_native().unwrap()), edge); + } + } + + #[test] + fn settle_at_does_not_fuse_past_a_delay_boundary() { + // Use a dedicated SDK design so settle_at itself advances to the due delay. + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Boundary").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let target = module.whole(q).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + let five = module.constant(Constant::two_state(5u8, 8).unwrap()); + let ten = module.constant(Constant::two_state(10u8, 8).unwrap()); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + assert_eq!(sim.state.settle_at(&mut sim.simulator, 5).unwrap(), Some(5)); + assert_eq!(sim.time(), 5); + assert_eq!(sim.ticks(), 1); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod process_review_tests { use super::*; + fn check_failed_batch(mut sim: Simulator) { + let event = sim.event("clk"); + let (completed, result) = SimulationExecutor::tick_many(&mut sim, event, 10); + assert_eq!(completed, 0); + assert!(result.is_err()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + } + + #[test] + fn failed_pre_edge_comb_does_not_complete_a_clock_tick() { + let source = "module Top(input bit clk, input bit ok, output bit q); always_comb assert(ok) else $fatal(1, \"failed comb\"); always_ff @(posedge clk) q <= 1; endmodule"; + let builder = + || Simulator::from_sv_sources(vec![(source, std::path::Path::new("batch.sv"))], "Top"); + check_failed_batch(builder().build_interpreter().unwrap()); + check_failed_batch(builder().build_cranelift().unwrap()); + check_failed_batch(builder().build_wasm().unwrap()); + check_failed_batch(builder().build_tiered().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_failed_batch(builder().build_native().unwrap()); + } + fn check(mut sim: Simulation) { sim.run_until(2).unwrap(); assert_eq!(sim.get(sim.signal("q")), 1u8.into()); @@ -1546,6 +1876,221 @@ mod process_review_tests { } } +#[cfg(test)] +mod bounded_clock_phase_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + + fn design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let enable = module.output("enable", bit).unwrap(); + let v = module.output("v", bit).unwrap(); + let one = module.constant(Constant::two_state(1u8, 1).unwrap()); + let zero = module.constant(Constant::two_state(0u8, 1).unwrap()); + let target = module.whole(enable).unwrap(); + module + .register(target, one, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let clock = module.read(clk).unwrap(); + let enabled = module.read(enable).unwrap(); + let previous = module.read(v).unwrap(); + let low = module.unary(UnaryOp::BitNot, clock, bit).unwrap(); + let active = module.binary(BinaryOp::And, low, enabled, bit).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let next = module.mux(active, toggled, zero).unwrap(); + let target = module.whole(v).unwrap(); + module.assign(target, next).unwrap(); + let count = module.constant(Constant::two_state(10u8, 64).unwrap()); + module + .process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + module.finish() + } + + fn check(mut sim: Simulation) { + assert!(sim.run_until(40).is_err()); + assert_eq!(sim.time(), 2); + assert_eq!(sim.ticks(), 1); + } + + #[test] + fn low_phase_comb_failures_stop_before_later_fused_edges() { + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_cranelift() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::from_frontend(design()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + .build_native() + .unwrap(), + ); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn step_until_leaves_later_events_queued() { + let source = + "module Top(input bit clk, output bit q); always_ff @(posedge clk) q<=1; endmodule"; + let mut sim = + Simulation::from_sv_sources(vec![(source, std::path::Path::new("limit.sv"))], "Top") + .build() + .unwrap(); + sim.schedule("clk", 5, 1).unwrap(); + assert_eq!(sim.state.step_until(&mut sim.simulator, 4).unwrap(), None); + assert_eq!(sim.time(), 0); + assert_eq!(sim.next_event_time(), Some(5)); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!( + sim.state.step_until(&mut sim.simulator, 5).unwrap(), + Some(5) + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + + #[cfg(feature = "systemverilog")] + fn check_past_limit(mut sim: Simulation) { + sim.run_until(100).unwrap(); + let gate = sim.signal("gate"); + let seen = sim.signal("seen"); + sim.set_wide(gate, 1u8.into()); + sim.run_until(60).unwrap(); + assert_eq!(sim.time(), 100); + assert_eq!(sim.get(seen), 0u8.into()); + assert!(sim.has_waiting_processes()); + sim.run_until(100).unwrap(); + assert_eq!(sim.get(seen), 1u8.into()); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn past_run_limit_does_not_poll_waiters_or_rewind_time() { + let source = "module Top(input bit gate, output bit seen); initial begin wait(gate); seen=1; end endmodule"; + let builder = + || Simulation::from_sv_sources(vec![(source, std::path::Path::new("past.sv"))], "Top"); + check_past_limit(builder().build_interpreter().unwrap()); + check_past_limit(builder().build_cranelift().unwrap()); + check_past_limit(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_past_limit(builder().build_native().unwrap()); + } + + fn coincident_design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let byte = ValueType::bits(8).unwrap(); + let mut module = ModuleBuilder::new("Coincident").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let other = module.internal("other", bit).unwrap(); + let count = module.output("count", byte).unwrap(); + let sampled = module.output("sampled", byte).unwrap(); + let seen = module.output("seen", bit).unwrap(); + let count_expr = module.read(count).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let two = module.constant(Constant::two_state(2u8, 8).unwrap()); + let next = module.binary(BinaryOp::Add, count_expr, one, byte).unwrap(); + let target = module.whole(count).unwrap(); + module + .register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + let target = module.whole(sampled).unwrap(); + module + .register(target, count_expr, other, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 4).unwrap(); + let target = module.whole(seen).unwrap(); + let value = module.read(clk).unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: one, + }, + Statement::Assign { target, value }, + ]) + .unwrap(); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: two, + }]) + .unwrap(); + module.finish() + } + + fn check_coincident(mut sim: Simulation) { + sim.schedule("other", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 1u8.into()); + assert_eq!(sim.ticks(), 2); + sim.run_until(2).unwrap(); + assert_eq!(sim.time(), 4); + assert_eq!(sim.ticks(), 2); + } + + #[test] + fn clock_wait_resumes_before_coincident_generated_edge() { + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_interpreter() + .unwrap(), + ); + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_cranelift() + .unwrap(), + ); + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_coincident( + Simulation::from_frontend(coincident_design()) + .build_native() + .unwrap(), + ); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod ff_counter_regressions { use super::*; @@ -1574,34 +2119,596 @@ mod ff_counter_regressions { } } -#[cfg(all(test, feature = "systemverilog"))] -mod active_ff_metadata_tests { - #[test] - fn pending_control_flags_do_not_request_active_settling() { - for (body, expected) in [("q<=d;", false), ("q=d;", true), ("q<=d; q=d;", true)] { - let code = format!( - "module Top(input bit clk,d,output bit q); always @(posedge clk) begin {body} end initial #1; endmodule" - ); - let sim = crate::Simulator::from_sv_sources( - vec![(&code, std::path::Path::new("active_ff.sv"))], - "Top", - ) - .build_interpreter() - .unwrap(); - assert_eq!( - !sim.program.runtime_schema.active_ff_events.is_empty(), - expected, - "{body}" - ); +#[cfg(test)] +mod clock_failure_progress_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + + fn design(on_rising: bool) -> crate::frontend_sdk::FrontendArtifact { + module_design(on_rising).0.finish() + } + + fn module_design(on_rising: bool) -> (ModuleBuilder, crate::frontend_sdk::SignalId) { + module_design_with_failure(on_rising, true) + } + + fn module_design_with_failure( + on_rising: bool, + after_first_rise: bool, + ) -> (ModuleBuilder, crate::frontend_sdk::SignalId) { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let mut m = ModuleBuilder::new("Progress").unwrap(); + let other = m.internal("other", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let bad = m.input("bad", bit).unwrap(); + let count = m.output("count", word).unwrap(); + let falls = m.output("falls", word).unwrap(); + let fallclk = m.internal("fallclk", bit).unwrap(); + let clk_expr = m.read(clk).unwrap(); + let low = m.unary(UnaryOp::BitNot, clk_expr, bit).unwrap(); + let count_expr = m.read(count).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 32).unwrap()); + let running = m.binary(BinaryOp::NotEqual, count_expr, zero, bit).unwrap(); + let fall_phase = m.binary(BinaryOp::And, low, running, bit).unwrap(); + let target = m.whole(fallclk).unwrap(); + m.assign(target, fall_phase).unwrap(); + for (signal, clock) in [(count, clk), (falls, fallclk)] { + let value = m.read(signal).unwrap(); + let one = m.constant(Constant::two_state(1u8, 32).unwrap()); + let next = m.binary(BinaryOp::Add, value, one, word).unwrap(); + let target = m.whole(signal).unwrap(); + m.register(target, next, clock, Edge::Posedge, None, None) + .unwrap(); } + let v = m.output("v", bit).unwrap(); + let phase = m.read(clk).unwrap(); + let phase = if on_rising { + phase + } else { + m.unary(UnaryOp::BitNot, phase, bit).unwrap() + }; + let bad = m.read(bad).unwrap(); + let active = m.binary(BinaryOp::And, phase, bad, bit).unwrap(); + let count = m.read(count).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 32).unwrap()); + let nonzero = m.binary(BinaryOp::NotEqual, count, zero, bit).unwrap(); + let active = if after_first_rise { + m.binary(BinaryOp::And, active, nonzero, bit).unwrap() + } else { + active + }; + let previous = m.read(v).unwrap(); + let toggled = m.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 1).unwrap()); + let next = m.mux(active, toggled, zero).unwrap(); + let target = m.whole(v).unwrap(); + m.assign(target, next).unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + (m, other) } -} -#[cfg(all(test, feature = "systemverilog"))] -mod rtl_finish_backend_tests { - use super::*; - #[test] - fn host_finish_stops_at_current_time_without_waiters() { + fn check(mut sim: Simulation, on_rising: bool) { + sim.set_wide(sim.signal("bad"), 1u8.into()); + let time = if on_rising { 0 } else { 2 }; + assert!(sim.run_until(time).is_err()); + assert_eq!(sim.time(), time); + assert_eq!(sim.ticks(), 1); + let count = sim.signal("count"); + let falls = sim.signal("falls"); + assert_eq!(sim.simulator.backend.get_as::(count), 1); + assert_eq!(sim.simulator.backend.get_as::(falls), 0); + assert_eq!(sim.next_event_time(), Some(2)); + sim.set_wide(sim.signal("bad"), 0u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(falls), 1u32.into()); + assert_eq!(sim.get(count), 1u32.into()); + assert_eq!(sim.ticks(), 1); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(count), 2u32.into()); + assert_eq!(sim.ticks(), 2); + } + + #[test] + fn generated_clock_failures_retain_committed_and_pending_phases() { + for on_rising in [true, false] { + let builder = || { + Simulation::from_frontend(design(on_rising)).true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check(builder().build_interpreter().unwrap(), on_rising); + check(builder().build_cranelift().unwrap(), on_rising); + check(builder().build_wasm().unwrap(), on_rising); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap(), on_rising); + } + } + + #[test] + fn escaped_memory_preserves_unpublished_generated_phase_retries() { + fn check(mut sim: Simulation, on_rising: bool) { + let clock = sim.signal("clk"); + let (pointer, length) = sim.memory_as_mut_ptr(); + assert!(clock.offset < length); + if !on_rising { + sim.run_until(0).unwrap(); + } + sim.set_wide(sim.signal("bad"), 1u8.into()); + let time = if on_rising { 0 } else { 2 }; + let error = sim.run_until(time).unwrap_err().to_string(); + assert!(!error.contains("direct host write"), "{error}"); + assert_eq!(sim.ticks(), u64::from(!on_rising)); + // Merely obtaining the pointer does not invalidate a retained + // scheduler drive, even before that drive is published. + let checkpoint = sim.checkpoint().unwrap(); + for step in [true, false] { + sim.restore(&checkpoint).unwrap(); + let parts = sim.state.export_schedule(&sim.simulator.backend); + sim.state.import_schedule(parts); + let error = sim.run_until(time).unwrap_err().to_string(); + assert!(!error.contains("direct host write"), "{error}"); + sim.set_wide(sim.signal("bad"), 0u8.into()); + if step { + assert_eq!(sim.step_until(time).unwrap(), Some(time)); + } else { + sim.run_until(time).unwrap(); + } + sim.run_until(2).unwrap(); + assert_eq!( + sim.get(sim.signal("count")), + 1u32.into(), + "rising={on_rising}, step={step}" + ); + assert_eq!(sim.get(sim.signal("falls")), 1u32.into()); + assert_eq!(sim.ticks(), 1); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 2u32.into()); + assert_eq!(sim.ticks(), 2); + } + sim.restore(&checkpoint).unwrap(); + // A real pointer write back to the OLD sampling baseline must + // still be rejected while the generated drive is pending. + unsafe { + pointer.add(clock.offset).write(u8::from(!on_rising)); + } + assert!(matches!( + sim.checkpoint(), + Err(CheckpointError::UntrackedHostClockWrite) + )); + let error = sim.step_until(time).unwrap_err().to_string(); + assert!(error.contains("direct host write"), "{error}"); + sim.restore(&checkpoint).unwrap(); + sim.set_wide(sim.signal("bad"), 0u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.ticks(), 2); + } + for on_rising in [true, false] { + let build = || { + Simulator::from_frontend(module_design_with_failure(on_rising, false).0.finish()) + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check( + Simulation::new(build().build_interpreter().unwrap()), + on_rising, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + on_rising, + ); + check(Simulation::new(build().build_wasm().unwrap()), on_rising); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), on_rising); + } + } + + #[test] + fn custom_executors_keep_per_edge_hooks_without_fusion_opt_in() { + struct Host { + sim: Simulator, + staged: Vec, + fired: Vec, + } + impl SimulationExecutor for Host { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn stage_external_event( + &mut self, + _event: B::Event, + time: u64, + ) -> Result<(), RuntimeErrorCode> { + self.staged.push(time); + Ok(()) + } + fn fire_external_event( + &mut self, + _event: B::Event, + time: u64, + ) -> Result<(), RuntimeErrorCode> { + self.fired.push(time); + Ok(()) + } + // Intentionally rely on the default capability and tick_many. + } + fn check(sim: Simulator) { + let mut state = simulation_state(&sim); + let mut host = Host { + sim, + staged: Vec::new(), + fired: Vec::new(), + }; + while state.next_event_time().is_some_and(|time| time <= 4) { + state.step_until(&mut host, 4).unwrap(); + } + assert_eq!(state.ticks(), 3); + assert_eq!(host.staged, vec![0, 2, 4]); + assert_eq!(host.fired, vec![0, 2, 4]); + assert_eq!(host.sim.backend.get_as::(host.sim.signal("q")), 3); + } + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", ValueType::bits(1).unwrap()).unwrap(); + let word = ValueType::bits(8).unwrap(); + let q = m.output("q", word).unwrap(); + let current = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, current, one, word).unwrap(); + m.register(m.whole(q).unwrap(), next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let count = m.constant(Constant::two_state(3u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + let design = m.finish(); + let build = || Simulator::from_frontend(design.clone()); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } + + struct FailingExecutor { + sim: Simulator, + fail: Option, + in_apply: bool, + } + impl SimulationExecutor for FailingExecutor { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + if !self.in_apply && self.fail == Some(event.id()) { + return Err(RuntimeErrorCode::Runtime { + message: "injected FF failure".into(), + signals: Vec::new(), + }); + } + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + if self.in_apply && self.fail == Some(event.id()) { + return Err(RuntimeErrorCode::Runtime { + message: "injected publication failure".into(), + signals: Vec::new(), + }); + } + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn fused_ticks_allowed(&self) -> bool { + false + } + } + + fn coincident_design() -> crate::frontend_sdk::FrontendArtifact { + let (mut m, other) = module_design(false); + let word = ValueType::bits(32).unwrap(); + let count = m.output("other_count", word).unwrap(); + let current = m.read(count).unwrap(); + let one = m.constant(Constant::two_state(1u8, 32).unwrap()); + let next = m.binary(BinaryOp::Add, current, one, word).unwrap(); + let target = m.whole(count).unwrap(); + m.register(target, next, other, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(other, 2).unwrap(); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: other, + count: two, + }]) + .unwrap(); + m.finish() + } + + fn check_coincident_failure(sim: Simulator, in_apply: bool) { + let mut state = simulation_state(&sim); + let mut executor = FailingExecutor { + sim, + fail: None, + in_apply, + }; + assert_eq!(state.step_until(&mut executor, 0).unwrap(), Some(0)); + let initial_ticks = state.ticks(); + assert_eq!(state.step_until(&mut executor, 1).unwrap(), Some(1)); + let failed = executor + .sim + .event(if in_apply { "fallclk" } else { "other" }); + executor.fail = Some(failed.id()); + assert!(state.step_until(&mut executor, 2).is_err()); + assert_eq!(state.ticks(), initial_ticks + u64::from(in_apply)); + let falls = executor.sim.signal("falls"); + assert_eq!(executor.backend().get_as::(falls), 0); + assert_eq!(state.next_event_time(), Some(2)); + assert!( + state + .escaped_host_clock_writes(executor.backend()) + .is_empty() + ); + executor.fail = None; + assert_eq!(state.step_until(&mut executor, 2).unwrap(), Some(2)); + assert_eq!(executor.backend().get_as::(falls), 1); + assert_eq!(state.ticks(), initial_ticks + 1); + assert_eq!( + executor + .backend() + .get_as::(executor.sim.signal("other_count")), + 2 + ); + } + + #[test] + fn coincident_ff_failures_do_not_discard_unpublished_falling_domains() { + for in_apply in [false, true] { + let builder = || { + Simulator::from_frontend(coincident_design()) + .emit_triggers() + .true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check_coincident_failure(builder().build_interpreter().unwrap(), in_apply); + check_coincident_failure(builder().build_cranelift().unwrap(), in_apply); + check_coincident_failure(builder().build_wasm().unwrap(), in_apply); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_coincident_failure(builder().build_native().unwrap(), in_apply); + } + } +} + +#[cfg(test)] +mod clock_provenance_checkpoint_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", ValueType::bits(1).unwrap()).unwrap(); + let q = m.output("q", ValueType::bits(1).unwrap()).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let value = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(q).unwrap(); + m.register(target, value, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + m.process(vec![ + Statement::Delay { amount: one }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + m.finish() + } + #[test] + fn failed_clock_activations_remain_errors_on_retry() { + fn check(mut sim: Simulation, scheduled: bool) { + if scheduled { + sim.schedule("clk", 0, 1).unwrap(); + } else { + sim.add_clock("clk", 4, 0); + } + assert_eq!(sim.step().unwrap(), Some(0)); + let expected = if scheduled { + "already driven by schedule" + } else { + "already driven by add_clock" + }; + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + let time = sim.time(); + for _ in 0..2 { + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + let error = sim.run_until(20).unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + assert_eq!(sim.time(), time); + assert_eq!(sim.ticks(), 0); + } + let saved = sim.checkpoint().unwrap(); + sim.restore(&saved).unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains(expected), "{error}"); + } + for scheduled in [false, true] { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + scheduled, + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + scheduled, + ); + check( + Simulation::from_frontend(design()).build_wasm().unwrap(), + scheduled, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::from_frontend(design()).build_native().unwrap(), + scheduled, + ); + } + } + #[test] + fn earlier_scheduled_drives_conflict_with_delayed_clock_activation() { + fn check(mut sim: Simulation) { + sim.schedule("clk", 0, 1).unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + } + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } + fn check(mut sim: Simulation) { + sim.schedule("clk", 0, 1).unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + let checkpoint = sim.checkpoint().unwrap(); + let error = sim.run_until(2).unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + sim.restore(&checkpoint).unwrap(); + // Model a host waking the suspended process at the restored timestamp. + let mut parts = sim.state.export_schedule(&sim.simulator.backend); + parts.process_wakeups = vec![(0, 0)]; + sim.state.import_schedule(parts); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + } + fn check_transfer(mut from: Simulation, mut to: Simulation) { + from.schedule("clk", 0, 1).unwrap(); + from.step().unwrap(); + let design = from.simulator.checkpoint().unwrap(); + let mut parts = from.state.export_schedule(&from.simulator.backend); + parts.process_wakeups = vec![(0, 0)]; + to.simulator.restore(&design).unwrap(); + to.state.import_schedule(parts); + let error = to.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(to.ticks(), 0); + } + #[test] + fn exported_schedule_retains_consumed_clock_drives() { + let build = || { + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap() + }; + check_transfer(build(), build()); + let build = || { + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap() + }; + check_transfer(build(), build()); + let build = || Simulation::from_frontend(design()).build_wasm().unwrap(); + check_transfer(build(), build()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + let build = || Simulation::from_frontend(design()).build_native().unwrap(); + check_transfer(build(), build()); + } + } + #[test] + fn restored_clock_drive_provenance_rejects_a_same_time_generator() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} +#[cfg(all(test, feature = "systemverilog"))] +mod active_ff_metadata_tests { + #[test] + fn pending_control_flags_do_not_request_active_settling() { + for (body, expected) in [("q<=d;", false), ("q=d;", true), ("q<=d; q=d;", true)] { + let code = format!( + "module Top(input bit clk,d,output bit q); always @(posedge clk) begin {body} end initial #1; endmodule" + ); + let sim = crate::Simulator::from_sv_sources( + vec![(&code, std::path::Path::new("active_ff.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + assert_eq!( + !sim.program.runtime_schema.active_ff_events.is_empty(), + expected, + "{body}" + ); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod rtl_finish_backend_tests { + use super::*; + #[test] + fn host_finish_stops_at_current_time_without_waiters() { fn check(mut sim: Simulation, future: bool) { if future { sim.schedule("clk", 10, 1).unwrap(); @@ -1660,6 +2767,135 @@ mod rtl_finish_backend_tests { } } +#[cfg(test)] +mod finish_clock_batch_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + #[test] + fn coincident_finish_suppresses_an_overflowing_next_edge() { + fn check(mut sim: Simulation) { + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let bit = ValueType::bits(1).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let dst = m.whole(q).unwrap(); + m.register(dst, one, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let start = m.constant(Constant::two_state(u64::MAX - 3, 64).unwrap()); + let end = m.constant(Constant::two_state(u64::MAX - 1, 64).unwrap()); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + m.process(vec![ + Statement::Delay { amount: start }, + Statement::ClockCycles { + clock: clk, + count: two, + }, + ]) + .unwrap(); + m.process(vec![Statement::Delay { amount: end }, Statement::Finish]) + .unwrap(); + let design = m.finish(); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_interpreter() + .unwrap(), + )); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_cranelift() + .unwrap(), + )); + check(Simulation::new( + Simulator::from_frontend(design.clone()) + .build_wasm() + .unwrap(), + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new( + Simulator::from_frontend(design).build_native().unwrap(), + )); + } + + #[test] + fn finish_suppresses_coincident_generated_edges() { + fn check(mut sim: Simulation, scheduled: bool) { + if scheduled { + sim.schedule("other", 4, 1).unwrap(); + } + sim.run_until(4).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(sim.ticks(), 2); + } + for scheduled in [false, true] { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let other = m.internal("other", bit).unwrap(); + let q = m.output("count", word).unwrap(); + let r = m.output("other_q", bit).unwrap(); + let v = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, v, one, word).unwrap(); + let dst = m.whole(q).unwrap(); + m.register(dst, next, clk, Edge::Posedge, None, None) + .unwrap(); + let dst = m.whole(r).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + m.register(dst, one, other, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 2).unwrap(); + let ten = m.constant(Constant::two_state(10u8, 64).unwrap()); + let four = m.constant(Constant::two_state(4u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: ten, + }]) + .unwrap(); + m.process(vec![Statement::Delay { amount: four }, Statement::Finish]) + .unwrap(); + let design = m.finish(); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_interpreter() + .unwrap(), + ), + scheduled, + ); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_cranelift() + .unwrap(), + ), + scheduled, + ); + check( + Simulation::new( + Simulator::from_frontend(design.clone()) + .build_wasm() + .unwrap(), + ), + scheduled, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(Simulator::from_frontend(design).build_native().unwrap()), + scheduled, + ); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod finish_and_cotrigger_tests { use super::*; @@ -1825,6 +3061,74 @@ mod direct_finish_tests { } } +#[cfg(test)] +mod pending_generated_clock_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let a = m.internal("a", bit).unwrap(); + let b = m.internal("b", bit).unwrap(); + let qa = m.output("qa", bit).unwrap(); + let qb = m.output("qb", bit).unwrap(); + let old = m.read(qb).unwrap(); + let next = m.unary(UnaryOp::BitNot, old, bit).unwrap(); + let qa_target = m.whole(qa).unwrap(); + let qb_target = m.whole(qb).unwrap(); + m.register(qa_target, old, a, Edge::Posedge, None, None) + .unwrap(); + m.register(qb_target, next, b, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(a, 4).unwrap(); + m.clock_period(b, 4).unwrap(); + let two = m.constant(Constant::two_state(2u8, 64).unwrap()); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let four = m.constant(Constant::two_state(4u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: b, + count: two, + }]) + .unwrap(); + m.process(vec![ + Statement::Delay { amount: four }, + Statement::ClockCycles { + clock: a, + count: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("qb")), 1u8.into()); + // A failed round can leave this generated drive high without publishing its FF batch. + sim.simulator.backend.set(sim.signal("b"), 1u8); + sim.step().unwrap(); + assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); + assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); + // B rose once at time zero; both A and B rise at time four. + assert_eq!(sim.ticks(), 3); + } + #[test] + fn pending_rises_share_pre_edge_state_with_new_clocks() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod current_time_settle_tests { use super::*; @@ -1931,36 +3235,332 @@ mod scheduled_pulse_tests { assert_eq!(sim.get(sim.signal("level_woke")), 0u8.into()); } #[test] - fn scheduled_pulses_wake_waiters_after_the_batch() { - let source = "module Top(output bit any_woke,neg_woke,pos_woke,ffneg,sampled,level_woke);bit clk=1;initial begin wait(clk==0);level_woke=1;end always @(negedge clk)ffneg<=1;initial begin @(clk);any_woke=1;sampled=clk;end initial begin @(negedge clk);neg_woke=1;end initial begin @(posedge clk);pos_woke=1;end endmodule"; - let compound = source - .replace("@(clk)", "@({clk,1'b0})") - .replace("@(negedge clk);", "@(negedge (clk | 1'b0));") - .replace("@(posedge clk);", "@(posedge (clk | 1'b0));"); - for source in [source, compound.as_str()] { - let build = || { - Simulator::from_sv_sources( - vec![(source, std::path::Path::new("scheduled-pulse.sv"))], - "Top", - ) - }; - check(Simulation::new(build().build_interpreter().unwrap())); - check(Simulation::new(build().build_cranelift().unwrap())); - check(Simulation::new(build().build_wasm().unwrap())); + fn scheduled_pulses_wake_waiters_after_the_batch() { + let source = "module Top(output bit any_woke,neg_woke,pos_woke,ffneg,sampled,level_woke);bit clk=1;initial begin wait(clk==0);level_woke=1;end always @(negedge clk)ffneg<=1;initial begin @(clk);any_woke=1;sampled=clk;end initial begin @(negedge clk);neg_woke=1;end initial begin @(posedge clk);pos_woke=1;end endmodule"; + let compound = source + .replace("@(clk)", "@({clk,1'b0})") + .replace("@(negedge clk);", "@(negedge (clk | 1'b0));") + .replace("@(posedge clk);", "@(posedge (clk | 1'b0));"); + for source in [source, compound.as_str()] { + let build = || { + Simulator::from_sv_sources( + vec![(source, std::path::Path::new("scheduled-pulse.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + check(Simulation::new(build().build_native().unwrap())); + let image = build().compile_native().unwrap().into_program_image(); + let image = crate::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + check(Simulation::new( + Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + )); + } + } + } +} + +#[cfg(test)] +mod host_clock_review_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut module = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let q = module.output("q", word).unwrap(); + module + .set_initial(q, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + let value = module.read(q).unwrap(); + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let next = module.binary(BinaryOp::Add, value, one, word).unwrap(); + let target = module.whole(q).unwrap(); + module + .register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, 2).unwrap(); + let ten = module.constant(Constant::two_state(10u8, 64).unwrap()); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: ten, + }]) + .unwrap(); + module.finish() + } + fn settle(mut sim: Simulation) { + sim.settle().unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), Some(1)); + } + fn host(mut sim: Simulation, mode: u8) { + let clk = sim.signal("clk"); + let before = sim.checkpoint().unwrap(); + match mode { + 0 => sim.set_wide(clk, 1u8.into()), + 1 => sim.set_four_state(clk, 1u8.into(), 0u8.into()), + 2 => sim + .modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(), + _ => { + sim.set_wide(clk, 1u8.into()); + sim.get(sim.signal("q")); + } + } + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("direct host write"), "{error}"); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.ticks(), 0); + assert!( + sim.run_until(0) + .unwrap_err() + .to_string() + .contains("direct host write") + ); + sim.restore(&before).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn settling_a_process_clock_keeps_current_time() { + let build = || Simulator::from_frontend(design()); + settle(Simulation::new(build().build_interpreter().unwrap())); + settle(Simulation::new(build().build_cranelift().unwrap())); + settle(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + settle(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn checkpoint_rejects_escaped_generated_clock_writes() { + fn check(mut sim: Simulation) { + let clk = sim.signal("clk"); + let (ptr, len) = sim.memory_as_mut_ptr(); + assert!(clk.offset < len); + sim.run_until(1).unwrap(); + sim.checkpoint().unwrap(); + unsafe { + ptr.add(clk.offset).write(1); + } + assert!(sim.checkpoint().is_err()); + unsafe { + ptr.add(clk.offset).write(0); + } + let checkpoint = sim.checkpoint().unwrap(); + sim.restore(&checkpoint).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.ticks(), 2); + } + let build = || Simulator::from_frontend(design()); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn retained_memory_cannot_inject_generated_clock_edges() { + fn check(mut sim: Simulation, explicit: bool) { + let clk = sim.signal("clk"); + let (ptr, len) = sim.memory_as_mut_ptr(); + assert!(clk.offset < len); + sim.run_until(1).unwrap(); + assert_eq!(sim.ticks(), 1); + unsafe { + ptr.add(clk.offset).write(1); + } + let result = if explicit { + sim.eval_comb() + } else { + sim.run_until(2) + }; + assert!( + result + .unwrap_err() + .to_string() + .contains("direct host write") + ); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.time(), 1); + assert_eq!(sim.simulator.backend.get(sim.signal("q")), 1u8.into()); + } + for explicit in [false, true] { + let build = || Simulator::from_frontend(design()); + check( + Simulation::new(build().build_interpreter().unwrap()), + explicit, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + explicit, + ); + check(Simulation::new(build().build_wasm().unwrap()), explicit); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap()), explicit); + } + } + #[test] + fn direct_host_clock_writes_are_rejected_before_activation() { + let build = || Simulator::from_frontend(design()); + for mode in 0..4 { + host(Simulation::new(build().build_interpreter().unwrap()), mode); + host(Simulation::new(build().build_cranelift().unwrap()), mode); + host(Simulation::new(build().build_wasm().unwrap()), mode); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + host(Simulation::new(build().build_native().unwrap()), mode); + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod failed_ff_progress_tests { + use super::*; + fn check(mut sim: Simulator) { + let event = sim.event("clk"); + let (completed, result) = SimulationExecutor::tick_many(&mut sim, event, 10); + assert_eq!(completed, 0, "{}", std::any::type_name::()); + assert!(result.is_err()); + assert_eq!( + sim.get(sim.signal("q")), + 0u8.into(), + "{}", + std::any::type_name::() + ); + } + #[test] + fn failed_ff_evaluation_does_not_complete_a_tick() { + let source = "module Top(input bit clk,ok,output bit q);always_ff @(posedge clk)begin assert(ok)else $fatal(1,\"failed FF\");q<=1;end endmodule"; + let build = || { + Simulator::from_sv_sources(vec![(source, std::path::Path::new("failed-ff.sv"))], "Top") + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + check(build().build_tiered().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + check(build().build_native().unwrap()); + check( + build() + .threads(4) + .parallel_partition(crate::ParallelPartition::Always) + .build_native() + .unwrap(), + ); + } + } +} + +#[cfg(test)] +mod generated_phase_review_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design(unknown: Option, edge: Edge) -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("ClockPhases").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let clk = m.internal("clk", ValueType::logic(1).unwrap()).unwrap(); + m.set_initial( + clk, + match unknown { + Some(value) => Constant::four_state(value, 1u8, 1).unwrap(), + None => Constant::two_state(0u8, 1).unwrap(), + }, + ) + .unwrap(); + let q = m.output("q", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(q).unwrap(); + m.register(target, one, clk, edge, None, None).unwrap(); + m.clock_period(clk, 4).unwrap(); + let three = m.constant(Constant::two_state(3u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + m.finish() + } + fn fall(mut sim: Simulation) { + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.state.settle_at(&mut sim.simulator, 2).unwrap(), Some(2)); + assert_eq!(sim.time(), 2); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.next_event_time(), Some(4)); + } + fn unknown(mut sim: Simulation, payload: u8, edge: Edge) { + assert_eq!( + sim.get_four_state(sim.signal("clk")), + (payload.into(), 1u8.into()) + ); + sim.run_until(0).unwrap(); + assert_eq!( + sim.get(sim.signal("q")), + u8::from(edge == Edge::Posedge).into() + ); + assert_eq!( + sim.get_four_state(sim.signal("clk")), + (1u8.into(), 0u8.into()) + ); + assert_eq!(sim.ticks(), 1); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + #[test] + fn settle_at_drains_a_generated_fall_at_the_target() { + let build = || Simulator::from_frontend(design(None, Edge::Negedge)); + fall(Simulation::new(build().build_interpreter().unwrap())); + fall(Simulation::new(build().build_cranelift().unwrap())); + fall(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + fall(Simulation::new(build().build_native().unwrap())); + } + #[test] + fn unknown_initial_clock_payloads_have_the_same_edge_sequence() { + for (payload, edge) in [ + (0, Edge::Posedge), + (1, Edge::Posedge), + (0, Edge::Negedge), + (1, Edge::Negedge), + ] { + let build = || Simulator::from_frontend(design(Some(payload), edge)).four_state(true); + unknown( + Simulation::new(build().build_interpreter().unwrap()), + payload, + edge, + ); + unknown( + Simulation::new(build().build_cranelift().unwrap()), + payload, + edge, + ); + unknown( + Simulation::new(build().build_wasm().unwrap()), + payload, + edge, + ); #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] - { - check(Simulation::new(build().build_native().unwrap())); - let image = build().compile_native().unwrap().into_program_image(); - let image = crate::NativeProgramImage::from_container_bytes( - &image.to_container_bytes().unwrap(), - ) - .unwrap(); - check(Simulation::new( - Simulator::from_sources(Vec::new(), "Top") - .build_native_from_image(image) - .unwrap(), - )); - } + unknown( + Simulation::new(build().build_native().unwrap()), + payload, + edge, + ); } } } @@ -2116,6 +3716,80 @@ mod staged_edge_review_tests { } } +#[cfg(test)] +mod normalizing_fall_review_tests { + use super::*; + use crate::frontend_sdk::{ + BinaryOp, Constant, Edge, ModuleBuilder, Statement, UnaryOp, ValueType, + }; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.internal("clk", bit).unwrap(); + m.set_initial(clk, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let enable = m.input("enable", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let v = m.output("v", bit).unwrap(); + m.set_initial(q, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let clock_value = m.read(clk).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 1).unwrap()); + m.register( + m.whole(q).unwrap(), + clock_value, + clk, + Edge::Negedge, + None, + None, + ) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + + let low = m.unary(UnaryOp::BitNot, clock_value, bit).unwrap(); + let enabled = m.read(enable).unwrap(); + let active = m.binary(BinaryOp::And, low, enabled, bit).unwrap(); + let previous = m.read(v).unwrap(); + let toggled = m.unary(UnaryOp::BitNot, previous, bit).unwrap(); + let next = m.mux(active, toggled, zero).unwrap(); + m.assign(m.whole(v).unwrap(), next).unwrap(); + let count = m.constant(Constant::two_state(1u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.memory_as_mut_ptr(); + assert_eq!(sim.get(sim.signal("clk")), 1u8.into()); + sim.set_wide(sim.signal("enable"), 1u8.into()); + assert!(sim.run_until(0).is_err()); + assert_eq!(sim.ticks(), 0); + sim.checkpoint().unwrap(); + let parts = sim.state.export_schedule(&sim.simulator.backend); + assert_eq!(parts.process_clocks[0].falling_edge, Some(0)); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.set_wide(sim.signal("enable"), 0u8.into()); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn failed_initial_falls_publish_before_the_first_rise_on_retry() { + let build = || { + Simulator::from_frontend(design()).true_loop( + (Vec::new(), vec!["v".into()]), + (Vec::new(), vec!["v".into()]), + 8, + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod finished_host_write_review_tests { use super::*; @@ -2549,6 +4223,118 @@ mod queued_derived_ff_review_tests { } } +#[cfg(test)] +mod coincident_host_edge_limit_review_tests { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + design_with_initial_host(false) + } + fn design_with_initial_host(high: bool) -> crate::frontend_sdk::FrontendArtifact { + let bit = ValueType::bits(1).unwrap(); + let byte = ValueType::bits(8).unwrap(); + let mut m = ModuleBuilder::new("Top").unwrap(); + let host = m.input("host", bit).unwrap(); + if high { + m.set_initial(host, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + } + let clk = m.internal("clk", bit).unwrap(); + let seen = m.output("seen", bit).unwrap(); + let q = m.output("q", byte).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(seen).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let value = m.read(q).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, value, one, byte).unwrap(); + let target = m.whole(q).unwrap(); + m.register(target, next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(8u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { clock: clk, count }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation, method: &str, limit: u64) { + sim.set_wide(sim.signal("host"), 1u8.into()); + if method == "step_until" { + let reached = sim.step_until(limit).unwrap().unwrap(); + assert_eq!(reached, sim.time()); + assert!(reached <= limit); + } else { + sim.run_until(limit).unwrap(); + } + if method == "run_until" { + assert_eq!(sim.time(), limit); + } + let ticks = 1 + sim.time() / 4; + assert_eq!(sim.ticks(), ticks); + assert_eq!(sim.get(sim.signal("q")), (ticks as u8).into()); + assert_eq!(sim.get(sim.signal("seen")), 1u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.time(), 4); + assert_eq!(sim.ticks(), 2); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + sim.run_until(28).unwrap(); + assert_eq!(sim.ticks(), 8); + assert_eq!(sim.get(sim.signal("q")), 8u8.into()); + } + #[test] + fn coincident_host_edges_report_the_time_reached_by_step() { + fn check(mut sim: Simulation) { + sim.set_wide(sim.signal("host"), 0u8.into()); + let reached = sim.step().unwrap().unwrap(); + assert_eq!(reached, sim.time()); + assert_eq!(sim.get(sim.signal("q")), (sim.ticks() as u8).into()); + sim.run_until(28).unwrap(); + assert_eq!(sim.ticks(), 8); + assert_eq!(sim.get(sim.signal("q")), 8u8.into()); + } + let build = || Simulator::from_frontend(design_with_initial_host(true)); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + + #[test] + fn coincident_host_edges_do_not_fuse_past_public_time_limits() { + for (method, limit) in [ + ("step_until", 0), + ("step_until", 4), + ("run_until", 0), + ("run_until", 4), + ] { + let build = || Simulator::from_frontend(design()); + check( + Simulation::new(build().build_interpreter().unwrap()), + method, + limit, + ); + check( + Simulation::new(build().build_cranelift().unwrap()), + method, + limit, + ); + check( + Simulation::new(build().build_wasm().unwrap()), + method, + limit, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulation::new(build().build_native().unwrap()), + method, + limit, + ); + } + } +} + #[cfg(all(test, feature = "systemverilog"))] mod host_finish_edge_review_tests { use super::*; @@ -3563,6 +5349,60 @@ mod nba_waiter_sampling_review { } } +#[cfg(test)] +mod host_clock_activation_review { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let host = m.input("host", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let source = m.output("source", bit).unwrap(); + let sampled = m.output("sampled", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(source).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let old = m.read(source).unwrap(); + let target = m.whole(sampled).unwrap(); + m.register(target, old, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + let host = sim.signal("host"); + sim.modify(|io| io.set(host, 1u8)).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("source")), 1u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn captured_host_edges_share_pre_edge_state_with_first_clock_wait() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod mixed_other_domain_host_review { use super::*; @@ -3770,6 +5610,86 @@ mod cross_depth_write_review { } } +#[cfg(test)] +mod transient_clock_activation_review { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let host = m.internal("host", bit).unwrap(); + let word = ValueType::bits(32).unwrap(); + let rises = m.internal("rises", word).unwrap(); + let falls = m.internal("falls", word).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let source = m.output("source", bit).unwrap(); + let sampled = m.output("sampled", bit).unwrap(); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let target = m.whole(source).unwrap(); + m.register(target, one, host, Edge::Posedge, None, None) + .unwrap(); + let old = m.read(source).unwrap(); + let target = m.whole(sampled).unwrap(); + m.register(target, old, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let one = m.constant(Constant::two_state(1u8, 64).unwrap()); + let high = m.constant(Constant::two_state(1u8, 1).unwrap()); + let low = m.constant(Constant::two_state(0u8, 1).unwrap()); + let target = m.whole(host).unwrap(); + let edge = m.constant(Constant::two_state(1u8, 32).unwrap()); + m.process(vec![ + Statement::Assign { + target, + value: high, + }, + Statement::Assign { target, value: low }, + Statement::Assign { + target: m.whole(rises).unwrap(), + value: edge, + }, + Statement::Assign { + target: m.whole(falls).unwrap(), + value: edge, + }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + let signal = sim.signal("host"); + let rises = sim.signal("rises"); + let falls = sim.signal("falls"); + sim.state = sim + .state + .with_process_event_counters(vec![(signal, rises, falls)]); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("source")), 1u8.into()); + assert_eq!(sim.get(sim.signal("sampled")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + #[test] + fn transient_process_edges_share_pre_edge_state_with_first_clock_wait() { + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod wait_and_finish_review { use super::*; @@ -4966,6 +6886,357 @@ mod round57_sdk_tests { } } +#[cfg(test)] +mod clean_waiter_settle_review { + use super::*; + use crate::frontend_sdk::{BinaryOp, Constant, Edge, ModuleBuilder, Statement, ValueType}; + use celox_frontend_core::process::ProcessKernelBuilder; + use celox_sir::{SIRInstruction, SIROffset, SIRValue}; + + fn program() -> crate::ir::LaidOutProgram { + program_with_sampling_waiter(false) + } + fn program_with_sampling_waiter(extra: bool) -> crate::ir::LaidOutProgram { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(8).unwrap(); + let go = m.input("go", bit).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", word).unwrap(); + let done = m.output("done", bit).unwrap(); + let old = m.read(q).unwrap(); + let input = m.read(go).unwrap(); + let next = m.binary(BinaryOp::Add, old, input, word).unwrap(); + m.register(m.whole(q).unwrap(), next, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(4u8, 64).unwrap()); + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + m.process(vec![ + Statement::ClockCycles { clock: clk, count }, + Statement::Assign { + target: m.whole(done).unwrap(), + value: one, + }, + ]) + .unwrap(); + let noise = if extra { + let noise = m.input("noise", bit).unwrap(); + let echo = m.output("noise_seen", bit).unwrap(); + let value = m.read(noise).unwrap(); + m.assign(m.whole(echo).unwrap(), value).unwrap(); + let falls = m.output("falls", word).unwrap(); + let old = m.read(falls).unwrap(); + let one = m.constant(Constant::two_state(1u8, 8).unwrap()); + let next = m.binary(BinaryOp::Add, old, one, word).unwrap(); + let fallclk = m.internal("fallclk", bit).unwrap(); + let clk_value = m.read(clk).unwrap(); + let go_value = m.read(go).unwrap(); + let low = m + .unary(crate::frontend_sdk::UnaryOp::BitNot, clk_value, bit) + .unwrap(); + let active_low = m.binary(BinaryOp::And, low, go_value, bit).unwrap(); + m.assign(m.whole(fallclk).unwrap(), active_low).unwrap(); + m.register( + m.whole(falls).unwrap(), + next, + fallclk, + Edge::Posedge, + None, + None, + ) + .unwrap(); + m.process(vec![Statement::Finish]).unwrap(); + Some(noise) + } else { + None + }; + let (mut program, _) = crate::compile_frontend_to_sir( + &m.finish(), + &[], + &[], + false, + &Default::default(), + None, + &Default::default(), + ) + .unwrap(); + let address = |id| { + *program + .design + .state_objects + .keys() + .find(|a| { + program + .design + .variable(a) + .is_some_and(|v| v.source_id == crate::ir::SourceVarId(id)) + }) + .unwrap() + }; + let go = address(noise.unwrap_or(go).index()); + let done = address(done.index()); + let mut addresses = Vec::new(); + let mut intern = |address| { + let index = match addresses.iter().position(|a| *a == address) { + Some(index) => index, + None => { + addresses.push(address); + addresses.len() - 1 + } + }; + crate::ir::SourceVarId(index as u32) + }; + let index = usize::from(extra); + let slots = program.runtime_schema.processes[index] + .clone() + .map(&mut intern); + let go = intern(go); + let done = intern(done); + let stable = |var_id| celox_design::RegionedVarAddrBase { + region: celox_design::STABLE_REGION, + var_id, + }; + // The SDK has clock waits but no level-wait statement. Build the + // combined kernel through the shared frontend process contract. + let mut kernel = ProcessKernelBuilder::new(slots); + kernel.begin_wait().unwrap(); + let condition = kernel.builder().alloc_bit(1, false); + kernel.builder().emit(SIRInstruction::Load( + condition, + stable(go), + SIROffset::Static(0), + 1, + )); + kernel.wake_if(condition); + if !extra { + let count = kernel.builder().alloc_bit(64, false); + kernel + .builder() + .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); + kernel.wait_clock(0, count).unwrap(); + let one = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + kernel.builder().emit(SIRInstruction::Store( + stable(done), + SIROffset::Static(0), + 1, + one, + Vec::new(), + Vec::new(), + )); + } + kernel.finish(); + program.sir.processes[index] = kernel.build().into_map_addr(&mut |addr| { + let address = addresses[addr.var_id.0 as usize]; + crate::ir::RegionedAbsoluteAddr { + region: addr.region, + instance_id: address.instance_id, + var_id: address.var_id, + } + }); + program.into_laid_out(false) + } + struct SamplingFailure { + sim: Simulator, + fail: bool, + low_samples: usize, + } + impl SimulationExecutor for SamplingFailure { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(&mut self.sim) + } + fn eval_apply_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(&mut self.sim, e) + } + fn eval_only_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, e) + } + fn apply_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, e) + } + fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + let slots = &self.sim.program.runtime_schema.processes[index]; + let mode = self + .sim + .backend + .get_as::(self.sim.backend.resolve_signal(&slots.delay)); + let clk = self.sim.backend.get_as::(self.sim.signal("clk")); + if self.fail && index == 1 && mode == 1 && clk == 0 { + self.low_samples += 1; + // Skip sampling during scheduled-value application, then fail + // the post-settle sample before the falling-edge FF is run. + if self.low_samples == 2 { + return Err(RuntimeErrorCode::Runtime { + message: "injected wait sampling failure".into(), + signals: Vec::new(), + }); + } + } + SimulationExecutor::run_process(&mut self.sim, index) + } + } + #[test] + fn round61_failed_wait_sampling_retains_unpublished_generated_fall() { + fn check(mut sim: Simulator) { + sim.apply_initial_values(); + let go = sim.signal("go"); + sim.set_wide(go, 1u8.into()); + let mut state = simulation_state(&sim); + let mut executor = SamplingFailure { + sim, + fail: false, + low_samples: 0, + }; + assert_eq!(state.step_until(&mut executor, 0).unwrap(), Some(0)); + executor.fail = true; + let error = state.step_until(&mut executor, 2).unwrap_err().to_string(); + assert!(error.contains("injected wait sampling failure"), "{error}"); + assert_eq!(executor.low_samples, 2); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("falls")), + 0 + ); + let schedule = state.export_schedule(executor.backend()); + assert_eq!(schedule.process_clocks[0].falling_edge, Some(2)); + assert_eq!(state.next_event_time(), Some(2)); + executor.fail = false; + assert_eq!(state.step_until(&mut executor, 2).unwrap(), Some(2)); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("falls")), + 1 + ); + } + let program = program_with_sampling_waiter(true); + let options = crate::SimulatorOptions { + emit_triggers: true, + ..Default::default() + }; + macro_rules! run { + ($backend:expr) => { + check(Simulator::with_backend_and_program( + $backend.unwrap(), + program.runtime().clone(), + Vec::new(), + )); + }; + } + run!(crate::backend::InterpBackend::new(&program, &options)); + run!(crate::backend::JitBackend::new(&program, &options, None)); + run!(crate::backend::wasm_runtime::WasmBackend::new( + &program, &options + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + run!(crate::backend::native::NativeBackend::new( + &program, &options + )); + } + #[test] + fn round61_zero_count_delta_errors_remain_retryable() { + fn check(mut sim: Simulation) { + for _ in 0..2 { + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.next_event_time(), Some(0)); + let saved = sim.checkpoint().unwrap(); + sim.restore(&saved).unwrap(); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 0); + } + } + let build = || { + let mut m = ModuleBuilder::new("Top").unwrap(); + let clk = m.input("clk", ValueType::bits(1).unwrap()).unwrap(); + let q = m.output("q", ValueType::bits(8).unwrap()).unwrap(); + let value = m.read(q).unwrap(); + m.register(m.whole(q).unwrap(), value, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let zero = m.constant(Constant::two_state(0u8, 64).unwrap()); + m.process(vec![Statement::Forever { + body: vec![Statement::ClockCycles { + clock: clk, + count: zero, + }], + }]) + .unwrap(); + Simulator::from_frontend(m.finish()) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + fn check(mut simulator: Simulator) { + simulator.apply_initial_values(); + let mut sim = Simulation::new(simulator); + sim.run_until(0).unwrap(); + assert_eq!(sim.next_event_time(), None); + let go = sim.signal("go"); + let (pointer, length) = sim.memory_as_mut_ptr(); + assert!(go.offset < length); + unsafe { + pointer.add(go.offset).write(1); + } + assert!(!sim.simulator.dirty); + assert!(sim.simulator.pending_host_writes.is_empty()); + assert!(sim.simulator.backend.get_triggered_bits().is_empty()); + assert!(!sim.state.has_unsettled_edges(&sim.simulator.backend)); + sim.settle().unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("done")), 0u8.into()); + sim.run_until(16).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 4u8.into()); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + } + #[test] + fn clean_raw_level_waiter_settle_keeps_current_time() { + let program = program(); + let options = crate::SimulatorOptions { + emit_triggers: true, + ..Default::default() + }; + macro_rules! run { + ($backend:expr) => { + check(Simulator::with_backend_and_program( + $backend.unwrap(), + program.runtime().clone(), + Vec::new(), + )); + }; + } + run!(crate::backend::InterpBackend::new(&program, &options)); + run!(crate::backend::JitBackend::new(&program, &options, None)); + run!(crate::backend::wasm_runtime::WasmBackend::new( + &program, &options + )); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + run!(crate::backend::native::NativeBackend::new( + &program, &options + )); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod round62_review_tests { use super::*; diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 684131155b8..a0fc53e39e0 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -100,6 +100,9 @@ mod host { pub(crate) program: RuntimeProgram, pub(crate) vcd_writer: Option, pub(crate) dirty: bool, + pub(crate) pending_host_writes: Vec, + host_clock_signals: Vec, + pub(crate) escaped_mutable_memory: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, pub(crate) component_simulation: Option>, @@ -676,11 +679,21 @@ mod host { program: RuntimeProgram, warnings: Vec, ) -> Self { + let host_clock_signals = program + .runtime_schema + .processes + .iter() + .flat_map(|process| &process.clocks) + .map(|clock| backend.resolve_signal(&clock.signal)) + .collect(); let mut sim = Self { + host_clock_signals, backend, program, vcd_writer: None, dirty: false, + pending_host_writes: Vec::new(), + escaped_mutable_memory: false, warnings, components: Default::default(), component_simulation: None, @@ -1165,6 +1178,11 @@ mod host { /// values and truncating bits beyond the signal width. Integer type /// size does not need to match the signal storage size. pub fn set(&mut self, signal: SignalRef, val: T) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set(signal, val); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1172,6 +1190,11 @@ mod host { /// Sets a wide signal value and marks combinational logic as dirty. pub fn set_wide(&mut self, signal: SignalRef, val: BigUint) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set_wide(signal, val); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1179,6 +1202,11 @@ mod host { /// Sets a four-state signal value and marks combinational logic as dirty. pub fn set_four_state(&mut self, signal: SignalRef, val: BigUint, mask: BigUint) { + if self.host_clock_signals.contains(&signal) + && !self.pending_host_writes.contains(&signal) + { + self.pending_host_writes.push(signal); + } self.backend.set_four_state(signal, val, mask); self.dirty = true; self.settle_dirty_for_runtime_event_drain(); @@ -1191,6 +1219,8 @@ mod host { { let mut ctx = IOContext { backend: &mut self.backend, + host_writes: &mut self.pending_host_writes, + host_clock_signals: &self.host_clock_signals, }; f(&mut ctx); self.dirty = true; @@ -1200,6 +1230,10 @@ mod host { Ok(()) } + pub(crate) fn take_host_writes(&mut self) -> Vec { + std::mem::take(&mut self.pending_host_writes) + } + pub(super) fn settle_dirty_for_runtime_event_drain(&mut self) { if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain().unwrap(); @@ -1516,7 +1550,8 @@ mod host { return (0, Ok(())); } if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty { - return (1, self.tick_deferred_comb(event)); + let result = self.tick_deferred_comb(event); + return (u64::from(result.is_ok()), result); } let (completed, result) = self.backend.eval_comb_apply_ff_many_at(event, count); self.dirty = true; @@ -1605,6 +1640,7 @@ mod host { /// Returns a mutable raw pointer to the backend memory and its total size in bytes. pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { + self.escaped_mutable_memory = true; self.backend.memory_as_mut_ptr() } diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 7a470a8c662..e601cd720c8 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -95,6 +95,7 @@ pub struct Checkpoint { comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, runtime_finish_requested: bool, + pending_host_writes: Vec, } impl Checkpoint { @@ -115,6 +116,10 @@ impl std::fmt::Debug for Checkpoint { /// Reasons a checkpoint cannot be taken or restored. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CheckpointError { + #[error( + "cannot checkpoint a process clock changed by a direct host write through escaped memory" + )] + UntrackedHostClockWrite, /// External component instances hold opaque state. They currently exist /// only while a testbench runs, when no checkpoint can be taken. #[error( @@ -146,6 +151,7 @@ impl Simulator { comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, runtime_finish_requested: self.has_pending_runtime_finish(), + pending_host_writes: self.pending_host_writes.clone(), }) } @@ -165,6 +171,8 @@ impl Simulator { .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; self.reset_runtime_finish(checkpoint.runtime_finish_requested); + self.pending_host_writes + .clone_from(&checkpoint.pending_host_writes); if let Some(writer) = &mut self.vcd_writer { writer.rescan(); } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 1e93ab000fa..1e183fc73e1 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -292,6 +292,7 @@ impl Simulator { .as_ref() .is_some_and(|schedule| schedule.finished), ); + self.pending_host_writes.clear(); self.comb_observer_snapshots = self.snapshot_all_comb_observers(); self.comb_observer_initial_eval = false; if let Some(writer) = &mut self.vcd_writer { @@ -507,6 +508,12 @@ impl Simulator { // State files are rejected for designs with processes. process_wakeups: Vec::new(), waiting_processes: Vec::new(), + process_clocks: Vec::new(), + clock_waits: Vec::new(), + done_processes: Vec::new(), + ticks: 0, + scheduled_clock_time: record.time, + scheduled_clock_drives: Vec::new(), inactive_processes: Vec::new(), finished: record.finished, }) diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 64a1bdf2471..d742551fdbb 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1990,7 +1990,7 @@ fn exec_one_detailed( let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; - if completed == 0 || completed > batch { + if (completed == 0 && result.is_ok()) || completed > batch { return ExecResult::Fail( "backend made invalid progress in a deferred tick batch".into(), ); @@ -2058,7 +2058,7 @@ fn exec_one_detailed( let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; - if completed == 0 || completed > batch { + if (completed == 0 && result.is_ok()) || completed > batch { return ExecResult::Fail( "backend made invalid progress in a reset tick batch".into(), ); diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 8cf5452eb97..36e6d5400c4 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -622,3 +622,691 @@ fn zero_delay_pulse_triggers_registers() { assert_eq!(sim.get(clk), 1u8.into()); assert_eq!(sim.next_event_time(), None); } + +/// A counter clocked by `clk`, which only processes drive: the runtime +/// generates its edges while a process waits on it. +fn clocked_by_process_waits( + period: u64, +) -> ( + ModuleBuilder, + celox::frontend_sdk::SignalId, + celox::frontend_sdk::SignalId, +) { + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let mut module = ModuleBuilder::new("ClockWaits").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let count = module.output("count", word).unwrap(); + module + .set_initial(count, Constant::two_state(0u8, 32).unwrap()) + .unwrap(); + let count_expr = module.read(count).unwrap(); + let one = constant(&mut module, 1, 32); + let next = module.binary(BinaryOp::Add, count_expr, one, word).unwrap(); + let count_target = module.whole(count).unwrap(); + module + .register(count_target, next, clk, Edge::Posedge, None, None) + .unwrap(); + module.clock_period(clk, period).unwrap(); + (module, clk, count) +} + +#[test] +fn clock_waits_count_rising_edges_and_resume_before_the_next() { + let (mut module, clk, count) = clocked_by_process_waits(2); + let word = ValueType::bits(32).unwrap(); + let seen = module.output("seen", word).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let count_expr = module.read(count).unwrap(); + let ten = constant(&mut module, 10, 64); + let three = constant(&mut module, 3, 64); + let zero = constant(&mut module, 0, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: zero, + }, + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let seen = sim.signal("seen"); + // Edges at 0, 2, ..., 18; the process resumes at 20, before the edge there. + sim.run_until(19).unwrap(); + assert_eq!(sim.get(count), 10u32.into()); + assert_eq!(sim.get(seen), 0u32.into()); + assert_eq!(sim.ticks(), 10); + sim.run_until(20).unwrap(); + assert_eq!(sim.get(seen), 10u32.into()); + assert!(!sim.is_finished()); + // Three more edges at 20, 22 and 24; the process finishes at 26. + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 26); + assert_eq!(sim.get(count), 13u32.into()); + assert_eq!(sim.ticks(), 13); +} + +#[test] +fn clock_waits_of_several_processes_share_fused_edges() { + let (mut module, clk, count) = clocked_by_process_waits(10); + let word = ValueType::bits(32).unwrap(); + let early = module.output("early", word).unwrap(); + let late = module.output("late", word).unwrap(); + let count_expr = module.read(count).unwrap(); + let early_target = module.whole(early).unwrap(); + let late_target = module.whole(late).unwrap(); + let a_lot = constant(&mut module, 1_000_000, 64); + let fewer = constant(&mut module, 300_000, 64); + let some = constant(&mut module, 5, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: a_lot, + }, + Statement::Assign { + target: late_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: fewer, + }, + Statement::Assign { + target: early_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: some, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let early = sim.signal("early"); + let late = sim.signal("late"); + sim.run_until(u64::MAX - 1).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(early), 300_000u32.into()); + assert_eq!(sim.get(late), 1_000_000u32.into()); + assert_eq!(sim.ticks(), 1_000_000); + assert_eq!(sim.time(), 10_000_000); +} + +#[test] +fn clock_waits_interleave_with_delays_and_checkpoints() { + let (mut module, clk, count) = clocked_by_process_waits(2); + let word = ValueType::bits(32).unwrap(); + let bit = ValueType::bits(1).unwrap(); + let seen = module.output("seen", word).unwrap(); + let flag = module.output("flag", bit).unwrap(); + let count_expr = module.read(count).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let flag_target = module.whole(flag).unwrap(); + let ten = constant(&mut module, 10, 64); + let five = constant(&mut module, 5, 64); + let one = constant(&mut module, 1, 1); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::Assign { + target: flag_target, + value: one, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let seen = sim.signal("seen"); + let flag = sim.signal("flag"); + let clk = sim.signal("clk"); + // Edges at 0, 2 and 4 run one by one around the delay at 5; the clock + // signal shows them. + sim.run_until(2).unwrap(); + assert_eq!(sim.get(count), 2u32.into()); + assert_eq!(sim.get(clk), 1u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(flag), 1u8.into()); + assert_eq!(sim.get(count), 3u32.into()); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(20).unwrap(); + // The process resumed at 20 before the edge there, and waits again, so + // that edge fires. + assert_eq!(sim.get(seen), 10u32.into()); + assert_eq!(sim.get(count), 11u32.into()); + sim.restore(&checkpoint).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(seen), 0u32.into()); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 40); + assert_eq!(sim.get(seen), 10u32.into()); + assert_eq!(sim.get(count), 20u32.into()); +} + +/// A step whose clock waits ran as fused ticks reports the time it reached. +#[test] +fn a_fused_step_returns_the_time_it_reached() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + // Edges at 0, 2, ..., 18 run as one step. + assert_eq!(sim.step().unwrap(), Some(18)); + assert_eq!(sim.time(), 18); + assert_eq!(sim.ticks(), 10); +} + +/// A process clock that is high when a wait begins falls first: only real +/// rising edges count, so the registers see every counted edge. +#[test] +fn a_high_process_clock_falls_before_its_first_counted_edge() { + let (mut module, clk, count) = clocked_by_process_waits(2); + module + .set_initial(clk, Constant::two_state(1u8, 1).unwrap()) + .unwrap(); + let word = ValueType::bits(32).unwrap(); + let seen = module.output("seen", word).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let count_expr = module.read(count).unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Assign { + target: seen_target, + value: count_expr, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let seen = sim.signal("seen"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(seen), 3u32.into()); + assert_eq!(sim.ticks(), 3); +} + +/// A clock edge that would lie beyond simulation time is an error, like a +/// delay that overflows. +#[test] +fn clock_edges_beyond_simulation_time_are_an_error() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let late = module.constant(Constant::two_state(u64::MAX - 2, 64).unwrap()); + let two = constant(&mut module, 2, 64); + module + .process(vec![ + Statement::Delay { amount: late }, + Statement::ClockCycles { + clock: clk, + count: two, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + loop { + match sim.step() { + Ok(Some(_)) => {} + Ok(None) => panic!("the overflowing edge was not reported"), + Err(error) => { + assert!( + error.to_string().contains("overflows simulation time"), + "{error}" + ); + break; + } + } + } +} + +/// A design whose registers drive another clock keeps the scheduler's +/// rounds: the derived clock's domain fires on every clock wait too. +#[test] +fn clock_waits_keep_derived_clocks_running() { + let (mut module, clk, _count) = clocked_by_process_waits(2); + let bit = ValueType::bits(1).unwrap(); + let word = ValueType::bits(32).unwrap(); + let half = module.internal("half", bit).unwrap(); + module + .set_initial(half, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + let half_expr = module.read(half).unwrap(); + let toggled = module.unary(UnaryOp::BitNot, half_expr, bit).unwrap(); + let half_target = module.whole(half).unwrap(); + module + .register(half_target, toggled, clk, Edge::Posedge, None, None) + .unwrap(); + let slow = module.output("slow", word).unwrap(); + module + .set_initial(slow, Constant::two_state(0u8, 32).unwrap()) + .unwrap(); + let slow_expr = module.read(slow).unwrap(); + let one = constant(&mut module, 1, 32); + let next = module.binary(BinaryOp::Add, slow_expr, one, word).unwrap(); + let slow_target = module.whole(slow).unwrap(); + module + .register(slow_target, next, half, Edge::Posedge, None, None) + .unwrap(); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: ten, + }, + Statement::Finish, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let count = sim.signal("count"); + let slow = sim.signal("slow"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(count), 10u32.into()); + // `half` rises on every second edge of `clk`. + assert_eq!(sim.get(slow), 5u32.into()); +} + +#[test] +fn zero_clock_wait_does_not_yield_to_another_process() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let bit = ValueType::bits(1).unwrap(); + let x = module.output("x", bit).unwrap(); + let seen = module.output("seen", bit).unwrap(); + let x_target = module.whole(x).unwrap(); + let seen_target = module.whole(seen).unwrap(); + let x_value = module.read(x).unwrap(); + let zero = constant(&mut module, 0, 1); + let one = constant(&mut module, 1, 1); + module + .process(vec![ + Statement::Assign { + target: x_target, + value: one, + }, + Statement::ClockCycles { + clock: clk, + count: zero, + }, + Statement::Assign { + target: seen_target, + value: x_value, + }, + ]) + .unwrap(); + module + .process(vec![Statement::Assign { + target: x_target, + value: zero, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 1u8.into()); + assert_eq!(sim.get(sim.signal("x")), 0u8.into()); + assert_eq!(sim.ticks(), 0); +} + +#[test] +fn settle_bounds_clock_waits_started_by_a_due_delay() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let five = constant(&mut module, 5, 64); + let ten = constant(&mut module, 10, 64); + module + .process(vec![ + Statement::Delay { amount: five }, + Statement::ClockCycles { + clock: clk, + count: ten, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.run_until(5).unwrap(); + sim.settle().unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); +} + +#[test] +fn scheduled_and_process_clock_edges_sample_the_same_old_state() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let bit = ValueType::bits(1).unwrap(); + let manual = module.input("manual", bit).unwrap(); + let b = module.output("b", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let one = constant(&mut module, 1, 1); + let b_value = module.read(b).unwrap(); + let b_target = module.whole(b).unwrap(); + let q_target = module.whole(q).unwrap(); + module + .register(b_target, one, manual, Edge::Posedge, None, None) + .unwrap(); + module + .register(q_target, b_value, clk, Edge::Posedge, None, None) + .unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + sim.schedule("manual", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("b")), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + sim.run_until(8).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); +} + +#[test] +fn clock_wait_vcd_records_each_edge_timestamp() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let three = constant(&mut module, 3, 64); + module + .process(vec![ + Statement::ClockCycles { + clock: clk, + count: three, + }, + Statement::Finish, + ]) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("wait.vcd"); + let mut sim = Simulation::from_frontend(module.finish()) + .vcd(&path) + .build() + .unwrap(); + sim.run_until(20).unwrap(); + sim.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + for time in [2, 4, 6, 8, 10, 12] { + assert!( + text.lines().any(|line| line == format!("#{time}")), + "missing timestamp {time}: {text}" + ); + } +} + +#[test] +fn overflowing_generated_edges_do_not_commit_or_credit_on_retry() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let delay = constant(&mut module, u64::MAX - 3, 64); + let one = constant(&mut module, 1, 64); + module + .process(vec![ + Statement::Delay { amount: delay }, + Statement::ClockCycles { + clock: clk, + count: one, + }, + ]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + assert_eq!(sim.step().unwrap(), Some(0)); + for _ in 0..2 { + let error = sim.step().unwrap_err(); + assert!( + error.to_string().contains("overflows simulation time"), + "{error}" + ); + assert_eq!(sim.get(sim.signal("count")), 0u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.ticks(), 0); + } +} + +#[test] +fn periodic_and_process_generators_for_one_clock_are_rejected() { + for register_first in [true, false] { + let (mut module, clk, _) = clocked_by_process_waits(4); + let two = constant(&mut module, 2, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: two, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + if !register_first { + sim.step().unwrap(); + } + let count = sim.get(sim.signal("count")); + let ticks = sim.ticks(); + // Register a valid current-time edge so this tests competing drivers. + sim.add_clock("clk", 4, sim.time()); + let error = sim.step().unwrap_err(); + assert!( + error.to_string().contains("already driven by add_clock"), + "{error}" + ); + assert_eq!(sim.get(sim.signal("count")), count); + assert_eq!(sim.ticks(), ticks); + } +} + +#[test] +fn imported_clock_periods_reject_duplicate_signal_entries() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let one = constant(&mut module, 1, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let mut value: serde_json::Value = + serde_json::from_str(&module.finish().to_json().unwrap()).unwrap(); + let periods = value["clock_periods"].as_array_mut().unwrap(); + let mut duplicate = periods[0].clone(); + duplicate[1] = 8.into(); + periods.push(duplicate); + let error = FrontendArtifact::from_json(&value.to_string()).unwrap_err(); + assert!( + error.to_string().contains("duplicate process-clock period"), + "{error}" + ); +} + +#[test] +fn one_shot_events_conflict_with_new_process_clock_generators() { + for time in [0, 4] { + let (mut m, clk, _) = clocked_by_process_waits(4); + let one = constant(&mut m, 1, 64); + m.process(vec![Statement::ClockCycles { + clock: clk, + count: one, + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(m.finish()).build().unwrap(); + sim.schedule("clk", time, 1).unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("already driven by schedule"), "{error}"); + assert_eq!(sim.ticks(), 0); + assert_eq!(sim.get(sim.signal("count")), 0u32.into()); + } +} + +#[test] +fn newly_started_process_clocks_share_scheduled_domains_pre_edge_state() { + fn design() -> FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let a = m.internal("a", bit).unwrap(); + let b = m.input("b", bit).unwrap(); + let qa = m.output("qa", bit).unwrap(); + let qb = m.output("qb", bit).unwrap(); + let one = constant(&mut m, 1, 1); + let qb_read = m.read(qb).unwrap(); + let qa_target = m.whole(qa).unwrap(); + let qb_target = m.whole(qb).unwrap(); + m.register(qa_target, qb_read, a, Edge::Posedge, None, None) + .unwrap(); + m.register(qb_target, one, b, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(a, 4).unwrap(); + let four = constant(&mut m, 4, 64); + let count = constant(&mut m, 1, 64); + m.process(vec![ + Statement::Delay { amount: four }, + Statement::ClockCycles { clock: a, count }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.schedule("b", 4, 1).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("qb")), 1u8.into()); + assert_eq!(sim.get(sim.signal("qa")), 0u8.into()); + assert_eq!(sim.ticks(), 1); + } + check( + Simulation::from_frontend(design()) + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_frontend(design()) + .build_cranelift() + .unwrap(), + ); + check(Simulation::from_frontend(design()).build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::from_frontend(design()).build_native().unwrap()); +} + +#[test] +fn repeating_zero_count_clock_waits_report_non_progress() { + let (mut module, clk, _) = clocked_by_process_waits(2); + let zero = constant(&mut module, 0, 64); + module + .process(vec![Statement::Forever { + body: vec![Statement::ClockCycles { + clock: clk, + count: zero, + }], + }]) + .unwrap(); + let mut sim = Simulation::from_frontend(module.finish()).build().unwrap(); + let error = sim.step().unwrap_err().to_string(); + assert!(error.contains("delta limit"), "{error}"); + assert_eq!(sim.time(), 0); + assert_eq!(sim.ticks(), 0); +} + +#[test] +fn due_process_clock_batches_with_a_combinationally_derived_edge() { + let (mut module, clk, _) = clocked_by_process_waits(4); + let bit = ValueType::bits(1).unwrap(); + let src = module.internal("src", bit).unwrap(); + let enable = module.input("enable", bit).unwrap(); + let gated = module.internal("gated", bit).unwrap(); + let b = module.output("b", bit).unwrap(); + let q = module.output("q", bit).unwrap(); + let src_expr = module.read(src).unwrap(); + let en_expr = module.read(enable).unwrap(); + let value = module + .binary(BinaryOp::And, src_expr, en_expr, bit) + .unwrap(); + let gate_target = module.whole(gated).unwrap(); + module.assign(gate_target, value).unwrap(); + let one = constant(&mut module, 1, 1); + let b_target = module.whole(b).unwrap(); + module + .register(b_target, one, gated, Edge::Posedge, None, None) + .unwrap(); + let b_expr = module.read(b).unwrap(); + let q_target = module.whole(q).unwrap(); + module + .register(q_target, b_expr, clk, Edge::Posedge, None, None) + .unwrap(); + let three = constant(&mut module, 3, 64); + module + .process(vec![Statement::ClockCycles { + clock: clk, + count: three, + }]) + .unwrap(); + let four = constant(&mut module, 4, 64); + let src_target = module.whole(src).unwrap(); + module + .process(vec![ + Statement::Delay { amount: four }, + Statement::Assign { + target: src_target, + value: one, + }, + ]) + .unwrap(); + let artifact = module.finish(); + fn check(mut sim: Simulation) { + let en = sim.signal("enable"); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("b")), 1u8.into()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + sim.run_until(8).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + let build = || Simulation::from_frontend(artifact.clone()); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} diff --git a/docs/guide/external-frontends.md b/docs/guide/external-frontends.md index cce58382da4..cf78b51ca2b 100644 --- a/docs/guide/external-frontends.md +++ b/docs/guide/external-frontends.md @@ -131,6 +131,7 @@ in order: | `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. | +| `ClockCycles` | Suspend until a number of rising edges of a clock have passed. The clock must clock a register and have a period set with `ModuleBuilder::clock_period`; the runtime generates its edges from the first wait on it, and the process resumes one period after the last counted edge, before the edge that follows. | | `Finish` | End the simulation. | ```rust @@ -155,6 +156,15 @@ 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. +A clock that processes wait on with `ClockCycles` toggles every half period +once a process has waited on it, as long as one does. While every live +process waits on the same clock and nothing else is scheduled, the edges run +as fused ticks inside the backend's generated code, so a long wait costs no +more than the same number of ticks of an event-driven `Simulator`; such a +run skips the clock signal's own edges and the per-edge hooks of external +components, which are honored again as soon as another process or event +interleaves. + 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 diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index e58c4718cf6..a45d4f22c4a 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -184,9 +184,12 @@ 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, a wait, 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 a delay, a wait, a clock wait, + the end of the process, or `$finish` before it returns; +- a delay slot, which holds the wait amount: time units or clock edges; +- a clock slot, which names the process clock of a clock wait among the + clocks the process may wait on, listed with their periods in the runtime + schema. 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 @@ -215,11 +218,26 @@ waited for zero time, or that the settled state wakes, resume in a further round at the same time, which repeats the edge detection and settling; a round in which every waiting process reports a pending wait ends the time. `Simulation::step` and `run_until` also run such a round first, so a host -write between steps wakes the processes that wait for it. Because the slots -are ordinary state, a checkpoint captures suspended processes. 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. +write between steps wakes the processes that wait for it. + +A clock wait asks for a number of rising edges of a process clock. The +scheduler generates that clock's edges from the first wait on it: a rising +edge is due at the clock's next edge time whenever a process waits, applied +after the processes of that time have run, and its falling edge half a +period later; each rising edge counts against the waits, and a process whose +count is reached resumes one period after that edge, before the edge that +follows. When every live process waits on the single clock that is due and +no event, resumption or falling edge is pending, the scheduler instead runs +as many edges as the earliest resumption needs through +`SimulationExecutor::tick_many`, the same fused combinational-plus-sequential +loop that event-driven ticks use, and advances time past them in one step. +Those ticks leave the clock signal untouched and skip the per-edge hooks of +external components, which is why the host can veto them. Because the slots +are ordinary state, a checkpoint captures suspended processes, and the +scheduler's snapshot carries the generated clocks and clock waits. 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. A running simulator retains the elaborated design, source lookup, runtime schema, bound testbench bytecode, and compiled backend. The backend owns the finalized diff --git a/docs/ja/guide/external-frontends.md b/docs/ja/guide/external-frontends.md index 56c75432a36..8b613c79806 100644 --- a/docs/ja/guide/external-frontends.md +++ b/docs/ja/guide/external-frontends.md @@ -131,6 +131,7 @@ Celox artifact JSON も parse しません。build 可能な addon と load test | `If` | 条件で分岐します。不定 bit を含む条件は偽として扱います。 | | `While` / `Forever` | 条件が成り立つ間、または永久に body を繰り返します。 | | `Delay` | 指定した時間単位だけ suspend します。量は 64 bit 以下です。 | +| `ClockCycles` | clock の立ち上がりエッジが指定回数過ぎるまで suspend します。clock は register の clock で、`ModuleBuilder::clock_period` で周期を設定しておきます。runtime は最初の待ちからその clock のエッジを生成し、process は最後に数えたエッジの 1 周期後、次のエッジの前に再開します。 | | `Finish` | simulation を終了します。 | ```rust @@ -155,6 +156,13 @@ schedule された event と同様にその時刻の register を trigger しま trigger した register が settle した後で再開します。そのため 0 の delay で区切った pulse も edge になります。 +`ClockCycles` で待つ clock は、いずれかの process が待っている間、半周期ごとに +toggle します。生きている process がすべて同じ clock を待っていて他に schedule +された event がないときは、その edge は backend が生成したコードの中で fused tick +として実行されるため、長い待ちも event 駆動の `Simulator` で同じ回数 tick する +のと同程度の cost で済みます。この間は clock signal 自身の edge と外部 component +の edge ごとの hook を省略し、他の process や event が割り込むと再び有効になります。 + process が書けるのは、continuous assignment や register が駆動していない output と internal signal です。同じ signal を複数の process が書いても 構いません。checkpoint は suspend 中の process を保存しますが、process を