From b5b100e34329799de98abcc3047a0f6b9479d49c Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 13:03:41 +0900 Subject: [PATCH 1/5] feat(sv)!: judge iff-qualified event controls in processes An event control item `expr iff condition` in a process (IEEE 1800-2023 9.4.2.3) is an event only if the condition is a known 1 when the occurrence happens; an occurrence while it is false is consumed, and the wait does not watch the condition's operands. A plain always whose event has iff runs as a process; always_ff keeps rejecting iff (#452). The condition becomes the term's gate: a one-bit module variable, or the hidden $event[k] assignment of its truth value with process-local operands sampled before the process suspends. - When the term's signal and its gate are variables, every write of the signal judges the gate at the write and bumps per-term counters: SIR instrumentation of process kernels and imperative combinational processes (which keep their procedural order), process nonblocking updates in issue order, scheduled and add_clock edges, and host writes. Raw host writes are counted from the wait's baseline when the host notes them; every piece of this state lives in the wait baselines and the counters, which checkpoints and state files keep. - Other gates, and signals a flip-flop domain (#1830) or a continuous assignment writes, are judged when the runtime detects the occurrence, after combinational logic settled. - Kernels whose waits have iff conditions stay out of compiled slots. - Designs without iff run the previous wait check unchanged. Closes #1444. BREAKING CHANGE: celox_design::WaitSite has a new public field `gates` (Vec>) and celox_design::schedule::TermModel a new field `gate`; celox_runtime::timing::Baseline and celox_runtime::BaselineRecord have a new variant `Gated` (state-file baseline tag 2, which older builds reject). Change-Id: I59402e1356cac2aaf254082d1feef6348380447a --- crates/celox-design/src/lib.rs | 68 ++++ crates/celox-design/src/schedule.rs | 18 +- crates/celox-frontend-core/src/sdk.rs | 2 + .../src/symbolic/assembly.rs | 231 +++++++++--- crates/celox-frontend-core/src/watch.rs | 35 +- crates/celox-frontend-sv/src/lowering.rs | 41 ++- crates/celox-frontend-sv/src/lowering/ff.rs | 124 ++++++- .../src/lowering/procedural.rs | 2 +- crates/celox-runtime/src/schedule.rs | 94 ++++- crates/celox-runtime/src/scheduler.rs | 1 + crates/celox-runtime/src/simulation/host.rs | 25 +- .../celox-runtime/src/simulation/process.rs | 4 +- crates/celox-runtime/src/simulation/round.rs | 24 +- crates/celox-runtime/src/simulation/time.rs | 2 +- crates/celox-runtime/src/simulation/wait.rs | 344 +++++++++++++++++- crates/celox-runtime/src/state_file.rs | 36 +- crates/celox-runtime/src/timing.rs | 99 ++++- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 8 +- .../src/ast/procedural/timed_tasks.rs | 1 + .../src/ast/procedural/timing.rs | 4 +- .../celox-sv-analyzer/src/ast/validation.rs | 5 + crates/celox-sv-analyzer/src/ir.rs | 5 +- crates/celox-sv-analyzer/src/lib.rs | 1 - crates/celox-sv-analyzer/src/procedural.rs | 9 +- .../src/source_tree/tests/timing_controls.rs | 1 - crates/celox-sv-analyzer/src/tests.rs | 8 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 5 + crates/celox/src/simulation.rs | 5 + crates/celox/src/simulator/state_file.rs | 75 +++- docs/guide/systemverilog-reference.md | 29 +- docs/guide/systemverilog.md | 2 +- docs/ja/guide/external-frontends.md | 4 +- docs/ja/guide/systemverilog-reference.md | 25 +- docs/ja/guide/systemverilog.md | 2 +- 35 files changed, 1186 insertions(+), 155 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 8e9f73a561d..1aab3df485e 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -722,6 +722,55 @@ pub struct WaitSite { /// checks a condition at its resume point decides itself whether it /// continues. pub terms: Vec<(A, CounterKind)>, + /// The `iff` condition of each term, or empty when no term has one. An + /// occurrence of a term with a gate satisfies the wait only if the gate + /// is a known 1 when the occurrence happens (IEEE 1800-2023 9.4.2.3). + #[serde(default = "Vec::new")] + pub gates: Vec>>, +} + +/// The `iff` condition of a wait term: a signal whose least significant bit +/// holds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct WaitGate { + pub signal: A, + /// Counters that the writes of the term's signal bump at the write + /// itself, judging the gate there. Without them the gate is read when + /// the runtime detects the occurrence, after combinational logic + /// settled: for a gate or a signal that a continuous assignment or a + /// flip-flop drives. + pub counters: Option>, +} + +/// The occurrences of a gated term's kind that writes caused: `gated` those +/// while the gate was a known 1, `all` every one. A change of the signal +/// that neither counted, such as a raw host write, is judged with the gate +/// when it is detected. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct GateCounters { + pub gated: A, + pub all: A, +} + +impl WaitGate { + pub fn map(&self, mut map: impl FnMut(A) -> B) -> WaitGate { + WaitGate { + signal: map(self.signal), + counters: self.counters.map(|counters| GateCounters { + gated: map(counters.gated), + all: map(counters.all), + }), + } + } + + /// The gate's signal and counters. + pub fn reads(&self) -> impl Iterator { + std::iter::once(self.signal).chain( + self.counters + .into_iter() + .flat_map(|counters| [counters.gated, counters.all]), + ) + } } impl WaitSite { @@ -733,8 +782,27 @@ impl WaitSite { .iter() .map(|&(signal, kind)| (map(signal), kind)) .collect(), + gates: self + .gates + .iter() + .map(|gate| gate.as_ref().map(|gate| gate.map(&mut map))) + .collect(), } } + + /// The gate of term `index`. + pub fn gate(&self, index: usize) -> Option> { + self.gates.get(index).copied().flatten() + } + + /// The signals the runtime reads to judge the wait: its terms' signals, + /// gates and gate counters. + pub fn reads(&self) -> impl Iterator + '_ { + self.terms + .iter() + .map(|&(signal, _)| signal) + .chain(self.gates.iter().flatten().flat_map(WaitGate::reads)) + } } /// A nonblocking assignment of a process kernel. A kernel that returns diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index fa96b6ed9e5..06c31a79d8a 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -76,6 +76,8 @@ pub struct TermModel { /// Design code may write the signal. Otherwise only the host and the /// scheduler do. pub driven: bool, + /// The term's `iff` condition ([`crate::WaitSite::gates`]). + pub gate: Option>, } impl ScheduleModel { @@ -112,10 +114,18 @@ impl ScheduleModel { let terms = site .terms .iter() - .map(|&(signal, kind)| TermModel { - signal, - kind, - driven: driven.contains(&signal), + .enumerate() + .map(|(index, &(signal, kind))| { + let gate = site.gate(index); + TermModel { + signal, + kind, + // A gate without counters is judged at checks + // after settling, which only check driven terms. + driven: driven.contains(&signal) + || gate.is_some_and(|gate| gate.counters.is_none()), + gate, + } }) .collect(); processes[site.process].waits.push(terms); diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f955fda9e87..c81b695e0d2 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1366,6 +1366,7 @@ fn lower_statements( (source_id(term.signal), kind) }) .collect(), + gates: Vec::new(), }); // The runtime resumes the process at the first occurrence // after the wait began; no condition is left to check. @@ -1390,6 +1391,7 @@ fn lower_statements( .into_iter() .map(|signal| (signal, CounterKind::Changes)) .collect(), + gates: Vec::new(), }); let mut error = None; kernel.wait_level(index, |builder| { diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index e96f8bbb7fb..a044de68bec 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -12,11 +12,11 @@ use crate::{ }; use celox_design::{ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, - EventTopology, EventWatch, ExternFunction, GateOp, HostRequestSite, InitialStateData, - InitialStateValue, InstanceId, ModuleId, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, - RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, - RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase, - VariableMetadata, WORKING_REGION, WaitSite, + EventTopology, EventWatch, ExternFunction, GateCounters, GateOp, HostRequestSite, + InitialStateData, InitialStateValue, InstanceId, ModuleId, NbaSite, ProcessSlots, + RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, + RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, + TriggerSet, VarAtomBase, VariableMetadata, WORKING_REGION, WaitSite, }; use celox_sir::{ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIROffset, @@ -852,11 +852,29 @@ pub fn schedule_symbolic_rtl_reporting_loops( ) .collect(); let counted = counted_signals(&timing, &event_addresses); + // A combinational process writing the signal or the gate of a gated + // wait keeps its procedural order (IEEE 1800-2023 9.4.2.3). + let gated: HashSet = timing + .wait_sites + .iter() + .flat_map(|site| { + site.terms + .iter() + .zip(&site.gates) + .filter_map(|(&(signal, _), gate)| { + gate.as_ref() + .filter(|gate| gate.counters.is_some()) + .map(|gate| [signal, gate.signal]) + }) + }) + .flatten() + .collect(); choose_comb_alternatives( bindings, &instance_modules, &modules, &counted, + &gated, &mut comb_blocks, ); // Count sensitivity occurrences before any optimizer can coalesce @@ -961,6 +979,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( offset: offset.clone(), four_state, counters: vec![(CounterKind::Changes, stable(counter))], + gated: Vec::new(), }, ) }; @@ -993,6 +1012,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( offset: offset.clone(), four_state, counters: vec![(CounterKind::Changes, stable(counter))], + gated: Vec::new(), }, ) }; @@ -1012,11 +1032,39 @@ pub fn schedule_symbolic_rtl_reporting_loops( offset: offset.clone(), four_state, counters: vec![(CounterKind::Changes, counter)], + gated: Vec::new(), }) }); } } } + let ff_written: HashSet = eval_apply_ffs + .values() + .chain(eval_only_ffs.values()) + .chain(apply_ffs.values()) + .flatten() + .chain( + parallel_ff_units + .values() + .flatten() + .flat_map(|(_, part)| [&part.evaluate, &part.apply]), + ) + .chain( + split_commits + .values() + .flatten() + .flatten() + .flat_map(|split| [&split.active, &split.nba]), + ) + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .filter_map(|instruction| match instruction { + SIRInstruction::Store(destination, ..) + | SIRInstruction::Commit(_, destination, ..) => Some(destination.absolute_addr()), + _ => None, + }) + .collect(); + let gated = gated_terms(&mut timing, &comb_blocks, &ff_written); let ff_units = eval_apply_ffs .values_mut() .chain(eval_only_ffs.values_mut()) @@ -1038,6 +1086,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( let counted = instrument_counted_signals( &timing, counted, + &gated, &variables, four_state, &mut processes, @@ -1069,6 +1118,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .into_iter() .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) .collect(), + gated: Vec::new(), }, ) }; @@ -1691,10 +1741,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( split_commits, &comb_sources, processes.iter().map(|process| &process.kernel), - timing - .wait_sites - .iter() - .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)), + timing.wait_sites.iter().flat_map(WaitSite::reads), &events, &clock_domains, ); @@ -1860,7 +1907,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( let mut observed: HashSet = timing .wait_sites .iter() - .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)) + .flat_map(WaitSite::reads) .chain(timing.counter_slots.iter().map(|slots| slots.signal)) .chain( clock_domains @@ -2200,11 +2247,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .map(|(_, counter)| counter) .collect::>() }) - .chain( - wait_sites - .iter() - .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)), - ) + .chain(wait_sites.iter().flat_map(WaitSite::reads)) .chain( nba_sites .iter() @@ -4073,6 +4116,7 @@ fn choose_comb_alternatives( instance_modules: &HashMap, modules: &HashMap, counted: &BTreeMap>, + gated: &HashSet, comb_blocks: &mut Vec>, ) { let mut imperative = HashSet::default(); @@ -4080,11 +4124,10 @@ fn choose_comb_alternatives( for (&instance, module) in instance_modules { for alternative in &modules[module].comb_alternatives { let locate = |var_id| bindings.locate(instance, var_id); - if alternative - .candidates - .iter() - .any(|&candidate| counted.contains_key(&locate(candidate))) - { + if alternative.candidates.iter().any(|&candidate| { + let candidate = locate(candidate); + counted.contains_key(&candidate) || gated.contains(&candidate) + }) { for target in &alternative.targets { symbolic .entry(locate(target.id)) @@ -4112,64 +4155,143 @@ fn choose_comb_alternatives( }); } +/// A term with a gate counter (IEEE 1800-2023 9.4.2.3): the kind of its +/// signal's occurrences, the gate, and the counters a write bumps. +type GatedTerm = (CounterKind, AbsoluteAddr, GateCounters); + +/// The gated terms whose counters the writes of their signal bump, by +/// signal. A gate counts at the write only when the signal and the gate are +/// variables that process kernels, combinational processes, the runtime or +/// the host write: a continuous assignment is a scheduled evaluation (4.7), +/// and a flip-flop publishes its writes after the process evaluated them +/// (#1830). The other gates lose their counters, so the runtime reads them +/// when it detects the occurrence. +fn gated_terms( + timing: &mut TimingMetadata, + comb_blocks: &[LogicPath], + ff_written: &HashSet, +) -> HashMap> { + let continuous: HashSet = comb_blocks + .iter() + .filter_map(|path| match &path.target { + LogicPathTarget::Var(target) => Some(target.id), + _ => None, + }) + .collect(); + let mut gated: HashMap> = HashMap::default(); + for site in &mut timing.wait_sites { + for (&(signal, kind), gate) in site.terms.iter().zip(&mut site.gates) { + let Some(gate) = gate else { + continue; + }; + let Some(counters) = gate.counters else { + continue; + }; + if ff_written.contains(&signal) + || continuous.contains(&signal) + || continuous.contains(&gate.signal) + { + gate.counters = None; + continue; + } + gated + .entry(signal) + .or_default() + .push((kind, gate.signal, counters)); + } + } + gated +} + +/// The code that counts the writes of `signal` in its `counted` counters +/// and the counters of its `gated` terms, each object addressed through +/// `address`, or `None` if nothing counts them. +fn watch_code( + signal: AbsoluteAddr, + counted: &BTreeMap>, + gated: &HashMap>, + variables: &HashMap, + four_state: bool, + address: impl Fn(AbsoluteAddr) -> A, +) -> Option> { + let slots = counted.get(&signal); + let terms = gated.get(&signal); + if slots.is_none() && terms.is_none() { + return None; + } + let (width, is_4state) = variables[&signal]; + Some(crate::watch::WatchCode { + signal: address(signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: slots + .into_iter() + .flat_map(|slots| { + CounterKind::ALL + .into_iter() + .map(|kind| (kind, address(slots.counter(kind)))) + }) + .collect(), + gated: terms + .into_iter() + .flatten() + .map(|&(kind, gate, counters)| crate::watch::GatedCode { + kind, + gate: address(gate), + gate_four_state: four_state && variables[&gate].1, + gated: address(counters.gated), + all: address(counters.all), + }) + .collect(), + }) +} + /// Instrument the process kernels, combinational process units and -/// flip-flop units that write a `counted` signal, and return `counted`; no -/// other unit changes. +/// flip-flop units that write a `counted` signal, and the process kernels +/// and combinational process units that write the signal of a `gated` term, +/// and return `counted`; no other unit changes. fn instrument_counted_signals<'u>( timing: &TimingMetadata, counted: BTreeMap>, + gated: &HashMap>, variables: &HashMap, four_state: bool, processes: &mut [RelocatedProcess], comb_blocks: &mut [LogicPath], ff_units: impl Iterator>, ) -> BTreeMap> { - if counted.is_empty() { + if counted.is_empty() && gated.is_empty() { return counted; } - let code = |signal: AbsoluteAddr| { - let slots = counted.get(&signal)?; - let (width, is_4state) = variables[&signal]; - Some((slots, width, four_state && is_4state)) + let code = |signal: AbsoluteAddr, address: &dyn Fn(AbsoluteAddr) -> RegionedAbsoluteAddr| { + watch_code(signal, &counted, gated, variables, four_state, address) }; + let code_comb = |signal: AbsoluteAddr| { + watch_code(signal, &counted, gated, variables, four_state, |var| var) + }; + let stable = |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var); for process in processes { crate::watch::instrument_unit(&mut process.kernel, |address| { if address.region != STABLE_REGION { return None; } - let (slots, width, four_state) = code(address.absolute_addr())?; - let stable = - |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var); - Some(crate::watch::WatchCode { - signal: stable(slots.signal), - offset: celox_sir::SIROffset::Static(0), - width, - four_state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, stable(slots.counter(kind)))) - .collect(), - }) + code(address.absolute_addr(), &stable) }); } for path in comb_blocks { if let LogicPathTarget::Process { unit, .. } = &mut path.target { - crate::watch::instrument_unit(unit, |address| { - let (slots, width, four_state) = code(*address)?; - Some(crate::watch::WatchCode { - signal: slots.signal, - offset: celox_sir::SIROffset::Static(0), - width, - four_state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, slots.counter(kind))) - .collect(), - }) - }); + crate::watch::instrument_unit(unit, |address| code_comb(*address)); } } - let stable = |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var); + if counted.is_empty() { + return counted; + } + let code = |signal: AbsoluteAddr| { + let slots = counted.get(&signal)?; + let (width, is_4state) = variables[&signal]; + Some((slots, width, four_state && is_4state)) + }; let working = |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, var); let watch = |signal: AbsoluteAddr| { let (slots, width, four_state) = code(signal)?; @@ -4182,6 +4304,7 @@ fn instrument_counted_signals<'u>( .into_iter() .map(|kind| (kind, stable(slots.counter(kind)))) .collect(), + gated: Vec::new(), }) }; // A flip-flop writes its next state, and a commit publishes it. Repeated diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 6043ddcbc9a..25d926b322d 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -29,6 +29,21 @@ pub struct WatchCode { /// Whether the signal is held in four-state form. pub four_state: bool, pub counters: Vec<(CounterKind, A)>, + /// Gated wait terms on the signal, whose counters a write bumps. + pub gated: Vec>, +} + +/// A gated wait term on a watched signal (`celox_design::GateCounters`): a +/// write that is an occurrence of `kind` bumps `all`, and `gated` too if +/// the least significant bit of `gate` is a known 1 after it (IEEE +/// 1800-2023 9.4.2.3). +#[derive(Clone, Debug)] +pub struct GatedCode { + pub kind: CounterKind, + pub gate: A, + pub gate_four_state: bool, + pub gated: A, + pub all: A, } impl WatchCode { @@ -44,6 +59,7 @@ impl WatchCode { .counters() .map(|(kind, counter)| (kind, address(counter))) .collect(), + gated: Vec::new(), } } } @@ -140,7 +156,7 @@ pub fn emit_watched( // so no backend can re-read the written state for it. let old_lsb = lsb(b, old, watch.width, watch.four_state); b.emit(write); - if watch.counters.is_empty() { + if watch.counters.is_empty() && watch.gated.is_empty() { return; } let new = match stored { @@ -165,6 +181,23 @@ pub fn emit_watched( ); bump(b, counter, occurred); } + for term in &watch.gated { + let occurred = occurrence( + b, + term.kind, + (old, old_lsb), + (new, new_lsb), + watch.width, + watch.four_state, + ); + bump(b, &term.all, occurred); + let gate = load_range(b, &term.gate, SIROffset::Static(0), 1, term.gate_four_state); + let one = constant(b, 1, 1, term.gate_four_state); + // Case equality: an unknown gate does not hold. + let holds = binary(b, gate, BinaryOp::EqCase, one); + let counted = binary(b, occurred, BinaryOp::And, holds); + bump(b, &term.gated, counted); + } } /// The least significant bit of `value`, kept at the signal's width: the diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0202c7f5c14..f2861e1cce1 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4350,10 +4350,16 @@ pub(crate) fn attach_instance_glue( .values() .any(|module| !module.sim_module.nba_switches.is_empty())) .then(|| { + // A gate is read at each write of its term's signal too. let mut seeds: HashSet = module .wait_sites .iter() - .flat_map(|site| site.terms.iter().map(|&(signal, _)| signal)) + .flat_map(|site| { + site.terms + .iter() + .map(|&(signal, _)| signal) + .chain(site.gates.iter().flatten().map(|gate| gate.signal)) + }) .collect(); let triggers = module .eval_only_ff_blocks @@ -4404,6 +4410,24 @@ pub(crate) fn attach_instance_glue( ); seeds }); + // The signals and gates of this module's gated waits: a combinational + // process writing one keeps its procedural order (IEEE 1800-2023 + // 9.4.2.3 judges the gate at the write). + let gated: HashSet = module + .wait_sites + .iter() + .flat_map(|site| { + site.terms + .iter() + .zip(&site.gates) + .filter_map(|(&(signal, _), gate)| { + gate.as_ref() + .filter(|gate| gate.counters.is_some()) + .map(|gate| [signal, gate.signal]) + }) + }) + .flatten() + .collect(); let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) = lower_comb_processes( &lowered.source, @@ -4419,6 +4443,7 @@ pub(crate) fn attach_instance_glue( warnings, waits, watch_seeds.as_ref(), + &gated, ) .map_err(|error| match error { sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { @@ -5005,6 +5030,7 @@ fn lower_comb_processes( warnings: &mut Vec, waits: bool, watch_seeds: Option<&HashSet>, + gated: &HashSet, ) -> Result< ( Vec>, @@ -5109,6 +5135,7 @@ fn lower_comb_processes( process, random_seeds[&(2, index)], targets, + gated, &mut arena, ) { comb_blocks.extend(paths); @@ -5291,13 +5318,15 @@ fn watchable_variables( /// The imperative unit of an `always_comb` process lowered symbolically to /// `targets`, and its [`CombAlternative`], if the unit may store a variable -/// of the design twice in one execution. Otherwise nothing of the attempt +/// of the design twice in one execution or writes one in `gated`, the +/// signals and gates of gated waits. Otherwise nothing of the attempt /// remains in `pm`. fn lower_comb_alternative( pm: &mut procedural::ProcModule<'_>, process: &sv::ir::CombProcess, random_seed: u32, targets: Vec>, + gated: &HashSet, arena: &mut SLTNodeArena, ) -> Option<(Vec>, CombAlternative)> { let checkpoint = pm.checkpoint(); @@ -5321,11 +5350,17 @@ fn lower_comb_alternative( _ => None, }) .map(|(id, unit)| { - let candidates: Vec<_> = + let mut candidates: Vec<_> = celox_frontend_core::watch::multi_store_candidates(unit, |&address| { (!pm.is_hidden(address) && pm.var(address).array_dims.is_empty()) .then_some(address) }); + candidates.extend( + targets + .iter() + .map(|target| target.id) + .filter(|id| gated.contains(id)), + ); (id, candidates) }) .filter(|(_, candidates)| !candidates.is_empty()) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6058fabcc4a..4d845b5c445 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -18,7 +18,8 @@ mod strings; use super::procedural::*; use super::*; use celox_design::{ - CounterKind, DeferredSite, NbaPosition, NbaSite, SPARSE_WORKING_REGION, WaitSite, + CounterKind, DeferredSite, EVENT_COUNTER_WIDTH, GateCounters, NbaPosition, NbaSite, + SPARSE_WORKING_REGION, WaitGate, WaitSite, }; use celox_frontend_core::process::{NBA_POSITION_WIDTH, ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; @@ -5401,9 +5402,10 @@ impl Ff<'_, '_> { /// control samples as it begins. fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); + let mut gates = Vec::new(); let mut samples = Vec::new(); - self.event_terms(items, &mut terms, &mut samples)?; - self.suspend_on(terms, samples) + self.event_terms(items, &mut terms, &mut gates, &mut samples)?; + self.suspend_on(terms, gates, samples) } /// `@*` (IEEE 1800-2023 9.4.2.2): wait for a change of a variable that @@ -5446,19 +5448,22 @@ impl Ff<'_, '_> { .map(|name| sv::ir::EventItem { edge: sv::ir::EventEdge::Any, expr: sv::ir::Expr::Ident(name), + iff: None, }) .collect(); + let mut gates = vec![None; terms.len()]; let mut samples = Vec::new(); - self.event_terms(&locals, &mut terms, &mut samples)?; - self.suspend_on(terms, samples) + self.event_terms(&locals, &mut terms, &mut gates, &mut samples)?; + self.suspend_on(terms, gates, samples) } - /// The counter terms of `items` and the samples the process takes of - /// their expressions before it suspends. + /// The counter terms of `items`, their `iff` gates, and the samples the + /// process takes of their expressions before it suspends. fn event_terms( &mut self, items: &[sv::ir::EventItem], terms: &mut Vec<(SourceVarId, CounterKind)>, + gates: &mut Vec>>, samples: &mut Vec<(String, sv::ir::Expr)>, ) -> Result<(), sv::AnalyzerError> { for item in items { @@ -5474,9 +5479,13 @@ impl Ff<'_, '_> { { return Err(sv::AnalyzerError::RealEdgeEvent { edge }); } + let mut variable = false; let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { - Some(id) if !self.m.is_hidden(id) => id, + Some(id) if !self.m.is_hidden(id) => { + variable = self.m.var(id).array_dims.is_empty(); + id + } Some(_) => self.event_expression(&expr, samples)?, // A constant never changes. None if self.m.constants.contains_key(name) => continue, @@ -5484,29 +5493,44 @@ impl Ff<'_, '_> { }, _ => self.event_expression(&expr, samples)?, }; - match item.edge { - sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), - sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), - sv::ir::EventEdge::Neg => terms.push((id, CounterKind::Falls)), - sv::ir::EventEdge::Both => { - terms.push((id, CounterKind::Rises)); - terms.push((id, CounterKind::Falls)); - } + let gate = match &item.iff { + Some(iff) => Some(self.event_gate(iff, samples)?), + None => None, + }; + let kinds: &[CounterKind] = match item.edge { + sv::ir::EventEdge::Any => &[CounterKind::Changes], + sv::ir::EventEdge::Pos => &[CounterKind::Rises], + sv::ir::EventEdge::Neg => &[CounterKind::Falls], + sv::ir::EventEdge::Both => &[CounterKind::Rises, CounterKind::Falls], + }; + for &kind in kinds { + terms.push((id, kind)); + gates.push(gate.map(|(signal, gate_variable)| WaitGate { + signal, + // A variable's write is judged with a variable gate at + // the write itself. + counters: (variable && gate_variable).then(|| self.gate_counters()), + })); } } Ok(()) } - /// Suspend until one of `terms` counts, after taking `samples`. + /// Suspend until one of `terms` counts while its gate in `gates` holds, + /// after taking `samples`. fn suspend_on( &mut self, terms: Vec<(SourceVarId, CounterKind)>, + mut gates: Vec>>, samples: Vec<(String, sv::ir::Expr)>, ) -> Result<(), sv::AnalyzerError> { for (target, value) in samples { self.assign(&sv::ir::LValue::Ident(target), &value)?; } - let site = self.wait_site(terms); + if gates.iter().all(Option::is_none) { + gates.clear(); + } + let site = self.wait_site(terms, gates); self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { kernel.suspend_wait(site)?; let woken = kernel.builder().alloc_bit(1, false); @@ -5519,6 +5543,62 @@ impl Ff<'_, '_> { .map_err(kernel_error) } + /// The signal whose least significant bit is the `iff` condition `iff` + /// of an event item (IEEE 1800-2023 9.4.2.3): a one-bit variable itself, + /// or the variable `$event[k]` of the condition's truth value. Its + /// operands are not terms of the wait; the runtime reads it when it + /// detects an occurrence. + fn event_gate( + &mut self, + iff: &sv::ir::Expr, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result<(SourceVarId, bool), sv::AnalyzerError> { + let iff = self.propagate(iff); + if let sv::ir::Expr::Ident(name) = &iff + && let Some(id) = self.m.id(name) + && !self.m.is_hidden(id) + && self.m.var(id).width == 1 + && self.m.var(id).float.is_none() + && self.m.var(id).array_dims.is_empty() + { + return Ok((id, true)); + } + let not = |expr| sv::ir::Expr::Unary { + op: sv::ir::UnaryOp::LogicNot, + expr: Box::new(expr), + }; + Ok((self.event_expression(¬(not(iff)), samples)?, false)) + } + + /// The counters of a new gated term ([`GateCounters`]): `$event[k]` + /// counts the occurrences while the gate holds, `$event[k].all` all + /// of them. + fn gate_counters(&mut self) -> GateCounters { + let index = self.m.next_event_index(); + let counter = SvVariable { + float: None, + path: Vec::new(), + width: EVENT_COUNTER_WIDTH, + signed: false, + is_4state: false, + packed_ranges: vec![(EVENT_COUNTER_WIDTH as i128 - 1, 0)], + array_dims: Vec::new(), + unpacked_ranges: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + type_kind: PortTypeKind::Bit, + source: None, + hidden: true, + force_control: None, + value_kind: Default::default(), + }; + let (gated, _) = self.m.event_variable(index, None, counter.clone()); + let (all, _) = self + .m + .event_variable(index, Some("all".to_string()), counter); + GateCounters { gated, all } + } + /// The variable `$event[k]` of a new event expression `expr`, with its /// continuous assignment added to the module. `samples` gets the /// assignments the process makes before it suspends: the copies of the @@ -5659,6 +5739,7 @@ impl Ff<'_, '_> { ids.into_iter() .map(|id| (id, CounterKind::Changes)) .collect(), + Vec::new(), ); // The condition is lowered once per check: before the process // suspends and at every resume. @@ -5688,11 +5769,16 @@ impl Ff<'_, '_> { /// Declare a wait site of the process with the given terms and return /// its local index. - fn wait_site(&mut self, terms: Vec<(SourceVarId, CounterKind)>) -> u32 { + fn wait_site( + &mut self, + terms: Vec<(SourceVarId, CounterKind)>, + gates: Vec>>, + ) -> u32 { let index = self.wait_sites.len() as u32; self.wait_sites.push(WaitSite { process: self.process, terms, + gates, }); index } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index def194c3e1d..9564818825c 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -384,7 +384,7 @@ impl<'a> ProcModule<'a> { ) -> bool { let mut listed = HashSet::default(); for item in items { - let sv::ir::Expr::Ident(name) = &item.expr else { + let (sv::ir::Expr::Ident(name), None) = (&item.expr, &item.iff) else { return false; }; let Some(id) = self.id(name).filter(|id| !self.is_hidden(*id)) else { diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 064c9049bad..6d5f6375f50 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -6,7 +6,10 @@ use fxhash::{FxHashMap, FxHashSet}; use crate::{ AbsoluteAddr, EventDomain, EventInfo, HostWatch, SignalRef, backend::{EventHandle, SimBackend}, - timing::{CountedDomainRefs, CountedRefs, NbaSiteRefs, ProbeRefs, ProcessRefs, TermRefs}, + timing::{ + CountedDomainRefs, CountedRefs, GateCounterRefs, GateRefs, GatedWriteRefs, NbaSiteRefs, + ProbeRefs, ProcessRefs, TermRefs, + }, }; /// The facts a timed simulation keeps but never changes: event signals, @@ -23,6 +26,12 @@ pub struct ResolvedSchedule { pub(crate) processes: Vec, /// The kernels of program instances, in declaration order. pub(crate) program_processes: Vec, + /// The `iff` gate of each term by process, wait site and term; empty + /// when no wait has one, and a site without one has no entries. + pub(crate) wait_gates: Vec>>>, + /// The gated terms with counters by the offset of their signal, which + /// the runtime's writes of the signal bump. + pub(crate) gated_writes: FxHashMap>, /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, @@ -194,6 +203,62 @@ impl ResolvedSchedule { .find(|counted| counted.refs.signal == signal) .map(|counted| counted.refs.counter(kind)) }; + let gate_refs = |gate: &celox_design::WaitGate| GateRefs { + signal: resolve(&gate.signal), + counters: gate.counters.map(|counters| GateCounterRefs { + gated: resolve(&counters.gated), + all: resolve(&counters.all), + }), + }; + let mut gated_writes: FxHashMap> = FxHashMap::default(); + for term in model + .processes + .iter() + .flat_map(|process| process.waits.iter().flatten()) + { + let Some(gate) = term.gate.as_ref().map(gate_refs) else { + continue; + }; + if let Some(counters) = gate.counters { + gated_writes + .entry(resolve(&term.signal).offset) + .or_default() + .push(GatedWriteRefs { + signal: resolve(&term.signal), + kind: term.kind, + gate: gate.signal, + counters, + }); + } + } + let wait_gates: Vec>>> = if model + .processes + .iter() + .flat_map(|process| process.waits.iter().flatten()) + .any(|term| term.gate.is_some()) + { + model + .processes + .iter() + .map(|process| { + process + .waits + .iter() + .map(|terms| { + if terms.iter().all(|term| term.gate.is_none()) { + return Vec::new(); + } + terms + .iter() + .map(|term| term.gate.as_ref().map(gate_refs)) + .collect() + }) + .collect() + }) + .collect() + } else { + Vec::new() + }; let processes: Vec = model .processes .iter() @@ -316,6 +381,8 @@ impl ResolvedSchedule { .map(|(index, _)| index) .collect(), processes, + wait_gates, + gated_writes, counted, counted_by_offset, counted_triggers, @@ -459,6 +526,30 @@ fn counted_refs( /// Host writes a timed simulation of a design observes one at a time: those /// of counted signals and of signals a wait watches. pub fn host_watch(backend: &B, model: &ScheduleModel) -> HostWatch { + let mut gated: FxHashMap> = FxHashMap::default(); + for term in model + .processes + .iter() + .flat_map(|process| process.waits.iter().flatten()) + { + let Some(gate) = &term.gate else { + continue; + }; + if let Some(counters) = gate.counters { + gated + .entry(backend.resolve_signal(&term.signal).offset) + .or_default() + .push(GatedWriteRefs { + signal: backend.resolve_signal(&term.signal), + kind: term.kind, + gate: backend.resolve_signal(&gate.signal), + counters: GateCounterRefs { + gated: backend.resolve_signal(&counters.gated), + all: backend.resolve_signal(&counters.all), + }, + }); + } + } HostWatch::new( model .counted @@ -470,4 +561,5 @@ pub fn host_watch(backend: &B, model: &ScheduleModel>(), ) + .with_gated(gated) } diff --git a/crates/celox-runtime/src/scheduler.rs b/crates/celox-runtime/src/scheduler.rs index c328336c445..320e60f0cce 100644 --- a/crates/celox-runtime/src/scheduler.rs +++ b/crates/celox-runtime/src/scheduler.rs @@ -85,6 +85,7 @@ impl Scheduler { self.event_queue.peek().map(|e| e.time) } + #[inline] pub fn push(&mut self, event: SimEvent) { self.event_queue.push(event); } diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 5e31cbfa1c6..7c0eb5d2c8b 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -5,7 +5,7 @@ use fxhash::{FxHashMap, FxHashSet}; use crate::{ SignalRef, SimulatorErrorCode, backend::SimBackend, - timing::{CountedRefs, Halt, Value, read}, + timing::{CountedRefs, GatedWriteRefs, Halt, Value, read, write_gated}, }; /// The units a timed step executes: combinational settling, flip-flop @@ -175,6 +175,9 @@ impl SimulationExecutor for T {} pub struct HostWatch { counted: FxHashMap, waited: FxHashSet, + /// Gated wait terms by the offset of their signal, whose counters a + /// write bumps with the gate as the write leaves it. + gated: FxHashMap>, log: Vec<(SignalRef, Value)>, } @@ -186,12 +189,19 @@ impl HostWatch { .map(|refs| (refs.signal.offset, refs)) .collect(), waited, + gated: FxHashMap::default(), log: Vec::new(), } } + /// Also count the writes of the signals of `gated` terms. + pub fn with_gated(mut self, gated: FxHashMap>) -> Self { + self.gated = gated; + self + } + pub fn is_empty(&self) -> bool { - self.counted.is_empty() && self.waited.is_empty() + self.counted.is_empty() && self.waited.is_empty() && self.gated.is_empty() } /// Run `write`, which writes `signal` in `backend`, and observe it. @@ -204,7 +214,13 @@ impl HostWatch { let counted = self.counted.get(&signal.offset).copied(); let waited = self.waited.contains(&signal.offset); if counted.is_none() && !waited { - write(backend); + if !self.gated.is_empty() + && let Some(gated) = self.gated.get(&signal.offset) + { + write_gated(backend, signal, gated, write); + } else { + write(backend); + } return; } let old = read(backend, signal); @@ -213,6 +229,9 @@ impl HostWatch { if let Some(counted) = counted { counted.bump(backend, &old, &new); } + for term in self.gated.get(&signal.offset).into_iter().flatten() { + term.bump(backend, &old, &new); + } if waited && old != new { self.log.push((signal, new)); } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index bc74b2729d8..57cef7f4348 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -246,7 +246,7 @@ impl SimulationState { // one, the check following the settle sees them: a settle // does not write what processes write. if again || !self.region_ready(reactive).is_empty() { - self.observe_driven(executor.backend()); + self.observe_driven_unsettled(executor.backend()); } if !again { break; @@ -357,7 +357,7 @@ impl SimulationState { // host's view of the state, and what the settle derived. entry = false; if !self.process_state.waiters.is_empty() { - self.observe(executor.backend(), None); + self.observe_settled(executor.backend()); } } else { self.observe_driven(executor.backend()); diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 881f1d146e6..c130d773765 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -12,7 +12,7 @@ use crate::{ SimulatorErrorCode, backend::SimBackend, scheduler::SimEvent, - timing::{Halt, read}, + timing::{Halt, read, write_gated}, }; /// Bookkeeping of one round of a time slot. @@ -384,7 +384,7 @@ impl SimulationState { executor.apply_ff_at(event)?; } self.record_transitions(executor.backend(), round); - self.observe_driven(executor.backend()); + self.observe_driven_unsettled(executor.backend()); } } restore_working_image(executor.backend_mut(), &live); @@ -461,6 +461,22 @@ impl SimulationState { backend.set(signal, value); let new = read(backend, signal); self.model.counted[counted].refs.bump(backend, &old, &new); + // The gate as the scheduled values before this one left it. + for term in self + .model + .gated_writes + .get(&signal.offset) + .into_iter() + .flatten() + { + term.bump(backend, &old, &new); + } + } else if !self.model.gated_writes.is_empty() + && let Some(gated) = self.model.gated_writes.get(&signal.offset) + { + write_gated(executor.backend_mut(), signal, gated, |backend| { + backend.set(signal, value) + }); } else { executor.backend_mut().set(signal, value); } @@ -660,7 +676,7 @@ impl SimulationState { if newly_triggered.is_empty() && !any_new_outer_loop_trigger { if published { self.finish_publications(executor.backend_mut(), &mut round); - self.observe_driven(executor.backend()); + self.observe_driven_unsettled(executor.backend()); } // The NBA region still publishes the processes' assignments, // which may trigger further domains. @@ -678,7 +694,7 @@ impl SimulationState { } if round.publishing { self.finish_publications(executor.backend_mut(), &mut round); - self.observe_driven(executor.backend()); + self.observe_driven_unsettled(executor.backend()); } for id in &newly_triggered { if let Some(event) = self.model.event_info[*id].eval_ff_event { diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index e25822ae243..96305c767f6 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -108,7 +108,7 @@ impl SimulationState { self.observe_host_write(signal, &value); } self.settle_host_resume(executor, &mut suspended.round, &suspended.levels)?; - self.observe(executor.backend(), None); + self.observe_settled(executor.backend()); } self.continue_round( executor, diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index d9f4c083796..fe5876ec8a2 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -6,11 +6,12 @@ use celox_design::CounterKind; use super::SimulationState; use crate::{ - SignalRef, SimulatorErrorCode, + SignalRef, SimulatorErrorCode, TermRefs, backend::SimBackend, timing::{ - Halt, ProcessRefs, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, - planes, planes_equal, planes_occur, read, + GateCounterRefs, GateRefs, GatedWriteRefs, Halt, ProcessRefs, ProcessState, StateView, + Value, copy_planes, encode_planes, occurs, planes, planes_equal, planes_occur, read, + write_gated, }, }; @@ -35,6 +36,7 @@ impl SimulationState { .get(site) .ok_or_else(|| Self::site_error(process, site))?; let driven = terms.iter().any(|term| term.driven); + let gates = &self.model.wait_gates; self.process_state .waiters .register(process, driven, |waiter| { @@ -84,6 +86,24 @@ impl SimulationState { }, } } + let gates = gates.get(process).map_or(&[][..], |sites| &sites[site]); + for (index, gate) in gates.iter().enumerate() { + if let Some(GateRefs { + counters: Some(counters), + .. + }) = gate + { + let signal = terms[index].signal; + let image = planes(backend, signal).expect("a plain signal"); + let mut raw = Vec::with_capacity(image.len()); + copy_planes(&mut raw, image, signal.width); + waiter.baselines[index] = Baseline::Gated { + gated: backend.get_as(counters.gated), + all: backend.get_as(counters.all), + raw, + }; + } + } }); Ok(()) } @@ -107,7 +127,13 @@ impl SimulationState { 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); + if !self.model.gated_writes.is_empty() + && let Some(gated) = self.model.gated_writes.get(&signal.offset) + { + write_gated(backend, signal, gated, write); + } else { + write(backend); + } } else { let old = read(backend, signal); write(backend); @@ -115,6 +141,15 @@ impl SimulationState { if let Some(counted) = counted { self.model.counted[counted].refs.bump(backend, &old, &new); } + for term in self + .model + .gated_writes + .get(&signal.offset) + .into_iter() + .flatten() + { + term.bump(backend, &old, &new); + } // One counter can observe several ranges of the signal; a write // is one occurrence. let mut bumped: Vec = Vec::new(); @@ -131,22 +166,57 @@ impl SimulationState { } /// Test the waits against the current state, or only their terms on - /// signal `only` after a write of it. Woken processes become ready. - #[inline] + /// signal `only` after a write of it, before combinational logic has + /// settled. Woken processes become ready. + #[inline(always)] pub(super) fn observe(&mut self, backend: &B, only: Option) { - self.check_waits(backend, only, false); + if self.model.wait_gates.is_empty() { + self.check_waits(backend, only, false); + } else { + self.check_gated_waits(backend, only, false, false); + } } - /// Like [`Self::observe`], at a point where only design code wrote - /// state: terms on signals that only the host and the scheduler write - /// cannot have changed. - #[inline] + /// Like [`Self::observe`] of every term, after combinational logic has + /// settled. + #[inline(always)] + pub(super) fn observe_settled(&mut self, backend: &B) { + if self.model.wait_gates.is_empty() { + self.check_waits(backend, None, false); + } else { + self.check_gated_waits(backend, None, false, true); + } + } + + /// Like [`Self::observe_settled`], at a point where only design code + /// wrote state: terms on signals that only the host and the scheduler + /// write cannot have changed. + #[inline(always)] pub(super) fn observe_driven(&mut self, backend: &B) { if !self.process_state.waiters.none_driven() { - self.check_waits(backend, None, true); + if self.model.wait_gates.is_empty() { + self.check_waits(backend, None, true); + } else { + self.check_gated_waits(backend, None, true, true); + } } } + /// Like [`Self::observe_driven`], before combinational logic has + /// settled. + #[inline(always)] + pub(super) fn observe_driven_unsettled(&mut self, backend: &B) { + if !self.process_state.waiters.none_driven() { + if self.model.wait_gates.is_empty() { + self.check_waits(backend, None, true); + } else { + self.check_gated_waits(backend, None, true, false); + } + } + } + + /// The waits of a design without `iff` gates: [`Self::check_gated_waits`] + /// without the gates. fn check_waits(&mut self, backend: &B, only: Option, driven_only: bool) { let processes = &self.model.processes; let state = StateView::new(backend); @@ -199,6 +269,8 @@ impl SimulationState { } }, Baseline::Raw(_) => unreachable!("tested above"), + // Only gated terms with counters have it. + Baseline::Gated { .. } => false, Baseline::Value(last) => match state.planes(term.signal) { // A baseline loaded from a state file. Some(now) => { @@ -223,6 +295,184 @@ impl SimulationState { }); } + /// [`Self::check_waits`] for a design with `iff` gates. With + /// `settled`, combinational logic has settled since the last write. A + /// term whose gate has no counters is judged only then: the gate may be + /// computed from what was written, so before then its baseline is left + /// as it is and the occurrence is judged, with the gate, at the next + /// settled check. + #[inline(never)] + fn check_gated_waits( + &mut self, + backend: &B, + only: Option, + driven_only: bool, + settled: bool, + ) { + let processes = &self.model.processes; + let state = StateView::new(backend); + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; + let gates = &self.model.wait_gates; + waiters.retain(driven_only, |process, waiter| { + let terms = &processes[process].wait_sites[waiter.site]; + let gates = &gates[process][waiter.site]; + let mut wake = false; + for (index, term) in terms.iter().enumerate() { + if only.is_some_and(|signal| signal != term.signal) || (driven_only && !term.driven) + { + continue; + } + let baseline = &mut waiter.baselines[index]; + match gates.get(index).copied().flatten() { + None => wake |= Self::occurred(&state, backend, term, baseline), + Some(GateRefs { + signal: gate, + counters: Some(counters), + }) => { + wake |= + Self::gated_occurred(&state, backend, term, gate, counters, baseline); + } + Some(_) if !settled => {} + // The occurrence is consumed even when the gate does not + // hold (IEEE 1800-2023 9.4.2.3). + Some(gate) => { + if Self::occurred(&state, backend, term, baseline) { + if Self::gate_holds(&state, backend, gate.signal) { + wake = true; + } else if let Some(counter) = term.counter + && let Baseline::RawCounter { seen, .. } + | Baseline::Counter { seen, .. } = baseline + { + // The counted occurrences are consumed: a later + // check judges only new ones. + *seen = backend.get_as(counter); + } + } + } + } + } + if wake { + wake_in_region(processes, ready, reactive, process); + } + !wake + }); + } + + /// Whether a gated `term` with `counters` occurred since the wait began: + /// a write counted it while `gate` held, or the signal changed without + /// any write counting it, as a raw host write does, while `gate` holds. + fn gated_occurred( + state: &StateView<'_>, + backend: &B, + term: &TermRefs, + gate: SignalRef, + counters: GateCounterRefs, + baseline: &mut Baseline, + ) -> bool { + let now = state.planes(term.signal).expect("a plain signal"); + let all = state.counter(counters.all); + if !matches!(baseline, Baseline::Gated { .. }) { + // A baseline loaded from a state file. + let (gated, value) = match baseline { + Baseline::Counter { seen, value } => (*seen, value.clone()), + Baseline::Value(value) => (backend.get_as(counters.gated), value.clone()), + _ => (backend.get_as(counters.gated), read(backend, term.signal)), + }; + *baseline = Baseline::Gated { + gated, + all, + raw: encode_planes(&value, term.signal.width, now.len()), + }; + } + let Baseline::Gated { + gated, + all: counted, + raw, + } = baseline + else { + unreachable!("converted above"); + }; + let changed = Self::advance(term.kind, raw, now, term.signal.width); + let uncounted = changed && all == *counted; + *counted = all; + state.counter(counters.gated) != *gated + || (uncounted && Self::gate_holds(state, backend, gate)) + } + + /// Whether `term` occurred since `baseline`, which becomes the current + /// state: the body of [`Self::check_waits`] for one term. + #[inline(always)] + fn occurred( + state: &StateView<'_>, + backend: &B, + term: &TermRefs, + baseline: &mut Baseline, + ) -> bool { + // The common term: a plain signal no counter counts. + if let Baseline::Raw(last) = baseline { + let now = state.planes(term.signal).expect("a plain signal"); + return Self::advance(term.kind, last, now, term.signal.width); + } + let counted = |seen: u32| { + term.counter + .is_some_and(|counter| backend.get_as::(counter) != seen) + }; + match baseline { + Baseline::RawCounter { seen, raw } => { + let now = state.planes(term.signal).expect("a plain signal"); + let changed = Self::advance(term.kind, raw, now, term.signal.width); + counted(*seen) || changed + } + Baseline::Counter { seen, value } => match state.planes(term.signal) { + // A baseline loaded from a state file. + Some(now) => { + let seen = *seen; + let mut raw = encode_planes(value, term.signal.width, now.len()); + let changed = Self::advance(term.kind, &mut raw, now, term.signal.width); + *baseline = Baseline::RawCounter { seen, raw }; + counted(seen) || changed + } + None => { + let now = read(backend, term.signal); + let changed = occurs(term.kind, value, &now); + *value = now; + counted(*seen) || changed + } + }, + Baseline::Raw(_) => unreachable!("tested above"), + // Only gated terms with counters have it. + Baseline::Gated { .. } => false, + Baseline::Value(last) => match state.planes(term.signal) { + // A baseline loaded from a state file. + Some(now) => { + let mut raw = encode_planes(last, term.signal.width, now.len()); + let hit = Self::advance(term.kind, &mut raw, now, term.signal.width); + *baseline = Baseline::Raw(raw); + hit + } + None => { + let now = read(backend, term.signal); + let hit = occurs(term.kind, last, &now); + *last = now; + hit + } + }, + } + } + + /// Whether the least significant bit of `gate` is a known 1. + fn gate_holds(state: &StateView<'_>, backend: &B, gate: SignalRef) -> bool { + state.gate_holds(gate).unwrap_or_else(|| { + let (value, unknown) = read(backend, gate); + value.bit(0) && !unknown.bit(0) + }) + } + /// Whether the change from the image `last` to `now` is an occurrence of /// `kind`; `last` becomes `now`. #[inline] @@ -235,9 +485,57 @@ impl SimulationState { hit } + /// The host wrote gated signals between steps: with `raw`, in place, + /// otherwise through tracked writes, which counted their occurrences. + /// A raw change of a gated term's signal since its baseline counts as + /// one write, judging the gate as the writes left it. Either way the + /// baseline (the signal's planes and the counter of all occurrences) + /// becomes the current state, so the check that follows judges only + /// later changes, and checkpoints and state files keep it. + pub fn note_gated_host_writes(&mut self, backend: &mut B, raw: bool) { + if self.model.wait_gates.is_empty() { + return; + } + let processes = &self.model.processes; + let gates = &self.model.wait_gates; + for (process, waiter) in self.process_state.waiters.iter_mut() { + let Some(gates) = gates[process].get(waiter.site) else { + continue; + }; + for (index, gate) in gates.iter().enumerate() { + let Some(GateRefs { + signal: gate, + counters: Some(counters), + }) = *gate + else { + continue; + }; + let term = processes[process].wait_sites[waiter.site][index]; + let Baseline::Gated { all, raw: last, .. } = &mut waiter.baselines[index] else { + continue; + }; + let Some(now) = planes(backend, term.signal).map(<[u8]>::to_vec) else { + continue; + }; + if raw && planes_occur(term.kind, last, &now, term.signal.width) { + let refs = GatedWriteRefs { + signal: term.signal, + kind: term.kind, + gate, + counters, + }; + refs.count(backend); + } + copy_planes(last, &now, term.signal.width); + *all = backend.get_as(counters.all); + } + } + } + /// Show the waits one value the host wrote to `signal`. pub(super) fn observe_host_write(&mut self, signal: SignalRef, value: &Value) { let processes = &self.model.processes; + let gates = &self.model.wait_gates; let ProcessState { waiters, ready, @@ -245,15 +543,24 @@ impl SimulationState { .. } = &mut self.process_state; waiters.retain(false, |process, waiter| { - let terms = &processes[process].wait_sites[waiter.site]; + let gates = gates + .get(process) + .map_or(&[][..], |sites| &sites[waiter.site]); let mut wake = false; - for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { - if term.signal != signal { + for (index, (term, baseline)) in processes[process].wait_sites[waiter.site] + .iter() + .zip(&mut waiter.baselines) + .enumerate() + { + // A gated term is judged at the next settled check. + if term.signal != signal || gates.get(index).is_some_and(Option::is_some) { continue; } match baseline { // Counters are bumped by the write itself. - Baseline::Counter { .. } | Baseline::RawCounter { .. } => {} + Baseline::Counter { .. } + | Baseline::RawCounter { .. } + | Baseline::Gated { .. } => {} Baseline::Raw(last) => { let now = encode_planes(value, signal.width, last.len()); wake |= Self::advance(term.kind, last, &now, signal.width); @@ -305,6 +612,11 @@ pub enum Baseline { /// Like `Counter`, with the signal's state at the last check kept as /// in [`Baseline::Raw`]. RawCounter { seen: u32, raw: Vec }, + /// A term whose `iff` gate a write judges at the write + /// ([`celox_design::GateCounters`]): the gated counter when the wait + /// began, the counter of all occurrences and the signal's state as in + /// [`Baseline::Raw`] at the last check. + Gated { gated: u32, all: u32, raw: Vec }, } /// A process suspended at a wait. diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 98c61ea0cf8..ed97a2f7247 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -26,7 +26,8 @@ //! waiter count u32, then per waiter: //! process str | site u64 | baseline count u32, then per baseline: //! 0 u8 | counter u32 | value bytes | mask bytes, or -//! 1 u8 | value bytes | mask bytes +//! 1 u8 | value bytes | mask bytes, or +//! 2 u8 | gated counter u32 | all counter u32 | value bytes | mask bytes //! ready count u32, then per process: process str //! inactive count u32, then per process: process str //! update count u32, then per update: @@ -163,6 +164,15 @@ pub enum BaselineRecord { }, /// The signal's value at the last check, as little-endian bytes. Value { value: Vec, mask: Vec }, + /// A term whose `iff` gate a write judges at the write: its gated + /// counter when the wait began, its counter of all occurrences and the + /// signal's value at the last check, as little-endian bytes. + Gated { + gated: u32, + all: u32, + value: Vec, + mask: Vec, + }, } /// A queued nonblocking assignment. @@ -530,6 +540,18 @@ fn put_processes(w: &mut impl Write, processes: &ProcessRecord) -> io::Result<() put_bytes(w, value)?; put_bytes(w, mask)?; } + BaselineRecord::Gated { + gated, + all, + value, + mask, + } => { + w.write_all(&[2])?; + w.write_all(&gated.to_le_bytes())?; + w.write_all(&all.to_le_bytes())?; + put_bytes(w, value)?; + put_bytes(w, mask)?; + } } } } @@ -600,6 +622,12 @@ fn get_processes(r: &mut impl Read) -> Result { value: get_len_bytes(r)?, mask: get_len_bytes(r)?, }), + 2 => Ok(BaselineRecord::Gated { + gated: get_u32(r)?, + all: get_u32(r)?, + value: get_len_bytes(r)?, + mask: get_len_bytes(r)?, + }), other => Err(StateFileError::Malformed(format!("baseline {other}"))), } }) @@ -750,6 +778,12 @@ mod tests { value: vec![1], mask: vec![0], }, + BaselineRecord::Gated { + gated: 3, + all: 5, + value: vec![1], + mask: vec![], + }, ], }], ready: vec!["$process[2].status".into()], diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 9edb4ed0927..9edda393fb8 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -104,6 +104,90 @@ impl CountedRefs { } } +/// The `iff` gate of a wait term ([`celox_design::WaitGate`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GateRefs { + pub signal: SignalRef, + /// The counters of a gate judged at each write + /// ([`celox_design::GateCounters`]). + pub counters: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GateCounterRefs { + pub gated: SignalRef, + pub all: SignalRef, +} + +/// Whether the least significant bit of `gate` is a known 1. +pub fn gate_holds(backend: &B, gate: SignalRef) -> bool { + StateView::new(backend).gate_holds(gate).unwrap_or_else(|| { + let (value, unknown) = read(backend, gate); + value.bit(0) && !unknown.bit(0) + }) +} + +/// A gated term whose counters a write of its signal by the runtime or the +/// host bumps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GatedWriteRefs { + pub signal: SignalRef, + pub kind: CounterKind, + pub gate: SignalRef, + pub counters: GateCounterRefs, +} + +impl GatedWriteRefs { + /// Count a change from `old` to `new`, judging the gate after it. + pub fn bump(&self, backend: &mut B, old: &Value, new: &Value) { + if occurs(self.kind, old, new) { + self.count(backend); + } + } + + /// Count one occurrence, judging the gate as it is now. + pub fn count(&self, backend: &mut B) { + let all: u32 = backend.get_as(self.counters.all); + backend.set(self.counters.all, all.wrapping_add(1)); + if gate_holds(backend, self.gate) { + let gated: u32 = backend.get_as(self.counters.gated); + backend.set(self.counters.gated, gated.wrapping_add(1)); + } + } +} + +/// Run `write`, which writes `signal` in `backend`, and count it in the +/// gated `terms` on the signal, comparing the signal's planes in place. +pub fn write_gated( + backend: &mut B, + signal: SignalRef, + terms: &[GatedWriteRefs], + write: impl FnOnce(&mut B), +) { + // A plain signal's planes fit a small buffer; others are read as values. + const SMALL: usize = 32; + let len = planes(backend, signal).map_or(usize::MAX, <[u8]>::len); + if len > SMALL { + let old = read(backend, signal); + write(backend); + let new = read(backend, signal); + for term in terms { + term.bump(backend, &old, &new); + } + return; + } + let mut old = [0u8; SMALL]; + old[..len].copy_from_slice(planes(backend, signal).expect("a plain signal")); + write(backend); + let mut new = [0u8; SMALL]; + new[..len].copy_from_slice(planes(backend, signal).expect("a plain signal")); + for term in terms { + if planes_occur(term.kind, &old[..len], &new[..len], signal.width) { + term.count(backend); + } + } +} + /// A bit range whose changes bump an occurrence counter. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ProbeRefs { @@ -221,6 +305,19 @@ impl<'a> StateView<'a> { } } + /// Whether the least significant bit of a plain `gate` is a known 1. + pub fn gate_holds(&self, gate: SignalRef) -> Option { + let image = self.planes(gate)?; + let bytes = gate.width.div_ceil(8).max(1); + Some(image[0] & 1 == 1 && image.get(bytes).is_none_or(|unknown| unknown & 1 == 0)) + } + + /// The value of a 32-bit two-state counter. + pub fn counter(&self, counter: SignalRef) -> u32 { + let bytes = &self.memory[counter.offset..counter.offset + 4]; + u32::from_le_bytes(bytes.try_into().expect("four bytes")) + } + /// See [`planes`]. pub fn planes(&self, signal: SignalRef) -> Option<&'a [u8]> { if signal.array_layout.is_some() { @@ -310,7 +407,7 @@ pub fn encode_planes(value: &Value, width: usize, len: usize) -> Vec { /// Whether the change from plane image `old` to `new` of a `width`-bit /// signal is an occurrence of `kind` (Table 9-2 on the least significant /// bit). -#[inline] +#[inline(always)] pub fn planes_occur(kind: CounterKind, old: &[u8], new: &[u8], width: usize) -> bool { if kind == CounterKind::Changes { return !planes_equal(old, new, width); diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 884c9ebcffe..4ded5d27d49 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -608,6 +608,9 @@ impl Flow<'_> { Stmt::WaitEvent(items) => { for item in items { self.read(&item.expr, written)?; + if let Some(iff) = &item.iff { + self.read(iff, written)?; + } } Ok(Exits::next(written)) } @@ -759,7 +762,10 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { .collect(), Stmt::Local { init, .. } => init.iter().collect(), Stmt::Delay { amount: expr, .. } | Stmt::Wait(expr) => vec![expr], - Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), + Stmt::WaitEvent(items) => items + .iter() + .flat_map(|item| std::iter::once(&item.expr).chain(&item.iff)) + .collect(), // The statements of an `@*` describe its reads and do not run. Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 76e37f3c563..7aa050dc1ab 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -157,6 +157,7 @@ pub(in crate::ast) fn classify<'a>( FfEdge::Neg => EventEdge::Neg, }, expr: Expr::Ident(event.signal.clone()), + iff: None, }) .collect(), )]; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 6820026a578..ea341163204 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -35,9 +35,6 @@ impl BodyBuilder<'_, '_, '_> { EventControl::Items(items) => { let mut result = Vec::with_capacity(items.len()); for item in items { - if item.iff.is_some() { - return Err(unsupported("iff-qualified event")); - } let edge = match item.edge { TimingEdge::Any => EventEdge::Any, TimingEdge::Pos => EventEdge::Pos, @@ -47,6 +44,7 @@ impl BodyBuilder<'_, '_, '_> { result.push(EventItemBase { edge, expr: self.native_value(item.expression)?, + iff: item.iff.map(|iff| self.native_value(iff)).transpose()?, }); } Ok(Stmt::WaitEvent(result)) diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 669af79e830..8e859593a05 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -44,6 +44,11 @@ pub(super) fn always_kind( } match event { EventControl::Wildcard => AlwaysKind::Comb, + // An `iff` event is judged when it occurs, which only the + // process path does (IEEE 1800-2023 9.4.2.3). + EventControl::Items(items) if items.iter().any(|item| item.iff.is_some()) => { + AlwaysKind::Process + } EventControl::Items(items) if items.iter().any(|item| item.edge != TimingEdge::Any) => { diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 32df6c7df93..6d8449add52 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -109,6 +109,7 @@ impl Module { FfEdge::Neg => EventEdge::Neg, }, expr: Expr::Ident(event.signal.clone()), + iff: None, }) .collect(), )]; @@ -1229,7 +1230,9 @@ impl InitialProcess { }; (init.is_empty() && step.is_empty() - && items.iter().all(|item| item.edge == EventEdge::Any) + && items + .iter() + .all(|item| item.edge == EventEdge::Any && item.iff.is_none()) && !leaves_the_process_loop(body)) .then_some((items.as_slice(), body)) } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 19ec606ecd2..48284723e9b 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -196,7 +196,6 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("streaming concatenation", 447), ("loop-generate unroll limit exceeded", 448), ("iff-qualified always_ff event", 452), - ("iff-qualified event", 1444), ("nonblocking assignment inside always_comb", 453), ("genvar update operator", 455), ("reduction operator in parameter expression", 456), diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 2da16383d4f..d1de6c6988c 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -133,11 +133,14 @@ pub enum StmtBase { Wait(E), } -/// One item of an event control, `[edge] expr`. +/// One item of an event control, `[edge] expr [iff condition]`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EventItemBase { pub edge: EventEdge, pub expr: E, + /// The `iff` condition: an occurrence of `expr` is an event only if it + /// holds when the occurrence happens (9.4.2.3). + pub iff: Option, } /// Which transitions of an event expression are events (IEEE 1800-2023 @@ -359,6 +362,7 @@ impl StmtBase { .map(|item| EventItemBase { edge: item.edge, expr: fe(item.expr), + iff: item.iff.map(&mut *fe), }) .collect(), ), @@ -473,6 +477,9 @@ impl StmtBase { StmtBase::WaitEvent(items) => { for item in items { fe(&mut item.expr); + if let Some(iff) = &mut item.iff { + fe(iff); + } } } StmtBase::Wait(condition) => fe(condition), diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs index 4b10b9bf4e1..756a72a2c2f 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs @@ -114,7 +114,6 @@ fn native_timing_event_membership_and_delay_roles_are_authoritative() { #[test] fn native_timing_preserves_existing_restrictions_including_ff_iff_validation() { for (body, diagnostic) in [ - ("initial @(a iff en) q=1;", "iff-qualified event"), ("always_comb #1 q=d;", "delay control"), ("always_ff @(edge clk) q<=d;", "always_ff event expression"), ( diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c3c271322e4..03308d9ee8e 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3496,10 +3496,6 @@ fn rejects_unimplemented_timing_constructs() { // The `event` data type is rejected by name before its uses. ("event e; initial @e;", "named event"), ("event e; initial ->e;", "named event"), - ( - "logic clk, en; initial @(posedge clk iff en);", - "iff-qualified event", - ), ( "logic a, b; initial a = #1 b;", "intra-assignment timing control", @@ -3524,8 +3520,8 @@ fn rejects_unimplemented_timing_constructs() { ); } assert_eq!( - AnalyzerError::Unsupported("iff-qualified event".to_string()).tracking_issue(), - 1444 + AnalyzerError::Unsupported("iff-qualified always_ff event".to_string()).tracking_issue(), + 452 ); } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 7adfec4e3b5..b6dbcd8681e 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 36; +const CONTAINER_VERSION: u16 = 37; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 05002091ffb..c69237e7e7f 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -495,6 +495,11 @@ impl Plan { let term = &process.waits[0].first(); let wait = (|| -> Result { let term = term.ok_or("the process waits for a level")?; + // The compiled wait tests the edge alone (IEEE 1800-2023 + // 9.4.2.3: an `iff` condition is judged at the occurrence). + if term.gate.is_some() { + return Err("the process waits with an iff condition"); + } if process .waits .iter() diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 59740d44036..4526129a794 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -614,6 +614,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); + // The tracked writes counted their occurrences of gated waits. + self.state + .note_gated_host_writes(&mut self.simulator.backend, false); let finished = self.sync_finish_checked(); result?; finished?; @@ -984,6 +987,8 @@ impl Simulation { /// writes may wake a process or changed an event signal. Waits and /// counters see the values the writes left, not each write. pub fn note_raw_writes(&mut self) { + self.state + .note_gated_host_writes(&mut self.simulator.backend, true); self.state.note_host_writes(&self.simulator.backend, false); } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..a9cc2d041b0 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -577,6 +577,15 @@ impl Simulator { let (value, mask) = split(term, image); BaselineRecord::Value { value, mask } } + Baseline::Gated { gated, all, raw } => { + let (value, mask) = split(term, raw); + BaselineRecord::Gated { + gated: *gated, + all: *all, + value, + mask, + } + } Baseline::RawCounter { seen, raw } => { // The bytes a `Counter` baseline's value saves as. let (value, mask) = split(term, raw); @@ -717,7 +726,7 @@ impl Simulator { .collect::>(); let site = usize::try_from(waiter.site).ok(); // Each baseline has the kind of its term: a counter for a - // counted signal, a value otherwise. + // counted signal or a gate with counters, a value otherwise. let counted = |signal: &crate::AbsoluteAddr| { self.program .runtime_schema @@ -727,13 +736,17 @@ impl Simulator { }; if !site.and_then(|site| sites.get(site)).is_some_and(|site| { site.terms.len() == waiter.baselines.len() - && site - .terms - .iter() - .zip(&waiter.baselines) - .all(|((signal, _), baseline)| { - counted(signal) == matches!(baseline, BaselineRecord::Counter { .. }) - }) + && site.terms.iter().zip(&waiter.baselines).enumerate().all( + |(index, ((signal, _), baseline))| { + let gated = + site.gate(index).is_some_and(|gate| gate.counters.is_some()); + match baseline { + BaselineRecord::Gated { .. } => gated, + BaselineRecord::Counter { .. } => counted(signal) || gated, + BaselineRecord::Value { .. } => !counted(signal) && !gated, + } + }, + ) }) { unknown.push(format!("{} wait site {}", waiter.process, waiter.site)); continue; @@ -746,13 +759,19 @@ impl Simulator { .filter(|site| site.process == index) .nth(site.unwrap_or_default()) .is_some_and(|site| { - site.terms.iter().any(|(signal, _)| { - self.program - .runtime_schema - .rtl_writes - .iter() - .any(|atom| atom.id == *signal) - }) + // A gate without counters counts as driven + // (`TermModel::driven`). + site.gates + .iter() + .flatten() + .any(|gate| gate.counters.is_none()) + || site.terms.iter().any(|(signal, _)| { + self.program + .runtime_schema + .rtl_writes + .iter() + .any(|atom| atom.id == *signal) + }) }); waiters.insert( index, @@ -762,7 +781,31 @@ impl Simulator { baselines: waiter .baselines .iter() - .map(|baseline| match baseline { + .enumerate() + .map(|(term, baseline)| match baseline { + BaselineRecord::Gated { + gated, + all, + value, + mask, + } => { + let signal = sites[site.unwrap_or_default()].terms[term].0; + let signal = self.backend.resolve_signal(&signal); + let len = celox_runtime::timing::planes(&self.backend, signal) + .map_or(0, <[u8]>::len); + Baseline::Gated { + gated: *gated, + all: *all, + raw: celox_runtime::timing::encode_planes( + &( + BigUint::from_bytes_le(value), + BigUint::from_bytes_le(mask), + ), + signal.width, + len, + ), + } + } BaselineRecord::Counter { seen, value, mask } => Baseline::Counter { seen: *seen, value: ( diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 79e3ef8a4a5..384fb646277 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -53,7 +53,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: | Control | Supported | | --- | --- | | `#delay` | integral and real delays, `#(min:typ:max)` (the typical value), package-scoped values such as `#pkg::D`, and [time literals](#time-literal-delays); an X or Z delay counts as zero | -| `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads | +| `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, `iff` conditions on items (not in `always_ff`), and `@*` / `@(*)`, which waits on the variables its statement reads | | `wait (condition)` | any condition; an X or Z condition counts as false | | Assignments | blocking and nonblocking, to any target a blocking assignment takes, including unpacked array elements and run-time positions; nonblocking updates take effect in the NBA region of the time slot, at the position evaluated when the assignment executes, and bits outside the target or at a position with an X or Z bit are not written | @@ -191,9 +191,8 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. -- Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), - impure function calls in event expressions, and - `wait` or event expressions reading a static task argument. +- Timing controls in processes: impure function calls in event expressions and + `iff` conditions, and `wait`, event expressions or `iff` conditions reading a static task argument. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. - Ports and instances: non-ANSI port declarations ([#426](https://github.com/celox-sim/celox/issues/426)), `ref` ports @@ -202,7 +201,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs and `real`. -- Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) in event lists, and in +- Sequential processes: `iff` qualifiers in `always_ff` event lists ([#452](https://github.com/celox-sim/celox/issues/452)), and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit edge signals, and several edges without an asynchronous reset. - Combinational processes: nonblocking assignments inside `always_comb` @@ -499,6 +498,26 @@ unsupported, including when the inference option is enabled. before the edge and waits again before the nonblocking updates (IEEE 1800-2023 4.5). Icarus 13.0 gives the same values; Verilator 5.052 resumes the waiter after the nonblocking updates. +- An item `expr iff condition` is an event only if the condition is true + when the occurrence of `expr` happens (IEEE 1800-2023 9.4.2.3): X and Z + are false, and an occurrence while the condition is false is consumed. + The wait does not watch the condition's operands, so `@(posedge clk iff + en)` does not wake when only `en` changes. When `expr` and the condition + are both variables, the condition is judged at each write of `expr`: by + a process or a combinational process, by nonblocking updates in issue + order, by scheduled clock edges and by host writes. In one process, + `clk = 1; en = 0;` is an event and `en = 0; clk = 1;` is none. + Verilator 5.052 judges the condition later, after the process suspends, + and gives the opposite results. A condition that is an expression or a + net, an `expr` other than a variable, and a variable that a flip-flop + domain writes ([#1830](https://github.com/celox-sim/celox/issues/1830)) + are judged when the occurrence is detected, after combinational logic + settles: like an event expression, they see a process's writes when the + process reaches a timing control or ends (4.7). A raw memory write the + host notes with `Simulation::note_raw_writes` is judged with the + condition as the writes left it. + A plain `always @(posedge clk iff en)` runs as a process; `always_ff` + rejects `iff` ([#452](https://github.com/celox-sim/celox/issues/452)). ### Variable lifetimes diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 49f40d7e00d..d1231b898b3 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -96,7 +96,7 @@ Common reasons a design needs changes are: - Class-based verification beyond [simple classes](./systemverilog-reference#classes) and concurrent assertions. - `fork` / `join`, named events, intra-assignment timing such as `a = #1 b` - and `iff` in event controls ([#1444](https://github.com/celox-sim/celox/issues/1444)). + and `iff` in `always_ff` event controls ([#452](https://github.com/celox-sim/celox/issues/452)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. - `real`, unpacked structs and several interface features. diff --git a/docs/ja/guide/external-frontends.md b/docs/ja/guide/external-frontends.md index d1d0b66b663..5b5c399b198 100644 --- a/docs/ja/guide/external-frontends.md +++ b/docs/ja/guide/external-frontends.md @@ -170,7 +170,9 @@ kernel に compile され、delay の満了や wait の成立で simulation の IEEE 1800-2023 4.5 の region に従います。edge で起こされた process も含めて process は active region で実行され、その edge の register が nonblocking 代入を 反映する前に動きます。そのため `@(posedge clk)` で起きた process は edge 前の -register 出力を読みます。0 の `InactiveDelay` の process は active region の後に +register 出力を読みます。register domain のブロッキング書き込みで起きた process も +active region で実行され、その domain の nonblocking 代入の反映より前に動きます。 +0 の `InactiveDelay` の process は active region の後に 実行され、nonblocking 代入は両方が空になってから反映されます。同じ edge で register の入力を駆動する process は、SystemVerilog と同じく register と race します。 diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index fec9ec48260..996a2786760 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -51,7 +51,7 @@ outline: [2, 3] | 制御 | 対応範囲 | | --- | --- | | `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、`#pkg::D` のような package スコープの値、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | -| `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` | +| `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、項目の `iff` 条件(`always_ff` を除く)、文が読む変数を待つ `@*` / `@(*)` | | `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | | 代入 | ブロッキング代入とノンブロッキング代入。代入先はブロッキング代入と同じで、unpacked 配列の要素や実行時に決まる位置も使えます。ノンブロッキング代入は代入を実行した時点で評価した位置に、そのタイムスロットの NBA 領域で反映します。代入先の範囲外のビットと、X や Z のビットを含む位置には書き込みません | @@ -169,15 +169,14 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 - 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、並行アサーション、`force` / `release`。 -- プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、 - イベント式内の impure な関数呼び出し、 - static task 引数を読む `wait` 条件とイベント式。 +- プロセス内のタイミング制御:イベント式と `iff` 条件内の impure な関数呼び出し、 + static task 引数を読む `wait` 条件、イベント式、`iff` 条件。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 -- 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での +- 順序回路のプロセス:`always_ff` のイベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 - 組み合わせ回路のプロセス:`always_comb` 内のノンブロッキング代入([#453](https://github.com/celox-sim/celox/issues/453))。 @@ -348,6 +347,22 @@ Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatche 更新は NBA 領域で発行順に適用し、それぞれが1回の更新です(10.4.2)。子モジュールの出力ポートは 親のネットへの継続代入なので(23.3.3)、親の待ちは前の項目と同じく確定した値だけを見ます。 Verilator 5.052 は評価の最終値だけを見ます。Icarus 13.0 はポートを通したパルスも見ます。 +- エッジで起動する `always` のブロッキング代入は active 領域の更新です。それで起きたプロセスは、 + 同じエッジのノンブロッキングの更新より前に実行されます。`y = ~y; q <= q + 1;` では、`@(y)` の + 待ちはエッジ前の `q` を読み、ノンブロッキングの更新より前に再び待ちに入ります(IEEE 1800-2023 4.5)。 + Icarus 13.0 は同じ値になり、Verilator 5.052 はノンブロッキングの更新の後で待ちを再開します。 +- 項目 `expr iff condition` は、`expr` が発生した時点で条件が真のときだけイベントになります + (IEEE 1800-2023 9.4.2.3)。X と Z は偽で、条件が偽の間の発生は消費されます。条件のオペランドは + 待ちの対象ではないので、`@(posedge clk iff en)` は `en` だけが変化しても起きません。`expr` と条件が + どちらも変数のときは、プロセスや組み合わせ回路のプロセスの書き込み、発行順のノンブロッキングの更新、 + スケジュールされたクロックのエッジ、ホストの書き込みといった `expr` への書き込みごとに条件を判定します。 + 1つのプロセスで `clk = 1; en = 0;` はイベントになり、`en = 0; clk = 1;` はなりません。 + Verilator 5.052 はプロセスが suspend した後で条件を判定し、逆の結果になります。式やネットの条件、 + 変数以外の `expr`、flip-flop の domain が書く変数([#1830](https://github.com/celox-sim/celox/issues/1830))は、 + 組み合わせ回路が確定した後に発生を検出した時点で判定します。イベント式と同じく、プロセスの書き込みは + そのプロセスがタイミング制御に達するか終了した時点で参照します(4.7)。ホストが + `Simulation::note_raw_writes` で通知した生のメモリ書き込みは、書き込み後の条件で判定します。単純な `always @(posedge clk iff en)` はプロセスとして + 実行し、`always_ff` の `iff` は拒否します([#452](https://github.com/celox-sim/celox/issues/452))。 ### 変数の寿命 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 947852c6397..87e76cb5bdf 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -91,7 +91,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 - [単純なクラス](./systemverilog-reference#classes)を超えるクラスを使う検証、並行アサーション。 - `fork` / `join`、named event、`a = #1 b` のような代入内のタイミング制御、 - イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))。 + `always_ff` のイベント制御の `iff`([#452](https://github.com/celox-sim/celox/issues/452))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 - `real`、unpacked 構造体、interface の一部の機能。 From fb5ca3d5c20c74df68ee714e8c5f2954e436c0e1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 13:03:42 +0900 Subject: [PATCH 2/5] test(sv): cover iff-qualified event controls Timing cases for conditions judged at the write, nonblocking update order, combinational process order, consumed occurrences, automatic task arguments, unknown conditions and plain always procedures; Rust tests for scheduled clocks, host pulses, raw edges and state-file and checkpoint round trips between host writes. Icarus 13.0 rejects iff in event controls; Verilator 5.052 judges the condition late (excluded with probes). Change-Id: I47afd3cfa65b0ee5c7568f84d2f67cff0530bae9 --- crates/celox-test-suite/LIMITATIONS.md | 2 + .../src/sv/cases/timing.vtest | 262 +++++++++++ .../repros/sv_iff_event_controls_icarus.json | 25 ++ .../sv_iff_late_conditions_verilator.json | 48 +++ .../verification/sv/icarus/timing.json | 253 +++++++++++ .../verification/sv/limitations.json | 46 ++ .../verification/sv/verilator/timing.json | 80 ++++ .../tests/frontends/systemverilog/timing.rs | 405 +++++++++++++++++- 8 files changed, 1120 insertions(+), 1 deletion(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_iff_event_controls_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_iff_late_conditions_verilator.json diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index bc57d47a063..89aaba94c33 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -592,6 +592,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_program_exit` | execute | icarus | 1 | Icarus 13.0 does not define `$exit`; IEEE 1800-2023 24.7 ends the calling program's `initial` procedures. | | `sv_verilator_program_exit` | execute | verilator | 1 | Verilator 5.052 continues after `$exit` and keeps the program's other `initial` procedures (24.7). Icarus does not run the case; xezim 0.11.3 agrees with the expected output. | | `sv_verilator_program_items` | compile | verilator | 2 | Verilator 5.052 rejects an `always` procedure and a module instance in a program with syntax errors, which the run cannot count as language rejections. Both are illegal (IEEE 1800-2023 24.3); Icarus 13.0 rejects them with diagnostics that name the rule. | +| `sv_icarus_iff_event_controls` | compile | icarus | 11 | Icarus 13.0 rejects `iff` in an event control with "syntax error" and "Malformed event control expression." IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; [Standalone probe](verification/repros/sv_iff_event_controls_icarus.json); Verilator 5.052 runs the cases and gives the asserted counts. | +| `sv_verilator_iff_late_conditions` | execute | verilator | 3 | Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. [Standalone probes](verification/repros/sv_iff_late_conditions_verilator.json) print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) retains the failed Icarus runs and minimal sources. Cover comparisons enable diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 04d74494fac..e790b39bf41 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2663,3 +2663,265 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (top Top) (run_to_finish) (expect_output "cnt=0 n=1 q=0\n")) + +; An item with `iff` is an event only if the condition holds when the +; occurrence happens; changes of the condition alone are no events +; (IEEE 1800-2023 9.4.2.3). +(case iff_events_occur_only_while_the_condition_holds + (source "iff.sv" #" + module Top; + bit clk, en; + int n, m; + initial forever begin @(posedge clk iff en); n++; end + initial forever begin @(clk iff en); m++; end + initial begin + #1 clk = 1; + #1 clk = 0; + #1 en = 1; + #1 clk = 1; + #1 en = 0; + #1 en = 1; + #1 clk = 0; + #1 clk = 1; + #1 $display("n=%0d m=%0d", n, m); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=2 m=3\n")) + +; The process writes the condition before the clock: the edge occurs while +; the condition holds. +(case iff_conditions_see_writes_before_the_event + (source "iff_order.sv" #" + module Top; + bit clk, en; + int n; + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 en = 1; clk = 1; + #1 clk = 0; + #1 en = 0; + #1 clk = 1; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=1\n")) + +; Each item has its own condition; the condition's operands are not +; events of the wait. +(case iff_conditions_apply_to_their_own_items + (source "iff_items.sv" #" + module Top; + bit a, b, c; + int n; + initial forever begin @(a iff c or b); n++; end + initial begin + #1 a = 1; + #1 b = 1; + #1 c = 1; + #1 a = 0; + #1 c = 0; + #1 a = 1; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=2\n")) + +; A condition reading an automatic task argument uses the activation's +; value. +(case iff_conditions_read_automatic_task_arguments + (source "iff_task.sv" #" + module Top; + bit clk, en; + int n0, n1; + task automatic w(input bit m, output int hits); + hits = 0; + repeat (3) begin @(posedge clk iff (en & m)); hits++; end + endtask + initial w(1, n1); + initial w(0, n0); + initial begin + en = 1; + repeat (4) begin #1 clk = 1; #1 clk = 0; end + #1 $display("n1=%0d n0=%0d", n1, n0); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n1=3 n0=0\n")) + +; An X or Z condition is false. +(case unknown_iff_conditions_are_false + (source "iff_unknown.sv" #" + module Top; + logic en; + bit clk; + int n; + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 clk = 1; + #1 clk = 0; + #1 en = 1'bz; + #1 clk = 1; + #1 clk = 0; + #1 en = 1; + #1 clk = 1; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (four_state) + (run_to_finish) + (expect_output "n=1\n")) + +; A plain always with an `iff` event runs as a process. +(case plain_always_iff_events_run_as_processes + (source "iff_always.sv" #" + module Top; + bit clk, en; + int q; + always @(posedge clk iff en) q <= q + 1; + initial begin + #1 clk = 1; + #1 clk = 0; en = 1; + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 clk = 0; en = 0; + #1 clk = 1; + #1 $display("q=%0d", q); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "q=2\n")) + +; The condition is judged when the clock rises, before the edge process +; that the same edge triggers writes it. +(case iff_conditions_are_judged_before_edge_processes_run + (source "iff_edge.sv" #" + module Top; + bit clk, g; + int n; + always @(posedge clk) g = ~g; + initial forever begin @(posedge clk iff g); n++; end + initial begin + repeat (4) begin #1 clk = 1; #1 clk = 0; end + #1 $display("n=%0d g=%0d", n, g); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=2 g=0\n")) + +; With a variable condition, the occurrence is judged as the process +; writes the signal: `clk = 1; en = 0;` is an event, `en = 0; clk = 1;` +; is none (IEEE 1800-2023 9.4.2.3). +(case iff_conditions_are_judged_at_the_write + (source "iff_write.sv" #" + module Top; + bit clk, en; + int n; + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 en = 1; + #1 clk = 1; en = 0; + #1 clk = 0; + #1 en = 1; + #1 en = 0; clk = 1; + #1 clk = 0; en = 1; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=1\n")) + +; Nonblocking updates apply in issue order (10.4.2): an update of the +; condition issued before the clock's is seen at the edge, one issued after +; it is not. +(case iff_conditions_follow_nonblocking_update_order + (source "iff_nba.sv" #" + module Top; + bit clk, en; + int n; + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 en <= 1; clk <= 1; + #1 clk <= 0; + #1 en <= 0; clk <= 1; + #1 clk <= 0; en <= 1; + #1 clk <= 1; en <= 0; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=2\n")) + +; A pulse of a counted variable while the condition is false is consumed: +; the condition turning true later wakes no process (IEEE 1800-2023 +; 9.4.2.3), with a condition judged after settling and with one judged at +; the write. +(case iff_conditions_consume_occurrences_while_false + (source "iff_consumed.sv" #" + module Top; + bit y, z, en, m = 1; + int n, k; + initial forever begin @(posedge y iff (en & m)); n++; end + initial forever begin @(posedge z iff en); k++; end + initial begin + #1 y = 1; y = 0; z = 1; z = 0; + #1 en = 1; + #1 $display("n=%0d k=%0d", n, k); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=0 k=0\n")) + +; A combinational process writes in procedural order: `en` is 1 when it +; writes `clk`, so the edge is an event although the process leaves `en` +; at 0 (IEEE 1800-2023 9.4.2.3). +(case iff_conditions_follow_combinational_process_order + (source "iff_comb_order.sv" #" + module Top; + bit a, clk, en; + int n; + always_comb begin en = a; clk = a; en = 0; end + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 a = 1; + #1 $display("n=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "n=1\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_iff_event_controls_icarus.json b/crates/celox-test-suite/verification/repros/sv_iff_event_controls_icarus.json new file mode 100644 index 00000000000..a80515690ab --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_iff_event_controls_icarus.json @@ -0,0 +1,25 @@ +{ + "standard": "IEEE 1800-2023 9.4.2.3 and A.6.5", + "expected": "An event control item may be qualified by `iff expression`; the item triggers only if the expression is true when the event occurs.", + "probes": [ + { + "name": "iff_items", + "note": "The suite case iff_events_occur_only_while_the_condition_holds.", + "source": "module Top;\n bit clk, en;\n int n, m;\n initial forever begin @(posedge clk iff en); n++; end\n initial forever begin @(clk iff en); m++; end\n initial begin\n #1 clk = 1;\n #1 clk = 0;\n #1 en = 1;\n #1 clk = 1;\n #1 en = 0;\n #1 en = 1;\n #1 clk = 0;\n #1 clk = 1;\n #1 $display(\"n=%0d m=%0d\", n, m);\n $finish;\n end\nendmodule\n", + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 6, + "output": "/probe.sv:4: syntax error\n/probe.sv:4: error: Malformed event control expression.\n/probe.sv:4: error: Invalid event control.\n/probe.sv:5: syntax error\n/probe.sv:5: error: Malformed event control expression.\n/probe.sv:5: error: Invalid event control.\n" + }, + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "n=2 m=3\n- /probe.sv:16: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 9ps; walltime 0.000 s; speed 200.423 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + } + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_iff_late_conditions_verilator.json b/crates/celox-test-suite/verification/repros/sv_iff_late_conditions_verilator.json new file mode 100644 index 00000000000..e0ff1de0004 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_iff_late_conditions_verilator.json @@ -0,0 +1,48 @@ +{ + "standard": "IEEE 1800-2023 9.4.2.3 and 10.4.2", + "expected": "An item `expr iff condition` triggers only if the condition is true when the event occurs. With `clk = 1; en = 0;` from en = 1 the edge occurs while en is still 1, so it is an event; with `en = 0; clk = 1;` it is none. Nonblocking updates apply in issue order, so `en <= 1; clk <= 1;` is an event and `clk <= 1; en <= 0;` from en = 1 is one too, while `en <= 0; clk <= 1;` is none. An always_comb executes its statements in order, so `en = a; clk = a; en = 0;` writes clk while en is 1, which is an event.", + "probes": [ + { + "name": "write_order", + "note": "The suite case iff_conditions_are_judged_at_the_write.", + "source": "module Top;\n bit clk, en;\n int n;\n initial forever begin @(posedge clk iff en); n++; end\n initial begin\n #1 en = 1;\n #1 clk = 1; en = 0;\n #1 clk = 0;\n #1 en = 1;\n #1 en = 0; clk = 1;\n #1 clk = 0; en = 1;\n #1 $display(\"n=%0d\", n);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "n=0\n- /probe.sv:13: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 7ps; walltime 0.000 s; speed 168.387 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + } + }, + { + "name": "nonblocking_order", + "note": "The suite case iff_conditions_follow_nonblocking_update_order.", + "source": "module Top;\n bit clk, en;\n int n;\n initial forever begin @(posedge clk iff en); n++; end\n initial begin\n #1 en <= 1; clk <= 1;\n #1 clk <= 0;\n #1 en <= 0; clk <= 1;\n #1 clk <= 0; en <= 1;\n #1 clk <= 1; en <= 0;\n #1 $display(\"n=%0d\", n);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "n=1\n- /probe.sv:12: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 6ps; walltime 0.000 s; speed 156.242 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + } + }, + { + "name": "combinational_order", + "note": "The suite case iff_conditions_follow_combinational_process_order.", + "source": "module Top;\n bit a, clk, en;\n int n;\n always_comb begin en = a; clk = a; en = 0; end\n initial forever begin @(posedge clk iff en); n++; end\n initial begin\n #1 a = 1;\n #1 $display(\"n=%0d\", n);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "n=0\n- /probe.sv:9: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 2ps; walltime 0.000 s; speed 47.414 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + } + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 0a0b6efdeb2..aa6bf987afe 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -1412,6 +1412,259 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_events_occur_only_while_the_condition_holds", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_see_writes_before_the_event", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_apply_to_their_own_items", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_read_automatic_task_arguments", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::unknown_iff_conditions_are_false", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::plain_always_iff_events_run_as_processes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_are_judged_before_edge_processes_run", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_are_judged_at_the_write", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_follow_nonblocking_update_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_consume_occurrences_while_false", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [] + }, + "name": "timing::iff_conditions_follow_combinational_process_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 3f5e9c99ed6..f1565ac0f78 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2440,5 +2440,51 @@ "class::randomization_cyclic_enum_alias" ] } + }, + { + "id": "sv_icarus_iff_event_controls", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; Verilator 5.052 runs the cases and gives the asserted counts.", + "upstream": [], + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::iff_events_occur_only_while_the_condition_holds", + "timing::iff_conditions_see_writes_before_the_event", + "timing::iff_conditions_apply_to_their_own_items", + "timing::iff_conditions_read_automatic_task_arguments", + "timing::unknown_iff_conditions_are_false", + "timing::plain_always_iff_events_run_as_processes", + "timing::iff_conditions_are_judged_before_edge_processes_run", + "timing::iff_conditions_are_judged_at_the_write", + "timing::iff_conditions_follow_nonblocking_update_order", + "timing::iff_conditions_consume_occurrences_while_false", + "timing::iff_conditions_follow_combinational_process_order" + ] + } + }, + { + "id": "sv_verilator_iff_late_conditions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "upstream": [], + "evidence": [ + "verification/repros/sv_iff_late_conditions_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::iff_conditions_are_judged_at_the_write", + "timing::iff_conditions_follow_nonblocking_update_order", + "timing::iff_conditions_follow_combinational_process_order" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index b9969462312..ba1aed0c2cc 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -1595,6 +1595,86 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::unknown_iff_conditions_are_false", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_iff_late_conditions_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_iff_late_conditions", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "upstream": [] + }, + "name": "timing::iff_conditions_are_judged_at_the_write", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_iff_late_conditions_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_iff_late_conditions", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "upstream": [] + }, + "name": "timing::iff_conditions_follow_nonblocking_update_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_iff_late_conditions_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_iff_late_conditions", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls.", + "upstream": [] + }, + "name": "timing::iff_conditions_follow_combinational_process_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 9df87b6b032..63c822d8bff 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -200,6 +200,21 @@ timed_cases! { fn derived_clocks_follow_superseded_publications = "timing::derived_clocks_follow_superseded_publications"; } +// A second list: one invocation expands one item per recursion level. +timed_cases! { + fn iff_events_occur_only_while_the_condition_holds = "timing::iff_events_occur_only_while_the_condition_holds"; + fn iff_conditions_see_writes_before_the_event = "timing::iff_conditions_see_writes_before_the_event"; + fn iff_conditions_apply_to_their_own_items = "timing::iff_conditions_apply_to_their_own_items"; + fn iff_conditions_read_automatic_task_arguments = "timing::iff_conditions_read_automatic_task_arguments"; + fn unknown_iff_conditions_are_false = "timing::unknown_iff_conditions_are_false"; + fn plain_always_iff_events_run_as_processes = "timing::plain_always_iff_events_run_as_processes"; + fn iff_conditions_are_judged_before_edge_processes_run = "timing::iff_conditions_are_judged_before_edge_processes_run"; + fn iff_conditions_are_judged_at_the_write = "timing::iff_conditions_are_judged_at_the_write"; + fn iff_conditions_follow_nonblocking_update_order = "timing::iff_conditions_follow_nonblocking_update_order"; + fn iff_conditions_consume_occurrences_while_false = "timing::iff_conditions_consume_occurrences_while_false"; + fn iff_conditions_follow_combinational_process_order = "timing::iff_conditions_follow_combinational_process_order"; +} + #[test] fn timed_task_activations_survive_each_optimization_level() { let source = r#" @@ -460,7 +475,6 @@ fn event_expressions_with_effects_are_rejected() { #[test] fn unimplemented_timing_features_are_rejected() { for (body, construct, issue) in [ - ("bit a; initial @(a iff a);", "iff-qualified event", 1444), ("initial fork #1; join", "fork-join block", 88), ("initial fork #1; join_none", "fork-join block", 88), ("event e; initial -> e;", "named event", 88), @@ -1165,3 +1179,392 @@ fn design_processes_a_program_wakes_run_before_the_nonblocking_updates() { assert_eq!(values, [0u8.into(), 1u8.into()], "four_state={four_state}"); } } + +/// An `iff` wait on a clock only the scheduler drives: the occurrence is +/// judged with the condition after the edge settles, on every backend. +#[test] +fn iff_waits_on_scheduled_clocks_see_their_condition() { + let source = r#" + module Top(input bit clk, output int n, m); + timeunit 1ns / 1ns; + bit en, q; + wire gate = en & 1'b1; + always_ff @(posedge clk) q <= ~q; + initial forever begin @(posedge clk iff gate); n++; end + initial forever begin @(posedge clk); m++; end + initial begin + #25 en = 1; + #40 en = 0; + end + endmodule + "#; + let mut backends = vec!["cranelift", "cranelift-parallel"]; + if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) { + backends.extend(["native", "native-parallel"]); + } + for backend in backends { + let builder = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_clock.sv"))], + "Top", + ); + let builder = if backend.ends_with("-parallel") { + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + } else { + builder + }; + // The backends build different simulation types. + macro_rules! check { + ($sim:expr) => {{ + let mut sim = $sim.unwrap(); + // Rising edges at 0, 10, ..., 90; the waits begin after the + // first. `en` is 1 from 25 to 65. + sim.add_clock("clk", 10, 0); + sim.run_until(95).unwrap(); + let [n, m] = ["n", "m"].map(|name| sim.signal(name)); + assert_eq!(sim.get(m), 9u32.into(), "{backend}"); + assert_eq!(sim.get(n), 4u32.into(), "{backend}"); + }}; + } + if backend.starts_with("native") { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(builder.build_native()); + } else { + check!(builder.build_cranelift()); + } + } +} + +/// An `iff` wait on a clock only the scheduler drives, with a gate the host +/// writes: each edge is judged with the gate the host left, on every +/// backend. +#[test] +fn iff_waits_on_scheduled_clocks_judge_host_written_gates() { + let source = r#" + module Top(input bit clk, input bit en, output int n); + timeunit 1ns / 1ns; + bit q; + always_ff @(posedge clk) q <= ~q; + initial forever begin @(posedge clk iff en); n++; end + endmodule + "#; + let mut backends = vec!["cranelift", "cranelift-parallel"]; + if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) { + backends.extend(["native", "native-parallel"]); + } + for backend in backends { + let builder = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_host_gate.sv"))], + "Top", + ); + let builder = if backend.ends_with("-parallel") { + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + } else { + builder + }; + // The backends build different simulation types. + macro_rules! check { + ($sim:expr) => {{ + let mut sim = $sim.unwrap(); + let [en, n] = ["en", "n"].map(|name| sim.signal(name)); + // Rising edges at 0, 10, ..., 90; `en` is 1 from 25 to 65. + sim.add_clock("clk", 10, 0); + sim.run_until(25).unwrap(); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.run_until(65).unwrap(); + sim.modify(|io| io.set(en, 0u8)).unwrap(); + sim.run_until(95).unwrap(); + assert_eq!(sim.get(n), 4u32.into(), "{backend}"); + }}; + } + if backend.starts_with("native") { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(builder.build_native()); + } else { + check!(builder.build_cranelift()); + } + } +} + +/// The baselines of `iff` waits whose gate is judged at the write survive a +/// state file: a simulation loaded between edges wakes as the uninterrupted +/// one does, and saves the same baselines again. +#[test] +fn gated_wait_baselines_survive_a_state_file() { + let source = r#" + module Top(output int n); + timeunit 1ns / 1ns; + bit clk, en; + initial forever begin @(posedge clk iff en); n++; end + initial begin + #1 en = 1; + #1 clk = 1; en = 0; + #1 clk = 0; + #1 en = 1; + #1 clk = 1; + #1 clk = 0; en = 0; + #1 clk = 1; + end + endmodule + "#; + let build = || { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("gated_state.sv"))], + "Top", + ) + .build() + .unwrap() + }; + let through_bytes = |file: &celox::StateFile| { + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + celox::StateFile::read_from(bytes.as_slice()).unwrap() + }; + let count = |sim: &mut celox::Simulation| { + let n = sim.signal("n"); + sim.get(n) + }; + let mut whole = build(); + whole.run_until(10).unwrap(); + assert_eq!(count(&mut whole), 2u32.into()); + for at in [2, 4] { + let mut first = build(); + first.run_until(at).unwrap(); + let file = through_bytes(&first.save_state().unwrap()); + let mut loaded = build(); + loaded.load_state(&file).unwrap(); + assert_eq!( + through_bytes(&loaded.save_state().unwrap()), + file, + "at {at}" + ); + loaded.run_until(10).unwrap(); + assert_eq!(count(&mut loaded), 2u32.into(), "at {at}"); + } +} + +/// A host pulse `clk = 1; clk = 0;` between two steps, while the `iff` +/// condition holds, is one event of the wait (IEEE 1800-2023 9.4.2.3). +#[test] +fn host_pulses_of_iff_gated_clocks_wake_once() { + let source = r#" + module Top(input bit clk, input bit en, output int n); + timeunit 1ns / 1ns; + initial forever begin @(posedge clk iff en); n++; end + endmodule + "#; + let mut backends = vec!["cranelift", "cranelift-parallel"]; + if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) { + backends.extend(["native", "native-parallel"]); + } + for backend in backends { + let builder = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_host_pulse.sv"))], + "Top", + ); + let builder = if backend.ends_with("-parallel") { + builder + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + } else { + builder + }; + // The backends build different simulation types. + macro_rules! check { + ($sim:expr) => {{ + let mut sim = $sim.unwrap(); + let [clk, en, n] = ["clk", "en", "n"].map(|name| sim.signal(name)); + sim.run_until(1).unwrap(); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.run_until(2).unwrap(); + sim.modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(sim.get(n), 1u32.into(), "{backend}"); + }}; + } + if backend.starts_with("native") { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(builder.build_native()); + } else { + check!(builder.build_cranelift()); + } + } +} + +const IFF_HOST_GATE: &str = r#" + module Top(input bit clk, input bit en, output int n); + timeunit 1ns / 1ns; + initial forever begin @(posedge clk iff en); n++; end + endmodule +"#; + +fn iff_host_gate() -> celox::Simulation { + let mut sim = celox::Simulation::from_sv_sources( + vec![(IFF_HOST_GATE, std::path::Path::new("iff_host_gate.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(1).unwrap(); + sim +} + +/// A state file saved between host writes keeps what the writes already +/// counted: `clk = 1` while `en` is 0 is no event, and `en = 1` after it +/// does not turn it into one, in the loaded simulation as in the saved one. +#[test] +fn state_files_keep_occurrences_an_iff_gate_rejected() { + let mut whole = iff_host_gate(); + let [clk, en, n] = ["clk", "en", "n"].map(|name| whole.signal(name)); + whole.modify(|io| io.set(clk, 1u8)).unwrap(); + whole.modify(|io| io.set(en, 1u8)).unwrap(); + let file = whole.save_state().unwrap(); + whole.run_until(2).unwrap(); + assert_eq!(whole.get(n), 0u32.into()); + + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + let file = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + let mut loaded = iff_host_gate(); + loaded.load_state(&file).unwrap(); + loaded.run_until(2).unwrap(); + assert_eq!(loaded.get(n), 0u32.into()); +} + +/// A raw write after tracked host writes is judged from where they left +/// the signal: a rejected pulse `clk = 1; clk = 0;` while `en` is 0, then +/// raw writes of `en = 1` and `clk = 1`, wake the wait once. +#[test] +fn raw_edges_after_rejected_host_pulses_wake_iff_waits() { + let mut sim = iff_host_gate(); + let [clk, en, n] = ["clk", "en", "n"].map(|name| sim.signal(name)); + sim.modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(); + let (memory, size) = sim.memory_as_mut_ptr(); + assert!(clk.offset < size && en.offset < size); + // Safety: clk and en are live one-bit inputs within the allocation. + unsafe { + memory.add(en.offset).write(1); + memory.add(clk.offset).write(1); + } + sim.note_raw_writes(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(n), 1u32.into()); +} + +/// What the host does between and at the steps of an `iff` wait. +#[derive(Clone, Copy, Debug)] +enum HostOp { + Run(u64), + Set(&'static str, u8), + Raw(&'static str, u8), + NoteRaw, +} + +const IFF_HOST_OPS: &[HostOp] = &[ + HostOp::Run(1), + // An edge while the gate is 0 is no event; the gate rising after it is + // none either, nor is an unrelated raw write. + HostOp::Set("clk", 1), + HostOp::Set("en", 1), + HostOp::Raw("u", 1), + HostOp::NoteRaw, + HostOp::Run(2), + // A host pulse while the gate holds is one event. + HostOp::Set("clk", 0), + HostOp::Set("clk", 1), + HostOp::Set("clk", 0), + HostOp::Run(3), + // Raw edges: a rejected one, then one while the gate holds. + HostOp::Set("en", 0), + HostOp::Raw("clk", 1), + HostOp::NoteRaw, + HostOp::Raw("clk", 0), + HostOp::Set("en", 1), + HostOp::Raw("clk", 1), + HostOp::NoteRaw, + HostOp::Run(4), +]; + +/// The count after each step of `ops`. +fn apply_host_ops(sim: &mut celox::Simulation, ops: &[HostOp], counts: &mut Vec) { + for &op in ops { + match op { + HostOp::Run(time) => { + sim.run_until(time).unwrap(); + let n = sim.signal("n"); + counts.push(u32::try_from(sim.get(n)).unwrap()); + } + HostOp::Set(name, value) => { + let signal = sim.signal(name); + sim.modify(|io| io.set(signal, value)).unwrap(); + } + HostOp::Raw(name, value) => { + let signal = sim.signal(name); + let (memory, size) = sim.memory_as_mut_ptr(); + assert!(signal.offset < size); + // Safety: a live one-bit input within the allocation. + unsafe { memory.add(signal.offset).write(value) }; + } + HostOp::NoteRaw => sim.note_raw_writes(), + } + } +} + +/// Every piece of the state of an `iff` wait, its gate counters and the +/// host's tracked and raw writes survives a state file and a checkpoint at +/// any point: the rest of the run gives the same counts as without them. +#[test] +fn iff_wait_state_survives_saves_between_host_writes() { + let source = r#" + module Top(input bit clk, input bit en, input bit u, output int n); + timeunit 1ns / 1ns; + initial forever begin @(posedge clk iff en); n++; end + endmodule + "#; + let build = || { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_host_ops.sv"))], + "Top", + ) + .build() + .unwrap() + }; + let mut expected = Vec::new(); + apply_host_ops(&mut build(), IFF_HOST_OPS, &mut expected); + assert_eq!(expected, [0, 0, 1, 2], "the uninterrupted run"); + for at in 1..IFF_HOST_OPS.len() { + let (before, after) = IFF_HOST_OPS.split_at(at); + let mut first = build(); + let mut counts = Vec::new(); + apply_host_ops(&mut first, before, &mut counts); + let mut bytes = Vec::new(); + first.save_state().unwrap().write_to(&mut bytes).unwrap(); + let file = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + let checkpoint = first.checkpoint().unwrap(); + + let mut loaded = build(); + loaded.load_state(&file).unwrap(); + let mut loaded_counts = counts.clone(); + apply_host_ops(&mut loaded, after, &mut loaded_counts); + assert_eq!(loaded_counts, expected, "state file saved after {before:?}"); + + let mut continued = counts.clone(); + apply_host_ops(&mut first, after, &mut continued); + assert_eq!(continued, expected, "the run saved after {before:?}"); + first.restore(&checkpoint).unwrap(); + let mut restored = counts; + apply_host_ops(&mut first, after, &mut restored); + assert_eq!(restored, expected, "checkpoint taken after {before:?}"); + } +} From cb8e54c27121476cf4713660feb2ae29a19185bf Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 13:03:42 +0900 Subject: [PATCH 3/5] test(sv): expect 9.4.2.3 event_conditional to pass Change-Id: Ifdd7058d940a9394fb51d7121382b87c5d31f723 --- conformance/sv-tests/README.md | 10 ++++++++++ conformance/sv-tests/expected.tsv | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 24dc1a681cb..55c030b389e 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -229,3 +229,13 @@ These fixtures exercise the actual upstream runner with a controlled driver, including mode priority, skips, negative tests, assertions, timeouts, library injection and missing-environment failures. The Rust example is a single-case compiler/simulator driver; it does not parse sv-tests metadata or judge verdicts. + +`iff`-qualified event controls in processes update two rows: both state modes +for `9.4.2.3--event_conditional` change from fail to pass. The official runner +selects elaboration for this probe, a plain `always @(posedge clk iff en == 1)` +with a nonblocking body, which now runs as a process. A copy with driven clock, +enable and data was simulated: the register keeps its value at an edge with the +enable low and loads the data at the next edge with it high, as in Verilator +5.052. Full official runs at the pinned revision report 546 passing cases in +2state and 548 in 4state, with no passing case regressing. `iff` on `always_ff` +events stays rejected. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c5e36c0a10e..34e2166d30b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1623,8 +1623,8 @@ chapter-9/9.4.2.1--event_or_op.sv 2state pass chapter-9/9.4.2.1--event_or_op.sv 4state pass chapter-9/9.4.2.2--event_implicit.sv 2state pass chapter-9/9.4.2.2--event_implicit.sv 4state pass -chapter-9/9.4.2.3--event_conditional.sv 2state fail -chapter-9/9.4.2.3--event_conditional.sv 4state fail +chapter-9/9.4.2.3--event_conditional.sv 2state pass +chapter-9/9.4.2.3--event_conditional.sv 4state pass chapter-9/9.4.2.4--event_sequence.sv 2state fail chapter-9/9.4.2.4--event_sequence.sv 4state fail chapter-9/9.4.3--event_sequence_controls.sv 2state pass From 99618af6d525457ec757e670708d3db2db793d2c Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 07:03:07 +0900 Subject: [PATCH 4/5] fix(sv): observe gated automatic clocks at each write Record whether both iff operands are plain variables independently of global gate counters. Automatic clock pulses with module-level gates now observe each assignment; continuous and expression operands still wait for settling. The new regression failed on all six configurations before the fix and passes afterward. Full SV: 6185 passed; Clippy, NAPI/JS435 and retained evidence checks passed. Standalone external Top/Wrapped results retain the exact unsupported/disagreement outcomes. Change-Id: I5cf7b95d7a66a1bd4d30777197678472381c5ed7 --- crates/celox-design/src/lib.rs | 11 ++- .../src/symbolic/assembly.rs | 9 +- crates/celox-frontend-sv/src/lowering/ff.rs | 21 +++-- crates/celox-runtime/src/schedule.rs | 1 + crates/celox-runtime/src/simulation/wait.rs | 7 +- crates/celox-runtime/src/timing.rs | 1 + crates/celox-test-suite/LIMITATIONS.md | 6 +- .../src/sv/cases/timing.vtest | 17 ++++ ...utomatic_clock_preserves_enabled_pulses.sv | 14 +++ .../repros/sv_iff_hierarchy_automatic.json | 89 +++++++++++++++++++ .../verification/sv/icarus/timing.json | 24 +++++ .../verification/sv/limitations.json | 8 +- .../verification/sv/verilator/timing.json | 27 +++++- .../verification/sv/xezim/timing.json | 11 +++ .../verification/xezim-review.json | 12 +++ .../tests/frontends/systemverilog/timing.rs | 4 + 16 files changed, 234 insertions(+), 28 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index e356b23a4f1..4802b1bfb37 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -894,11 +894,13 @@ pub struct WaitSite { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct WaitGate { pub signal: A, + /// Both operands are plain variables whose values can be read at an + /// assignment boundary, including activation-local variables without counters. + pub at_write: bool, /// Counters that the writes of the term's signal bump at the write - /// itself, judging the gate there. Without them the gate is read when - /// the runtime detects the occurrence, after combinational logic - /// settled: for a gate or a signal that a continuous assignment or a - /// flip-flop drives. + /// itself, judging the gate there. Activation-local variables instead use + /// runtime assignment boundaries. Expressions and continuous/flip-flop + /// drivers clear `at_write` and require a settled observation. pub counters: Option>, } @@ -916,6 +918,7 @@ impl WaitGate { pub fn map(&self, mut map: impl FnMut(A) -> B) -> WaitGate { WaitGate { signal: map(self.signal), + at_write: self.at_write, counters: self.counters.map(|counters| GateCounters { gated: map(counters.gated), all: map(counters.all), diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 3a59619ffd4..cd7b58574b6 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1006,7 +1006,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .zip(&site.gates) .filter_map(|(&(signal, _), gate)| { gate.as_ref() - .filter(|gate| gate.counters.is_some()) + .filter(|gate| gate.at_write) .map(|gate| [signal, gate.signal]) }) }) @@ -4710,16 +4710,17 @@ fn gated_terms( let Some(gate) = gate else { continue; }; - let Some(counters) = gate.counters else { - continue; - }; if ff_written.contains(&signal) || continuous.contains(&signal) || continuous.contains(&gate.signal) { gate.counters = None; + gate.at_write = false; continue; } + let Some(counters) = gate.counters else { + continue; + }; gated .entry(signal) .or_default() diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 5628cdcdab0..07590f16263 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -6675,7 +6675,7 @@ impl Ff<'_, '_> { if !self.m.is_hidden(id) || (self.forked && self.frame_locals.contains(&id)) => { - variable = !self.m.is_hidden(id) && self.m.var(id).array_dims.is_empty(); + variable = self.m.var(id).array_dims.is_empty(); id } Some(_) => self.event_expression(&expr, samples)?, @@ -6697,11 +6697,18 @@ impl Ff<'_, '_> { }; for &kind in kinds { terms.push((id, kind)); - gates.push(gate.map(|(signal, gate_variable)| WaitGate { - signal, - // A variable's write is judged with a variable gate at - // the write itself. - counters: (variable && gate_variable).then(|| self.gate_counters()), + gates.push(gate.map(|(signal, gate_variable)| { + WaitGate { + signal, + at_write: variable && gate_variable, + // Shared module storage has counters; activation-local + // operands are read at each process assignment boundary. + counters: (variable + && gate_variable + && !self.m.is_hidden(id) + && !self.m.is_hidden(signal)) + .then(|| self.gate_counters()), + } })); } } @@ -6753,7 +6760,7 @@ impl Ff<'_, '_> { && self.m.var(id).float.is_none() && self.m.var(id).array_dims.is_empty() { - return Ok((id, !self.m.is_hidden(id))); + return Ok((id, true)); } let not = |expr| sv::ir::Expr::Unary { op: sv::ir::UnaryOp::LogicNot, diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index e6ba0bb87c9..8bead591e97 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -207,6 +207,7 @@ impl ResolvedSchedule { }; let gate_refs = |gate: &celox_design::WaitGate| GateRefs { signal: resolve(&gate.signal), + at_write: gate.at_write, counters: gate.counters.map(|counters| GateCounterRefs { gated: resolve(&counters.gated), all: resolve(&counters.all), diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index a5bf076b20e..777262ba022 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -267,11 +267,7 @@ impl SimulationState { ); continue; } - let local_variable = processes[process] - .frame - .as_ref() - .is_some_and(|frame| frame.locals.contains(&gate.signal)); - if !settled && !local_variable { + if !settled && !gate.at_write { continue; } } @@ -528,6 +524,7 @@ impl SimulationState { let Some(GateRefs { signal: gate, counters: Some(counters), + .. }) = *gate else { continue; diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index ae80fa269fb..7ea47d08440 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -108,6 +108,7 @@ impl CountedRefs { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct GateRefs { pub signal: SignalRef, + pub at_write: bool, /// The counters of a gate judged at each write /// ([`celox_design::GateCounters`]). pub counters: Option, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 2d4a513e437..0850b438f99 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -618,7 +618,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_program_exit` | execute | icarus | 1 | Icarus 13.0 does not define `$exit`; IEEE 1800-2023 24.7 ends the calling program's `initial` procedures. | | `sv_verilator_program_exit` | execute | verilator | 1 | Verilator 5.052 continues after `$exit` and keeps the program's other `initial` procedures (24.7). Icarus does not run the case; xezim 0.11.3 agrees with the expected output. | | `sv_verilator_program_items` | compile | verilator | 2 | Verilator 5.052 rejects an `always` procedure and a module instance in a program with syntax errors, which the run cannot count as language rejections. Both are illegal (IEEE 1800-2023 24.3); Icarus 13.0 rejects them with diagnostics that name the rule. | -| `sv_icarus_iff_event_controls` | compile | icarus | 14 | Icarus 13.0 rejects `iff` in an event control with "syntax error" and "Malformed event control expression." IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; [Standalone probe](verification/repros/sv_iff_event_controls_icarus.json); Verilator 5.052 runs the cases and gives the asserted counts. | +| `sv_icarus_iff_event_controls` | compile | icarus | 15 | Icarus 13.0 rejects `iff` in an event control with "syntax error" and "Malformed event control expression." IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; [Standalone probe](verification/repros/sv_iff_event_controls_icarus.json); Verilator 5.052 runs the cases and gives the asserted counts. | | `sv_verilator_iff_late_conditions` | execute | verilator | 4 | Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. [Standalone probes](verification/repros/sv_iff_late_conditions_verilator.json) print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) @@ -963,12 +963,12 @@ Assertions and exclusions are unchanged. ### Conditional events across hierarchy and automatic fork scopes -The three additional `timing::iff_*` regressions preserve strict event-time +The four additional `timing::iff_*` regressions preserve strict event-time conditions (IEEE 1800-2023 9.4.2.3) and shared automatic lifetimes (6.21). [Standalone Top and Wrapped probes](verification/repros/sv_iff_hierarchy_automatic.json) reproduce Verilator 5.052's late hierarchical gate and shared-local LIFETIME rejection, and Icarus 13.0's unsupported event syntax. The installed xezim 0.11.3 build -misorders gates and does not reflect the shared automatic gate update. Its five +misorders gates and does not reflect the shared automatic gate update. Its six failures remain executed evidence, not exclusions. The current flake pin could not be built because the dependency lock references a different xezim-core revision; the evidence identifies the installed binary and does not claim current-pin coverage. diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index bb8109ebb28..21a08717a56 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2980,3 +2980,20 @@ endmodule"#) endmodule"#) (top Top) (run_until 4) (assert_eq accepted 1) (assert_eq rejected 0)) + +; The clock, not only the gate, can live in a shared automatic cell. +(case iff_automatic_clock_preserves_enabled_pulses + (source "iff_automatic_clock.sv" #"module Top(output int accepted, rejected); + bit enable=1; + initial begin + automatic bit clock=0; + fork + begin @(posedge clock iff enable); accepted++; end + begin @(negedge clock iff enable); rejected++; end + begin #1 clock=1; enable=0; clock=0; end + join_none + #3; + end +endmodule"#) + (top Top) (run_until 4) + (assert_eq accepted 1) (assert_eq rejected 0)) diff --git a/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv b/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv new file mode 100644 index 00000000000..7866c3d4782 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv @@ -0,0 +1,14 @@ +module Top(output int accepted, rejected); + bit enable=1; + initial begin + automatic bit clock=0; + fork + begin @(posedge clock iff enable); accepted++; end + begin @(negedge clock iff enable); rejected++; end + begin #1 clock=1; enable=0; clock=0; end + join_none + #3; + end + initial begin #4; $display("accepted=%0d rejected=%0d", accepted, rejected); $finish; end +endmodule +module Wrapped; Top dut(); endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_iff_hierarchy_automatic.json b/crates/celox-test-suite/verification/repros/sv_iff_hierarchy_automatic.json index ee1a942e24b..fa15e3b510f 100644 --- a/crates/celox-test-suite/verification/repros/sv_iff_hierarchy_automatic.json +++ b/crates/celox-test-suite/verification/repros/sv_iff_hierarchy_automatic.json @@ -339,6 +339,95 @@ "exit_code": 0, "output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\nn=0\nSimulation finished at time 2 ($finish called)\n" } + }, + { + "case": "timing::iff_automatic_clock_preserves_enabled_pulses", + "source": "iff_automatic_clock_preserves_enabled_pulses.sv", + "expected_output": "accepted=1 rejected=0", + "observations": [ + { + "top": "Top", + "verilator_compile": { + "command": [ + "/nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator", + "--binary", + "--timing", + "-Wno-fatal", + "--top-module", + "Top", + "--Mdir", + "/work/p2-probe-Top", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 1, + "output": "%Error-LIFETIME: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:8:15: Invalid reference: Process might outlive variable 'clock'.\n : ... note: In instance 'Top'\n : ... Suggest use it as read-only to initialize a local copy at the beginning of the process, or declare it as static. It is also possible to refer by reference to objects and their members.\n 8 | begin #1 clock=1; enable=0; clock=0; end\n | ^~~~~\n ... For error description see https://verilator.org/warn/LIFETIME?v=5.052\n%Error-LIFETIME: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:8:34: Invalid reference: Process might outlive variable 'clock'.\n : ... note: In instance 'Top'\n : ... Suggest use it as read-only to initialize a local copy at the beginning of the process, or declare it as static. It is also possible to refer by reference to objects and their members.\n 8 | begin #1 clock=1; enable=0; clock=0; end\n | ^~~~~\n%Error: Exiting due to 2 error(s)\n" + }, + "icarus_compile": { + "command": [ + "/nix/store/l2wn6zv7pwybn4vi7q2xgw8snzla1azh-iverilog-13.0/bin/iverilog", + "-g2012", + "-s", + "Top", + "-o", + "/work/p2-probe-Top.vvp", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 7, + "output": "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:4: sorry: Overriding the default variable lifetime is not yet supported.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: syntax error\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: error: Malformed event control expression.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: error: Invalid event control.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: syntax error\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: error: Malformed event control expression.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: error: Invalid event control.\n" + }, + "xezim_run": { + "command": [ + "/nix/store/1869dyxd44fz4kh02dmng33gyxdx5m61-xezim-0.11.3/bin/xezim", + "-s", + "Top", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 0, + "output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\naccepted=1 rejected=1\nSimulation finished at time 4 ($finish called)\n" + } + }, + { + "top": "Wrapped", + "verilator_compile": { + "command": [ + "/nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator", + "--binary", + "--timing", + "-Wno-fatal", + "--top-module", + "Wrapped", + "--Mdir", + "/work/p2-probe-Wrapped", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 1, + "output": "%Warning-PINMISSING: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:14:21: Instance has missing pin: 'accepted'\n 14 | module Wrapped; Top dut(); endmodule\n | ^~~\n /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:1:23: ... Location of port declaration\n 1 | module Top(output int accepted, rejected);\n | ^~~~~~~~\n ... For warning description see https://verilator.org/warn/PINMISSING?v=5.052\n ... Use \"/* verilator lint_off PINMISSING */\" and lint_on around source to disable this message.\n%Warning-PINMISSING: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:14:21: Instance has missing pin: 'rejected'\n 14 | module Wrapped; Top dut(); endmodule\n | ^~~\n /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:1:33: ... Location of port declaration\n 1 | module Top(output int accepted, rejected);\n | ^~~~~~~~\n%Error-LIFETIME: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:8:15: Invalid reference: Process might outlive variable 'clock'.\n : ... note: In instance 'Wrapped.dut'\n : ... Suggest use it as read-only to initialize a local copy at the beginning of the process, or declare it as static. It is also possible to refer by reference to objects and their members.\n 8 | begin #1 clock=1; enable=0; clock=0; end\n | ^~~~~\n ... For error description see https://verilator.org/warn/LIFETIME?v=5.052\n%Error-LIFETIME: /crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:8:34: Invalid reference: Process might outlive variable 'clock'.\n : ... note: In instance 'Wrapped.dut'\n : ... Suggest use it as read-only to initialize a local copy at the beginning of the process, or declare it as static. It is also possible to refer by reference to objects and their members.\n 8 | begin #1 clock=1; enable=0; clock=0; end\n | ^~~~~\n%Error: Exiting due to 2 error(s)\n" + }, + "icarus_compile": { + "command": [ + "/nix/store/l2wn6zv7pwybn4vi7q2xgw8snzla1azh-iverilog-13.0/bin/iverilog", + "-g2012", + "-s", + "Wrapped", + "-o", + "/work/p2-probe-Wrapped.vvp", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 7, + "output": "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:4: sorry: Overriding the default variable lifetime is not yet supported.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: syntax error\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: error: Malformed event control expression.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:6: error: Invalid event control.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: syntax error\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: error: Malformed event control expression.\n/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv:7: error: Invalid event control.\n" + }, + "xezim_run": { + "command": [ + "/nix/store/1869dyxd44fz4kh02dmng33gyxdx5m61-xezim-0.11.3/bin/xezim", + "-s", + "Wrapped", + "/crates/celox-test-suite/verification/repros/iff_automatic_clock_preserves_enabled_pulses.sv" + ], + "exit_code": 0, + "output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\naccepted=1 rejected=1\nSimulation finished at time 4 ($finish called)\n" + } + } + ] } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 98efed19327..71f4f5a49a2 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -597,6 +597,30 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_event_controls_icarus.json", + "verification/repros/sv_iff_hierarchy_automatic.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_iff_event_controls", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`.", + "upstream": [] + }, + "name": "timing::iff_automatic_clock_preserves_enabled_pulses", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Icarus 13.0 rejects `iff` in an event control with \"syntax error\" and \"Malformed event control expression.\" IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 1a0d7e0d69e..c4d4a4ba489 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2764,7 +2764,8 @@ "timing::iff_conditions_follow_combinational_process_order", "timing::iff_conditions_preserve_cross_module_combinational_order", "timing::iff_forked_automatic_gates_are_separate", - "timing::iff_shared_automatic_gate_uses_edge_time_value" + "timing::iff_shared_automatic_gate_uses_edge_time_value", + "timing::iff_automatic_clock_preserves_enabled_pulses" ] } }, @@ -2794,7 +2795,7 @@ "category": "simulator_unsupported", "phase": "compile", "observed_version": "Verilator 5.052", - "reason": "Verilator 5.052 rejects the write to a shared automatic gate in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", + "reason": "Verilator 5.052 rejects the write to a shared automatic gate or event signal in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", "upstream": [], "evidence": [ "verification/repros/sv_iff_hierarchy_automatic.json", @@ -2802,7 +2803,8 @@ ], "cases": { "verilator": [ - "timing::iff_shared_automatic_gate_uses_edge_time_value" + "timing::iff_shared_automatic_gate_uses_edge_time_value", + "timing::iff_automatic_clock_preserves_enabled_pulses" ] } } diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 99632c8dc5f..61c08be3a6c 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -669,6 +669,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 rejects the write to a shared automatic gate or event signal in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_iff_hierarchy_automatic.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_iff_shared_automatic", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "Verilator 5.052 rejects the write to a shared automatic gate or event signal in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", + "upstream": [] + }, + "name": "timing::iff_automatic_clock_preserves_enabled_pulses", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. Standalone probes print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. A hierarchical waiter on clk also sees the later en write of a child always_comb (clk=a; en=a), giving rejected=2 instead of 0; reversing those writes correctly gives accepted=2.", @@ -767,7 +790,7 @@ }, { "category": "Sequential", - "detail": "Verilator 5.052 rejects the write to a shared automatic gate in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", + "detail": "Verilator 5.052 rejects the write to a shared automatic gate or event signal in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", "expectation": "Simulation", "known_issue": { "category": "simulator_unsupported", @@ -778,7 +801,7 @@ "id": "sv_verilator_iff_shared_automatic", "observed_version": "Verilator 5.052", "phase": "compile", - "reason": "Verilator 5.052 rejects the write to a shared automatic gate in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", + "reason": "Verilator 5.052 rejects the write to a shared automatic gate or event signal in fork/join_none with Error-LIFETIME. IEEE 1800-2023 6.21 extends the enclosing scope lifetime until its fork children complete; 9.4.2.3 judges each gate when its event occurs. Standalone Top and Wrapped probes reproduce the rejection. The assertions require accepted=1 and rejected=0.", "upstream": [] }, "name": "timing::iff_shared_automatic_gate_uses_edge_time_value", diff --git a/crates/celox-test-suite/verification/sv/xezim/timing.json b/crates/celox-test-suite/verification/sv/xezim/timing.json index 368451cc1f5..4457409a69b 100644 --- a/crates/celox-test-suite/verification/sv/xezim/timing.json +++ b/crates/celox-test-suite/verification/sv/xezim/timing.json @@ -627,6 +627,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "timing::iff_automatic_clock_preserves_enabled_pulses at 2999:25: assert_eq rejected: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::iff_automatic_clock_preserves_enabled_pulses", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "timing::iff_conditions_are_judged_at_the_write at 2864:3: expect_output: expected [110, 61, 49, 10], got [110, 61, 48, 10]", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 3913f831a93..1e81d465e3c 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -678,6 +678,10 @@ "sv_iff_shared_automatic": { "title": "fork children do not observe updates to their shared automatic iff gate", "standard": "IEEE 1800-2023 6.21, 9.3.2, 9.4.2.3" + }, + "sv_iff_automatic_clock": { + "title": "A wait on an automatic clock keeps an enabled iff gate after the gate was cleared", + "standard": "IEEE 1800-2023 9.4.2.3" } }, "cases": [ @@ -4167,6 +4171,14 @@ "classification": "xezim_bug", "bug": "sv_iff_shared_automatic", "note": "The shared automatic enable becomes 0 before second rises, but rejected=1 instead of 0. Independent standalone reproductions and exact installed build provenance are in verification/repros/sv_iff_hierarchy_automatic.json. Current flake-pin build was unavailable; these observations are from the installed xezim 0.11.3 build." + }, + { + "suite": "sv", + "name": "timing::iff_automatic_clock_preserves_enabled_pulses", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_iff_automatic_clock", + "note": "The module gate enable is cleared between the rising and falling writes to the shared automatic clock. Standalone Top/Wrapped print accepted=1 rejected=1; 9.4.2.3 requires accepted=1 rejected=0. See verification/repros/sv_iff_hierarchy_automatic.json for exact installed-build provenance and source; this is not current-pin validation." } ] } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 7bb0c6e2682..09bec292788 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -1841,3 +1841,7 @@ fn iff_fork_waits_keep_gates_across_state_files() { assert_eq!(loaded.get(loaded.signal(name)), expected.into(), "{name}"); } } + +timed_cases! { + fn iff_automatic_clock_preserves_enabled_pulses = "timing::iff_automatic_clock_preserves_enabled_pulses"; +} From c66d10df0414a8605afe7349850b5166382eb60f Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 28 Oct 2026 07:22:53 +0900 Subject: [PATCH 5/5] fix(sv): preserve automatic iff waits across implicit and host writes Reject unobserved function writes to direct activation-local gated-wait operands, matching the existing event-probe restriction. Replay tracked host pulses against the waiting activation gate when no gate counter preserves them; retain false-gate baseline updates. Both new regressions failed before the fix. Final timing regressions: 1277 passed, including interpreter/native/Cranelift/Wasm host pulses and state-file replay; Clippy and NAPI/JS435 passed. Shared language fixtures are unchanged. Change-Id: I8f5f03c395769d784bb92da31af6ab91c72220b8 --- crates/celox-frontend-sv/src/lowering/ff.rs | 18 +++- crates/celox-runtime/src/simulation/wait.rs | 27 ++++- .../tests/frontends/systemverilog/timing.rs | 102 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 3 + docs/ja/guide/systemverilog-reference.md | 2 + 5 files changed, 146 insertions(+), 6 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 07590f16263..50c20c4148c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -5977,12 +5977,26 @@ impl Ff<'_, '_> { "activation-local event expression without assignment observation boundaries", )); } - if self.event_probes.iter().any(|probe| { + let implicit_probe_write = self.event_probes.iter().any(|probe| { probe .inputs .iter() .any(|input| self.unobserved_function_writes.contains(input)) - }) { + }); + let implicit_gate_write = self.wait_sites.iter().any(|site| { + site.terms + .iter() + .zip(&site.gates) + .any(|(&(signal, _), gate)| { + gate.is_some_and(|gate| { + gate.at_write + && gate.counters.is_none() + && (self.unobserved_function_writes.contains(&signal) + || self.unobserved_function_writes.contains(&gate.signal)) + }) + }) + }); + if implicit_probe_write || implicit_gate_write { return Err(unsupported( "implicit write to an activation-local event operand without an observation boundary", )); diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 777262ba022..608873163b9 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -560,6 +560,7 @@ impl SimulationState { ready, reactive, activations, + cells, .. } = &mut self.process_state; waiters.retain(false, |process, waiter| { @@ -572,10 +573,28 @@ impl SimulationState { .zip(&mut waiter.baselines) .enumerate() { - // A gated term is judged at the next settled check. - if term.signal != signal || gates.get(index).is_some_and(Option::is_some) { + if term.signal != signal { continue; } + let gate_holds = match gates.get(index).copied().flatten() { + None => true, + Some(gate) if gate.at_write && gate.counters.is_none() => { + // No module counter can capture an activation-local + // gate. Replay each host value with that activation's + // unchanged gate before HDL execution resumes. + let Some(value) = super::activation::activation_value( + activations, + cells, + &processes[process], + process, + gate.signal, + ) else { + continue; + }; + value.0.bit(0) && !value.1.bit(0) + } + Some(_) => continue, + }; match baseline { // Counters are bumped by the write itself. Baseline::Counter { .. } @@ -583,10 +602,10 @@ impl SimulationState { | Baseline::Gated { .. } => {} Baseline::Raw(last) => { let now = encode_planes(value, signal.width, last.len()); - wake |= Self::advance(term.kind, last, &now, signal.width); + wake |= Self::advance(term.kind, last, &now, signal.width) & gate_holds; } Baseline::Value(last) => { - wake |= occurs(term.kind, last, value); + wake |= occurs(term.kind, last, value) & gate_holds; *last = value.clone(); } } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 09bec292788..5cac2654277 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -1845,3 +1845,105 @@ fn iff_fork_waits_keep_gates_across_state_files() { timed_cases! { fn iff_automatic_clock_preserves_enabled_pulses = "timing::iff_automatic_clock_preserves_enabled_pulses"; } + +#[test] +fn iff_automatic_gate_rejects_unobserved_function_writes() { + let source = r#" + module Top(output int n); + bit clk; + function automatic int pulse(output bit gate); + clk=1; gate=0; return 0; + endfunction + initial begin + automatic bit enable=1; + int unused; + fork + begin @(posedge clk iff enable); n++; end + begin #1; unused=pulse(enable); end + join_none + #3; + end + endmodule + "#; + let error = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_function_write.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("implicit function writes require observation boundaries")) + .to_string(); + assert!( + error.contains("implicit write to an activation-local event operand"), + "{error}" + ); + let unrelated = source + .replace("bit clk;", "bit clk, other;") + .replace("clk=1; gate=0;", "other=1; gate=0;") + .replace( + "automatic bit enable=1;", + "automatic bit enable=1, other_gate=0;", + ) + .replace("pulse(enable)", "pulse(other_gate)"); + assert!( + celox::Simulation::from_sv_sources( + vec![( + unrelated.as_str(), + std::path::Path::new("iff_unrelated_function.sv") + )], + "Top" + ) + .build() + .is_ok() + ); +} + +#[test] +fn iff_host_pulses_use_the_waiting_automatic_gate() { + let source = r#" + module Top(input bit clk, output int accepted, rejected); + timeunit 1ns / 1ns; + initial begin + automatic bit enabled=1, disabled=0; + fork + begin @(posedge clk iff enabled); accepted++; end + begin @(posedge clk iff disabled); rejected++; end + join_none + #4; + end + endmodule + "#; + let build = || { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("iff_local_host_pulse.sv"))], + "Top", + ) + }; + macro_rules! check { + ($sim:expr) => {{ + let mut sim = $sim.unwrap(); + sim.run_until(1).unwrap(); + let clk = sim.signal("clk"); + sim.modify(|io| { + io.set(clk, 1u8); + io.set(clk, 0u8); + }) + .unwrap(); + let mut bytes = Vec::new(); + sim.save_state().unwrap().write_to(&mut bytes).unwrap(); + let file = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + for restored in [false, true] { + if restored { + sim.load_state(&file).unwrap(); + } + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("accepted")), 1u32.into()); + assert_eq!(sim.get(sim.signal("rejected")), 0u32.into()); + } + }}; + } + check!(build().build_interpreter()); + check!(build().build_native()); + check!(build().build_cranelift()); + check!(build().build_wasm()); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7e009d5364e..512905916c6 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -761,6 +761,9 @@ unsupported, including when the inference option is enabled. `clk = 1; en = 0;` is an event and `en = 0; clk = 1;` is none. This also preserves assignment order across hierarchical references and reads automatic gates from the waiting activation, including shared fork locals. + Tracked host pulses also use that activation's gate. Implicit function or + output-argument writes to operands of an automatic gated wait are rejected + until those writes have safe assignment observation boundaries. Verilator 5.052 judges the condition later, after the process suspends, and gives the opposite results. A condition that is an expression or a net, an `expr` other than a variable, and a variable that a flip-flop diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 23a0026632d..5f92b8fe0ec 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -389,6 +389,8 @@ Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatche スケジュールされたクロックのエッジ、ホストの書き込みといった `expr` への書き込みごとに条件を判定します。 1つのプロセスで `clk = 1; en = 0;` はイベントになり、`en = 0; clk = 1;` はなりません。 階層参照でも書き込み順を保持し、automatic な条件は待機側の activation から読みます。fork で共有する局所変数も対象です。 + ホスト書き込みのパルスも待機側の条件で判定します。automatic 変数を含む gated wait のオペランドへの、 + 関数や出力引数経由の暗黙の書き込みは、安全な代入観測境界に未対応のため拒否します。 Verilator 5.052 はプロセスが suspend した後で条件を判定し、逆の結果になります。式やネットの条件、 変数以外の `expr`、flip-flop の domain が書く変数([#1830](https://github.com/celox-sim/celox/issues/1830))は、 組み合わせ回路が確定した後に発生を検出した時点で判定します。イベント式と同じく、プロセスの書き込みは