From a4de2ae73b4e877dc6c4963f7f62abdf89d94804 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 12:45:14 +0900 Subject: [PATCH 1/9] fix(sv): count intermediate writes of combinational and flip-flop units A process waiting on a variable missed a value that one evaluation of an always_comb, a blocking edge-triggered always or an always_ff writes and then overwrites (`y = 0; if (a) y = 1;`). Each store is an update event (IEEE 1800-2023 4.3, 9.4.2), and nonblocking updates apply in the NBA region in issue order, each its own update (10.4.2). In a design with a wait: - An always_comb that may store a variable twice is lowered both symbolically and as a gated imperative unit. Assembly keeps the unit for an instance in which such a variable is counted, and the symbolic definitions otherwise. - A flip-flop evaluation that may write a signal twice keeps its first written value and counts the occurrences between later writes as pending; the commit adds the occurrence from the published value to the first one, and the pending ones. Staged nonblocking writes of a variable also written by blocking assignments are counted on the value the NBA merge publishes. - Commits of a counted signal written once are counted at the commit. Units that write no counted signal are unchanged, and a design without a wait lowers exactly as before. Fixes #1706 Change-Id: I6096fe2d13f0205b53fd8342c9057801a71c2465 --- crates/celox-frontend-core/src/sdk.rs | 2 + .../src/symbolic/artifact.rs | 23 + .../src/symbolic/assembly.rs | 170 ++++- crates/celox-frontend-core/src/watch.rs | 598 ++++++++++++++++-- crates/celox-frontend-sv/src/lowering.rs | 228 ++++++- crates/celox-frontend-sv/src/lowering/ff.rs | 21 + .../src/lowering/procedural.rs | 62 ++ crates/celox-frontend-veryl/src/artifact.rs | 2 + 8 files changed, 1018 insertions(+), 88 deletions(-) diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 2a5196e29ef..35e23ba1a62 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1942,6 +1942,8 @@ pub fn lower_frontend_artifact( processes, package_bindings: HashMap::default(), counter_slots, + pending_slots: Vec::new(), + comb_alternatives: Vec::new(), wait_sites, nba_sites, nba_switches: Vec::new(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index a505345d621..2e43cf04ff7 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -66,6 +66,23 @@ pub struct SplitCommit { pub nba: ExecutionUnit, } +/// A combinational process that `comb_blocks` holds both as symbolic +/// definitions and as an imperative unit. The symbolic form computes only +/// the final value of each written variable; the unit performs every store, +/// so the counters of a watched variable see the intermediate values +/// (IEEE 1800-2023 4.3, 9.4.2). Assembly keeps the unit for an instance in +/// which a variable of `candidates` is counted, and the symbolic +/// definitions otherwise. +#[derive(Clone, Debug)] +pub struct CombAlternative { + /// The `process` of the unit's paths. + pub process: SourceVarId, + /// The variables the symbolic definitions write. + pub targets: Vec, + /// The variables the unit may store twice in one execution. + pub candidates: Vec, +} + #[derive(Clone)] pub struct SimModule { /// A frontend's global tick precision; absent for scale-free frontends. @@ -117,6 +134,12 @@ pub struct SimModule { /// `crate::watch::multi_store_candidates`). Assembly counts a signal's /// occurrences only if a flip-flop domain or a wait watches it. pub counter_slots: Vec>, + /// Objects that hold the occurrences of a flip-flop's repeated writes + /// to a signal until their commit (see `crate::watch::PendingSlots`). + /// Assembly uses them only for the signals it counts. + pub pending_slots: Vec>, + /// Combinational processes lowered both ways; see [`CombAlternative`]. + pub comb_alternatives: Vec, /// Wait sites of the module's processes; `process` indexes /// [`Self::processes`]. pub wait_sites: Vec>, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 9e7edb1dc0c..941669535a2 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -16,7 +16,7 @@ use celox_design::{ InitialStateValue, InstanceId, ModuleId, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase, - VariableMetadata, WaitSite, + VariableMetadata, WORKING_REGION, WaitSite, }; use celox_sir::{ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIROffset, @@ -745,6 +745,14 @@ pub fn schedule_symbolic_rtl_reporting_loops( .map(|(alias, _)| *alias), ) .collect(); + let counted = counted_signals(&timing, &event_addresses); + choose_comb_alternatives( + bindings, + &instance_modules, + &modules, + &counted, + &mut comb_blocks, + ); // Count sensitivity occurrences before any optimizer can coalesce // consecutive writes whose final value is unchanged. let mut probes = Vec::new(); @@ -868,13 +876,32 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } } + let ff_units = eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + .chain(apply_ffs.values_mut()) + .flatten() + .chain( + parallel_ff_units + .values_mut() + .flatten() + .flat_map(|(_, part)| [&mut part.evaluate, &mut part.apply]), + ) + .chain( + split_commits + .values_mut() + .flatten() + .flatten() + .flat_map(|split| [&mut split.active, &mut split.nba]), + ); instrument_counted_signals( &timing, - &event_addresses, + counted, &variables, four_state, &mut processes, &mut comb_blocks, + ff_units, ) }; // Combinational values and the variables they are computed from. @@ -3232,6 +3259,7 @@ struct RelocatedProcess { /// design. struct TimingMetadata { counter_slots: Vec>, + pending_slots: Vec>, wait_sites: Vec>, nba_sites: Vec>, host_request_sites: Vec>, @@ -3540,6 +3568,7 @@ fn relocate_timing( instances.sort_unstable_by_key(|(instance, _)| **instance); let mut metadata = TimingMetadata { counter_slots: Vec::new(), + pending_slots: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), host_request_sites: Vec::new(), @@ -3552,6 +3581,9 @@ fn relocate_timing( metadata .counter_slots .extend(module.counter_slots.iter().map(|slots| slots.map(locate))); + metadata + .pending_slots + .extend(module.pending_slots.iter().map(|slots| slots.map(locate))); metadata .wait_sites .extend(module.wait_sites.iter().map(|site| WaitSite { @@ -3588,28 +3620,72 @@ fn relocate_timing( /// Counted signals: those a unit may store twice between two runtime checks /// (a frontend declared counters for them) and that a flip-flop domain or a -/// wait watches. Returns their counters by signal and instruments the -/// process kernels and combinational process units that write them; no -/// other unit changes. -fn instrument_counted_signals( +/// wait watches, by signal. +fn counted_signals( timing: &TimingMetadata, event_addresses: &HashSet, - variables: &HashMap, - four_state: bool, - processes: &mut [RelocatedProcess], - comb_blocks: &mut [LogicPath], ) -> BTreeMap> { let waited: HashSet = timing .wait_sites .iter() .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)) .collect(); - let counted: BTreeMap> = timing + timing .counter_slots .iter() .filter(|slots| event_addresses.contains(&slots.signal) || waited.contains(&slots.signal)) .map(|slots| (slots.signal, *slots)) - .collect(); + .collect() +} + +/// Keep, for every instance of a process in `comb_alternatives`, either +/// its imperative unit, when a variable it may store twice is `counted`, or +/// its symbolic definitions, and remove the other form from `comb_blocks`. +fn choose_comb_alternatives( + bindings: &PackageBindings, + instance_modules: &HashMap, + modules: &HashMap, + counted: &BTreeMap>, + comb_blocks: &mut Vec>, +) { + let mut imperative = HashSet::default(); + let mut symbolic = HashSet::default(); + 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))) + { + symbolic.extend(alternative.targets.iter().map(|&target| locate(target))); + } else { + imperative.insert(locate(alternative.process)); + } + } + } + if imperative.is_empty() && symbolic.is_empty() { + return; + } + comb_blocks.retain(|path| match &path.target { + LogicPathTarget::Var(target) => !symbolic.contains(&target.id), + LogicPathTarget::Process { process, .. } => !imperative.contains(process), + LogicPathTarget::CombCaptureEvent { .. } => true, + }); +} + +/// Instrument the process kernels, combinational process units and +/// flip-flop units that write a `counted` signal, and return `counted`; no +/// other unit changes. +fn instrument_counted_signals<'u>( + timing: &TimingMetadata, + counted: BTreeMap>, + variables: &HashMap, + four_state: bool, + processes: &mut [RelocatedProcess], + comb_blocks: &mut [LogicPath], + ff_units: impl Iterator>, +) -> BTreeMap> { if counted.is_empty() { return counted; } @@ -3655,6 +3731,76 @@ fn instrument_counted_signals( }); } } + let stable = |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var); + let working = |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, var); + let watch = |signal: AbsoluteAddr| { + let (slots, width, four_state) = code(signal)?; + 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(), + }) + }; + // A flip-flop writes its next state, and a commit publishes it. Repeated + // writes are held back until the commit; a single write is counted at + // the commit itself. + let pending: Vec<_> = timing + .pending_slots + .iter() + .filter_map(|slots| { + Some(crate::watch::PendingCode { + watch: watch(slots.signal)?, + next: working(slots.signal), + staged: slots.staged.map(|staged| crate::watch::StagedSlots { + value: working(staged.value), + mask: working(staged.mask), + first_mask: stable(staged.first_mask), + }), + first: stable(slots.first), + has_first: stable(slots.has_first), + pending: CounterKind::ALL + .into_iter() + .map(|kind| (kind, stable(slots.pending(kind)))) + .collect(), + }) + }) + .collect(); + let held = |staged: bool| -> HashSet { + timing + .pending_slots + .iter() + .filter(|slots| slots.staged.is_some() == staged) + .map(|slots| slots.signal) + .collect() + }; + let (held_next, held_staged) = (held(false), held(true)); + for unit in ff_units { + crate::watch::instrument_writes(unit, |instruction| match instruction { + // The commit of the next state; a seed copies the other way. + SIRInstruction::Commit(source, destination, ..) + if source.region == WORKING_REGION + && destination.region == STABLE_REGION + && source.absolute_addr() == destination.absolute_addr() + && !held_next.contains(&destination.absolute_addr()) => + { + watch(destination.absolute_addr()) + } + // The merge of staged nonblocking values. + SIRInstruction::Store(destination, ..) + if destination.region == STABLE_REGION + && !held_staged.contains(&destination.absolute_addr()) => + { + watch(destination.absolute_addr()) + } + _ => None, + }); + crate::watch::instrument_pending(unit, &pending); + } counted } diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 008f9d44bc0..28564c159c2 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -367,13 +367,20 @@ pub fn write_destination(instruction: &SIRInstruction) -> Option<&A> { pub fn multi_store_candidates( unit: &ExecutionUnit, key: impl Fn(&A) -> Option, +) -> Vec { + multi_write_candidates(unit, |instruction| { + write_destination(instruction).and_then(&key) + }) +} + +/// [`multi_store_candidates`] with the written key of each instruction +/// given by `key`, for callers that count only some kinds of writes. +pub fn multi_write_candidates( + unit: &ExecutionUnit, + key: impl Fn(&SIRInstruction) -> Option, ) -> Vec { let writes = |block: &celox_sir::BasicBlock| -> Vec> { - block - .instructions - .iter() - .map(|instruction| write_destination(instruction).and_then(&key)) - .collect() + block.instructions.iter().map(&key).collect() }; let block_writes: crate::HashMap>> = unit .blocks @@ -419,6 +426,17 @@ pub fn multi_store_candidates( pub fn instrument_unit( unit: &mut ExecutionUnit, watch_for: impl Fn(&A) -> Option>, +) { + instrument_writes(unit, |instruction| { + write_destination(instruction).and_then(&watch_for) + }); +} + +/// [`instrument_unit`] with the watched signal of each instruction given +/// by `watch_for`, for callers that count only some kinds of writes. +pub fn instrument_writes( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&SIRInstruction) -> Option>, ) { let mut next_register = unit .register_map @@ -427,16 +445,16 @@ pub fn instrument_unit( .max() .unwrap_or(0); for block in unit.blocks.values_mut() { - if !block.instructions.iter().any(|instruction| { - write_destination(instruction) - .and_then(&watch_for) - .is_some() - }) { + if !block + .instructions + .iter() + .any(|instruction| watch_for(instruction).is_some()) + { continue; } let mut instructions = Vec::with_capacity(block.instructions.len()); for instruction in std::mem::take(&mut block.instructions) { - let Some(watch) = write_destination(&instruction).and_then(&watch_for) else { + let Some(watch) = watch_for(&instruction) else { instructions.push(instruction); continue; }; @@ -461,55 +479,487 @@ pub fn instrument_unit( } } +/// Objects that hold back the occurrences of one flip-flop evaluation's +/// writes to a signal until the commit that publishes them. +/// +/// A flip-flop evaluates into the signal's next state, and a commit +/// publishes it in the active or the NBA region. Every write is an update +/// of the signal there, applied in issue order (IEEE 1800-2023 4.5, +/// 10.4.2): `y <= 0; y <= 1;` is two updates. Counting at the writes would +/// wake a waiter before the commit, and counting at the commit alone sees +/// only the final value. So the evaluation keeps its first written value +/// and counts the occurrences between later writes as pending; the commit +/// adds the occurrence from the published value to the first one, and the +/// pending ones. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PendingSlots { + pub signal: A, + /// For the nonblocking writes of a variable the process also writes by + /// blocking assignments: the staging value and mask they go to. + /// Otherwise the writes go to the signal's next state. + pub staged: Option>, + /// The value after the first write, and whether there was one. + pub first: A, + pub has_first: A, + pub changes: A, + pub rises: A, + pub falls: A, +} + +/// The staging objects of [`PendingSlots`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StagedSlots { + pub value: A, + pub mask: A, + /// The mask after the first write: the bits the first value holds. + pub first_mask: A, +} + +impl PendingSlots { + pub fn pending(&self, kind: CounterKind) -> A { + match kind { + CounterKind::Changes => self.changes, + CounterKind::Rises => self.rises, + CounterKind::Falls => self.falls, + } + } + + pub fn map(self, mut map: impl FnMut(A) -> B) -> PendingSlots { + PendingSlots { + signal: map(self.signal), + staged: self.staged.map(|staged| StagedSlots { + value: map(staged.value), + mask: map(staged.mask), + first_mask: map(staged.first_mask), + }), + first: map(self.first), + has_first: map(self.has_first), + changes: map(self.changes), + rises: map(self.rises), + falls: map(self.falls), + } + } +} + +/// The code view of a signal's [`PendingSlots`]. +#[derive(Clone, Debug)] +pub struct PendingCode { + /// The signal's stable state and its counters. + pub watch: WatchCode, + /// The signal's next state. + pub next: A, + pub staged: Option>, + pub first: A, + pub has_first: A, + pub pending: Vec<(CounterKind, A)>, +} + +/// What an instruction of a flip-flop unit does to a [`PendingCode`] +/// stream. +enum PendingRole { + /// A write of the evaluation; `marks` for a store to the staging mask. + Write { marks: bool }, + /// The publication. + Release, +} + +impl PendingCode { + fn role(&self, instruction: &SIRInstruction) -> Option { + match (instruction, &self.staged) { + (SIRInstruction::Store(address, ..), None) => { + (*address == self.next).then_some(PendingRole::Write { marks: false }) + } + (SIRInstruction::Store(address, ..), Some(staged)) => { + if *address == staged.value { + Some(PendingRole::Write { marks: false }) + } else if *address == staged.mask { + Some(PendingRole::Write { marks: true }) + } else { + (*address == self.watch.signal).then_some(PendingRole::Release) + } + } + // A seed copies the stable state into the next state; it is + // not a write. + (SIRInstruction::Commit(source, destination, ..), None) => (*source == self.next + && *destination == self.watch.signal) + .then_some(PendingRole::Release), + _ => None, + } + } +} + +fn value_register(b: &mut SIRBuilder, width: usize, four_state: bool) -> RegisterId { + if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + } +} + +fn store(b: &mut SIRBuilder, address: &A, width: usize, value: RegisterId) { + b.emit(SIRInstruction::Store( + address.clone(), + SIROffset::Static(0), + width, + value, + Vec::new(), + Vec::new(), + )); +} + +/// `base` with the bits `mask` marks taken from `value`. +fn overlay( + b: &mut SIRBuilder, + base: RegisterId, + value: RegisterId, + mask: RegisterId, + width: usize, + four_state: bool, +) -> RegisterId { + let keep = b.alloc_bit(width, false); + b.emit(SIRInstruction::Unary( + keep, + celox_design::UnaryOp::BitNot, + mask, + )); + let kept = value_register(b, width, four_state); + b.emit(SIRInstruction::Binary(kept, base, BinaryOp::And, keep)); + let taken = value_register(b, width, four_state); + b.emit(SIRInstruction::Binary(taken, value, BinaryOp::And, mask)); + let merged = value_register(b, width, four_state); + b.emit(SIRInstruction::Binary(merged, kept, BinaryOp::Or, taken)); + merged +} + +/// The value the writes of `code` have produced so far: the next state, or +/// for a staged stream the next state with the staged bits replaced, as the +/// NBA merge will publish it. +fn pending_view(b: &mut SIRBuilder, code: &PendingCode) -> RegisterId { + let (width, four_state) = (code.watch.width, code.watch.four_state); + let next = load(b, &code.next, width, four_state); + let Some(staged) = &code.staged else { + return next; + }; + let value = load(b, &staged.value, width, four_state); + let mask = load(b, &staged.mask, width, false); + overlay(b, next, value, mask, width, four_state) +} + +/// Emit `write`, a write of the evaluation to the stream of `code`, and +/// keep its occurrence: the first write is remembered, a later one counts +/// as pending. +fn emit_pending_write( + b: &mut SIRBuilder, + code: &PendingCode, + write: SIRInstruction, + marks: bool, +) { + let (width, four_state) = (code.watch.width, code.watch.four_state); + let old = pending_view(b, code); + let old_lsb = lsb(b, old, width, four_state); + b.emit(write); + let new = pending_view(b, code); + let new_lsb = lsb(b, new, width, four_state); + let has_first = load(b, &code.has_first, 1, false); + for &(kind, ref pending) in &code.pending { + let occurred = occurrence(b, kind, (old, old_lsb), (new, new_lsb), width, four_state); + let held = binary(b, occurred, BinaryOp::And, has_first); + bump(b, pending, held); + } + // A staged value takes effect where its mask is marked, and the + // evaluation clears the mask before its body: the first write of a + // staged stream is the first mark. + if code.staged.is_some() && !marks { + return; + } + let none = b.alloc_bit(1, false); + b.emit(SIRInstruction::Unary( + none, + celox_design::UnaryOp::LogicNot, + has_first, + )); + let (first, set) = match &code.staged { + None => (new, none), + Some(staged) => { + let mask = load(b, &staged.mask, width, false); + let zero = constant(b, 0, width, false); + let marked = binary(b, mask, BinaryOp::NeCase, zero); + let set = binary(b, none, BinaryOp::And, marked); + let previous = load(b, &staged.first_mask, width, false); + let first_mask = b.alloc_bit(width, false); + b.emit(SIRInstruction::Mux(first_mask, set, mask, previous)); + store(b, &staged.first_mask, width, first_mask); + (load(b, &staged.value, width, four_state), set) + } + }; + let previous = load(b, &code.first, width, four_state); + let kept = value_register(b, width, four_state); + b.emit(SIRInstruction::Mux(kept, set, first, previous)); + store(b, &code.first, width, kept); + let started = binary(b, has_first, BinaryOp::Or, set); + store(b, &code.has_first, 1, started); +} + +/// After the publication of the stream of `code`, count its occurrences: +/// the one from `published`, the signal's value before the publication, to +/// the first written value in the bits the publication writes (`mask`), and +/// the pending ones. The stream is then empty. +fn emit_release( + b: &mut SIRBuilder, + code: &PendingCode, + published: RegisterId, + written: &num_bigint::BigUint, +) { + let (width, four_state) = (code.watch.width, code.watch.four_state); + let has_first = load(b, &code.has_first, 1, false); + let first = load(b, &code.first, width, four_state); + let mask = match &code.staged { + Some(staged) => load(b, &staged.first_mask, width, false), + None => { + let mask = b.alloc_bit(width, false); + b.emit(SIRInstruction::Imm(mask, SIRValue::new(written.clone()))); + mask + } + }; + let first = overlay(b, published, first, mask, width, four_state); + let published_lsb = lsb(b, published, width, four_state); + let first_lsb = lsb(b, first, width, four_state); + for &(kind, ref pending) in &code.pending { + let Some((_, counter)) = code.watch.counters.iter().find(|(k, _)| *k == kind) else { + continue; + }; + let occurred = occurrence( + b, + kind, + (published, published_lsb), + (first, first_lsb), + width, + four_state, + ); + let counted = binary(b, occurred, BinaryOp::And, has_first); + bump(b, counter, counted); + let total = load(b, counter, EVENT_COUNTER_WIDTH, false); + let held = load(b, pending, EVENT_COUNTER_WIDTH, false); + let sum = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Binary(sum, total, BinaryOp::Add, held)); + store(b, counter, EVENT_COUNTER_WIDTH, sum); + } + emit_clear(b, code); +} + +/// Empty the stream of `code`. +fn emit_clear(b: &mut SIRBuilder, code: &PendingCode) { + let zero = constant(b, 0, 1, false); + store(b, &code.has_first, 1, zero); + let zero = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + for (_, pending) in &code.pending { + store(b, pending, EVENT_COUNTER_WIDTH, zero); + } +} + +/// The instructions `emit` builds, with registers from `next_register` on. +fn emitted( + register_map: &mut impl Extend<(RegisterId, celox_sir::RegisterType)>, + next_register: &mut usize, + emit: impl FnOnce(&mut SIRBuilder), +) -> Vec> { + let mut b = SIRBuilder::new_with(*next_register); + emit(&mut b); + b.seal_block(SIRTerminator::Return); + let (mut blocks, registers, next) = b.drain(); + *next_register = next; + register_map.extend(registers); + blocks + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions +} + +/// Instrument the writes and publications of a flip-flop unit for the +/// streams of `codes` (see [`PendingSlots`]). A unit that writes a stream +/// starts it empty, so an evaluation that was superseded before its commit +/// leaves nothing behind. +pub fn instrument_pending( + unit: &mut ExecutionUnit, + codes: &[PendingCode], +) { + if codes.is_empty() { + return; + } + let mut next_register = unit + .register_map + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0); + let mut started = vec![false; codes.len()]; + let mut blocks: Vec<_> = unit.blocks.keys().copied().collect(); + blocks.sort_unstable(); + for id in blocks { + let block = unit.blocks.get_mut(&id).expect("a block of the unit"); + let roles: Vec<_> = block + .instructions + .iter() + .map(|instruction| { + codes + .iter() + .enumerate() + .find_map(|(index, code)| code.role(instruction).map(|role| (index, role))) + }) + .collect(); + if roles.iter().all(Option::is_none) { + continue; + } + // The bits each stream's commits in this block publish, and where + // its last publication is. + let mut written = vec![num_bigint::BigUint::default(); codes.len()]; + let mut last = vec![None; codes.len()]; + for (position, (instruction, role)) in block.instructions.iter().zip(&roles).enumerate() { + let Some((index, PendingRole::Release)) = role else { + continue; + }; + last[*index] = Some(position); + let width = codes[*index].watch.width; + let range = match instruction { + SIRInstruction::Commit(_, _, SIROffset::Static(lsb), bits, _) => { + ((num_bigint::BigUint::from(1u8) << *bits) - 1u8) << *lsb + } + _ => (num_bigint::BigUint::from(1u8) << width) - 1u8, + }; + written[*index] |= range; + } + let mut published: Vec> = vec![None; codes.len()]; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for (position, (instruction, role)) in std::mem::take(&mut block.instructions) + .into_iter() + .zip(roles) + .enumerate() + { + match role { + None => instructions.push(instruction), + Some((index, PendingRole::Write { marks })) => { + started[index] = true; + instructions.extend(emitted(&mut unit.register_map, &mut next_register, |b| { + emit_pending_write(b, &codes[index], instruction, marks) + })); + } + Some((index, PendingRole::Release)) => { + let code = &codes[index]; + if published[index].is_none() { + instructions.extend(emitted( + &mut unit.register_map, + &mut next_register, + |b| { + published[index] = Some(load( + b, + &code.watch.signal, + code.watch.width, + code.watch.four_state, + )); + }, + )); + } + instructions.push(instruction); + if last[index] == Some(position) { + let before = published[index].expect("loaded before the first commit"); + instructions.extend(emitted( + &mut unit.register_map, + &mut next_register, + |b| emit_release(b, code, before, &written[index]), + )); + } + } + } + } + block.instructions = instructions; + } + let mut entry = Vec::new(); + for (code, _) in codes.iter().zip(&started).filter(|(_, started)| **started) { + entry.extend(emitted(&mut unit.register_map, &mut next_register, |b| { + emit_clear(b, code) + })); + } + let block = unit + .blocks + .get_mut(&unit.entry_block_id) + .expect("the entry block"); + entry.append(&mut block.instructions); + block.instructions = entry; +} + +type SymbolicVariables = + crate::HashMap; + +/// Whether `id` is a signal of the design that an event control can watch: +/// state of the module (`module_affiliated`), since nothing outside the +/// module watches hidden state, and no unpacked array, which no event +/// control watches as a whole. +fn watchable(variables: &SymbolicVariables, id: &crate::SourceVarId) -> bool { + variables + .get(id) + .is_some_and(|var| var.module_affiliated && var.metadata.array_dims.is_empty()) +} + +/// Declare a hidden object `path` of `width` bits and return it. +fn declare_hidden( + variables: &mut SymbolicVariables, + path: Vec, + width: usize, + is_4state: bool, +) -> crate::SourceVarId { + use celox_design::{DomainKind, PortTypeKind, VariableMetadata}; + let id = crate::SourceVarId(variables.keys().map(|id| id.0 + 1).max().unwrap_or(0)); + variables.insert( + id, + crate::symbolic::artifact::SymbolicVariable { + path, + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state, + kind: DomainKind::Other, + type_kind: if is_4state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }, + array_dims: Vec::new(), + value_kind: Default::default(), + }, + unpacked_ranges: Vec::new(), + packed_dims: vec![width], + source: None, + module_affiliated: false, + }, + ); + id +} + /// Declare counter objects for `candidates` among the variables of a module -/// and return them. Candidates that are not signals of the design -/// (`module_affiliated`) are skipped, since nothing outside the module -/// watches hidden state, and so are unpacked arrays, which no event control -/// watches as a whole. +/// and return them. Candidates that are not [`watchable`] are skipped. pub fn declare_counter_slots( - variables: &mut crate::HashMap, + variables: &mut SymbolicVariables, candidates: impl IntoIterator, ) -> Vec> { - use celox_design::{DomainKind, PortTypeKind, VariableMetadata}; let mut candidates: Vec<_> = candidates .into_iter() - .filter(|id| { - variables - .get(id) - .is_some_and(|var| var.module_affiliated && var.metadata.array_dims.is_empty()) - }) + .filter(|id| watchable(variables, id)) .collect(); candidates.sort_unstable(); candidates.dedup(); - let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0); candidates .into_iter() .map(|signal| { let name = variables[&signal].path.join("."); let mut counter = |kind: &str| { - let id = crate::SourceVarId(next); - next += 1; - variables.insert( - id, - crate::symbolic::artifact::SymbolicVariable { - path: vec![format!("$counter[{name}]"), kind.to_string()], - kind: crate::VariableKind::Variable, - signed: false, - metadata: VariableMetadata { - width: EVENT_COUNTER_WIDTH, - is_4state: false, - kind: DomainKind::Other, - type_kind: PortTypeKind::Bit, - array_dims: Vec::new(), - value_kind: Default::default(), - }, - unpacked_ranges: Vec::new(), - packed_dims: vec![EVENT_COUNTER_WIDTH], - source: None, - module_affiliated: false, - }, - ); - id + declare_hidden( + variables, + vec![format!("$counter[{name}]"), kind.to_string()], + EVENT_COUNTER_WIDTH, + false, + ) }; celox_design::CounterSlots { signal, @@ -521,6 +971,62 @@ pub fn declare_counter_slots( .collect() } +/// Declare the [`PendingSlots`] of `streams` among the variables of a +/// module and return them. A stream is a signal and, for nonblocking writes +/// staged apart from blocking ones, its staging value and mask. Streams of +/// signals that are not [`watchable`] are skipped. +pub fn declare_pending_slots( + variables: &mut SymbolicVariables, + streams: impl IntoIterator< + Item = ( + crate::SourceVarId, + Option<(crate::SourceVarId, crate::SourceVarId)>, + ), + >, +) -> Vec> { + let mut streams: Vec<_> = streams + .into_iter() + .filter(|(signal, _)| watchable(variables, signal)) + .collect(); + streams.sort_unstable(); + streams.dedup(); + streams + .into_iter() + .map(|(signal, staged)| { + let name = variables[&signal].path.join("."); + let (width, is_4state) = { + let metadata = &variables[&signal].metadata; + (metadata.width, metadata.is_4state) + }; + let stream = match staged { + Some(_) => format!("$staged[{name}]"), + None => format!("$pending[{name}]"), + }; + let mut hidden = |kind: &str, width: usize, is_4state: bool| { + declare_hidden( + variables, + vec![stream.clone(), kind.to_string()], + width, + is_4state, + ) + }; + PendingSlots { + signal, + staged: staged.map(|(value, mask)| StagedSlots { + value, + mask, + first_mask: hidden("first_mask", width, false), + }), + first: hidden("first", width, is_4state), + has_first: hidden("has_first", 1, false), + changes: hidden("changes", EVENT_COUNTER_WIDTH, false), + rises: hidden("rises", EVENT_COUNTER_WIDTH, false), + falls: hidden("falls", EVENT_COUNTER_WIDTH, false), + } + }) + .collect() +} + #[cfg(test)] mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 751a066eef8..e8260cad82c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -18,7 +18,7 @@ use celox_design::{ }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ - ExternalHierarchy, ExternalModule, NbaSwitch, PackageBinding, SimModule, + CombAlternative, ExternalHierarchy, ExternalModule, NbaSwitch, PackageBinding, SimModule, SymbolicGlueAddr as GlueAddr, SymbolicProcess, SymbolicRtl, SymbolicVariable, }; use celox_frontend_core::{ @@ -157,6 +157,8 @@ pub(crate) struct LoweredSvModule { /// The creation orders of the `always @(list)` processes lowered like /// `always @*`. level_lists_lowered: Vec, + /// The write streams one flip-flop evaluation may write twice. + repeated_ff_writes: Vec, } #[derive(Clone)] @@ -1595,6 +1597,7 @@ fn prepare_external_hierarchy_collecting( event_copies: Vec::new(), event_assignments: Vec::new(), level_lists_lowered: Vec::new(), + repeated_ff_writes: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -3052,6 +3055,7 @@ fn lower_module_with_overrides( }) }); let module = level_sensitive.as_ref().unwrap_or(module); + let mut repeated_ff_writes = Vec::new(); let ( ( eval_only_ff_blocks, @@ -3075,8 +3079,14 @@ fn lower_module_with_overrides( four_state, warnings, ); - let blocks = - lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles, &shared_memories)?; + let blocks = lower_ff_processes( + module, + &mut pm, + ff_parts, + &ff_event_roles, + &shared_memories, + &mut repeated_ff_writes, + )?; ( blocks, std::mem::take(&mut pm.runtime_event_sites), @@ -3209,6 +3219,8 @@ fn lower_module_with_overrides( processes, package_bindings: HashMap::default(), counter_slots: Vec::new(), + pending_slots: Vec::new(), + comb_alternatives: Vec::new(), wait_sites, nba_sites, nba_switches, @@ -3225,6 +3237,7 @@ fn lower_module_with_overrides( event_copies: event_vars.copies, event_assignments, level_lists_lowered, + repeated_ff_writes, }) } @@ -3610,32 +3623,40 @@ pub(crate) fn attach_instance_glue( // An event expression is one more continuous assignment to a hidden // buffer the processes watch. port_assignments.extend(lowered.event_assignments.iter().cloned()); - let (comb_blocks, arena, created, comb_observers, comb_sites) = lower_comb_processes( - &lowered.source, - &port_assignments, - &mut parent_variables, - &mut signal_names, - &lowered.constants, - &lowered.parameter_types, - four_state, - allow_inferred_latches, - &mut module.runtime_errors, - &mut module.extern_functions, - warnings, - ) - .map_err(|error| match error { - sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { - detail, - source_location: None, - }, - error => ParserError::unsupported( - error.tracking_issue(), - LoweringPhase::SimulatorParser, - "systemverilog combinational process lowering", - error.to_string(), - None, - ), - })?; + // The repeated writes of flip-flops and combinational processes are + // counted only in a design with a wait, so a design without one, such + // as pure RTL, lowers exactly as before. + let waits = lowered_modules + .values() + .any(|module| !module.sim_module.wait_sites.is_empty()); + let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) = + lower_comb_processes( + &lowered.source, + &port_assignments, + &mut parent_variables, + &mut signal_names, + &lowered.constants, + &lowered.parameter_types, + four_state, + allow_inferred_latches, + &mut module.runtime_errors, + &mut module.extern_functions, + warnings, + waits, + ) + .map_err(|error| match error { + sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { + detail, + source_location: None, + }, + error => ParserError::unsupported( + error.tracking_issue(), + LoweringPhase::SimulatorParser, + "systemverilog combinational process lowering", + error.to_string(), + None, + ), + })?; let (mut comb_blocks, mut arena) = (comb_blocks, arena); push_event_copies(&lowered.event_copies, &mut comb_blocks, &mut arena)?; module.comb_boundaries = comb_boundaries(&comb_blocks); @@ -3728,8 +3749,21 @@ pub(crate) fn attach_instance_glue( arena: glue.2, }); } + if waits { + candidates.extend(lowered.repeated_ff_writes.iter().map(|&(signal, _)| signal)); + for alternative in &comb_alternatives { + candidates.extend(alternative.candidates.iter().copied()); + } + } + module.comb_alternatives = comb_alternatives; module.counter_slots = celox_frontend_core::watch::declare_counter_slots(&mut module.variables, candidates); + if waits { + module.pending_slots = celox_frontend_core::watch::declare_pending_slots( + &mut module.variables, + lowered.repeated_ff_writes.iter().copied(), + ); + } Ok(()) } @@ -4166,6 +4200,7 @@ fn lower_comb_processes( runtime_errors: &mut HashMap>, extern_functions: &mut Vec, warnings: &mut Vec, + waits: bool, ) -> Result< ( Vec>, @@ -4173,11 +4208,13 @@ fn lower_comb_processes( Vec, Vec>, Vec, + Vec, ), sv::AnalyzerError, > { let mut arena = SLTNodeArena::new(); let mut comb_blocks = Vec::new(); + let mut alternatives = Vec::new(); let mut observers = Vec::new(); let mut sites = Vec::new(); let mut pm = procedural::ProcModule::new( @@ -4232,6 +4269,38 @@ fn lower_comb_processes( comb.site_base = sites.len() as u32; comb.continuous = process.kind() == sv::ir::CombProcessKind::ContinuousAssign; match comb.lower_process(process.body()) { + // In a design with a wait, a variable the process stores twice + // may be watched, so it also gets its imperative alternative. + // A process with runtime events keeps only its symbolic form. + Ok(paths) + if waits + && process.kind() == sv::ir::CombProcessKind::AlwaysComb + && comb.observers.is_empty() + && comb.sites.is_empty() => + { + drop(comb); + let mut targets: Vec<_> = paths + .iter() + .filter_map(|path| match &path.target { + LogicPathTarget::Var(target) => Some(target.id), + _ => None, + }) + .collect(); + targets.sort_unstable(); + targets.dedup(); + comb_blocks.extend(paths); + if let Some((paths, alternative)) = lower_comb_alternative( + &mut pm, + process, + random_seeds[&(2, index)], + targets, + &mut arena, + ) { + comb_blocks.extend(paths); + alternatives.push(alternative); + } + continue; + } Ok(paths) => comb_blocks.extend(paths), Err(sv::AnalyzerError::Unsupported(reason)) if reason.starts_with("latch inference inside always_comb") @@ -4330,7 +4399,71 @@ fn lower_comb_processes( *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); let created = std::mem::take(&mut pm.created); - Ok((comb_blocks, arena, created, observers, sites)) + Ok((comb_blocks, arena, created, observers, sites, alternatives)) +} + +/// 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 +/// remains in `pm`. +fn lower_comb_alternative( + pm: &mut procedural::ProcModule<'_>, + process: &sv::ir::CombProcess, + random_seed: u32, + targets: Vec, + arena: &mut SLTNodeArena, +) -> Option<(Vec>, CombAlternative)> { + let checkpoint = pm.checkpoint(); + let mut scratch = SLTNodeArena::new(); + let lowered = ff::Ff::new(pm, random_seed) + .without_input_occurrences() + .lower_comb_process( + process.body(), + process.sensitivity_body(), + process.kind(), + false, + process.site(), + &[], + &mut scratch, + ); + let alternative = match lowered { + Ok(paths) if pm.runtime_event_sites.len() == checkpoint.runtime_event_sites() => paths + .first() + .and_then(|path| match &path.target { + LogicPathTarget::Process { process, unit, .. } => Some((*process, unit)), + _ => None, + }) + .map(|(id, unit)| { + let 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) + }); + (id, candidates) + }) + .filter(|(_, candidates)| !candidates.is_empty()) + .map(|(process, candidates)| (paths, process, candidates)), + _ => None, + }; + let Some((mut paths, process, mut candidates)) = alternative else { + pm.rollback(checkpoint); + return None; + }; + for path in &mut paths { + path.expr = arena + .alloc(scratch.get(path.expr).clone()) + .expect("an input node of a fresh arena"); + } + candidates.sort_unstable(); + candidates.dedup(); + Some(( + paths, + CombAlternative { + process, + targets, + candidates, + }, + )) } /// The continuous assignments `copy = signal` of the hidden event copies of @@ -7991,12 +8124,45 @@ impl FfEventVars { } } +/// A signal a flip-flop evaluation writes and, for nonblocking writes staged +/// apart from blocking ones, its staging value and mask; see +/// `celox_frontend_core::watch::PendingSlots`. +type FfWriteStream = (SourceVarId, Option<(SourceVarId, SourceVarId)>); + +/// The write streams one execution of the flip-flop evaluation `eval` may +/// write twice. `staged` lists its staged variables as (variable, value, +/// mask). +fn repeated_ff_writes( + eval: &ExecutionUnit, + staged: &[(SourceVarId, SourceVarId, SourceVarId)], +) -> Vec { + // A seed commits the stable state into the next state; only the stores + // of the body are writes. Every nonblocking write of a staged variable + // marks its mask, so the value alone tells a repeated write. + celox_frontend_core::watch::multi_write_candidates(eval, |instruction| match instruction { + SIRInstruction::Store(address, ..) if address.region == WORKING_REGION => { + Some(address.var_id) + } + _ => None, + }) + .into_iter() + .filter_map( + |id| match staged.iter().find(|&&(_, value, _)| value == id) { + Some(&(signal, value, mask)) => Some((signal, Some((value, mask)))), + None if staged.iter().any(|&(_, _, mask)| mask == id) => None, + None => Some((id, None)), + }, + ) + .collect() +} + fn lower_ff_processes( module: &sv::ir::Module, pm: &mut procedural::ProcModule<'_>, ff_parts: bool, ff_event_roles: &[FfEventRole], shared_memories: &HashSet, + repeated_writes: &mut Vec, ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); let mut eval_only_ff_blocks = HashMap::default(); @@ -8106,9 +8272,11 @@ fn lower_ff_processes( active, nba, targets, + staged, } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) .lower_process(process.body())?; + repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and // extern calls. let has_effects = diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3a992de49cd..5cf12e71bb1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -77,6 +77,9 @@ pub(super) struct Ff<'p, 'a> { /// The nonblocking sites with a staged and a queued path. nba_switches: Vec>, direct: bool, + /// Whether a combinational process also reruns for occurrences of its + /// inputs that left their value unchanged. + input_occurrences: bool, } fn stable(var_id: SourceVarId) -> Addr { @@ -122,6 +125,7 @@ impl<'p, 'a> Ff<'p, 'a> { dist_seed: None, kernel: None, direct: false, + input_occurrences: true, process: 0, wait_sites: Vec::new(), nba_sites: Vec::new(), @@ -130,6 +134,14 @@ impl<'p, 'a> Ff<'p, 'a> { } } + /// Lower a combinational process that reruns only when an input value + /// changed. Its inputs then need no occurrence counters, so the units + /// that write them stay unchanged. + pub fn without_input_occurrences(mut self) -> Self { + self.input_occurrences = false; + self + } + pub fn with_sparse_memories(mut self, names: &HashSet) -> Self { self.sparse_memories = names.iter().filter_map(|name| self.m.id(name)).collect(); self @@ -3722,6 +3734,9 @@ impl<'p, 'a> Ff<'p, 'a> { .emit(SIRInstruction::Binary(next, changed, BinaryOp::Or, differs)); changed = next; snapshots.push((saved, width, current)); + if !self.input_occurrences { + continue; + } // A source can change and return to its saved value inside one // initial activation. Count occurrences around stores before // optimization, rather than relying only on the settled value. @@ -4025,6 +4040,10 @@ impl<'p, 'a> Ff<'p, 'a> { active: seal_builder(active), nba: seal_builder(nba), targets, + staged: staged + .iter() + .map(|stage| (stage.id, stage.value, stage.mask)) + .collect(), }) } } @@ -4072,6 +4091,8 @@ pub(super) struct FfProcessUnits { pub active: ExecutionUnit, pub nba: ExecutionUnit, pub targets: Vec>, + /// The staged variables, as (variable, staging value, staging mask). + pub staged: Vec<(SourceVarId, SourceVarId, SourceVarId)>, } /// The staging of a variable a process writes both by blocking and by diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index cc1bc52ceb4..54a49321b97 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -18,6 +18,26 @@ pub(super) fn unsupported(construct: impl Into) -> sv::AnalyzerError { sv::AnalyzerError::Unsupported(construct.into()) } +/// What [`ProcModule::rollback`] restores. +pub(super) struct Checkpoint { + next_id: SourceVarId, + created: usize, + temp_counter: usize, + capture_counter: u64, + runtime_event_sites: usize, + runtime_errors: usize, + extern_functions: usize, + extern_calls: usize, + warnings: usize, +} + +impl Checkpoint { + /// The number of runtime event sites at the checkpoint. + pub fn runtime_event_sites(&self) -> usize { + self.runtime_event_sites + } +} + /// The variables and subroutines of the module being lowered. pub(super) struct ProcModule<'a> { pub variables: &'a mut HashMap, @@ -675,6 +695,48 @@ impl<'a> ProcModule<'a> { Ok((left, right, width)) } + /// The lowering state, for [`Self::rollback`]. + pub fn checkpoint(&self) -> Checkpoint { + Checkpoint { + next_id: self.next_id, + created: self.created.len(), + temp_counter: self.temp_counter, + capture_counter: self.capture_counter, + runtime_event_sites: self.runtime_event_sites.len(), + runtime_errors: self.runtime_errors.len(), + extern_functions: self.extern_functions.len(), + extern_calls: self.extern_calls, + warnings: self.warnings.len(), + } + } + + /// Forget everything lowered since `checkpoint`, so that the module + /// lowers as if it had never been. + pub fn rollback(&mut self, checkpoint: Checkpoint) { + for id in checkpoint.next_id.0..self.next_id.0 { + let Some(variable) = self.variables.remove(&SourceVarId(id)) else { + continue; + }; + if let Some(name) = variable.path.first() + && self.name_to_id.get(name) == Some(&SourceVarId(id)) + { + self.name_to_id.remove(name); + } + } + self.next_id = checkpoint.next_id; + self.created.truncate(checkpoint.created); + self.temp_counter = checkpoint.temp_counter; + self.capture_counter = checkpoint.capture_counter; + self.runtime_event_sites + .truncate(checkpoint.runtime_event_sites); + // Codes are numbered from one in registration order. + self.runtime_errors + .retain(|&code, _| code <= checkpoint.runtime_errors as i64); + self.extern_functions.truncate(checkpoint.extern_functions); + self.extern_calls = checkpoint.extern_calls; + self.warnings.truncate(checkpoint.warnings); + } + /// Register a runtime event site and return its local number. pub fn event_site(&mut self, site: RuntimeEventSite) -> u32 { self.runtime_event_sites.push(site); diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index f4fce2b13c3..5125c4af4cd 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -664,6 +664,8 @@ pub(crate) fn project_module_with_ids( processes: Vec::new(), package_bindings: HashMap::default(), counter_slots: Vec::new(), + pending_slots: Vec::new(), + comb_alternatives: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), nba_switches: Vec::new(), From b2e409a61beb5fc782f5839cc214a7d30dc89f41 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 12:45:15 +0900 Subject: [PATCH 2/9] test(sv): cover intermediate writes in timing cases Add timing cases for intermediate writes of always_comb, always @*, blocking edge-triggered always and always_ff bodies, for staged nonblocking writes, and for a pulse behind a child's output port. Verilator 5.052 sees only settled values, so the first three are excluded for it. Icarus 13.0 collapses the output port and counts the child's pulse, which 4.7 and 23.3.3 leave open; the port case asserts the settled count and is excluded for Icarus. Both exclusions keep standalone repros. Change-Id: Id2eb6d5daaefaa8604216f8cc543269a5716e59f --- crates/celox-test-suite/LIMITATIONS.md | 2 + .../src/sv/cases/timing.vtest | 120 ++++++++++++++++++ .../sv_intermediate_writes_verilator.json | 75 +++++++++++ .../repros/sv_port_pulses_icarus.json | 29 +++++ .../verification/sv/icarus/timing.json | 56 ++++++++ .../verification/sv/limitations.json | 36 ++++++ .../verification/sv/verilator/timing.json | 80 ++++++++++++ .../tests/frontends/systemverilog/timing.rs | 4 + 8 files changed, 402 insertions(+) create mode 100644 crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json create mode 100644 crates/celox-test-suite/verification/repros/sv_port_pulses_icarus.json diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index ebc1d9d5ed4..ca5354133f3 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -539,6 +539,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_urandom_narrow_seed` | execute | icarus | 1 | Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks. | | `sv_verilator_random_algorithm` | execute | verilator | 2 | Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator. | | `sv_verilator_time_in_combinational_logic` | execute | verilator | 1 | Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one. | +| `sv_verilator_intermediate_writes` | execute | verilator | 3 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. | +| `sv_icarus_port_pulses` | execute | icarus | 1 | Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give. The [standalone probe](verification/repros/sv_port_pulses_icarus.json) retains both outputs. | 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 6df07ab016a..1996e62dc9a 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1752,3 +1752,123 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (run_to_finish) (assert_eq cached 1) (assert_eq next 2) (assert_eq cached_again 1) (assert_eq next_again 3)) + +; A process waiting on a variable sees every store to it, including one a +; later store of the same evaluation overwrites (IEEE 1800-2023 4.3, 9.4.2). +(case intermediate_combinational_writes_wake_waiters + (source "comb.sv" #" + module Top; + bit a, b, c, d, y1, y2; + int n1, n2; + always_comb begin y1 = 0; if (a) y1 = 1; c = b; end + always @* begin y2 = 0; if (a) y2 = 1; d = b; end + initial forever begin @(y1); n1++; end + initial forever begin @(y2); n2++; end + initial begin + #1 a = 1; + // While a is 1, each change of b rewrites y 1 -> 0 -> 1. + #1 b = 1; + #1 b = 0; + #1 $display("comb=%0d star=%0d", n1, n2); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "comb=3 star=3\n")) + +; The processes share one clock, so a parallel build evaluates them as +; separate parts. Nonblocking updates apply in the NBA region in issue +; order, each its own update (IEEE 1800-2023 4.5, 10.4.2); edges are judged +; on each update. +(case intermediate_edge_process_writes_wake_waiters + (source "ff.sv" #" + module Top; + bit a, clk, y3, y4, y5; + int n3, n4, n5, p4, f5; + always @(posedge clk) begin y3 = 0; if (a) y3 = 1; end + always_ff @(posedge clk) begin y4 <= 0; if (a) y4 <= 1; end + always @(posedge clk) begin y5 = 0; y5 = 1; end + initial forever begin @(y3); n3++; end + initial forever begin @(y4); n4++; end + initial forever begin @(y5); n5++; end + initial forever begin @(posedge y4); p4++; end + initial forever begin @(negedge y5); f5++; end + initial begin + #1 a = 1; + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 $display("blk=%0d nba=%0d const=%0d rise=%0d fall=%0d", n3, n4, n5, p4, f5); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "blk=3 nba=3 const=3 rise=3 fall=2\n")) + +; A variable written by blocking and nonblocking assignments of one process: +; each nonblocking update, whole or partial, is its own update in the NBA +; region. The blocking value equals the old one, so no waiter runs between +; the regions. +(case staged_nonblocking_writes_wake_waiters + (source "staged.sv" #" + module Top; + bit clk, y = 1; + bit [1:0] z = 2'b11; + int n, m; + always @(posedge clk) begin y = 1; y <= 0; y <= 1; end + always @(posedge clk) begin + z = 2'b11; + z[0] <= 0; + z[1] <= 0; + z[0] <= 1; + z[1] <= 1; + end + initial forever begin @(y); n++; end + initial forever begin @(z); m++; end + initial begin + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 $display("y=%0d z=%0d", n, m); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=3 z=3\n")) + +; The output port of a child is a continuous assignment to the parent's +; net (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, +; so the parent may miss a pulse the child writes inside one evaluation +; (4.7). Celox, like Verilator, sees only the settled value. +(case child_port_pulses_reach_waiters_settled + (source "child.sv" #" + module Child(input bit a, b, output bit y, c); + always_comb begin y = 0; if (a) y = 1; c = b; end + endmodule + module Top; + bit a, b, y, c; + int n; + Child u(.a(a), .b(b), .y(y), .c(c)); + initial forever begin @(y); n++; end + initial begin + #1 a = 1; + #1 b = 1; + #1 b = 0; + #1 $display("child=%0d", n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "child=1\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json new file mode 100644 index 00000000000..068b538fc49 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json @@ -0,0 +1,75 @@ +{ + "standard": "IEEE 1800-2023 4.3, 4.5, 9.4.2 and 10.4.2", + "expected": "Every store to a variable is an update event that triggers a process waiting on it, including a store that a later store of the same evaluation overwrites; nonblocking updates apply in the NBA region in issue order, each its own update. A waiter on a variable an always_comb rewrites 1 -> 0 -> 1 therefore wakes, and an edge's `y <= 0; y <= 1;` from y=1 wakes a waiter on `@(y)` and on `@(posedge y)`.", + "probes": [ + { + "name": "combinational", + "note": "The suite case intermediate_combinational_writes_wake_waiters.", + "source": "module Top;\n bit a, b, c, d, y1, y2;\n int n1, n2;\n always_comb begin y1 = 0; if (a) y1 = 1; c = b; end\n always @* begin y2 = 0; if (a) y2 = 1; d = b; end\n initial forever begin @(y1); n1++; end\n initial forever begin @(y2); n2++; end\n initial begin #1 a = 1; #1 b = 1; #1 b = 0; #1 $display(\"comb=%0d star=%0d\", n1, n2); $finish; 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": "comb=1 star=1\n- /probe.sv:8: 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" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "comb=3 star=3\n/probe.sv:8: $finish called at 4 (1s)\n" + } + }, + { + "name": "edge_processes", + "note": "The suite case intermediate_edge_process_writes_wake_waiters.", + "source": "module Top;\n bit a, clk, y3, y4, y5;\n int n3, n4, n5, p4, f5;\n always @(posedge clk) begin y3 = 0; if (a) y3 = 1; end\n always_ff @(posedge clk) begin y4 <= 0; if (a) y4 <= 1; end\n always @(posedge clk) begin y5 = 0; y5 = 1; end\n initial forever begin @(y3); n3++; end\n initial forever begin @(y4); n4++; end\n initial forever begin @(y5); n5++; end\n initial forever begin @(posedge y4); p4++; end\n initial forever begin @(negedge y5); f5++; end\n initial begin #1 a = 1; #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 $display(\"blk=%0d nba=%0d const=%0d rise=%0d fall=%0d\", n3, n4, n5, p4, f5); $finish; 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": "blk=1 nba=1 const=1 rise=1 fall=0\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" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "blk=3 nba=3 const=3 rise=3 fall=2\n/probe.sv:12: $finish called at 7 (1s)\n" + } + }, + { + "name": "staged_nonblocking", + "note": "The suite case staged_nonblocking_writes_wake_waiters.", + "source": "module Top;\n bit clk, y = 1; bit [1:0] z = 2'b11;\n int n, m;\n always @(posedge clk) begin y = 1; y <= 0; y <= 1; end\n always @(posedge clk) begin z = 2'b11; z[0] <= 0; z[1] <= 0; z[0] <= 1; z[1] <= 1; end\n initial forever begin @(y); n++; end\n initial forever begin @(z); m++; end\n initial begin #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 $display(\"y=%0d z=%0d\", n, m); $finish; 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": "y=0 z=0\n- /probe.sv:8: 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" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "y=3 z=3\n/probe.sv:8: $finish called at 6 (1s)\n" + } + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_port_pulses_icarus.json b/crates/celox-test-suite/verification/repros/sv_port_pulses_icarus.json new file mode 100644 index 00000000000..73cff1095ea --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_port_pulses_icarus.json @@ -0,0 +1,29 @@ +{ + "standard": "IEEE 1800-2023 4.7 and 23.3.3", + "expected": "The output port connects the child's variable to the parent's net as a continuous assignment, which is evaluated after the child's process yields. A pulse the child's always_comb writes inside one evaluation may therefore reach the parent's waiter or not; both 1 and 3 are conforming counts.", + "probes": [ + { + "name": "output_port", + "note": "The suite case child_port_pulses_reach_waiters_settled. Icarus collapses the port and sees each intermediate value; Verilator and Celox see the settled value.", + "source": "module child(input bit a, b, output bit y, c);\n always_comb begin y = 0; if (a) y = 1; c = b; end\nendmodule\nmodule Top;\n bit a, b, y6, c6;\n int n6;\n child u(.a(a), .b(b), .y(y6), .c(c6));\n initial forever begin @(y6); n6++; end\n initial begin #1 a = 1; #1 b = 1; #1 b = 0; #1 $display(\"child=%0d\", n6); $finish; 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": "child=1\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" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "child=3\n/probe.sv:9: $finish called at 4 (1s)\n" + } + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index bdda61cc112..ee643a026ba 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -99,6 +99,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_port_pulses_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_port_pulses", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give.", + "upstream": [] + }, + "name": "timing::child_port_pulses_reach_waiters_settled", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -430,6 +453,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_wake_waiters", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_edge_process_writes_wake_waiters", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -694,6 +739,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::staged_nonblocking_writes_wake_waiters", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 42048791a99..6e64a92b39e 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1880,5 +1880,41 @@ "class::string_methods_on_properties" ] } + }, + { + "id": "sv_verilator_intermediate_writes", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [], + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::intermediate_combinational_writes_wake_waiters", + "timing::intermediate_edge_process_writes_wake_waiters", + "timing::staged_nonblocking_writes_wake_waiters" + ] + } + }, + { + "id": "sv_icarus_port_pulses", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give.", + "upstream": [], + "evidence": [ + "verification/repros/sv_port_pulses_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::child_port_pulses_reach_waiters_settled" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 97f86728b6f..5cda2533b12 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -99,6 +99,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::child_port_pulses_reach_waiters_settled", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -454,6 +465,52 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::intermediate_combinational_writes_wake_waiters", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::intermediate_edge_process_writes_wake_waiters", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -742,6 +799,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::staged_nonblocking_writes_wake_waiters", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index b9adf8fd474..adc684e453b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -148,6 +148,10 @@ timed_cases! { fn event_expressions_read_automatic_task_locals = "timing::event_expressions_read_automatic_task_locals"; fn event_controls_sample_the_expression_when_they_begin = "timing::event_controls_sample_the_expression_when_they_begin"; fn implicit_event_controls_in_processes_wait_on_their_reads = "timing::implicit_event_controls_in_processes_wait_on_their_reads"; + fn intermediate_combinational_writes_wake_waiters = "timing::intermediate_combinational_writes_wake_waiters"; + fn intermediate_edge_process_writes_wake_waiters = "timing::intermediate_edge_process_writes_wake_waiters"; + fn staged_nonblocking_writes_wake_waiters = "timing::staged_nonblocking_writes_wake_waiters"; + fn child_port_pulses_reach_waiters_settled = "timing::child_port_pulses_reach_waiters_settled"; } #[test] From e9cc5b5e9c6a2f96d90da2dc9f0168b3e4196caf Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 13:28:20 +0900 Subject: [PATCH 3/9] docs(sv): describe intermediate writes seen by waiters Replace the #1706 limitation in 'Event and level waits' with the behavior: every write of one evaluation is an update a waiter sees, nonblocking updates apply in issue order, and a child's output port shows only the settled value. Change-Id: Id7909b9972b7574eeabd8d5f1910df4ba47eb75b --- docs/guide/systemverilog-reference.md | 13 +++++++++---- docs/ja/guide/systemverilog-reference.md | 9 ++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7a776ac9a3c..95a61114e94 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -370,10 +370,15 @@ unsupported, including when the inference option is enabled. `a = 1; a = 0;` wakes `@(a)` but not `@(a ^ b)`; write `#0` between the writes to make the pulse visible. IEEE 1800-2023 4.7 permits this order; Icarus evaluates the expression at each write. -- A waiter does not yet see a value that one evaluation of `always_comb`, an - edge-triggered `always` or `always_ff` writes and then overwrites, as in - `y = 0; if (a) y = 1;` ([#1706](https://github.com/celox-sim/celox/issues/1706)). `always @*` already - reports that write. +- A waiter sees every value that one evaluation of `always_comb`, + `always @*`, an edge-triggered `always` or `always_ff` writes, including + one that a later write overwrites: with `a` at 1, `y = 0; if (a) y = 1;` + wakes `@(y)` (IEEE 1800-2023 4.3, 9.4.2). Nonblocking updates apply in the + NBA region in issue order, each its own update (10.4.2). A child's output + port is a continuous assignment to the parent's net (23.3.3), so a waiter + in the parent sees only the settled value, as in the previous item. + Verilator 5.052 sees only the final value of an evaluation; Icarus 13.0 + also sees the pulse through the port. ### Variable lifetimes diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7bce8fc86df..48ab4d12c28 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -275,9 +275,12 @@ Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatche 変化しておらず、パルス `a = 1; a = 0;` は `@(a)` を起こしますが `@(a ^ b)` は起こしません。 パルスを見せるには書き込みの間に `#0` を入れてください。この順序は IEEE 1800-2023 4.7 で 許されています。Icarus は書き込みごとに式を評価します。 -- `always_comb`、エッジで起動する `always`、`always_ff` の1回の評価の中で書いてから上書きした値 - (`y = 0; if (a) y = 1;` など)は、まだ待ち側から見えません - ([#1706](https://github.com/celox-sim/celox/issues/1706))。`always @*` ではすでに見えます。 +- `always_comb`、`always @*`、エッジで起動する `always`、`always_ff` の1回の評価が書いた値は、 + 後の書き込みで上書きされるものも含めてすべて待ち側から見えます。`a` が 1 のとき、 + `y = 0; if (a) y = 1;` は `@(y)` を起こします(IEEE 1800-2023 4.3、9.4.2)。ノンブロッキングの + 更新は NBA 領域で発行順に適用し、それぞれが1回の更新です(10.4.2)。子モジュールの出力ポートは + 親のネットへの継続代入なので(23.3.3)、親の待ちは前の項目と同じく確定した値だけを見ます。 + Verilator 5.052 は評価の最終値だけを見ます。Icarus 13.0 はポートを通したパルスも見ます。 ### 変数の寿命 From 6e70cd8b91dae08dccfcee5683600833c1226866 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:12:14 +0900 Subject: [PATCH 4/9] docs(sv): keep the watch slot docs free of private links Change-Id: Ie0a71ea46beca39a738c17cc203f752ea8173e2b --- crates/celox-frontend-core/src/watch.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 28564c159c2..5d0c70e488a 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -938,7 +938,8 @@ fn declare_hidden( } /// Declare counter objects for `candidates` among the variables of a module -/// and return them. Candidates that are not [`watchable`] are skipped. +/// and return them. Candidates that are no state of the module, or are +/// unpacked arrays, are skipped (see `watchable`). pub fn declare_counter_slots( variables: &mut SymbolicVariables, candidates: impl IntoIterator, @@ -974,7 +975,7 @@ pub fn declare_counter_slots( /// Declare the [`PendingSlots`] of `streams` among the variables of a /// module and return them. A stream is a signal and, for nonblocking writes /// staged apart from blocking ones, its staging value and mask. Streams of -/// signals that are not [`watchable`] are skipped. +/// signals that are not watchable (see `watchable`) are skipped. pub fn declare_pending_slots( variables: &mut SymbolicVariables, streams: impl IntoIterator< From bcdca7bec46454ae838d94950214c1e32a5f49fd Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 00:05:28 +0900 Subject: [PATCH 5/9] fix(sv): hold flip-flop occurrences per published bit A flip-flop stream now applies each write to a private copy and marks the bits written so far. A write that changes covered bits is an occurrence; a write of uncovered bits compares at the commit with the value the commit publishes over, so a staged nonblocking update is judged against the final blocking value. Each commit releases only the bits it publishes and no unit clears the stream on entry, so the parts of a parallel build no longer wipe each other's held writes. An instance that keeps the imperative alternative of an always_comb removes only the symbolic paths of that process's target ranges, so other drivers of the same variables keep theirs. Change-Id: I93f3569cb5edb5ed981fda8bf33fdf3401e19d17 --- .../src/symbolic/artifact.rs | 7 +- .../src/symbolic/assembly.rs | 31 +- crates/celox-frontend-core/src/watch.rs | 400 +++++++++--------- crates/celox-frontend-sv/src/lowering.rs | 10 +- 4 files changed, 237 insertions(+), 211 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 2e43cf04ff7..cf8d54a5bba 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -3,7 +3,7 @@ use std::{collections::BTreeSet, fmt}; use celox_design::{ CounterSlots, ExternFunction, InitialStateValue, ModuleId, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet, - VariableMetadata, WaitSite, + VarAtomBase, VariableMetadata, WaitSite, }; use celox_sir::ExecutionUnit; use celox_slt::{CombObserver, FfAccessSummary, GlueBlockBase, LogicPath, SLTNodeArena}; @@ -77,8 +77,9 @@ pub struct SplitCommit { pub struct CombAlternative { /// The `process` of the unit's paths. pub process: SourceVarId, - /// The variables the symbolic definitions write. - pub targets: Vec, + /// The ranges the symbolic definitions write; other drivers may write + /// the other bits of the same variables. + pub targets: Vec>, /// The variables the unit may store twice in one execution. pub candidates: Vec, } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 941669535a2..df65a566828 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -3640,7 +3640,8 @@ fn counted_signals( /// Keep, for every instance of a process in `comb_alternatives`, either /// its imperative unit, when a variable it may store twice is `counted`, or -/// its symbolic definitions, and remove the other form from `comb_blocks`. +/// its symbolic definitions, and remove the paths of the other form from +/// `comb_blocks`. Paths of other drivers of the same variables stay. fn choose_comb_alternatives( bindings: &PackageBindings, instance_modules: &HashMap, @@ -3658,7 +3659,10 @@ fn choose_comb_alternatives( .iter() .any(|&candidate| counted.contains_key(&locate(candidate))) { - symbolic.extend(alternative.targets.iter().map(|&target| locate(target))); + symbolic.extend(alternative.targets.iter().map(|target| VarAtomBase { + id: locate(target.id), + access: target.access, + })); } else { imperative.insert(locate(alternative.process)); } @@ -3668,7 +3672,7 @@ fn choose_comb_alternatives( return; } comb_blocks.retain(|path| match &path.target { - LogicPathTarget::Var(target) => !symbolic.contains(&target.id), + LogicPathTarget::Var(target) => !symbolic.contains(target), LogicPathTarget::Process { process, .. } => !imperative.contains(process), LogicPathTarget::CombCaptureEvent { .. } => true, }); @@ -3755,18 +3759,17 @@ fn instrument_counted_signals<'u>( .filter_map(|slots| { Some(crate::watch::PendingCode { watch: watch(slots.signal)?, - next: working(slots.signal), - staged: slots.staged.map(|staged| crate::watch::StagedSlots { - value: working(staged.value), - mask: working(staged.mask), - first_mask: stable(staged.first_mask), - }), + write: working(slots.staged.unwrap_or(slots.signal)), + staged: slots.staged.is_some(), + value: stable(slots.value), + covered: stable(slots.covered), first: stable(slots.first), - has_first: stable(slots.has_first), - pending: CounterKind::ALL - .into_iter() - .map(|kind| (kind, stable(slots.pending(kind)))) - .collect(), + changed: stable(slots.changed), + written: stable(slots.written), + edges: vec![ + (CounterKind::Rises, stable(slots.rises)), + (CounterKind::Falls, stable(slots.falls)), + ], }) }) .collect(); diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 5d0c70e488a..7035b3004e4 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -487,54 +487,46 @@ pub fn instrument_writes( /// of the signal there, applied in issue order (IEEE 1800-2023 4.5, /// 10.4.2): `y <= 0; y <= 1;` is two updates. Counting at the writes would /// wake a waiter before the commit, and counting at the commit alone sees -/// only the final value. So the evaluation keeps its first written value -/// and counts the occurrences between later writes as pending; the commit -/// adds the occurrence from the published value to the first one, and the -/// pending ones. +/// only the final value. +/// +/// So the writes go to a private copy of the stream (`value`) as well, and +/// `covered` marks the bits written so far. A write that changes covered +/// bits is an occurrence whatever the published value is: it marks its bits +/// in `changed`, and an edge of the least significant bit counts in `rises` +/// or `falls`. A write of uncovered bits compares with the value the commit +/// publishes over, so `first` keeps the value it wrote there. A commit +/// counts, in the bits it publishes, the occurrence from the published value +/// to `first` and the held ones, and releases those bits. +/// +/// A waiter compares a counter only with the value it saw, so the commit +/// counts one change for all the changes it releases. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PendingSlots { pub signal: A, /// For the nonblocking writes of a variable the process also writes by - /// blocking assignments: the staging value and mask they go to. - /// Otherwise the writes go to the signal's next state. - pub staged: Option>, - /// The value after the first write, and whether there was one. + /// blocking assignments: the staging value they go to. Otherwise the + /// writes go to the signal's next state. + pub staged: Option, + pub value: A, + pub covered: A, pub first: A, - pub has_first: A, - pub changes: A, + pub changed: A, + /// The bits of the write being counted. + pub written: A, pub rises: A, pub falls: A, } -/// The staging objects of [`PendingSlots`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct StagedSlots { - pub value: A, - pub mask: A, - /// The mask after the first write: the bits the first value holds. - pub first_mask: A, -} - impl PendingSlots { - pub fn pending(&self, kind: CounterKind) -> A { - match kind { - CounterKind::Changes => self.changes, - CounterKind::Rises => self.rises, - CounterKind::Falls => self.falls, - } - } - pub fn map(self, mut map: impl FnMut(A) -> B) -> PendingSlots { PendingSlots { signal: map(self.signal), - staged: self.staged.map(|staged| StagedSlots { - value: map(staged.value), - mask: map(staged.mask), - first_mask: map(staged.first_mask), - }), + staged: self.staged.map(&mut map), + value: map(self.value), + covered: map(self.covered), first: map(self.first), - has_first: map(self.has_first), - changes: map(self.changes), + changed: map(self.changed), + written: map(self.written), rises: map(self.rises), falls: map(self.falls), } @@ -546,43 +538,45 @@ impl PendingSlots { pub struct PendingCode { /// The signal's stable state and its counters. pub watch: WatchCode, - /// The signal's next state. - pub next: A, - pub staged: Option>, + /// Where the writes go: the signal's next state, or its staging value. + pub write: A, + /// Whether `write` is a staging value, which a store to the signal + /// publishes. + pub staged: bool, + pub value: A, + pub covered: A, pub first: A, - pub has_first: A, - pub pending: Vec<(CounterKind, A)>, + pub changed: A, + pub written: A, + /// The held edges of the least significant bit. + pub edges: Vec<(CounterKind, A)>, } /// What an instruction of a flip-flop unit does to a [`PendingCode`] /// stream. enum PendingRole { - /// A write of the evaluation; `marks` for a store to the staging mask. - Write { marks: bool }, + /// A write of the evaluation. + Write, /// The publication. Release, } impl PendingCode { fn role(&self, instruction: &SIRInstruction) -> Option { - match (instruction, &self.staged) { - (SIRInstruction::Store(address, ..), None) => { - (*address == self.next).then_some(PendingRole::Write { marks: false }) + match instruction { + SIRInstruction::Store(address, ..) if *address == self.write => { + Some(PendingRole::Write) } - (SIRInstruction::Store(address, ..), Some(staged)) => { - if *address == staged.value { - Some(PendingRole::Write { marks: false }) - } else if *address == staged.mask { - Some(PendingRole::Write { marks: true }) - } else { - (*address == self.watch.signal).then_some(PendingRole::Release) - } + SIRInstruction::Store(address, ..) if self.staged && *address == self.watch.signal => { + Some(PendingRole::Release) } // A seed copies the stable state into the next state; it is // not a write. - (SIRInstruction::Commit(source, destination, ..), None) => (*source == self.next - && *destination == self.watch.signal) - .then_some(PendingRole::Release), + SIRInstruction::Commit(source, destination, ..) + if !self.staged && *source == self.write && *destination == self.watch.signal => + { + Some(PendingRole::Release) + } _ => None, } } @@ -607,6 +601,16 @@ fn store(b: &mut SIRBuilder, address: &A, width: usize, value: Regi )); } +fn mask(b: &mut SIRBuilder, bits: &num_bigint::BigUint, width: usize) -> RegisterId { + let mask = b.alloc_bit(width, false); + b.emit(SIRInstruction::Imm(mask, SIRValue::new(bits.clone()))); + mask +} + +fn ones(width: usize) -> num_bigint::BigUint { + (num_bigint::BigUint::from(1u8) << width) - 1u8 +} + /// `base` with the bits `mask` marks taken from `value`. fn overlay( b: &mut SIRBuilder, @@ -631,131 +635,171 @@ fn overlay( merged } -/// The value the writes of `code` have produced so far: the next state, or -/// for a staged stream the next state with the staged bits replaced, as the -/// NBA merge will publish it. -fn pending_view(b: &mut SIRBuilder, code: &PendingCode) -> RegisterId { - let (width, four_state) = (code.watch.width, code.watch.four_state); - let next = load(b, &code.next, width, four_state); - let Some(staged) = &code.staged else { - return next; - }; - let value = load(b, &staged.value, width, four_state); - let mask = load(b, &staged.mask, width, false); - overlay(b, next, value, mask, width, four_state) +/// `lhs & !rhs`, both masks. +fn and_not(b: &mut SIRBuilder, lhs: RegisterId, rhs: RegisterId, width: usize) -> RegisterId { + let inverted = b.alloc_bit(width, false); + b.emit(SIRInstruction::Unary( + inverted, + celox_design::UnaryOp::BitNot, + rhs, + )); + let result = b.alloc_bit(width, false); + b.emit(SIRInstruction::Binary(result, lhs, BinaryOp::And, inverted)); + result } -/// Emit `write`, a write of the evaluation to the stream of `code`, and -/// keep its occurrence: the first write is remembered, a later one counts -/// as pending. +/// Emit `write`, a store of the evaluation to the stream of `code`, and +/// keep its occurrence (see [`PendingSlots`]). fn emit_pending_write( b: &mut SIRBuilder, code: &PendingCode, write: SIRInstruction, - marks: bool, ) { let (width, four_state) = (code.watch.width, code.watch.four_state); - let old = pending_view(b, code); - let old_lsb = lsb(b, old, width, four_state); + let SIRInstruction::Store(_, offset, bits, source, ..) = &write else { + unreachable!("a write of a stream is a store"); + }; + let (offset, bits, source) = (offset.clone(), *bits, *source); + let old = load(b, &code.value, width, four_state); + let covered = load(b, &code.covered, width, false); b.emit(write); - let new = pending_view(b, code); - let new_lsb = lsb(b, new, width, four_state); - let has_first = load(b, &code.has_first, 1, false); - for &(kind, ref pending) in &code.pending { - let occurred = occurrence(b, kind, (old, old_lsb), (new, new_lsb), width, four_state); - let held = binary(b, occurred, BinaryOp::And, has_first); - bump(b, pending, held); - } - // A staged value takes effect where its mask is marked, and the - // evaluation clears the mask before its body: the first write of a - // staged stream is the first mark. - if code.staged.is_some() && !marks { - return; + // The write applied to the private copy, and the bits it writes. + b.emit(SIRInstruction::Store( + code.value.clone(), + offset.clone(), + bits, + source, + Vec::new(), + Vec::new(), + )); + let none = mask(b, &num_bigint::BigUint::default(), width); + store(b, &code.written, width, none); + let all = mask(b, &ones(bits), bits); + b.emit(SIRInstruction::Store( + code.written.clone(), + offset, + bits, + all, + Vec::new(), + Vec::new(), + )); + let written = load(b, &code.written, width, false); + let new = load(b, &code.value, width, four_state); + // The covered bits before the write, on a fixed background. + let background = constant(b, 0, width, four_state); + let before = overlay(b, background, old, covered, width, four_state); + let after = overlay(b, background, new, covered, width, four_state); + let changed = binary(b, before, BinaryOp::NeCase, after); + let marked = load(b, &code.changed, width, false); + let with_write = b.alloc_bit(width, false); + b.emit(SIRInstruction::Binary( + with_write, + marked, + BinaryOp::Or, + written, + )); + let next_marked = b.alloc_bit(width, false); + b.emit(SIRInstruction::Mux( + next_marked, + changed, + with_write, + marked, + )); + store(b, &code.changed, width, next_marked); + let before_lsb = lsb(b, before, width, four_state); + let after_lsb = lsb(b, after, width, four_state); + for &(kind, ref held) in &code.edges { + let occurred = occurrence( + b, + kind, + (before, before_lsb), + (after, after_lsb), + width, + four_state, + ); + bump(b, held, occurred); } - let none = b.alloc_bit(1, false); - b.emit(SIRInstruction::Unary( - none, - celox_design::UnaryOp::LogicNot, - has_first, + // The bits the write covers first keep its value. + let fresh = and_not(b, written, covered, width); + let first = load(b, &code.first, width, four_state); + let first = overlay(b, first, new, fresh, width, four_state); + store(b, &code.first, width, first); + let now_covered = b.alloc_bit(width, false); + b.emit(SIRInstruction::Binary( + now_covered, + covered, + BinaryOp::Or, + written, )); - let (first, set) = match &code.staged { - None => (new, none), - Some(staged) => { - let mask = load(b, &staged.mask, width, false); - let zero = constant(b, 0, width, false); - let marked = binary(b, mask, BinaryOp::NeCase, zero); - let set = binary(b, none, BinaryOp::And, marked); - let previous = load(b, &staged.first_mask, width, false); - let first_mask = b.alloc_bit(width, false); - b.emit(SIRInstruction::Mux(first_mask, set, mask, previous)); - store(b, &staged.first_mask, width, first_mask); - (load(b, &staged.value, width, four_state), set) - } - }; - let previous = load(b, &code.first, width, four_state); - let kept = value_register(b, width, four_state); - b.emit(SIRInstruction::Mux(kept, set, first, previous)); - store(b, &code.first, width, kept); - let started = binary(b, has_first, BinaryOp::Or, set); - store(b, &code.has_first, 1, started); + store(b, &code.covered, width, now_covered); } -/// After the publication of the stream of `code`, count its occurrences: -/// the one from `published`, the signal's value before the publication, to -/// the first written value in the bits the publication writes (`mask`), and -/// the pending ones. The stream is then empty. +/// After a publication of the stream of `code` in the bits `published` +/// writes, count their occurrences: the one from `before`, the signal's +/// value before the publication, to the first written values, the held +/// changes, and with the least significant bit its held edges. Those bits +/// of the stream are then empty. fn emit_release( b: &mut SIRBuilder, code: &PendingCode, - published: RegisterId, - written: &num_bigint::BigUint, + before: RegisterId, + published: &num_bigint::BigUint, ) { let (width, four_state) = (code.watch.width, code.watch.four_state); - let has_first = load(b, &code.has_first, 1, false); + let bits = mask(b, published, width); + let covered = load(b, &code.covered, width, false); + let released = b.alloc_bit(width, false); + b.emit(SIRInstruction::Binary( + released, + covered, + BinaryOp::And, + bits, + )); let first = load(b, &code.first, width, four_state); - let mask = match &code.staged { - Some(staged) => load(b, &staged.first_mask, width, false), - None => { - let mask = b.alloc_bit(width, false); - b.emit(SIRInstruction::Imm(mask, SIRValue::new(written.clone()))); - mask - } - }; - let first = overlay(b, published, first, mask, width, four_state); - let published_lsb = lsb(b, published, width, four_state); + let first = overlay(b, before, first, released, width, four_state); + let before_lsb = lsb(b, before, width, four_state); let first_lsb = lsb(b, first, width, four_state); - for &(kind, ref pending) in &code.pending { - let Some((_, counter)) = code.watch.counters.iter().find(|(k, _)| *k == kind) else { - continue; - }; + let lsb_released = published.bit(0); + for (kind, counter) in &code.watch.counters { let occurred = occurrence( b, - kind, - (published, published_lsb), + *kind, + (before, before_lsb), (first, first_lsb), width, four_state, ); - let counted = binary(b, occurred, BinaryOp::And, has_first); - bump(b, counter, counted); + if *kind == CounterKind::Changes { + let marked = load(b, &code.changed, width, false); + let held = b.alloc_bit(width, false); + b.emit(SIRInstruction::Binary(held, marked, BinaryOp::And, bits)); + let none = mask(b, &num_bigint::BigUint::default(), width); + let held = binary(b, held, BinaryOp::Ne, none); + let occurred = binary(b, occurred, BinaryOp::Or, held); + bump(b, counter, occurred); + continue; + } + bump(b, counter, occurred); + let Some((_, held)) = code.edges.iter().find(|(k, _)| k == kind) else { + continue; + }; + if !lsb_released { + continue; + } let total = load(b, counter, EVENT_COUNTER_WIDTH, false); - let held = load(b, pending, EVENT_COUNTER_WIDTH, false); + let pending = load(b, held, EVENT_COUNTER_WIDTH, false); let sum = b.alloc_bit(EVENT_COUNTER_WIDTH, false); - b.emit(SIRInstruction::Binary(sum, total, BinaryOp::Add, held)); + b.emit(SIRInstruction::Binary(sum, total, BinaryOp::Add, pending)); store(b, counter, EVENT_COUNTER_WIDTH, sum); + let zero = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + store(b, held, EVENT_COUNTER_WIDTH, zero); } - emit_clear(b, code); -} - -/// Empty the stream of `code`. -fn emit_clear(b: &mut SIRBuilder, code: &PendingCode) { - let zero = constant(b, 0, 1, false); - store(b, &code.has_first, 1, zero); - let zero = b.alloc_bit(EVENT_COUNTER_WIDTH, false); - b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); - for (_, pending) in &code.pending { - store(b, pending, EVENT_COUNTER_WIDTH, zero); - } + let remaining = and_not(b, covered, bits, width); + store(b, &code.covered, width, remaining); + let marked = load(b, &code.changed, width, false); + let remaining = and_not(b, marked, bits, width); + store(b, &code.changed, width, remaining); } /// The instructions `emit` builds, with registers from `next_register` on. @@ -777,9 +821,9 @@ fn emitted( } /// Instrument the writes and publications of a flip-flop unit for the -/// streams of `codes` (see [`PendingSlots`]). A unit that writes a stream -/// starts it empty, so an evaluation that was superseded before its commit -/// leaves nothing behind. +/// streams of `codes` (see [`PendingSlots`]). The units of one evaluation, +/// such as the parts of a parallel build, share a stream: each publication +/// releases only the bits it publishes. pub fn instrument_pending( unit: &mut ExecutionUnit, codes: &[PendingCode], @@ -793,7 +837,6 @@ pub fn instrument_pending( .map(|id| id.0 + 1) .max() .unwrap_or(0); - let mut started = vec![false; codes.len()]; let mut blocks: Vec<_> = unit.blocks.keys().copied().collect(); blocks.sort_unstable(); for id in blocks { @@ -811,8 +854,8 @@ pub fn instrument_pending( if roles.iter().all(Option::is_none) { continue; } - // The bits each stream's commits in this block publish, and where - // its last publication is. + // The bits each stream's publications in this block write, and + // where its last publication is. let mut written = vec![num_bigint::BigUint::default(); codes.len()]; let mut last = vec![None; codes.len()]; for (position, (instruction, role)) in block.instructions.iter().zip(&roles).enumerate() { @@ -820,12 +863,11 @@ pub fn instrument_pending( continue; }; last[*index] = Some(position); - let width = codes[*index].watch.width; let range = match instruction { SIRInstruction::Commit(_, _, SIROffset::Static(lsb), bits, _) => { - ((num_bigint::BigUint::from(1u8) << *bits) - 1u8) << *lsb + ones(*bits) << *lsb } - _ => (num_bigint::BigUint::from(1u8) << width) - 1u8, + _ => ones(codes[*index].watch.width), }; written[*index] |= range; } @@ -838,10 +880,9 @@ pub fn instrument_pending( { match role { None => instructions.push(instruction), - Some((index, PendingRole::Write { marks })) => { - started[index] = true; + Some((index, PendingRole::Write)) => { instructions.extend(emitted(&mut unit.register_map, &mut next_register, |b| { - emit_pending_write(b, &codes[index], instruction, marks) + emit_pending_write(b, &codes[index], instruction) })); } Some((index, PendingRole::Release)) => { @@ -874,18 +915,6 @@ pub fn instrument_pending( } block.instructions = instructions; } - let mut entry = Vec::new(); - for (code, _) in codes.iter().zip(&started).filter(|(_, started)| **started) { - entry.extend(emitted(&mut unit.register_map, &mut next_register, |b| { - emit_clear(b, code) - })); - } - let block = unit - .blocks - .get_mut(&unit.entry_block_id) - .expect("the entry block"); - entry.append(&mut block.instructions); - block.instructions = entry; } type SymbolicVariables = @@ -974,16 +1003,11 @@ pub fn declare_counter_slots( /// Declare the [`PendingSlots`] of `streams` among the variables of a /// module and return them. A stream is a signal and, for nonblocking writes -/// staged apart from blocking ones, its staging value and mask. Streams of -/// signals that are not watchable (see `watchable`) are skipped. +/// staged apart from blocking ones, its staging value. Streams of signals +/// that are not watchable (see `watchable`) are skipped. pub fn declare_pending_slots( variables: &mut SymbolicVariables, - streams: impl IntoIterator< - Item = ( - crate::SourceVarId, - Option<(crate::SourceVarId, crate::SourceVarId)>, - ), - >, + streams: impl IntoIterator)>, ) -> Vec> { let mut streams: Vec<_> = streams .into_iter() @@ -1013,14 +1037,12 @@ pub fn declare_pending_slots( }; PendingSlots { signal, - staged: staged.map(|(value, mask)| StagedSlots { - value, - mask, - first_mask: hidden("first_mask", width, false), - }), + staged, + value: hidden("value", width, is_4state), + covered: hidden("covered", width, false), first: hidden("first", width, is_4state), - has_first: hidden("has_first", 1, false), - changes: hidden("changes", EVENT_COUNTER_WIDTH, false), + changed: hidden("changed", width, false), + written: hidden("written", width, false), rises: hidden("rises", EVENT_COUNTER_WIDTH, false), falls: hidden("falls", EVENT_COUNTER_WIDTH, false), } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index e8260cad82c..49e57379adc 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4282,7 +4282,7 @@ fn lower_comb_processes( let mut targets: Vec<_> = paths .iter() .filter_map(|path| match &path.target { - LogicPathTarget::Var(target) => Some(target.id), + LogicPathTarget::Var(target) => Some(*target), _ => None, }) .collect(); @@ -4410,7 +4410,7 @@ fn lower_comb_alternative( pm: &mut procedural::ProcModule<'_>, process: &sv::ir::CombProcess, random_seed: u32, - targets: Vec, + targets: Vec>, arena: &mut SLTNodeArena, ) -> Option<(Vec>, CombAlternative)> { let checkpoint = pm.checkpoint(); @@ -8125,9 +8125,9 @@ impl FfEventVars { } /// A signal a flip-flop evaluation writes and, for nonblocking writes staged -/// apart from blocking ones, its staging value and mask; see +/// apart from blocking ones, its staging value; see /// `celox_frontend_core::watch::PendingSlots`. -type FfWriteStream = (SourceVarId, Option<(SourceVarId, SourceVarId)>); +type FfWriteStream = (SourceVarId, Option); /// The write streams one execution of the flip-flop evaluation `eval` may /// write twice. `staged` lists its staged variables as (variable, value, @@ -8148,7 +8148,7 @@ fn repeated_ff_writes( .into_iter() .filter_map( |id| match staged.iter().find(|&&(_, value, _)| value == id) { - Some(&(signal, value, mask)) => Some((signal, Some((value, mask)))), + Some(&(signal, value, _)) => Some((signal, Some(value))), None if staged.iter().any(|&(_, _, mask)| mask == id) => None, None => Some((id, None)), }, From 9f359d5aadb5a67b1812fd723309ae7e1bb3b0ad Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 00:05:28 +0900 Subject: [PATCH 6/9] test(sv): cover other drivers, parallel parts and late blocking writes Three timing cases for the review findings on intermediate writes, verified with Icarus 13.0. Verilator 5.052 sees only final values and joins the existing sv_verilator_intermediate_writes exclusion, with standalone probes. Change-Id: I795ddad81bf28d02100c45a6c7d25fe358160fe3 --- crates/celox-test-suite/LIMITATIONS.md | 2 +- .../src/sv/cases/timing.vtest | 88 +++++++++++++++++++ .../sv_intermediate_writes_verilator.json | 69 +++++++++++++++ .../verification/sv/icarus/timing.json | 33 +++++++ .../verification/sv/limitations.json | 7 +- .../verification/sv/verilator/timing.json | 81 +++++++++++++++-- .../tests/frontends/systemverilog/timing.rs | 3 + 7 files changed, 274 insertions(+), 9 deletions(-) diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index ca5354133f3..561a596305d 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -539,7 +539,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_urandom_narrow_seed` | execute | icarus | 1 | Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks. | | `sv_verilator_random_algorithm` | execute | verilator | 2 | Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator. | | `sv_verilator_time_in_combinational_logic` | execute | verilator | 1 | Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one. | -| `sv_verilator_intermediate_writes` | execute | verilator | 3 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. | +| `sv_verilator_intermediate_writes` | execute | verilator | 6 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. | | `sv_icarus_port_pulses` | execute | icarus | 1 | Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give. The [standalone probe](verification/repros/sv_port_pulses_icarus.json) retains both outputs. | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1996e62dc9a..0ea102f05c6 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1872,3 +1872,91 @@ 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 "child=1\n")) + +; A process whose intermediate writes are counted drives only some bits of +; its variable; the other bits keep their own drivers. +(case intermediate_combinational_writes_keep_other_drivers + (source "drivers.sv" #" + module Top; + logic a = 0, b = 0, e = 0, c, d; + logic [7:0] y, z; + int n, m; + assign y[7:4] = 4'hA; + always_comb begin y[3:0] = 0; if (a) y[3:0] = 1; c = b; end + always_comb begin z[3:0] = 0; if (a) z[3:0] = 1; d = b; end + always_comb z[7:4] = {4{e}}; + initial #1 forever begin @(y); n++; end + initial #1 forever begin @(z); m++; end + initial begin + #2 a = 1; + // While a is 1, each change of b rewrites y and z + // 1 -> 0 -> 1 in their low bits. + #1 b = 1; + #1 e = 1; + #1 $display("y=%h z=%h n=%0d m=%0d", y, z, n, m); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=a1 z=f1 n=2 m=3\n")) + +; One process pulses y[0] back to its value, and processes of the same clock +; write the other bits of y unchanged. A parallel build evaluates every +; process before any commits; the pulse still counts. +(case parallel_flip_flop_parts_keep_pulses + (source "parts.sv" #" + module Top; + bit clk; + bit [2:0] y = 3'b001; + bit [63:0] p, q, r, s; + int n, f; + always_ff @(posedge clk) y[2] <= y[2]; + always_ff @(posedge clk) begin y[0] <= 0; y[0] <= 1; end + always_ff @(posedge clk) y[1] <= y[1]; + // Independent work, so that a parallel build splits the + // processes into parts. + always_ff @(posedge clk) p <= p * 64'd7 + (p >> 3) + 64'd1; + always_ff @(posedge clk) q <= q * 64'd11 + (q >> 5) + 64'd3; + always_ff @(posedge clk) r <= r * 64'd13 + (r >> 7) + 64'd5; + always_ff @(posedge clk) s <= s * 64'd17 + (s >> 9) + 64'd9; + initial forever begin @(y); n++; end + initial forever begin @(negedge y); f++; end + initial begin + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 $display("y=%b n=%0d f=%0d", y, n, f); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=001 n=2 f=2\n")) + +; The nonblocking updates apply after the blocking value was published: +; y[0] <= 1 rises from the final blocking value 0, not from the 1 it held +; when the update was issued. The blocking writes only fall, so the waiter +; sees the rise in the NBA region. +(case staged_nonblocking_writes_follow_later_blocking_writes + (source "staged_order.sv" #" + module Top; + bit clk; + bit [1:0] y = 2'b01; + int r; + always @(posedge clk) begin y[1] <= 0; y[0] <= 1; y = 2'b00; end + initial forever begin @(posedge y); r++; end + initial begin + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + #1 $display("y=%b r=%0d", y, r); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=01 r=2\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json index 068b538fc49..d34cf8fbc9f 100644 --- a/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json +++ b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json @@ -70,6 +70,75 @@ "exit_code": 0, "output": "y=3 z=3\n/probe.sv:8: $finish called at 6 (1s)\n" } + }, + { + "name": "other_drivers", + "note": "The suite case intermediate_combinational_writes_keep_other_drivers.", + "source": "module Top;\n logic a = 0, b = 0, e = 0, c, d;\n logic [7:0] y, z;\n int n, m;\n assign y[7:4] = 4'hA;\n always_comb begin y[3:0] = 0; if (a) y[3:0] = 1; c = b; end\n always_comb begin z[3:0] = 0; if (a) z[3:0] = 1; d = b; end\n always_comb z[7:4] = {4{e}};\n initial #1 forever begin @(y); n++; end\n initial #1 forever begin @(z); m++; end\n initial begin #2 a = 1; #1 b = 1; #1 e = 1; #1 $display(\"y=%h z=%h n=%0d m=%0d\", y, z, n, m); $finish; 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": "y=a1 z=f1 n=1 m=2\n- /probe.sv:11: 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 5ps; walltime 0.000 s; speed 196.711 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "y=a1 z=f1 n=2 m=3\n/probe.sv:11: $finish called at 5 (1s)\n" + } + }, + { + "name": "parallel_parts", + "note": "The suite case parallel_flip_flop_parts_keep_pulses.", + "source": "module Top;\n bit clk;\n bit [2:0] y = 3'b001;\n bit [63:0] p, q, r, s;\n int n, f;\n always_ff @(posedge clk) y[2] <= y[2];\n always_ff @(posedge clk) begin y[0] <= 0; y[0] <= 1; end\n always_ff @(posedge clk) y[1] <= y[1];\n always_ff @(posedge clk) p <= p * 64'd7 + (p >> 3) + 64'd1;\n always_ff @(posedge clk) q <= q * 64'd11 + (q >> 5) + 64'd3;\n always_ff @(posedge clk) r <= r * 64'd13 + (r >> 7) + 64'd5;\n always_ff @(posedge clk) s <= s * 64'd17 + (s >> 9) + 64'd9;\n initial forever begin @(y); n++; end\n initial forever begin @(negedge y); f++; end\n initial begin #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 $display(\"y=%b n=%0d f=%0d\", y, n, f); $finish; 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": "y=001 n=0 f=0\n- /probe.sv:15: 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 4ps; walltime 0.000 s; speed 171.821 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "y=001 n=2 f=2\n/probe.sv:15: $finish called at 4 (1s)\n" + } + }, + { + "name": "staged_order", + "note": "The suite case staged_nonblocking_writes_follow_later_blocking_writes.", + "source": "module Top;\n bit clk;\n bit [1:0] y = 2'b01;\n int r;\n always @(posedge clk) begin y[1] <= 0; y[0] <= 1; y = 2'b00; end\n initial forever begin @(posedge y); r++; end\n initial begin #1 clk = 1; #1 clk = 0; #1 clk = 1; #1 $display(\"y=%b r=%0d\", y, r); $finish; 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": "y=01 r=0\n- /probe.sv:7: 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 4ps; walltime 0.000 s; speed 185.675 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "y=01 r=2\n/probe.sv:7: $finish called at 4 (1s)\n" + } } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index ee643a026ba..ee225e3bc42 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -453,6 +453,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_keep_other_drivers", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -585,6 +596,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::parallel_flip_flop_parts_keep_pulses", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -739,6 +761,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::staged_nonblocking_writes_follow_later_blocking_writes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 6e64a92b39e..95c09cb0639 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1886,7 +1886,7 @@ "category": "simulator_disagreement", "phase": "execute", "observed_version": "Verilator 5.052", - "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "upstream": [], "evidence": [ "verification/repros/sv_intermediate_writes_verilator.json", @@ -1896,7 +1896,10 @@ "verilator": [ "timing::intermediate_combinational_writes_wake_waiters", "timing::intermediate_edge_process_writes_wake_waiters", - "timing::staged_nonblocking_writes_wake_waiters" + "timing::staged_nonblocking_writes_wake_waiters", + "timing::intermediate_combinational_writes_keep_other_drivers", + "timing::parallel_flip_flop_parts_keep_pulses", + "timing::staged_nonblocking_writes_follow_later_blocking_writes" ] } }, diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 5cda2533b12..60d7928dcee 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -467,7 +467,7 @@ }, { "category": "Sequential", - "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "expectation": "Simulation", "known_issue": { "category": "simulator_disagreement", @@ -478,7 +478,30 @@ "id": "sv_verilator_intermediate_writes", "observed_version": "Verilator 5.052", "phase": "execute", - "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::intermediate_combinational_writes_keep_other_drivers", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "upstream": [] }, "name": "timing::intermediate_combinational_writes_wake_waiters", @@ -490,7 +513,7 @@ }, { "category": "Sequential", - "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "expectation": "Simulation", "known_issue": { "category": "simulator_disagreement", @@ -501,7 +524,7 @@ "id": "sv_verilator_intermediate_writes", "observed_version": "Verilator 5.052", "phase": "execute", - "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "upstream": [] }, "name": "timing::intermediate_edge_process_writes_wake_waiters", @@ -645,6 +668,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::parallel_flip_flop_parts_keep_pulses", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -801,7 +847,30 @@ }, { "category": "Sequential", - "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "timing::staged_nonblocking_writes_follow_later_blocking_writes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "expectation": "Simulation", "known_issue": { "category": "simulator_disagreement", @@ -812,7 +881,7 @@ "id": "sv_verilator_intermediate_writes", "observed_version": "Verilator 5.052", "phase": "execute", - "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", "upstream": [] }, "name": "timing::staged_nonblocking_writes_wake_waiters", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index adc684e453b..f54f22628c2 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -152,6 +152,9 @@ timed_cases! { fn intermediate_edge_process_writes_wake_waiters = "timing::intermediate_edge_process_writes_wake_waiters"; fn staged_nonblocking_writes_wake_waiters = "timing::staged_nonblocking_writes_wake_waiters"; fn child_port_pulses_reach_waiters_settled = "timing::child_port_pulses_reach_waiters_settled"; + fn intermediate_combinational_writes_keep_other_drivers = "timing::intermediate_combinational_writes_keep_other_drivers"; + fn parallel_flip_flop_parts_keep_pulses = "timing::parallel_flip_flop_parts_keep_pulses"; + fn staged_nonblocking_writes_follow_later_blocking_writes = "timing::staged_nonblocking_writes_follow_later_blocking_writes"; } #[test] From 83c39d0b8587e0946b9f2d782c82eb877934a135 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 01:06:07 +0900 Subject: [PATCH 7/9] fix(sv): replace split definitions and clear held writes per unit Flattening may split the symbolic definition of a counted always_comb at the boundaries of its readers, so an instance that keeps the imperative unit now removes every path overlapping one of the process's target ranges, not only exact ones. Overlapping drivers are rejected earlier, so no other driver loses a path. A flip-flop unit starts the bits of a held stream that it seeds empty, or a whole staging value, which one process writes. An evaluation that a runtime error ended before its commit, and that the host continues, no longer leaves held writes for the next one, while the other parts of an evaluation keep theirs. Change-Id: If3d08166804161c395482b6534e6aa8238c0d971 --- .../src/symbolic/assembly.rs | 20 ++++-- crates/celox-frontend-core/src/watch.rs | 65 +++++++++++++++++++ 2 files changed, 79 insertions(+), 6 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index df65a566828..2c6fcd74880 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -3650,7 +3650,7 @@ fn choose_comb_alternatives( comb_blocks: &mut Vec>, ) { let mut imperative = HashSet::default(); - let mut symbolic = HashSet::default(); + let mut symbolic = HashMap::>::default(); for (&instance, module) in instance_modules { for alternative in &modules[module].comb_alternatives { let locate = |var_id| bindings.locate(instance, var_id); @@ -3659,10 +3659,12 @@ fn choose_comb_alternatives( .iter() .any(|&candidate| counted.contains_key(&locate(candidate))) { - symbolic.extend(alternative.targets.iter().map(|target| VarAtomBase { - id: locate(target.id), - access: target.access, - })); + for target in &alternative.targets { + symbolic + .entry(locate(target.id)) + .or_default() + .push(target.access); + } } else { imperative.insert(locate(alternative.process)); } @@ -3671,8 +3673,14 @@ fn choose_comb_alternatives( if imperative.is_empty() && symbolic.is_empty() { return; } + // Flattening may have split a definition at the boundaries of its + // readers, so a path of the process is any piece of one of its ranges. + // No other driver writes those bits: the SV frontend rejects overlapping + // drivers (`validate_variable_driver_ranges`). comb_blocks.retain(|path| match &path.target { - LogicPathTarget::Var(target) => !symbolic.contains(target), + LogicPathTarget::Var(target) => !symbolic + .get(&target.id) + .is_some_and(|ranges| ranges.iter().any(|range| range.overlaps(&target.access))), LogicPathTarget::Process { process, .. } => !imperative.contains(process), LogicPathTarget::CombCaptureEvent { .. } => true, }); diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 7035b3004e4..1b5e271996d 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -802,6 +802,29 @@ fn emit_release( store(b, &code.changed, width, remaining); } +/// Empty the bits `cleared` of the stream of `code`, with the held edges +/// when they include the least significant bit. +fn emit_clear( + b: &mut SIRBuilder, + code: &PendingCode, + cleared: &num_bigint::BigUint, +) { + let width = code.watch.width; + let bits = mask(b, cleared, width); + for address in [&code.covered, &code.changed] { + let held = load(b, address, width, false); + let remaining = and_not(b, held, bits, width); + store(b, address, width, remaining); + } + if cleared.bit(0) { + let zero = b.alloc_bit(EVENT_COUNTER_WIDTH, false); + b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + for (_, held) in &code.edges { + store(b, held, EVENT_COUNTER_WIDTH, zero); + } + } +} + /// The instructions `emit` builds, with registers from `next_register` on. fn emitted( register_map: &mut impl Extend<(RegisterId, celox_sir::RegisterType)>, @@ -824,6 +847,12 @@ fn emitted( /// streams of `codes` (see [`PendingSlots`]). The units of one evaluation, /// such as the parts of a parallel build, share a stream: each publication /// releases only the bits it publishes. +/// +/// A unit starts its own bits of a stream empty: the bits it seeds into the +/// next state, or all of a staging value, which one process writes. An +/// evaluation that a runtime error ended before its commit, and that the +/// host then continues, leaves nothing behind for the next one, and other +/// units of the same evaluation keep what they hold. pub fn instrument_pending( unit: &mut ExecutionUnit, codes: &[PendingCode], @@ -915,6 +944,42 @@ pub fn instrument_pending( } block.instructions = instructions; } + let mut entry = Vec::new(); + for code in codes { + let cleared = owned_bits(unit, code); + if cleared != num_bigint::BigUint::default() { + entry.extend(emitted(&mut unit.register_map, &mut next_register, |b| { + emit_clear(b, code, &cleared) + })); + } + } + let block = unit + .blocks + .get_mut(&unit.entry_block_id) + .expect("the entry block"); + entry.append(&mut block.instructions); + block.instructions = entry; +} + +/// The bits of the stream of `code` that `unit` owns: the bits it seeds +/// from the signal into the next state, or the whole staging value if it +/// writes it. +fn owned_bits(unit: &ExecutionUnit, code: &PendingCode) -> num_bigint::BigUint { + let mut owned = num_bigint::BigUint::default(); + for instruction in unit.blocks.values().flat_map(|block| &block.instructions) { + match instruction { + SIRInstruction::Store(address, ..) if code.staged && *address == code.write => { + return ones(code.watch.width); + } + SIRInstruction::Commit(source, destination, SIROffset::Static(lsb), bits, _) + if !code.staged && *source == code.watch.signal && *destination == code.write => + { + owned |= ones(*bits) << *lsb; + } + _ => {} + } + } + owned } type SymbolicVariables = From 0483eec3f31054b2795cb859baff442f2144d5f8 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 01:06:07 +0900 Subject: [PATCH 8/9] test(sv): cover split definitions and concatenated output ports A reader of some bits of a counted always_comb variable, and a counted output port connected to a concatenation. Icarus 13.0 and Verilator 5.052 both pass them. Change-Id: I5fb7bf6c32594eb3403a1a2eff64ec98257f1d35 --- .../src/sv/cases/timing.vtest | 54 +++++++++++++++++++ .../verification/sv/icarus/timing.json | 22 ++++++++ .../verification/sv/verilator/timing.json | 22 ++++++++ .../tests/frontends/systemverilog/timing.rs | 2 + 4 files changed, 100 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 0ea102f05c6..912ecf270c5 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1960,3 +1960,57 @@ 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 "y=01 r=2\n")) + +; A reader of some bits of the counted variable splits its symbolic +; definition at those bits; the imperative unit replaces every piece. +(case intermediate_combinational_writes_replace_split_definitions + (source "split.sv" #" + module Top; + logic [3:0] y, a = 4'b0101, b; + logic [1:0] w; + logic c = 0; + int n; + always_comb begin y = 4'b0; if (c) y = a; b = a; end + assign w = y[1:0]; + initial #1 forever begin @(y); n++; end + initial begin + #2 c = 1; + // While c is 1, each change of a rewrites y through 0. + #1 a = 4'b0110; + #1 a = 4'b0111; + #1 $display("y=%b w=%b n=%0d", y, w, n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=0111 w=11 n=3\n")) + +; The counted variable is an output port that the parent connects to a +; concatenation. +(case intermediate_combinational_writes_reach_concatenated_ports + (source "ports.sv" #" + module Child(input logic c, input logic [3:0] a, output logic [3:0] y); + int n; + always_comb begin y = 4'b0; if (c) y = a; end + initial #1 forever begin @(y); n++; end + initial #5 $display("y=%b n=%0d", y, n); + endmodule + module Top; + logic [3:0] a = 4'b0101; + logic [1:0] p, q; + logic c = 0; + Child u(.c(c), .a(a), .y({p, q})); + initial begin + #2 c = 1; + #1 a = 4'b0110; + #1 a = 4'b1001; + #2 $display("p=%b q=%b", p, q); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=1001 n=3\np=10 q=01\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index ee225e3bc42..ec43a64d592 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -464,6 +464,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_reach_concatenated_ports", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_replace_split_definitions", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 60d7928dcee..717dc6e5563 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -488,6 +488,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_reach_concatenated_ports", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::intermediate_combinational_writes_replace_split_definitions", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index f54f22628c2..6b41ddbdf35 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -155,6 +155,8 @@ timed_cases! { fn intermediate_combinational_writes_keep_other_drivers = "timing::intermediate_combinational_writes_keep_other_drivers"; fn parallel_flip_flop_parts_keep_pulses = "timing::parallel_flip_flop_parts_keep_pulses"; fn staged_nonblocking_writes_follow_later_blocking_writes = "timing::staged_nonblocking_writes_follow_later_blocking_writes"; + fn intermediate_combinational_writes_replace_split_definitions = "timing::intermediate_combinational_writes_replace_split_definitions"; + fn intermediate_combinational_writes_reach_concatenated_ports = "timing::intermediate_combinational_writes_reach_concatenated_ports"; } #[test] From 4f4d93af0cfa18938d84b78f707e78174c440465 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 01:26:57 +0900 Subject: [PATCH 9/9] test(sv): continue after a fatal edge without held writes A $fatal ends an always_ff evaluation after it wrote a watched variable and before its commit; the host continues, and later edges that rewrite the bit to its own value wake no waiter on every backend. Change-Id: Ia88c8150faf478de68e42a7a270684b3e881d240 --- .../tests/frontends/systemverilog/timing.rs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 6b41ddbdf35..9394797babc 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -678,3 +678,70 @@ sv_backends! { @case "timing::static_function_readonly_initializer_calls_execute_once"; } } + +/// An edge whose evaluation a `$fatal` ends before its commit leaves no +/// held write of a watched variable behind: when the host continues, the +/// later edges rewrite `y[0]` to its own value and wake no waiter. +#[test] +fn runtime_error_before_a_commit_leaves_no_held_writes() { + let source = r#" + module Top(output bit [1:0] y, output int n, r, f); + timeunit 1ns / 1ns; + bit clk, bad = 1; + initial y = 2'b01; + always_ff @(posedge clk) begin + if (bad) begin y[0] <= 0; $fatal(1, "bad edge"); end + else begin y[0] <= 1; y[0] <= 1; end + end + initial #2 forever begin @(y); n++; end + initial #2 forever begin @(posedge y); r++; end + initial #2 forever begin @(negedge y); f++; end + initial begin + #1 clk = 1; + #1 clk = 0; bad = 0; + #1 clk = 1; + #1 clk = 0; + #1 clk = 1; + 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("held_after_error.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 [y, n, r, f] = ["y", "n", "r", "f"].map(|name| sim.signal(name)); + assert!( + sim.run_until(1).is_err(), + "{backend}: the first edge reports $fatal" + ); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(y), 1u8.into(), "{backend}"); + for (signal, label) in [(n, "n"), (r, "r"), (f, "f")] { + assert_eq!(sim.get(signal), 0u32.into(), "{backend}: {label}"); + } + }}; + } + if backend.starts_with("native") { + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(builder.build_native()); + } else { + check!(builder.build_cranelift()); + } + } +}