diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 088c230da03..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(), @@ -1804,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 3597877c643..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); @@ -1654,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(); @@ -1869,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(); @@ -2014,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 @@ -2086,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, @@ -3696,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. 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/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/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 76d361f2870..cb7cff24b0f 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -403,6 +403,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) processes: Vec>, 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 d475dd0eadc..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 { 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/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/flake.lock b/flake.lock index bc239f01aa4..d7f1e5b8c23 100644 --- a/flake.lock +++ b/flake.lock @@ -50,17 +50,17 @@ ] }, "locked": { - "lastModified": 1792653800, - "narHash": "sha256-E8zFJilWlORqzIUJizyhZ/0WKBOizuM6s1nRSgPRomo=", + "lastModified": 1792739799, + "narHash": "sha256-M2rr/yPbTHvgAzCyZ+zHJHflFM0XU7t42Sw2skA3TQM=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2", + "rev": "b0829a2cc9f7b596583331d78a942c1e5170d8a0", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2", + "rev": "b0829a2cc9f7b596583331d78a942c1e5170d8a0", "type": "github" } } diff --git a/flake.nix b/flake.nix index aa84fea5b01..f4bdf4dbf28 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2"; + url = "github:oxalica/rust-overlay/b0829a2cc9f7b596583331d78a942c1e5170d8a0"; inputs.nixpkgs.follows = "nixpkgs"; }; };