diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7cb1572d8e2..e85b91d5cc7 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -216,6 +216,11 @@ pub struct RuntimeCombObserver { pub site_id: u32, pub activation_group: u32, pub sensitivity: Vec>, + /// Occurrence counters of the sensitivity: a counter that moved since + /// the last check activates the observer even when the settled value + /// equals the last one. + #[serde(default = "Vec::new")] + pub occurrence_counters: Vec, pub written_inputs: Vec, } @@ -826,6 +831,11 @@ pub struct RuntimeSchema { pub process_origins: Vec, /// Counted signals and their occurrence counters. pub watches: Vec>, + /// Bit ranges whose changes bump an occurrence counter: the sensitivity + /// of change-gated combinational processes and comb observers. Design + /// code counts its own writes; the runtime counts the writes it makes, + /// such as the nonblocking updates it publishes. + pub occurrence_probes: Vec<(VarAtomBase, A)>, /// Wait sites of the process kernels. A process's sites appear in the /// order of its local site indices. pub wait_sites: Vec>, @@ -999,6 +1009,7 @@ impl Default for RuntimeSchema { processes: Vec::new(), process_origins: Vec::new(), watches: Vec::new(), + occurrence_probes: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), host_request_sites: Vec::new(), @@ -1054,6 +1065,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 +1166,7 @@ impl Default for EventTopology { combinational_derived: BTreeMap::new(), independent_derived: BTreeSet::new(), combinationally_read: BTreeSet::new(), + level_unread_by_domain: BTreeSet::new(), } } } @@ -1797,6 +1815,7 @@ mod tests { id: initial.address, access: BitAccess { lsb: 3, msb: 7 }, }], + occurrence_counters: Vec::new(), written_inputs: vec![initial.address], }); runtime.testbench_read_roots.insert(initial.address); diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index e492266cc18..fa96b6ed9e5 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -26,12 +26,15 @@ pub struct ScheduleModel { /// Counted signals with all their counters, and the canonical domains /// each counter triggers, in [`RuntimeSchema::watches`] order. pub counted: Vec>, + /// Bit ranges whose changes bump an occurrence counter + /// ([`RuntimeSchema::occurrence_probes`]). + pub probes: Vec<(crate::VarAtomBase, A)>, /// Process kernels in kernel order. pub processes: Vec>, /// Signals a wait watches, which the host's writes must be logged for. pub waited: Vec, - /// The design has process kernels or counted signals. Without either, - /// a round of the scheduler is the batch step. + /// The design has process kernels. Without them, a round of the + /// scheduler is the batch step, which also checks counted signals. pub timed: bool, /// Some nonblocking site has a pending flag. pub has_pending_nba_sites: bool, @@ -134,8 +137,9 @@ impl ScheduleModel { Self { events: design.events.clone(), kinds: design.event_kinds(), - timed: !processes.is_empty() || !counted.is_empty(), + timed: !processes.is_empty(), counted, + probes: schema.occurrence_probes.clone(), processes, waited, has_pending_nba_sites, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 6a8f45347bb..1fe600a2173 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -738,6 +738,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) .collect(); let declaration_probes; + let occurrence_probes: Vec<(VarAtomBase, AbsoluteAddr)>; let counted = { // Flip-flop event domains and the aliases that resolve to them. let event_addresses: HashSet = eval_apply_ffs @@ -774,6 +775,13 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } } + for observer in &comb_observers { + for &(source, counter) in &observer.sensitivity_counters { + if !probes.contains(&(source, counter)) { + probes.push((source, counter)); + } + } + } // A direct wire/port connection carries occurrences as well as its // settled value. Preserve them when a kernel writes the upstream // object twice before the copy path is evaluated. Only equal-width, @@ -821,6 +829,13 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } declaration_probes = probes.clone(); + occurrence_probes = probes.clone(); + // Signals a flip-flop evaluation may store twice in its working + // state. Each store is an update event (IEEE 1800-2023 4.3, 10.4.2) + // that the commit of the final value alone would not show; the + // working state is seeded with the stable value first, so a store + // compares with the value its update replaces. + let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); for (source, counter) in probes { let width = source.access.msb - source.access.lsb + 1; let four_state = four_state && variables[&source.id].1; @@ -867,6 +882,27 @@ pub fn schedule_symbolic_rtl_reporting_loops( crate::watch::instrument_unit(&mut part.apply, code); } } + if ff_multi_stored.contains(&source.id) { + let working = + |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let code = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( + || crate::watch::WatchCode { + signal: working(source.id), + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, stable(counter))], + }, + ) + }; + for_each_ff_evaluation( + &mut eval_apply_ffs, + &mut eval_only_ffs, + &mut parallel_ff_units, + |unit| instrument_stores(unit, code), + ); + } for path in &mut comb_blocks { if let LogicPathTarget::Process { unit, .. } = &mut path.target { crate::watch::instrument_unit(unit, |address| { @@ -899,7 +935,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .flatten() .flat_map(|split| [&mut split.active, &mut split.nba]), ); - instrument_counted_signals( + let counted = instrument_counted_signals( &timing, counted, &variables, @@ -907,7 +943,43 @@ pub fn schedule_symbolic_rtl_reporting_loops( &mut processes, &mut comb_blocks, ff_units, - ) + ); + // A counted signal without pending slots (a design without waits) + // is counted at its commit, which sees only the final value. Count + // each store of an evaluation that may store it twice as well. + let pending: HashSet = timing + .pending_slots + .iter() + .map(|slots| slots.signal) + .collect(); + for (signal, slots) in &counted { + if !ff_multi_stored.contains(signal) || pending.contains(signal) { + continue; + } + let (width, is_4state) = variables[signal]; + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let code = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( + || crate::watch::WatchCode { + signal: regioned(WORKING_REGION, *signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }, + ) + }; + for_each_ff_evaluation( + &mut eval_apply_ffs, + &mut eval_only_ffs, + &mut parallel_ff_units, + |unit| instrument_stores(unit, code), + ); + } + counted }; // Combinational values and the variables they are computed from. let comb_sources = comb_sources(&comb_blocks, &global_arena); @@ -956,6 +1028,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( @@ -1653,6 +1726,11 @@ pub fn schedule_symbolic_rtl_reporting_loops( site_id: observer.site_id, activation_group: observer.activation_group, sensitivity: observer.sensitivity.clone(), + occurrence_counters: observer + .sensitivity_counters + .iter() + .map(|&(_, counter)| counter) + .collect(), written_inputs: observer.written_inputs.clone(), }) .collect(); @@ -1802,6 +1880,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)| { @@ -1867,6 +1946,11 @@ pub fn schedule_symbolic_rtl_reporting_loops( access: atom.access, }) .collect(), + occurrence_counters: observer + .occurrence_counters + .into_iter() + .map(project) + .collect(), written_inputs: observer.written_inputs.into_iter().map(project).collect(), }) .collect(); @@ -2012,6 +2096,24 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain(host_request_sites.iter().flat_map(|site| site.slots())) .collect(); let declaration_startup = declaration_startup.map(|startup| startup.map(project)); + let occurrence_probes: Vec<(VarAtomBase, StateAddr)> = occurrence_probes + .into_iter() + .map(|(source, counter)| { + ( + VarAtomBase { + id: project(source.id), + access: source.access, + }, + project(counter), + ) + }) + .collect(); + // The runtime counts the occurrences its own writes cause. + timing_read_roots.extend( + occurrence_probes + .iter() + .flat_map(|(source, counter)| [source.id, *counter]), + ); if let Some(startup) = &declaration_startup { timing_read_roots.extend( startup @@ -2084,6 +2186,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( processes: process_slots, process_origins, watches, + occurrence_probes, wait_sites, nba_sites, host_request_sites, @@ -3694,6 +3797,65 @@ fn relocate_timing( metadata } +type FfUnits = HashMap>>; +type FfParts = HashMap)>>; + +/// The signals some flip-flop evaluation may store twice in its working +/// state in one execution. +fn ff_multi_stored( + eval_apply_ffs: &FfUnits, + eval_only_ffs: &FfUnits, + parallel_ff_units: &FfParts, +) -> HashSet { + let working = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION).then(|| address.absolute_addr()) + }; + eval_apply_ffs + .values() + .chain(eval_only_ffs.values()) + .flatten() + .chain( + parallel_ff_units + .values() + .flatten() + .map(|(_, part)| &part.evaluate), + ) + .flat_map(|unit| crate::watch::multi_store_only_candidates(unit, working)) + .collect() +} + +/// [`crate::watch::instrument_unit`] for the stores alone: the commits that +/// seed a flip-flop evaluation's working state are not writes of the +/// process. +fn instrument_stores( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&RegionedAbsoluteAddr) -> Option>, +) { + crate::watch::instrument_writes(unit, |instruction| match instruction { + SIRInstruction::Store(address, ..) => watch_for(address), + _ => None, + }); +} + +/// Run `f` on every flip-flop evaluation. +fn for_each_ff_evaluation( + eval_apply_ffs: &mut FfUnits, + eval_only_ffs: &mut FfUnits, + parallel_ff_units: &mut FfParts, + mut f: impl FnMut(&mut ExecutionUnit), +) { + for unit in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + .flatten() + { + f(unit); + } + for (_, part) in parallel_ff_units.values_mut().flatten() { + f(&mut part.evaluate); + } +} + /// Counted signals: those a unit may store twice between two runtime checks /// (a frontend declared counters for them) and that a flip-flop domain or a /// wait watches, by signal. @@ -4629,6 +4791,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 +5187,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 +5255,7 @@ fn analyze_clock_dependencies( combinational_derived, independent_derived, combinationally_read, + level_unread_by_domain, } } diff --git a/crates/celox-frontend-core/src/symbolic/flattening.rs b/crates/celox-frontend-core/src/symbolic/flattening.rs index 878f6df13bf..d12fe533003 100644 --- a/crates/celox-frontend-core/src/symbolic/flattening.rs +++ b/crates/celox-frontend-core/src/symbolic/flattening.rs @@ -1050,6 +1050,16 @@ fn convert_comb_observer< .iter() .map(|v| VarAtomBase::new(f(&v.id), v.access.lsb, v.access.msb)) .collect(), + sensitivity_counters: observer + .sensitivity_counters + .iter() + .map(|(v, counter)| { + ( + VarAtomBase::new(f(&v.id), v.access.lsb, v.access.msb), + f(counter), + ) + }) + .collect(), local_inputs: observer .local_inputs .iter() diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 1b5e271996d..6043ddcbc9a 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -373,6 +373,19 @@ pub fn multi_store_candidates( }) } +/// Like [`multi_store_candidates`], over the stores alone. A flip-flop +/// evaluation seeds its working state with commits; only its stores are +/// writes of the process. +pub fn multi_store_only_candidates( + unit: &ExecutionUnit, + key: impl Fn(&A) -> Option, +) -> Vec { + multi_write_candidates(unit, |instruction| match instruction { + SIRInstruction::Store(address, ..) => key(address), + _ => None, + }) +} + /// [`multi_store_candidates`] with the written key of each instruction /// given by `key`, for callers that count only some kinds of writes. pub fn multi_write_candidates( diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 39b1094cd7a..605b02f32bb 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -3733,6 +3733,14 @@ pub(crate) fn attach_instance_glue( )); } } + // A flip-flop evaluation stores each update in the working state; two + // of one execution are two update events (IEEE 1800-2023 4.3, 10.4.2). + for unit in module.eval_only_ff_blocks.values() { + candidates.extend(celox_frontend_core::watch::multi_store_only_candidates( + unit, + |address| (address.region == WORKING_REGION).then_some(address.var_id), + )); + } module.arena = arena; // Combinational event sites follow the flip-flop ones, including the // events run-time loops emit. @@ -4430,10 +4438,35 @@ fn lower_comb_processes( .collect(); } } - // The sites of one process activate together. + // The sites of one process activate together. Every change of a + // source schedules the process (IEEE 1800-2023 4.3), also one that a + // later write of the same time slot undoes, so each sensitivity atom + // counts its occurrences. let base = sites.len() as u32; + let mut counters: Vec<(VarAtomBase, SourceVarId)> = Vec::new(); for mut observer in std::mem::take(&mut comb.observers) { observer.activation_group = base; + for atom in &observer.sensitivity { + if !counters.iter().any(|(counted, _)| counted == atom) { + let (counter, _) = comb.m.temp( + "comb_occurrences", + celox_design::EVENT_COUNTER_WIDTH, + false, + false, + ); + counters.push((*atom, counter)); + } + } + observer.sensitivity_counters = observer + .sensitivity + .iter() + .map(|atom| { + *counters + .iter() + .find(|(counted, _)| counted == atom) + .expect("a counter for every sensitivity atom") + }) + .collect(); observers.push(observer); } sites.append(&mut comb.sites); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 17c328b0190..cc10985fc16 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3624,6 +3624,7 @@ impl<'p, 'a> Comb<'p, 'a> { args: captured, loop_runner: None, sensitivity: Vec::new(), + sensitivity_counters: Vec::new(), local_inputs, observed_inputs: observed .into_iter() diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 5125c4af4cd..2c9bcdd35ec 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -373,6 +373,16 @@ fn map_observer( .collect::>()?, loop_runner: observer.loop_runner.map(&mut map_node).transpose()?, sensitivity: map_atoms(&observer.sensitivity), + sensitivity_counters: observer + .sensitivity_counters + .iter() + .map(|(atom, counter)| { + ( + VarAtomBase::new(ids[&atom.id], atom.access.lsb, atom.access.msb), + ids[counter], + ) + }) + .collect(), local_inputs: observer .local_inputs .iter() diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 94cfa90963d..c4623e4f940 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -342,6 +342,7 @@ fn collect_system_function_effect( args: observer_args, loop_runner: None, sensitivity: Vec::new(), + sensitivity_counters: Vec::new(), local_inputs, observed_inputs: observed_inputs.into_iter().collect(), position_inputs: position_inputs.into_iter().collect(), 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/schedule.rs b/crates/celox-runtime/src/schedule.rs index e555082d04d..4085f6d7977 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -6,7 +6,7 @@ use fxhash::{FxHashMap, FxHashSet}; use crate::{ AbsoluteAddr, EventDomain, EventInfo, HostWatch, SignalRef, backend::{EventHandle, SimBackend}, - timing::{CountedDomainRefs, CountedRefs, NbaSiteRefs, ProcessRefs, TermRefs}, + timing::{CountedDomainRefs, CountedRefs, NbaSiteRefs, ProbeRefs, ProcessRefs, TermRefs}, }; /// The facts a timed simulation keeps but never changes: event signals, @@ -24,13 +24,18 @@ pub struct ResolvedSchedule { /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, + /// Each counter that triggers a domain: the counter, the event id, and + /// where its last seen value is kept ([`ProcessState::domain_counters`]). + pub(crate) counted_triggers: Vec, + /// Occurrence probes by the offset of their signal. + pub(crate) probes_by_offset: FxHashMap>, /// Whether any process has a nonblocking site with a pending flag. pub(crate) has_pending_nba_sites: bool, /// Per event ID, the event IDs of clocks computed combinationally from /// the event's signal. Empty when the design has none. pub(crate) combinational_derived: Vec>, - /// The design has process kernels or counted signals. Without either, a - /// round is exactly the batch step and skips every process check. + /// The design has process kernels. Without them, a round is the batch + /// step and skips every process check. pub(crate) timed: bool, /// Canonical event IDs whose evaluation commits their blocking results. pub(crate) active_commits: bit_set::BitSet, @@ -221,6 +226,34 @@ impl ResolvedSchedule { .enumerate() .map(|(index, counted)| (counted.refs.signal.offset, index)) .collect(); + let counted_triggers = counted + .iter() + .enumerate() + .flat_map(|(index, counted)| { + counted + .domains + .iter() + .map(move |&(id, kind)| CountedTrigger { + counter: counted.refs.counter(kind), + id, + seen: (index, crate::timing::kind_index(kind)), + }) + }) + .collect(); + let mut probes_by_offset: FxHashMap> = FxHashMap::default(); + for (source, counter) in &model.probes { + let probe = ProbeRefs { + lsb: source.access.lsb, + msb: source.access.msb, + counter: resolve(counter), + }; + let probes = probes_by_offset + .entry(resolve(&source.id).offset) + .or_default(); + if !probes.contains(&probe) { + probes.push(probe); + } + } Self { topo_signals, domain_kinds, @@ -230,6 +263,8 @@ impl ResolvedSchedule { processes, counted, counted_by_offset, + counted_triggers, + probes_by_offset, has_pending_nba_sites: model.has_pending_nba_sites, combinational_derived, timed: model.timed, @@ -273,6 +308,15 @@ impl ResolvedSchedule { } } +/// A counter that triggers a domain. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CountedTrigger { + pub counter: SignalRef, + pub id: usize, + /// The index of the counted signal and of the counter kind. + pub seen: (usize, usize), +} + fn counted_refs( backend: &B, counted: &celox_design::schedule::CountedModel, diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 0972bd60d3a..449175c28cc 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -1,12 +1,17 @@ -//! The round of a design without processes and counted signals, and the -//! stable-edge helpers it calls, kept in one module. +//! The round of a design without processes, and the stable-edge helpers it +//! calls, kept in one module. use bit_set::BitSet; use celox_design::edges::{LEVEL_UNKNOWN, settled_edge}; use super::SimulationState; use super::host::SimulationExecutor; -use crate::{SignalRef, backend::SimBackend, scheduler::SimEvent, timing::Halt}; +use crate::{ + SignalRef, + backend::SimBackend, + scheduler::SimEvent, + timing::{Halt, read}, +}; /// The level of an event signal: its value bits, without the unused bits /// above its width that share its storage byte. Backends need not keep those @@ -101,9 +106,10 @@ impl SimulationState { } } - /// The round of a design without processes and counted signals: the - /// batch step as it was before process rounds, kept apart from - /// [`Self::step_round`] so that such designs run its code unchanged. + /// The round of a design without processes: the batch step as it was + /// before process rounds, kept apart from [`Self::step_round`] so that + /// such designs run its code unchanged. Counted signals add only a + /// check of their counters after each evaluation. pub(super) fn batch_round( &mut self, executor: &mut E, @@ -116,8 +122,21 @@ impl SimulationState { self.scheduler.time = current_time; let num_events = executor.backend().num_events(); + let counted = !self.model.counted.is_empty(); for event in &events_to_process { - executor.backend_mut().set(event.signal, event.next_val); + let backend = executor.backend_mut(); + match counted + .then(|| self.model.counted_by_offset.get(&event.signal.offset)) + .flatten() + { + Some(&counted) => { + let old = read(backend, event.signal); + backend.set(event.signal, event.next_val); + let new = read(backend, event.signal); + self.model.counted[counted].refs.bump(backend, &old, &new); + } + None => backend.set(event.signal, event.next_val), + } } let mut triggered_domains = BitSet::with_capacity(num_events); @@ -181,6 +200,9 @@ impl SimulationState { // with the edge) gives a further edge, as the update events of the // NBA region do. let mut edge_approved: Option = None; + if counted { + self.mark_counted_domains_in_batch(executor.backend_mut(), &mut edge_approved); + } for &source in &gating_sources { for index in 0..self.model.combinational_derived[source].len() { let id = self.model.combinational_derived[source][index]; @@ -230,6 +252,12 @@ impl SimulationState { if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); } + if counted { + self.mark_counted_domains_in_batch( + executor.backend_mut(), + &mut edge_approved, + ); + } comb_already_done = true; break; } @@ -301,6 +329,9 @@ impl SimulationState { if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); } + if counted { + self.mark_counted_domains_in_batch(executor.backend_mut(), &mut edge_approved); + } } } diff --git a/crates/celox-runtime/src/simulation/edges.rs b/crates/celox-runtime/src/simulation/edges.rs index 25d14024a09..d39c37cb958 100644 --- a/crates/celox-runtime/src/simulation/edges.rs +++ b/crates/celox-runtime/src/simulation/edges.rs @@ -152,6 +152,28 @@ impl SimulationState { } } + /// Like [`Self::mark_counted_domains`], for the batch round: a counted + /// occurrence is an edge even where the settled levels show none, so + /// the marked domains are added to `approved`. + pub(super) fn mark_counted_domains_in_batch( + &mut self, + backend: &mut B, + approved: &mut Option, + ) { + for trigger in &self.model.counted_triggers { + let value: u32 = backend.get_as(trigger.counter); + let (index, kind) = trigger.seen; + let seen = &mut self.process_state.domain_counters[index][kind]; + if value != *seen { + *seen = value; + backend.mark_triggered_bit(trigger.id); + approved + .get_or_insert_with(Default::default) + .insert(trigger.id); + } + } + } + /// Mark the domains a scheduled or process-driven value of an event /// signal triggers, against the values of the last settled round. #[inline] diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index bccba803ea5..813b446c1a2 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -1,4 +1,4 @@ -//! Rounds of a time slot with processes or counted signals: settling, +//! Rounds of a time slot with processes: settling, //! derived-clock edges, domains evaluated before an inactive region and //! their publication. diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 1bb95a744e9..301f74432ac 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -95,18 +95,33 @@ impl SimulationState { signal: SignalRef, write: impl FnOnce(&mut B), ) { - if self.model.counted.is_empty() && self.process_state.waiters.is_empty() { + if self.model.counted.is_empty() + && self.model.probes_by_offset.is_empty() + && self.process_state.waiters.is_empty() + { write(backend); return; } - match self.model.counted_by_offset.get(&signal.offset).copied() { - Some(counted) => { - let old = read(backend, signal); - write(backend); - let new = read(backend, signal); + let counted = self.model.counted_by_offset.get(&signal.offset).copied(); + let probes = self.model.probes_by_offset.get(&signal.offset); + if counted.is_none() && probes.is_none() { + write(backend); + } else { + let old = read(backend, signal); + write(backend); + let new = read(backend, signal); + if let Some(counted) = counted { self.model.counted[counted].refs.bump(backend, &old, &new); } - None => write(backend), + // One counter can observe several ranges of the signal; a write + // is one occurrence. + let mut bumped: Vec = Vec::new(); + for probe in probes.into_iter().flatten() { + if !bumped.contains(&probe.counter) && probe.changed(&old, &new) { + probe.bump(backend); + bumped.push(probe.counter); + } + } } if !self.process_state.waiters.is_empty() { self.observe(backend, Some(signal)); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 87b98bb827f..7c1144c404a 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -104,6 +104,29 @@ impl CountedRefs { } } +/// A bit range whose changes bump an occurrence counter. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProbeRefs { + pub lsb: usize, + pub msb: usize, + pub counter: SignalRef, +} + +impl ProbeRefs { + /// Whether the probed range differs between `old` and `new`. + pub fn changed(&self, old: &Value, new: &Value) -> bool { + let width = self.msb - self.lsb + 1; + let mask = (BigUint::from(1u8) << width) - 1u8; + let bits = |plane: &BigUint| (plane >> self.lsb) & &mask; + bits(&old.0) != bits(&new.0) || bits(&old.1) != bits(&new.1) + } + + pub fn bump(&self, backend: &mut B) { + let value: u32 = backend.get_as(self.counter); + backend.set(self.counter, value.wrapping_add(1)); + } +} + /// One term of a wait site. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TermRefs { diff --git a/crates/celox-slt/src/lib.rs b/crates/celox-slt/src/lib.rs index fe5e99b2481..ac8a9ec8a9a 100644 --- a/crates/celox-slt/src/lib.rs +++ b/crates/celox-slt/src/lib.rs @@ -56,6 +56,10 @@ pub struct CombObserver { pub args: Vec, pub loop_runner: Option, pub sensitivity: Vec>, + /// Occurrence counters of sensitivity atoms, each paired with its atom. + /// Writers count every change, so a value that changes and changes back + /// between two activation checks still activates the observer. + pub sensitivity_counters: Vec<(VarAtomBase, A)>, pub local_inputs: Vec<(A, NodeId)>, pub observed_inputs: Vec>, pub position_inputs: Vec>, 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>, pub(crate) process_origins: Vec, pub(crate) watches: Vec>, + pub(crate) occurrence_probes: Vec<(celox_design::VarAtomBase, AbsoluteAddr)>, pub(crate) wait_sites: Vec>, pub(crate) nba_sites: Vec>, pub(crate) host_request_sites: Vec>, @@ -518,6 +519,7 @@ impl NativeProgramImage { processes: self.runtime_schema.processes.clone(), process_origins: self.runtime_schema.process_origins.clone(), watches: self.runtime_schema.watches.clone(), + occurrence_probes: self.runtime_schema.occurrence_probes.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), nba_sites: self.runtime_schema.nba_sites.clone(), host_request_sites: self.runtime_schema.host_request_sites.clone(), @@ -2433,6 +2435,7 @@ fn compile_program( processes: sir.runtime().runtime_schema.processes.clone(), process_origins: sir.runtime().runtime_schema.process_origins.clone(), watches: sir.runtime().runtime_schema.watches.clone(), + occurrence_probes: sir.runtime().runtime_schema.occurrence_probes.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), host_request_sites: sir.runtime().runtime_schema.host_request_sites.clone(), diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 3e1bc73d563..ff7cbbfbb6e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -44,7 +44,10 @@ pub struct NativeProgramInstance { shared: Arc, backend: NativeBackend, runtime_event_read_seq: u64, - comb_observer_snapshots: Vec>, + comb_observer_snapshots: Vec, + /// Storage reused for the next snapshot. + comb_observer_scratch: Vec, + comb_observer_reads: crate::comb_activation::ObserverReads, comb_observer_initial_eval: bool, forced_values: crate::HashMap, } @@ -63,11 +66,17 @@ impl NativeProgramInstance { .map_err(NativeProgramLoadError::Attach)?, ); let backend = NativeBackend::from_shared(Arc::clone(&shared)); + let comb_observer_reads = crate::comb_activation::ObserverReads::new( + &backend, + &shared.program_image().runtime_schema().comb_observers, + ); let mut instance = Self { shared, backend, runtime_event_read_seq: 0, comb_observer_snapshots: Vec::new(), + comb_observer_scratch: Vec::new(), + comb_observer_reads, comb_observer_initial_eval: true, forced_values: crate::HashMap::default(), }; @@ -421,37 +430,29 @@ impl NativeProgramInstance { return result; } - let before = self.snapshot_all_comb_observers(); - let active_before = before - .iter() - .zip(&self.comb_observer_snapshots) - .map(|(current, previous)| current != previous) - .collect::>(); - let mut active_sites = vec![false; self.runtime_schema().runtime_event_sites.len()]; - for (observer, active) in self - .runtime_schema() - .comb_observers - .iter() - .zip(active_before) - { - if active || self.comb_observer_initial_eval { - for group_observer in &self.runtime_schema().comb_observers { - if group_observer.activation_group == observer.activation_group { - active_sites[group_observer.site_id as usize] = true; - } - } - } - } + let mut snapshots = std::mem::take(&mut self.comb_observer_scratch); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); + let active_sites = crate::comb_activation::active_sites( + &self.runtime_schema().comb_observers, + self.runtime_schema().runtime_event_sites.len(), + &self.comb_observer_reads, + &snapshots, + &self.comb_observer_snapshots, + self.comb_observer_initial_eval, + ); self.backend.set_comb_capture_event_enabled(&active_sites); let result = self.eval_comb_backend(); - let after = self.snapshot_all_comb_observers(); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); self.backend.set_comb_capture_event_enabled(&vec![ false; self.runtime_schema() .runtime_event_sites .len() ]); - self.comb_observer_snapshots = after; + self.comb_observer_scratch = + std::mem::replace(&mut self.comb_observer_snapshots, snapshots); self.comb_observer_initial_eval = false; self.check_fatal_events_since(start_seq, context)?; result @@ -529,36 +530,7 @@ impl NativeProgramInstance { Ok(()) } - fn snapshot_all_comb_observers(&self) -> Vec> { - self.runtime_schema() - .comb_observers - .iter() - .map(|observer| { - observer - .sensitivity - .iter() - .map(|atom| { - let signal = self.backend.resolve_signal(&atom.id); - let (value, mask) = if signal.is_4state { - self.backend.get_four_state(signal) - } else { - (self.backend.get(signal), BigUint::default()) - }; - ( - slice_biguint(&value, atom.access.lsb, atom.access.msb), - slice_biguint(&mask, atom.access.lsb, atom.access.msb), - ) - }) - .collect() - }) - .collect() - } -} - -fn slice_biguint(value: &BigUint, least: usize, most: usize) -> BigUint { - if most < least { - return BigUint::default(); + fn snapshot_all_comb_observers(&self) -> Vec { + self.comb_observer_reads.take(&self.backend) } - let width = most - least + 1; - (value >> least) & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) } diff --git a/crates/celox/src/comb_activation.rs b/crates/celox/src/comb_activation.rs new file mode 100644 index 00000000000..293f2e5eecf --- /dev/null +++ b/crates/celox/src/comb_activation.rs @@ -0,0 +1,185 @@ +//! Activation of combinational observers: a process is observed again when +//! the values of its sensitivity, or the occurrence counters of those +//! values, differ from their last snapshot. +//! +//! The reads are resolved once. A range of a signal of at most 64 bits is +//! read as a word; only wider signals go through `BigUint`. + +use num_bigint::BigUint; + +use crate::backend::{SimBackend, get_byte_size}; +use celox_design::RuntimeCombObserver; +use celox_runtime::{AbsoluteAddr, SignalRef}; + +#[derive(Clone, Debug)] +enum Read { + /// Bits `lsb..lsb + width` of a signal of at most 64 bits, with its + /// mask plane when the signal is held in four-state form. + Word { + value: SignalRef, + mask: Option, + lsb: usize, + bits: u64, + }, + Wide { + signal: SignalRef, + lsb: usize, + msb: usize, + }, + Counter(SignalRef), +} + +/// The resolved reads of every observer, in schema order. +#[derive(Clone, Debug, Default)] +pub(crate) struct ObserverReads { + observers: Vec>, + /// Each observer's activation group, numbered densely from 0. + groups: Vec, + group_count: usize, +} + +/// The values one observer's reads returned. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct ObserverSnapshot { + words: Vec, + wide: Vec<(BigUint, BigUint)>, +} + +impl ObserverReads { + pub(crate) fn new( + backend: &B, + observers: &[RuntimeCombObserver], + ) -> Self { + let four_state = backend.layout().four_state; + let reads = observers + .iter() + .map(|observer| { + observer + .sensitivity + .iter() + .map(|atom| { + let signal = backend.resolve_signal(&atom.id); + let (lsb, msb) = (atom.access.lsb, atom.access.msb); + if signal.width > 64 || signal.array_layout.is_some() || msb < lsb { + return Read::Wide { signal, lsb, msb }; + } + let mask = (four_state && signal.is_4state).then(|| SignalRef { + offset: signal.offset + get_byte_size(signal.width), + width: signal.width, + is_4state: false, + array_layout: None, + }); + Read::Word { + value: signal, + mask, + lsb, + bits: u64::MAX >> (63 - (msb - lsb)), + } + }) + .chain( + observer + .occurrence_counters + .iter() + .map(|counter| Read::Counter(backend.resolve_signal(counter))), + ) + .collect() + }) + .collect(); + let mut numbers = crate::HashMap::default(); + let groups = observers + .iter() + .map(|observer| { + let next = numbers.len(); + *numbers.entry(observer.activation_group).or_insert(next) + }) + .collect(); + Self { + observers: reads, + groups, + group_count: numbers.len(), + } + } + + /// Read every observer into `snapshots`, reusing its storage. + pub(crate) fn snapshot( + &self, + backend: &B, + snapshots: &mut Vec, + ) { + snapshots.resize_with(self.observers.len(), Default::default); + for (reads, snapshot) in self.observers.iter().zip(snapshots.iter_mut()) { + snapshot.words.clear(); + snapshot.wide.clear(); + for read in reads { + match *read { + Read::Word { + value, + mask, + lsb, + bits, + } => { + let word = |signal| (backend.get_as::(signal) >> lsb) & bits; + snapshot.words.push(word(value)); + if let Some(mask) = mask { + snapshot.words.push(word(mask)); + } + } + Read::Wide { signal, lsb, msb } => { + let (value, mask) = if signal.is_4state { + backend.get_four_state(signal) + } else { + (backend.get(signal), BigUint::default()) + }; + snapshot + .wide + .push((slice(&value, lsb, msb), slice(&mask, lsb, msb))); + } + Read::Counter(counter) => snapshot + .words + .push(u64::from(backend.get_as::(counter))), + } + } + } + } + + /// A snapshot of every observer. + pub(crate) fn take(&self, backend: &B) -> Vec { + let mut snapshots = Vec::new(); + self.snapshot(backend, &mut snapshots); + snapshots + } +} + +fn slice(value: &BigUint, lsb: usize, msb: usize) -> BigUint { + if msb < lsb { + return BigUint::default(); + } + let width = msb - lsb + 1; + (value >> lsb) & ((BigUint::from(1u8) << width) - 1u8) +} + +/// The event sites whose observers are active: an observer whose snapshot +/// differs from the last one, or every observer at the first evaluation, +/// activates the sites of its activation group. +pub(crate) fn active_sites( + observers: &[RuntimeCombObserver], + site_count: usize, + reads: &ObserverReads, + now: &[ObserverSnapshot], + last: &[ObserverSnapshot], + initial: bool, +) -> Vec { + let mut active_groups = vec![false; reads.group_count]; + for (index, &group) in reads.groups.iter().enumerate() { + if initial || now.get(index) != last.get(index) { + active_groups[group] = true; + } + } + let mut active_sites = vec![false; site_count]; + for (observer, &group) in observers.iter().zip(&reads.groups) { + if active_groups[group] { + active_sites[observer.site_id as usize] = true; + } + } + active_sites +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 9d7d34825df..f8c7072b4f3 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -9,6 +9,8 @@ mod backend; #[cfg(all(feature = "arm64-codegen", feature = "x86_64-codegen"))] compile_error!("arm64-codegen and x86_64-codegen cannot be enabled together"); #[cfg(feature = "host-runtime")] +mod comb_activation; +#[cfg(feature = "host-runtime")] mod component; #[cfg(feature = "host-runtime")] pub use component::{ diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 524a7281730..4579bc5414e 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -144,7 +144,10 @@ mod host { pub(crate) component_simulation: Option>, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, - pub(super) comb_observer_snapshots: Vec>, + pub(super) comb_observer_snapshots: Vec, + /// Storage reused for the next snapshot. + comb_observer_scratch: Vec, + comb_observer_reads: crate::comb_activation::ObserverReads, pub(super) comb_observer_initial_eval: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, @@ -374,21 +377,6 @@ mod host { } } - fn mask_width(value: BigUint, width: usize) -> BigUint { - if width == 0 { - BigUint::from(0u8) - } else { - value & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) - } - } - - fn slice_biguint(value: &BigUint, lsb: usize, msb: usize) -> BigUint { - if msb < lsb { - return BigUint::from(0u8); - } - mask_width(value >> lsb, msb - lsb + 1) - } - fn write_bits_to_memory(mem: &mut [u8], dst_bit_offset: usize, bit_width: usize, src: &[u8]) { write_bits_to_memory_from(mem, dst_bit_offset, bit_width, src, 0); } @@ -862,6 +850,10 @@ mod host { celox_runtime::build_derived_tick_plans(&backend, &schedule); let event_edges = celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); + let comb_observer_reads = crate::comb_activation::ObserverReads::new( + &backend, + &program.runtime_schema.comb_observers, + ); let mut sim = Self { backend, program, @@ -880,6 +872,8 @@ mod host { runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_event_drain_active: Arc::new(AtomicBool::new(false)), comb_observer_snapshots: Vec::new(), + comb_observer_scratch: Vec::new(), + comb_observer_reads, comb_observer_initial_eval: true, checkpoint_fingerprint: std::sync::OnceLock::new(), state_schema: std::sync::OnceLock::new(), @@ -1573,33 +1567,21 @@ mod host { return (result, events); } - let before = self.snapshot_all_comb_observers(); - let active_before: Vec = before - .iter() - .zip(&self.comb_observer_snapshots) - .map(|(now, prev)| now != prev) - .collect(); - let mut active_sites = - vec![false; self.program.runtime_schema.runtime_event_sites.len()]; - for (observer, is_active) in self - .program - .runtime_schema - .comb_observers - .iter() - .zip(active_before.iter().copied()) - { - if is_active || self.comb_observer_initial_eval { - let group = observer.activation_group; - for group_observer in &self.program.runtime_schema.comb_observers { - if group_observer.activation_group == group { - active_sites[group_observer.site_id as usize] = true; - } - } - } - } + let mut snapshots = std::mem::take(&mut self.comb_observer_scratch); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); + let active_sites = crate::comb_activation::active_sites( + &self.program.runtime_schema.comb_observers, + self.program.runtime_schema.runtime_event_sites.len(), + &self.comb_observer_reads, + &snapshots, + &self.comb_observer_snapshots, + self.comb_observer_initial_eval, + ); self.backend.set_comb_capture_event_enabled(&active_sites); let eval_result = self.backend.eval_comb(); - let after = self.snapshot_all_comb_observers(); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); let runtime_events = self.peek_backend_runtime_events_from(runtime_event_start_seq); self.backend.set_comb_capture_event_enabled(&vec![ false; @@ -1608,35 +1590,16 @@ mod host { .runtime_event_sites .len() ]); - self.comb_observer_snapshots = after; + self.comb_observer_scratch = + std::mem::replace(&mut self.comb_observer_snapshots, snapshots); self.comb_observer_initial_eval = false; (eval_result, runtime_events) } - pub(super) fn snapshot_all_comb_observers(&self) -> Vec> { - self.program - .runtime_schema - .comb_observers - .iter() - .map(|observer| { - observer - .sensitivity - .iter() - .map(|atom| { - let signal = self.backend.resolve_signal(&atom.id); - let (value, mask) = if signal.is_4state { - self.backend.get_four_state(signal) - } else { - (self.backend.get(signal), BigUint::default()) - }; - ( - slice_biguint(&value, atom.access.lsb, atom.access.msb), - slice_biguint(&mask, atom.access.lsb, atom.access.msb), - ) - }) - .collect() - }) - .collect() + pub(super) fn snapshot_all_comb_observers( + &self, + ) -> Vec { + self.comb_observer_reads.take(&self.backend) } fn fatal_comb_capture_error(&self, events: &[RawRuntimeEvent]) -> Option { @@ -1724,16 +1687,27 @@ mod host { let info = self.event_edges[event.id()]; let active = info.active_edge(); let inactive = active.opposite(); - let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); - if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { + if info.inactive_runs || !self.host_watch.is_empty() { self.active_edge(event)?; return self.inactive_edge(event); } + if let Some(Some(_)) = self.derived_ticks.get(event.id()) { + return self.tick_derived_quiet(event); + } // Everything is read before the domain runs: right after its // kernel, loads of host tables can wait behind the kernel's // stores (4 KiB aliasing), which made a period cost almost two // domain runs. The inactive edge runs nothing and only stores. let observers = !self.program.runtime_schema.comb_observers.is_empty(); + if !info.level_read + && !observers + && celox_runtime::at_level(&self.backend, &info, inactive) + { + // Nothing the domain runs reads the level, which is the + // inactive one before and after the period: both stores are + // unobservable, and the period is one run of the domain. + return self.fire(event); + } let moved = celox_runtime::move_signal( &mut self.backend, &info, @@ -1755,6 +1729,25 @@ mod host { Ok(()) } + /// [`Self::tick`] of an event with derived domains whose inactive + /// edge runs nothing: the active edge, then only the inactive level. + #[inline(never)] + fn tick_derived_quiet(&mut self, event: B::Event) -> 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 +2030,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 +2200,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/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 569d454a274..29d48e87623 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -9,7 +9,6 @@ //! state header in front of it holds host pointers and is never copied. use celox_state_layout::STATE_HEADER_SIZE; -use num_bigint::BigUint; use super::host::Simulator; use crate::backend::SimBackend; @@ -98,7 +97,7 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - comb_observer_snapshots: Vec>, + comb_observer_snapshots: Vec, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. frozen: bool, 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/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/sv_update_events.rs b/crates/celox/tests/sv_update_events.rs new file mode 100644 index 00000000000..86eb3f3aa72 --- /dev/null +++ b/crates/celox/tests/sv_update_events.rs @@ -0,0 +1,166 @@ +#![cfg(feature = "systemverilog")] +//! Every change of a variable is an update event that schedules the +//! processes sensitive to it (IEEE 1800-2023 4.3, 4.5), also a change that +//! a later write of the same time slot undoes. Nonblocking updates are +//! performed one by one, in the order they were scheduled (10.4.2). +use std::path::Path; + +macro_rules! update_events { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit a, c;\n int count;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("update_events.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + /// The `$display`s of `sim` until `time`. + fn displays(sim: &mut celox::Simulation, time: u64) -> usize { + sim.run_until(time).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| matches!(event, celox::RuntimeEvent::Display { .. })) + .count() + } + + /// The assertion failures of `sim` until `time`. + fn failures(sim: &mut celox::Simulation, time: u64) -> usize { + sim.run_until(time).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| matches!(event, celox::RuntimeEvent::AssertContinue { .. })) + .count() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + #[test] + fn blocking_writes_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_comb if (!a) $display(\"low\");\n \ + initial begin #1; a = 1; a = 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn kernel_nonblocking_updates_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_comb if (!a) $display(\"low\");\n \ + initial begin #1; a <= 1; a <= 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_nonblocking_updates_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_ff @(posedge c) begin a <= 1; a <= 0; end\n \ + always_comb if (!a) $display(\"low\");\n \ + initial #1 c = 1;", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn immediate_assertions_in_always_comb_report_each_reexecution() { + let mut sim = simulation( + " always_comb assert (a) else $error(\"a low\");\n \ + initial begin #1; a = 1; a = 0; end", + ); + assert_eq!(failures(&mut sim, 0), 1); + assert_eq!(failures(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_nonblocking_updates_that_restore_a_signal_are_events() { + let mut sim = simulation( + " always @(posedge c) begin a <= 1; a <= 0; end\n \ + initial begin @(a) count = count + 1; end\n \ + always @(posedge a) count = count + 10;\n \ + initial #1 c = 1;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "count"), 11); + assert_eq!(value(&mut sim, "a"), 0); + } + + #[test] + fn flip_flop_blocking_writes_that_restore_a_signal_are_events() { + let mut sim = simulation( + " always @(posedge c) begin a = 1; a = 0; end\n \ + initial begin @(a) count = count + 1; end\n \ + initial #1 c = 1;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "count"), 1); + } + + #[test] + fn updates_that_keep_the_value_are_no_events() { + let mut sim = simulation( + " always_ff @(posedge c) begin a <= 0; a <= 0; end\n \ + always_comb if (!a) $display(\"low\");\n \ + initial begin @(a) count = count + 1; end\n \ + initial begin #1; c = 1; #1; a = 0; a = 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 2), 0); + assert_eq!(value(&mut sim, "count"), 0); + } + + #[test] + fn updates_in_exclusive_branches_are_one_event() { + let mut sim = simulation( + " always_ff @(posedge c) if (count == 0) a <= 1; else a <= 0;\n \ + always_comb if (a) $display(\"high\");\n \ + initial #1 c = 1;", + ); + assert_eq!(displays(&mut sim, 0), 0); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_pulses_trigger_domains_without_processes() { + // No process: the batch round checks the counted signal. + let source = "module Top(input bit c);\n \ + bit d;\n int count;\n \ + always_ff @(posedge c) begin d <= 1; d <= 0; end\n \ + always_ff @(posedge d) count <= count + 1;\n\ + endmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("pulse.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.schedule("c", 1, 1).unwrap(); + sim.schedule("c", 2, 0).unwrap(); + sim.schedule("c", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "count"), 2); + assert_eq!(value(&mut sim, "d"), 0); + } + } + }; +} + +update_events!(interpreter, build_interpreter); +update_events!(cranelift, build); +#[cfg(target_arch = "x86_64")] +update_events!(native, build_native); +update_events!(wasm, build_wasm); 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 {