diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7cb1572d8e2..088c230da03 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1054,6 +1054,12 @@ pub struct EventTopology { /// a signal needs a settle before its domains evaluate. #[serde(default)] pub combinationally_read: BTreeSet, + /// Canonical events whose own domain reads no level of their signal: its + /// flip-flops do not sample the signal as data. With + /// [`Self::combinationally_read`] it says whether a run of the domain + /// observes the signal's level. Absent means it may. + #[serde(default)] + pub level_unread_by_domain: BTreeSet, } /// A clock computed combinationally from an event's signal. @@ -1149,6 +1155,7 @@ impl Default for EventTopology { combinational_derived: BTreeMap::new(), independent_derived: BTreeSet::new(), combinationally_read: BTreeSet::new(), + level_unread_by_domain: BTreeSet::new(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 6a8f45347bb..3597877c643 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -956,6 +956,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( combinational_derived, independent_derived, combinationally_read, + level_unread_by_domain, } = timed_sub!( "analyze_clock_dependencies", analyze_clock_dependencies( @@ -1802,6 +1803,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(), independent_derived: independent_derived.into_iter().map(project).collect(), combinationally_read: combinationally_read.into_iter().map(project).collect(), + level_unread_by_domain: level_unread_by_domain.into_iter().map(project).collect(), combinational_derived: combinational_derived .into_iter() .map(|(event, clocks)| { @@ -4629,6 +4631,8 @@ struct ClockAnalysis { independent_derived: BTreeSet, /// Events whose signal combinational logic reads. combinationally_read: BTreeSet, + /// Events whose own domain does not read their signal. + level_unread_by_domain: BTreeSet, } fn analyze_clock_dependencies( @@ -5023,6 +5027,27 @@ fn analyze_clock_dependencies( } Some((reads, writes)) }; + // A domain reads its own clock's level when a flip-flop samples it as + // data. An external call may read anything. + let canonical = |address: AbsoluteAddr| clock_domains.get(&address).copied().unwrap_or(address); + let level_unread_by_domain: BTreeSet = eval_apply_ffs + .iter() + .filter(|(domain, units)| { + let domain = canonical(**domain); + !units + .iter() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .any(|instruction| match instruction { + SIRInstruction::Load(_, address, ..) | SIRInstruction::Commit(address, ..) => { + canonical(address.absolute_addr()) == domain + } + SIRInstruction::ExternCall { .. } => true, + _ => false, + }) + }) + .map(|(domain, _)| canonical(*domain)) + .collect(); let mut independent_derived = BTreeSet::new(); let combinationally_read: BTreeSet = comb_deps .values() @@ -5070,6 +5095,7 @@ fn analyze_clock_dependencies( combinational_derived, independent_derived, combinationally_read, + level_unread_by_domain, } } diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 1b971593394..1348822b39f 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -13,7 +13,7 @@ //! so the inactive edge of a clock that only clocks flip-flops costs no //! settle on the next active edge. -use celox_design::{DomainKind, EventTopology, edges::LEVEL_UNKNOWN}; +use celox_design::{DomainKind, EventTopology, GateOp, edges::LEVEL_UNKNOWN}; use crate::{ AbsoluteAddr, SignalRef, @@ -60,6 +60,15 @@ pub struct EventEdge { pub kind: Option, /// Combinational logic reads the signal. pub comb_read: bool, + /// A run of the event's own domain can observe the signal's level: + /// combinational logic or one of the domain's flip-flops reads it. + pub level_read: bool, + /// The edge opposite to [`Self::active_edge`] can run a domain: the + /// event's own, or that of a clock computed combinationally from the + /// signal that this edge can move to its active edge. When it cannot, + /// nothing commits on that edge, so no domain clocked from state runs + /// either, and a host only needs to store the level. + pub inactive_runs: bool, } impl EventEdge { @@ -108,15 +117,130 @@ pub fn build_event_edges( .iter() .map(|address| { let canonical = events.canonical(*address); - EventEdge { + let kind = kinds.get(&canonical).copied(); + let comb_read = events.combinationally_read.contains(&canonical); + let mut info = EventEdge { signal: backend.resolve_signal(&canonical), - kind: kinds.get(&canonical).copied(), - comb_read: events.combinationally_read.contains(&canonical), - } + kind, + comb_read, + level_read: comb_read || !events.level_unread_by_domain.contains(&canonical), + inactive_runs: false, + }; + let inactive = info.active_edge().opposite(); + info.inactive_runs = info.can_fire(inactive) + || events + .combinational_derived + .get(&canonical) + .into_iter() + .flatten() + // A clock without a domain of its own runs nothing. + .filter(|clock| backend.resolve_event_opt(&clock.clock).is_some()) + .any(|clock| { + let moves = clock + .gate + .as_deref() + .and_then(dependence) + .unwrap_or(Dependence::Mixed); + moves.can_reach(inactive, kinds.get(&clock.clock).copied()) + }); + info }) .collect() } +/// How a gate program's value depends on its source's level, bitwise: +/// whether raising the source can only raise each bit, only lower it, or +/// either. The operations it treats as monotone also are over the order +/// 0 < x < 1 of four-state values, so it holds for four-state designs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dependence { + Independent, + Positive, + Negative, + Mixed, +} + +impl Dependence { + fn invert(self) -> Self { + match self { + Dependence::Positive => Dependence::Negative, + Dependence::Negative => Dependence::Positive, + other => other, + } + } + + /// A monotone function of both operands, such as `&` or `|`. + fn join(self, other: Self) -> Self { + match (self, other) { + (Dependence::Independent, other) | (other, Dependence::Independent) => other, + (lhs, rhs) if lhs == rhs => lhs, + _ => Dependence::Mixed, + } + } + + /// A function of the operands that is not monotone, such as `^`. + fn scramble(self, other: Self) -> Self { + if self == Dependence::Independent && other == Dependence::Independent { + Dependence::Independent + } else { + Dependence::Mixed + } + } + + /// Whether `edge` of the source can be an edge of a clock of `kind` + /// computed with this dependence. + fn can_reach(self, edge: Edge, kind: Option) -> bool { + let moves = match self { + Dependence::Independent => return false, + Dependence::Mixed => return true, + Dependence::Positive => edge, + Dependence::Negative => edge.opposite(), + }; + match kind { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => moves == Edge::Rising, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => moves == Edge::Falling, + _ => true, + } + } +} + +/// The [`Dependence`] of a gate program's value on its source, or `None` +/// for a malformed program. +fn dependence(ops: &[GateOp]) -> Option { + let mut stack: Vec = Vec::new(); + for op in ops { + let value = match op { + GateOp::Source => Dependence::Positive, + GateOp::Load { .. } | GateOp::Const(_) => Dependence::Independent, + GateOp::Not { .. } | GateOp::LogicNot => stack.pop()?.invert(), + GateOp::ReduceAnd { .. } | GateOp::ReduceOr | GateOp::Slice { .. } => stack.pop()?, + GateOp::ReduceXor => stack.pop()?.scramble(Dependence::Independent), + GateOp::And | GateOp::Or | GateOp::LogicAnd | GateOp::LogicOr => { + let rhs = stack.pop()?; + stack.pop()?.join(rhs) + } + GateOp::Xor | GateOp::Eq | GateOp::Ne => { + let rhs = stack.pop()?; + stack.pop()?.scramble(rhs) + } + GateOp::Mux => { + let otherwise = stack.pop()?; + let then = stack.pop()?; + match stack.pop()? { + // A fixed condition selects one of two monotone values. + Dependence::Independent => then.join(otherwise), + _ => Dependence::Mixed, + } + } + }; + stack.push(value); + } + match stack.as_slice() { + [value] => Some(*value), + _ => None, + } +} + /// What an edge did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EdgeOutcome { @@ -174,6 +298,12 @@ pub fn set_level(backend: &mut B, signal: SignalRef, level: u8) { backend.set(signal, level); } +/// Whether `info`'s signal is at the known level `edge` leaves it at. +#[inline] +pub fn at_level(backend: &B, info: &EventEdge, edge: Edge) -> bool { + level(backend, info.signal) == edge.level() +} + /// Move `info`'s signal to the level of `edge` through `write`. Returns the /// level it had (`None` while unknown), or `None` when it already was at /// that level. @@ -398,3 +528,69 @@ where } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + type Op = GateOp<()>; + + const LOAD: Op = GateOp::Load { + address: (), + lsb: 0, + width: 1, + }; + + #[test] + fn gates_follow_their_source_through_monotone_operations() { + use Dependence::*; + let cases: [(&[Op], Dependence); 8] = [ + (&[GateOp::Source, LOAD, GateOp::And], Positive), + (&[GateOp::Source, GateOp::Not { width: 1 }], Negative), + ( + &[GateOp::Source, GateOp::LogicNot, LOAD, GateOp::LogicOr], + Negative, + ), + (&[LOAD, GateOp::Const(1), GateOp::Or], Independent), + (&[GateOp::Source, LOAD, GateOp::Xor], Mixed), + ( + &[ + GateOp::Source, + GateOp::Source, + GateOp::Not { width: 1 }, + GateOp::Or, + ], + Mixed, + ), + ( + &[LOAD, GateOp::Source, GateOp::Const(0), GateOp::Mux], + Positive, + ), + ( + &[GateOp::Source, LOAD, GateOp::Const(0), GateOp::Mux], + Mixed, + ), + ]; + for (ops, expected) in cases { + assert_eq!(dependence(ops), Some(expected), "{ops:?}"); + } + assert_eq!(dependence::<()>(&[GateOp::And]), None); + assert_eq!(dependence::<()>(&[GateOp::Source, GateOp::Source]), None); + } + + #[test] + fn a_clock_is_reached_by_the_edges_its_dependence_allows() { + use DomainKind::*; + let posedge = Some(ClockPosedge); + let negedge = Some(ClockNegedge); + // The falling edge of a positive-edge clock's source. + let edge = Edge::Falling; + assert!(!Dependence::Positive.can_reach(edge, posedge)); + assert!(Dependence::Positive.can_reach(edge, negedge)); + assert!(Dependence::Negative.can_reach(edge, posedge)); + assert!(!Dependence::Negative.can_reach(edge, Some(ResetAsyncLow))); + assert!(Dependence::Positive.can_reach(edge, None)); + assert!(!Dependence::Independent.can_reach(edge, None)); + assert!(Dependence::Mixed.can_reach(edge, posedge)); + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 6dd1b5f2158..2a32ee2d4d0 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -24,8 +24,8 @@ pub use derived_tick::{ EventDomain, Gate, GatedDomain, TickExecutor, build_derived_tick_plans, }; pub use edge::{ - Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal, - run_edge, run_edges, run_tick, set_level, + Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, at_level, build_event_edges, + move_signal, run_edge, run_edges, run_tick, set_level, }; pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site}; pub use event_buffer::RuntimeEventBuffer; diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index f8497a81a6d..1bb95a744e9 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -48,9 +48,24 @@ impl SimulationState { for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { match term.counter { Some(counter) => { - *baseline = Baseline::Counter { - seen: backend.get_as(counter), - value: read(backend, term.signal), + let seen = backend.get_as(counter); + match planes(backend, term.signal) { + Some(image) => { + if let Baseline::RawCounter { seen: last, raw } = baseline { + *last = seen; + copy_planes(raw, image, term.signal.width); + } else { + let mut raw = Vec::with_capacity(image.len()); + copy_planes(&mut raw, image, term.signal.width); + *baseline = Baseline::RawCounter { seen, raw }; + } + } + None => { + *baseline = Baseline::Counter { + seen, + value: read(backend, term.signal), + } + } } } None => match planes(backend, term.signal) { @@ -128,20 +143,40 @@ impl SimulationState { continue; } let baseline = &mut waiter.baselines[index]; + // The common term: a plain signal no counter counts. + if let Baseline::Raw(last) = baseline { + let now = state.planes(term.signal).expect("a plain signal"); + wake |= Self::advance(term.kind, last, now, term.signal.width); + continue; + } + let counted = |seen: u32| { + term.counter + .is_some_and(|counter| backend.get_as::(counter) != seen) + }; wake |= match baseline { - Baseline::Counter { seen, value } => { - let counted = term - .counter - .is_some_and(|counter| backend.get_as::(counter) != *seen); - let now = read(backend, term.signal); - let changed = occurs(term.kind, value, &now); - *value = now; - counted || changed - } - Baseline::Raw(last) => { + Baseline::RawCounter { seen, raw } => { let now = state.planes(term.signal).expect("a plain signal"); - Self::advance(term.kind, last, now, term.signal.width) + let changed = Self::advance(term.kind, raw, now, term.signal.width); + counted(*seen) || changed } + Baseline::Counter { seen, value } => match state.planes(term.signal) { + // A baseline loaded from a state file. + Some(now) => { + let seen = *seen; + let mut raw = encode_planes(value, term.signal.width, now.len()); + let changed = + Self::advance(term.kind, &mut raw, now, term.signal.width); + *baseline = Baseline::RawCounter { seen, raw }; + counted(seen) || changed + } + None => { + let now = read(backend, term.signal); + let changed = occurs(term.kind, value, &now); + *value = now; + counted(*seen) || changed + } + }, + Baseline::Raw(_) => unreachable!("tested above"), Baseline::Value(last) => match state.planes(term.signal) { // A baseline loaded from a state file. Some(now) => { @@ -191,7 +226,7 @@ impl SimulationState { } match baseline { // Counters are bumped by the write itself. - Baseline::Counter { .. } => {} + Baseline::Counter { .. } | Baseline::RawCounter { .. } => {} Baseline::Raw(last) => { let now = encode_planes(value, signal.width, last.len()); wake |= Self::advance(term.kind, last, &now, signal.width); @@ -224,6 +259,9 @@ pub enum Baseline { /// (see [`planes`]) with the bits above its width cleared. Checks /// compare it with the state in place. Raw(Vec), + /// Like `Counter`, with the signal's state at the last check kept as + /// in [`Baseline::Raw`]. + RawCounter { seen: u32, raw: Vec }, } /// A process suspended at a wait. diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index c768f78170a..0c42bc267c0 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -29,6 +29,8 @@ pub(super) struct ScopeBinding { pub(super) struct ArrayBinding { pub elements: Vec, pub shape: Vec, + /// Authored bounds, retained for selecting actual interface array elements. + pub ranges: Vec<(i128, i128)>, } pub(super) fn analyze_module( @@ -419,6 +421,7 @@ pub(super) fn analyze_module( }) .collect(), shape: elements.shape.clone(), + ranges: elements.ranges.clone(), }; imported.interface_arrays.insert(qualified, absolute); if let Some(item) = &generated_item { @@ -636,26 +639,7 @@ pub(super) fn analyze_module( let actual = connection_expression(authored, &port.name, interfaces.get(&original))?; let env = &item.env; - let handle = match actual { - Some(actual) => { - actual_handle_key(actual, tree, env, &active_scope.type_aliases)? - } - None => port.name.clone(), - }; - let actuals = if port.array_rank == 0 { - ArrayBinding { - elements: vec![handle.clone()], - shape: Vec::new(), - } - } else { - active_scope - .interface_arrays - .get(&handle) - .cloned() - .ok_or_else(|| { - unsupported(format!("interface array actual `{handle}`")) - })? - }; + let actuals = connection_array(actual, &port.name, tree, env, &active_scope)?; if actuals.shape.len() != port.array_rank { return Err(unsupported(format!( "interface array rank mismatch at `{original}.{}`", @@ -1239,6 +1223,7 @@ fn instance_elements( let ranges = constant_binding::bind_unpacked_ranges(dimensions, tree, &context)?; validate_unpacked_dimension_sizes(&tree.state, &ranges, env)?; let mut shape = Vec::new(); + let mut bounds = Vec::new(); let mut elements = vec![handle.to_string()]; for range in ranges { let left = eval_ast_const_expr(&tree.state, &range.left, env) @@ -1256,6 +1241,7 @@ fn instance_elements( }) .ok_or_else(|| unsupported("interface array elaboration limit exceeded"))?; shape.push(count); + bounds.push((left, right)); elements = elements .into_iter() .flat_map(|prefix| { @@ -1270,7 +1256,165 @@ fn instance_elements( }) .collect(); } - Ok(ArrayBinding { elements, shape }) + Ok(ArrayBinding { + elements, + shape, + ranges: bounds, + }) +} + +/// Bind an interface actual as a selection of elaborated instances. Selections +/// consume authored dimensions; a slice retains its dimension while an index +/// removes it. Elements stay in declaration order for left-to-left port mapping. +fn connection_array( + actual: Option, + implicit: &str, + tree: &AnalysisContext<'_>, + env: &HashMap, + scope: &scope::ScopeSymbols, +) -> Converted { + use celox_sv_syntax::ExprKind; + let native = tree.declarations(); + let mut selections = Vec::new(); + let mut root = actual; + while let Some(id) = root { + let id = expression_binding::ungroup(id, native); + if let ExprKind::Select { + expression, + dimension, + } = &native.expression(id).kind + { + selections.push(&dimension.kind); + root = Some(*expression); + } else { + root = Some(id); + break; + } + } + let handle = match root { + Some(root) => actual_handle_key(root, tree, env, &scope.type_aliases)?, + None => implicit.to_string(), + }; + let Some(array) = scope.interface_arrays.get(&handle) else { + // A selection in a hierarchical prefix may name a generated scope; + // retain the existing scalar-handle resolution for that case. + return Ok(ArrayBinding { + elements: vec![match actual { + Some(actual) => actual_handle_key(actual, tree, env, &scope.type_aliases)?, + None => handle, + }], + shape: Vec::new(), + ranges: Vec::new(), + }); + }; + if selections.is_empty() { + return Ok(array.clone()); + } + if selections.len() > array.shape.len() { + return Err(unsupported("too many interface array selections")); + } + if selections + .iter() + .filter(|selection| { + matches!( + selection, + celox_sv_syntax::DimensionKind::Range { .. } + | celox_sv_syntax::DimensionKind::Indexed { .. } + ) + }) + .count() + > 1 + { + return Err(unsupported("interface array slices in multiple dimensions")); + } + let context = PackedDimensions::new(HashMap::default(), env, &scope.type_aliases); + let evaluate = |root| -> Converted { + constant_binding::bind(root, tree, &context)? + .and_then(|value| eval_ast_const_expr(&tree.state, &value, env)) + .ok_or_else(|| unsupported("nonconstant interface array selection")) + }; + let selections = selections.into_iter().rev().collect::>(); + let mut offsets = vec![0]; + let mut shape = Vec::new(); + let mut ranges = Vec::new(); + for (dimension, (&size, &(left, right))) in array.shape.iter().zip(&array.ranges).enumerate() { + let (selected_left, selected_right, retain) = match selections.get(dimension) { + None => (left, right, true), + Some(celox_sv_syntax::DimensionKind::Index(index)) => { + let index = evaluate(*index)?; + (index, index, false) + } + Some(selection) => { + let (start, end) = selection_range(selection, left <= right, &evaluate)?; + (start, end, true) + } + }; + if selected_left < left.min(right) + || selected_left > left.max(right) + || selected_right < left.min(right) + || selected_right > left.max(right) + { + return Err(unsupported( + "interface array selection outside its declared range", + )); + } + if selected_left != selected_right && (selected_left < selected_right) != (left < right) { + return Err(unsupported("reversed interface array selection")); + } + // Bounds were checked against an elaborated dimension (at most 4096 + // elements), so these differences and products fit in usize. + let start = left.abs_diff(selected_left) as usize; + let end = left.abs_diff(selected_right) as usize; + offsets = offsets + .into_iter() + .flat_map(|prefix| (start..=end).map(move |index| prefix * size + index)) + .collect(); + if retain { + shape.push(end - start + 1); + ranges.push((selected_left, selected_right)); + } + } + Ok(ArrayBinding { + elements: offsets + .into_iter() + .map(|offset| array.elements[offset].clone()) + .collect(), + shape, + ranges, + }) +} + +fn selection_range( + selection: &celox_sv_syntax::DimensionKind, + ascending: bool, + evaluate: &impl Fn(celox_sv_syntax::ExprId) -> Converted, +) -> Converted<(i128, i128)> { + use celox_sv_syntax::DimensionKind; + match selection { + DimensionKind::Range { left, right } => Ok((evaluate(*left)?, evaluate(*right)?)), + DimensionKind::Indexed { + base, + operator, + width, + } => { + let base = evaluate(*base)?; + let width = evaluate(*width)?; + let extent = width + .checked_sub(1) + .filter(|_| width > 0) + .ok_or_else(|| unsupported("nonpositive interface array selection width"))?; + let (low, high) = if operator == "+:" { + (Some(base), base.checked_add(extent)) + } else { + (base.checked_sub(extent), Some(base)) + }; + let (low, high) = low + .zip(high) + .ok_or_else(|| unsupported("interface array selection bound overflow"))?; + Ok(if ascending { (low, high) } else { (high, low) }) + } + _ => Err(unsupported("interface array selection")), + } } pub(super) fn actual_handle_key( @@ -1288,6 +1432,7 @@ pub(super) fn actual_handle_key( let mut root = root; let mut suffixes = Vec::new(); let mut handle = loop { + root = expression_binding::ungroup(root, native); match &native.expression(root).kind { ExprKind::Name(name) => break instances::normalize_identifier(&name.spelling), ExprKind::Member { diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index c7a6e0db247..dfe0c33870b 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -2205,7 +2205,7 @@ struct TokenReference { /// The interface handle an actual names, optionally selected and qualified by a modport. fn actual_handle(expression: ExprId, file: &File<'_>) -> Converted> { let native = file.syntax_tree.declarations(); - let mut base = expression; + let mut base = expression_binding::ungroup(expression, native); let mut modport = None; if let native::ExprKind::Member { expression, @@ -2217,13 +2217,13 @@ fn actual_handle(expression: ExprId, file: &File<'_>) -> Converted Result<(), RuntimeErrorCode> { + self.active_edge(event)?; + let info = self.event_edges[event.id()]; + if self.dirty { + // Combinational logic did not settle, so the inactive edge + // may still find a derived clock moved by the settle. + return self.inactive_edge(event); + } + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + Ok(()) + } + /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2037,22 +2067,39 @@ mod host { return self.tick(*event); } let only_active_edges = self.host_watch.is_empty() - && events.iter().all(|event| { - let info = self.event_edges[event.id()]; - !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) - && !info.can_fire(info.active_edge().opposite()) - }); - if !only_active_edges { + && events + .iter() + .all(|event| !self.event_edges[event.id()].inactive_runs); + let derived = events + .iter() + .any(|event| matches!(self.derived_ticks.get(event.id()), Some(Some(_)))); + if !only_active_edges || derived { + let edges = std::sync::Arc::clone(&self.event_edges); let moves = |edge: fn(celox_runtime::EventEdge) -> celox_runtime::Edge| { events .iter() - .map(|&event| (event, edge(self.event_edges[event.id()]))) + .map(|&event| (event, edge(edges[event.id()]))) .collect::>() }; let active = moves(|info| info.active_edge()); - let inactive = moves(|info| info.active_edge().opposite()); self.edges(&active)?; - return self.edges(&inactive); + if !only_active_edges || self.dirty { + let inactive = moves(|info| info.active_edge().opposite()); + return self.edges(&inactive); + } + // The inactive edges run nothing and only store. + for &event in events { + let info = self.event_edges[event.id()]; + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read { + self.dirty = true; + } + } + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + return Ok(()); } // The inactive edges run nothing and only store. let mut fired = Vec::with_capacity(events.len()); @@ -2190,14 +2237,11 @@ mod host { Ok(()) } - /// Whether a period of `event`'s signal, a rise and a fall, runs only - /// the event's own domain, once: no domain reacts to the other edge - /// and no clock derives from the signal. - pub(crate) fn period_runs_only_own_domain(&self, event: B::Event) -> bool { - let info = self.event_edges[event.id()]; - !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) - && !info.can_fire(info.active_edge().opposite()) - && self.host_watch.is_empty() + /// Whether a period of `event`'s signal, a rise and a fall, runs + /// domains only at its active edge: the event's own and those derived + /// from it, while the inactive edge runs nothing. + pub(crate) fn period_runs_only_active_edge(&self, event: B::Event) -> bool { + !self.event_edges[event.id()].inactive_runs && self.host_watch.is_empty() } /// Advance a run of identical deferred-comb ticks. Native code may keep diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 9359e2afc0f..2fc6b63fb8e 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -546,6 +546,13 @@ impl Simulator { .collect() }) .unwrap_or_default(); + let split = |term: usize, image: &[u8]| { + let bytes = widths + .get(term) + .map_or(image.len(), |width| width.div_ceil(8).max(1)) + .min(image.len()); + (image[..bytes].to_vec(), image[bytes..].to_vec()) + }; WaiterRecord { process: process(index), site: waiter.site as u64, @@ -567,13 +574,18 @@ impl Simulator { mask: mask.to_bytes_le(), }, Baseline::Raw(image) => { - let bytes = widths - .get(term) - .map_or(image.len(), |width| width.div_ceil(8).max(1)) - .min(image.len()); - BaselineRecord::Value { - value: image[..bytes].to_vec(), - mask: image[bytes..].to_vec(), + let (value, mask) = split(term, image); + BaselineRecord::Value { value, mask } + } + Baseline::RawCounter { seen, raw } => { + // The bytes a `Counter` baseline's value saves as. + let (value, mask) = split(term, raw); + let number = + |bytes: &[u8]| BigUint::from_bytes_le(bytes).to_bytes_le(); + BaselineRecord::Counter { + seen: *seen, + value: number(&value), + mask: number(&mask), } } }) diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index f1239aa8884..1f60c315077 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -2425,7 +2425,7 @@ fn clock_periods( event: B::Event, count: u64, ) -> (u64, Result<(), crate::RuntimeErrorCode>) { - if sim.period_runs_only_own_domain(event) { + if sim.period_runs_only_active_edge(event) { return sim.tick_deferred_comb_many(event, count); } let result = sim diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index 373ba9c845e..6c3c216bd41 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -1,6 +1,16 @@ use super::*; sv_backends! { + fn connects_interface_array_slices_in_declaration_order(sim) { + @case "interfaces::connects_interface_array_slices_in_declaration_order"; + } + fn drives_interface_array_slices_through_generated_relays(sim) { + @case "interfaces::drives_interface_array_slices_through_generated_relays"; + } + fn connects_multidimensional_interface_array_slices(sim) { + @case "interfaces::connects_multidimensional_interface_array_slices"; + } + fn distributes_multidimensional_connections_to_interface_arrays(sim) { @case "interfaces::distributes_multidimensional_connections_to_interface_arrays"; } @@ -197,3 +207,73 @@ sv_backends! { assert!(!sim.warnings().is_empty()); } } + +#[test] +fn rejects_invalid_interface_array_selections() { + for (selection, expected) in [ + ("lanes[4:3]", "outside its declared range"), + ("lanes[0:1]", "reversed interface array selection"), + ( + "lanes[1 +: 0]", + "nonpositive interface array selection width", + ), + ("lanes[index +: 2]", "nonconstant interface array selection"), + ("lanes[0][0]", "too many interface array selections"), + ("lanes[3:1]", "interface array dimension mismatch"), + ( + "lanes[128'h7fffffffffffffffffffffffffffffff +: 2]", + "selection bound overflow", + ), + ] { + let source = format!( + r#" + interface Lane; + logic value; + modport reader(input value); + endinterface + module Reader(Lane.reader ports[2], output wire y); + assign y=ports[0].value ^ ports[1].value; + endmodule + module Top(input int index, output wire y); + Lane lanes[3:0](); + for(genvar n=0;n<4;n++) begin: g + assign lanes[n].value=1'b0; + end + Reader r(.ports({selection}),.y(y)); + endmodule + "# + ); + let error = Simulator::from_sv_sources( + vec![(source.as_str(), Path::new("invalid_interface_slice.sv"))], + "Top", + ) + .build_interpreter() + .expect_err(selection) + .to_string(); + assert!(error.contains(expected), "{selection}: {error}"); + } +} + +#[test] +fn rejects_interface_array_slices_in_multiple_dimensions() { + let source = r#" + interface Lane; logic value; endinterface + module Reader(Lane lanes[1][1], output wire y); + assign y=lanes[0][0].value; + endmodule + module Top(output wire y); + Lane lanes[2][2](); + Reader r(.lanes(lanes[0:0][0:0]),.y(y)); + endmodule + "#; + let error = + Simulator::from_sv_sources(vec![(source, Path::new("invalid_matrix_slice.sv"))], "Top") + .build_interpreter() + .err() + .unwrap() + .to_string(); + assert!( + error.contains("interface array slices in multiple dimensions"), + "{error}" + ); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 809fe25b00b..95b9a964de4 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -784,3 +784,88 @@ fn runtime_error_before_a_commit_leaves_no_held_writes() { } } } + +/// The baselines of waits on a counted variable survive a state file: a +/// simulation loaded between two pulses of `y` wakes the waiters as the +/// uninterrupted one does, and saves the same baselines again. +#[test] +fn counted_wait_baselines_survive_a_state_file() { + let source = r#" + module Top(output int n, r); + timeunit 1ns / 1ns; + bit a, b, c; + logic y; + always_comb begin y = 0; if (a) y = 1; c = b; end + initial #1 forever begin @(y); n++; end + initial #1 forever begin @(posedge y); r++; end + initial begin + #2 a = 1; + #1 b = 1; + #1 b = 0; + #1 b = 1; + #1 a = 0; + end + endmodule + "#; + let build = |four_state: bool| { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("counted_state.sv"))], + "Top", + ) + .four_state(four_state) + .build() + .unwrap() + }; + let through_bytes = |file: &celox::StateFile| { + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + celox::StateFile::read_from(bytes.as_slice()).unwrap() + }; + for four_state in [false, true] { + let counts = |sim: &mut celox::Simulation| { + ["n", "r"].map(|name| { + let signal = sim.signal(name); + sim.get(signal) + }) + }; + let mut whole = build(four_state); + whole.run_until(10).unwrap(); + let expected = counts(&mut whole); + assert_eq!( + expected, + [5u32.into(), 4u32.into()], + "four_state={four_state}" + ); + + let mut first = build(four_state); + first.run_until(3).unwrap(); + let file = through_bytes(&first.save_state().unwrap()); + assert!( + file.schedule + .as_ref() + .unwrap() + .processes + .waiters + .iter() + .flat_map(|waiter| &waiter.baselines) + .any(|baseline| matches!(baseline, celox::BaselineRecord::Counter { .. })), + "four_state={four_state}: `y` is counted" + ); + let mut loaded = build(four_state); + loaded.load_state(&file).unwrap(); + assert_eq!( + through_bytes(&loaded.save_state().unwrap()), + file, + "four_state={four_state}" + ); + loaded.run_until(10).unwrap(); + assert_eq!(counts(&mut loaded), expected, "four_state={four_state}"); + // A baseline taken at a check in this run saves as the loaded one. + first.run_until(4).unwrap(); + loaded = build(four_state); + let file = through_bytes(&first.save_state().unwrap()); + loaded.load_state(&file).unwrap(); + loaded.run_until(10).unwrap(); + assert_eq!(counts(&mut loaded), expected, "four_state={four_state}"); + } +} diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index a5df2eb8ac1..61cef16d016 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -105,6 +105,65 @@ fn test_native_testbench_ff_condition_reads_pre_edge_value_after_write() { ); } +/// `clk.next(n)` runs gated and divided domains on every period whose +/// inactive edge runs nothing, and leaves the clock low. +#[test] +fn test_native_testbench_next_runs_gated_and_divided_domains() { + let code = r#" + module Dut ( + clk: input '_ clock, + en : input '_ logic, + g : output '_ logic<8>, + d : output '_ logic<8>, + lvl: output '_ logic, + ) { + var a: logic<2>; + always_ff (clk) { + a = a + 2'd1; + } + let divided: '_ clock = a[0]; + always_ff (divided) { + d = d + 8'd1; + } + let gated: '_ clock = clk & en; + always_ff (gated) { + g = g + 8'd1; + } + assign lvl = clk; + } + + #[test(t)] + module t { + inst clk: $tb::clock_gen; + var en : logic; + var g : logic<8>; + var d : logic<8>; + var lvl: logic; + inst dut: Dut (clk, en, g, d, lvl); + + initial { + en = 1'b1; + clk.next(4); + $assert(g == 8'd4); + $assert(d == 8'd2); + $assert(lvl == 1'b0); + + en = 1'b0; + clk.next(3); + $assert(g == 8'd4); + $assert(d == 8'd4); + $assert(lvl == 1'b0); + $finish(); + } + } + "#; + + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + TestResult::Pass, + ); +} + #[test] fn test_native_testbench_overlapping_ff_writes_preserve_last_write() { let code = r#" diff --git a/crates/celox/tests/tick_inactive_edge.rs b/crates/celox/tests/tick_inactive_edge.rs new file mode 100644 index 00000000000..a2efcddd3dc --- /dev/null +++ b/crates/celox/tests/tick_inactive_edge.rs @@ -0,0 +1,385 @@ +//! The inactive edge of a tick stores only the level when nothing can run on +//! it, and still runs every domain that can. Each design is checked as +//! `tick_semantics` checks the host API: the timed `Simulation` of the +//! statements a host operation stands for must observe the same values, +//! unknown bits included, after every operation: +//! +//! - `set(x, v)` is `x = v;`, +//! - `edge(e, lvl)` is `s <= lvl;`, +//! - `tick(e)` is `s <= A; #H; s <= I; #L;`, +//! - `tick_events(e1..ek)` makes the moves of all their signals together. + +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{Edge, EventHandle, Simulation, Simulator}; +use num_bigint::BigUint; + +/// Inputs of every design, all one bit wide. +const INPUTS: [&str; 4] = ["clk", "clk2", "en", "rst"]; + +/// Event signals with their active levels. +const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst", 1)]; + +/// A gated clock clocking only rising edges, and combinational logic reading +/// the clock: the inactive edge of `clk` runs nothing. +const GATED: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] g, + output logic [7:0] c2, + output logic [7:0] lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge gclk or posedge rst) + if (rst) g <= 8'd0; + else g <= g + 8'd1; + always_ff @(posedge clk2 or posedge rst) + if (rst) c2 <= 8'd0; + else c2 <= c2 + 8'd1; + assign lvl = {6'd0, gclk, clk}; +endmodule +"#; + +/// A domain on the falling edge of a gated clock runs on the inactive edge. +const GATED_NEGEDGE: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] g, + output logic [7:0] ng, + output logic [7:0] lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge gclk or posedge rst) + if (rst) g <= 8'd0; + else g <= g + 8'd1; + always_ff @(negedge gclk or posedge rst) + if (rst) ng <= 8'd0; + else ng <= ng + 8'd1; + assign lvl = {7'd0, clk}; +endmodule +"#; + +/// The rising edge of `~clk` is the falling edge of `clk`. +const INVERTED: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] q, + output logic [7:0] lvl +); + logic nclk; + assign nclk = ~clk; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge nclk or posedge rst) + if (rst) q <= 8'd0; + else q <= q + 8'd1; + assign lvl = {7'd0, clk}; +endmodule +"#; + +/// A register divider; with `en` low the divided clock stays where it is. +const DIVIDER: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] d, + output logic [7:0] lvl +); + logic div; + always_ff @(posedge clk or posedge rst) + if (rst) begin + p <= 8'd0; + div <= 1'b0; + end else begin + p <= p + 8'd1; + if (en) div <= ~div; + end + always_ff @(posedge div or posedge rst) + if (rst) d <= 8'd0; + else d <= d + 8'd1; + assign lvl = {6'd0, div, clk}; +endmodule +"#; + +/// A plain clock nothing reads as data, and one a flip-flop samples. +const PLAIN: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] q +); + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge clk2 or posedge rst) + if (rst) q <= 8'd0; + else q <= {6'd0, clk2, en}; +endmodule +"#; + +#[derive(Clone, Copy, Debug)] +enum Op { + Set(&'static str, u8), + Edge(&'static str, u8), + Tick(&'static [&'static str]), +} + +fn active(name: &str) -> u8 { + EVENTS.iter().find(|(event, _)| *event == name).unwrap().1 +} + +/// The statements `op` stands for, with the half periods of a tick at 1. +fn statements(op: Op) -> String { + match op { + Op::Set(name, value) => format!("{name} = {value};"), + Op::Edge(name, level) => format!("{name} <= {level};"), + Op::Tick(names) => { + let moves = |level: fn(u8) -> u8| { + names + .iter() + .map(|name| format!("{name} <= {}; ", level(active(name)))) + .collect::() + }; + format!("{}#1; {}#1;", moves(|a| a), moves(|a| 1 - a)) + } + } +} + +type Values = Vec<(BigUint, BigUint)>; + +/// The outputs after each operation, from the timed simulation of the +/// operations' statements. Operation `k` starts at time `4k + 1`. +fn reference(dut: &str, outputs: &[&str], four_state: bool, ops: &[Op]) -> Vec { + let mut body = String::new(); + for (k, &op) in ops.iter().enumerate() { + body += &format!(" #({} - $time) {}\n", 4 * k + 1, statements(op)); + } + let top = format!( + r#" +`timescale 1ns/1ns +module Top; + logic {inputs}; + wire [7:0] {outputs}; + Dut u (.{ports}); + initial begin +{body} end +endmodule +"#, + inputs = INPUTS.join(", "), + outputs = outputs.join(", "), + ports = INPUTS + .iter() + .chain(outputs) + .copied() + .collect::>() + .join(", ."), + ); + let mut sim = Simulation::from_sv_sources( + vec![(dut, Path::new("dut.sv")), (&top, Path::new("top.sv"))], + "Top", + ) + .four_state(four_state) + .build() + .unwrap(); + (0..ops.len()) + .map(|k| { + sim.run_until(4 * k as u64 + 4).unwrap(); + outputs + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get_four_state(signal) + }) + .collect() + }) + .collect() +} + +fn hosted( + dut: &str, + outputs: &[&str], + four_state: bool, + inactive_runs: bool, + ops: &[Op], +) -> Vec { + let mut sim = Simulator::from_sv_sources(vec![(dut, Path::new("dut.sv"))], "Dut") + .four_state(four_state) + .build() + .unwrap(); + let clk = sim.event("clk"); + assert_eq!( + sim.event_edges()[clk.id()].inactive_runs, + inactive_runs, + "whether the inactive edge of clk can run a domain" + ); + ops.iter() + .map(|&op| { + match op { + Op::Set(name, value) => { + let signal = sim.signal(name); + sim.set(signal, value); + } + Op::Edge(name, level) => { + let event = sim.event(name); + let edge = if level == 1 { + Edge::Rising + } else { + Edge::Falling + }; + sim.edge(event, edge).unwrap(); + } + Op::Tick([name]) => { + let event = sim.event(name); + sim.tick(event).unwrap(); + } + Op::Tick(names) => { + let events: Vec<_> = names.iter().map(|name| sim.event(name)).collect(); + sim.tick_events(&events).unwrap(); + } + } + outputs + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get_four_state(signal) + }) + .collect() + }) + .collect() +} + +/// Operations before [`RESET`] leave the counters unknown, and the timed +/// simulation's start-up settle may already clock them; they are not +/// compared. +const RESET: usize = 4; + +fn check(dut: &str, outputs: &[&str], inactive_runs: bool, ops: &[Op]) { + for four_state in [false, true] { + let expected = reference(dut, outputs, four_state, ops); + let actual = hosted(dut, outputs, four_state, inactive_runs, ops); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate().skip(RESET) { + assert_eq!( + actual, expected, + "four_state {four_state}: after {:?} (operation {k}), outputs {outputs:?}", + ops[k] + ); + } + } +} + +/// Reset, then periods with the gate open, closed and open again. The clock +/// starts unknown in a four-state design. +const PERIODS: &[Op] = &[ + Op::Set("en", 0), + Op::Set("clk2", 0), + Op::Edge("rst", 1), + Op::Edge("rst", 0), + Op::Tick(&["clk"]), + Op::Set("en", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Set("en", 0), + Op::Tick(&["clk"]), + Op::Set("en", 1), + Op::Tick(&["clk"]), +]; + +/// A gated clock that clocks only rising edges: combinational logic reading +/// the clock and the gated clock sees both low after every tick, and ticks +/// coincident with another clock still gate. +#[test] +fn a_gated_rising_edge_domain_leaves_the_inactive_edge_quiet() { + let mut ops = PERIODS.to_vec(); + ops.extend([ + Op::Tick(&["clk", "clk2"]), + Op::Set("en", 0), + Op::Tick(&["clk", "clk2"]), + Op::Set("en", 1), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + ]); + check(GATED, &["p", "g", "c2", "lvl"], false, &ops); +} + +/// A domain on the falling edge of a gated clock runs on every tick that +/// opens the gate. +#[test] +fn a_gated_falling_edge_domain_runs_on_every_tick() { + check(GATED_NEGEDGE, &["p", "g", "ng", "lvl"], true, PERIODS); +} + +/// The rising edge of an inverted clock runs on the inactive edge. +#[test] +fn an_inverted_clock_domain_runs_on_the_inactive_edge() { + check(INVERTED, &["p", "q", "lvl"], true, PERIODS); +} + +/// A divided domain runs when the divider rises and not while the divider +/// holds. +#[test] +fn a_divided_domain_runs_only_when_the_divider_rises() { + check(DIVIDER, &["p", "d", "lvl"], false, PERIODS); +} + +/// A plain tick whose level stores nothing observes is one run of the +/// domain; a domain that samples its clock still sees it high. A tick from +/// an unknown or active level still moves the signal. +#[test] +fn a_plain_tick_skips_only_unobservable_level_stores() { + for four_state in [false, true] { + let sim = Simulator::from_sv_sources(vec![(PLAIN, Path::new("dut.sv"))], "Dut") + .four_state(four_state) + .build() + .unwrap(); + let level_read = |name| sim.event_edges()[sim.event(name).id()].level_read; + assert!(!level_read("clk"), "nothing reads the level of clk"); + assert!(level_read("clk2"), "a flip-flop samples clk2"); + } + let mut ops = PERIODS.to_vec(); + ops.extend([ + Op::Tick(&["clk2"]), + Op::Set("en", 1), + Op::Tick(&["clk2"]), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Edge("clk2", 1), + Op::Tick(&["clk2"]), + ]); + check(PLAIN, &["p", "q"], false, &ops); +} diff --git a/crates/celox/tests/vcd.rs b/crates/celox/tests/vcd.rs index 0bbd3f71f5e..12b3bb60c99 100644 --- a/crates/celox/tests/vcd.rs +++ b/crates/celox/tests/vcd.rs @@ -195,6 +195,63 @@ mod tests { } out } + + /// A tick whose two level stores nothing observes skips them; a VCD of + /// ticks is the same as one of periods whose levels are stored. + #[test] + fn test_vcd_of_ticks_matches_stored_periods() { + let code = r#" + module Top ( + clk: input clock, + rst: input reset, + cnt: output logic<8>, + ) { + always_ff (clk, rst) { + if_reset { + cnt = 0; + } else { + cnt += 1; + } + } + } + "#; + for four_state in [false, true] { + let ticked_path = format!("test_vcd_ticks_{four_state}.vcd"); + let stored_path = format!("test_vcd_stored_periods_{four_state}.vcd"); + let run = |path: &str, stored: bool| { + let mut sim = SimulatorBuilder::new(code, "Top") + .four_state(four_state) + .vcd(path) + .build() + .unwrap(); + let clk = sim.event("clk"); + assert!( + !sim.event_edges()[celox::EventHandle::id(&clk)].level_read, + "nothing reads the level of clk" + ); + let rst = sim.signal("rst"); + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + for period in 0..6u64 { + if period == 2 { + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + } + if stored { + sim.active_edge(clk).unwrap(); + sim.inactive_edge(clk).unwrap(); + } else { + sim.tick(clk).unwrap(); + } + sim.dump(10 * period); + } + sim.flush_vcd().unwrap(); + }; + run(&ticked_path, false); + run(&stored_path, true); + assert_eq!(without_date(&ticked_path), without_date(&stored_path)); + fs::remove_file(ticked_path).unwrap(); + fs::remove_file(stored_path).unwrap(); + } + } } mod activity {