From a4de2ae73b4e877dc6c4963f7f62abdf89d94804 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 12:45:14 +0900 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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 04/11] 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 05/11] 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 06/11] 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 07/11] 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 08/11] 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 09/11] 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()); + } + } +} From 535f07bbdcde0fac8a831e34ab0d777a452db91f Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 22:06:58 +0900 Subject: [PATCH 10/11] feat(sv): support static class members, super and base constructors Classes may now extend a class that has a constructor, call members of their base through `super`, and declare static properties and methods (IEEE 1800-2023 8.9, 8.10, 8.15, 8.17, 8.23). - A `new` expression allocates the object and passes it to the constructor `C::new(this, args)`, which only initializes it: it calls the base constructor with the arguments of a leading `super.new(...)` or of `extends Base(...)`, runs the initializers of the properties its class declares, then its body. Constructors are no longer inherited, so a class without one gets an implicit constructor that calls its base. - `super.m()` and `super.p` reach the members of the base through `this`. `C::new` creates an object of class `C`. - A static property is a variable of the module that declares the class, initialized like other module variables, so each module instance has its own. `h.p`, `C::p` and unqualified names inside methods refer to it. A static method takes no `this` and may be called through a handle, as `C::m()` or unqualified inside the class; a static method that uses a non-static member is rejected. - `C::name` with a class `C` is no longer looked up as a package item. - `++` and `--` work on properties. sv-tests: 8.7-constructor_super, 8.8-typed_constructor, 8.9-static_properties, 8.10-static_methods, 8.13-inheritance, 8.14-override_member, 8.15-super, 8.17-constructor_const_arg and 8.23-scope_resolution now pass in both state modes (509 / 511). Icarus 13.0 cannot parse class scope resolution; its failure on the new static-member case is recorded as a reviewed limitation. Change-Id: I15a7dd1a41d0358f92163d3683ed46b3caa06f7a --- conformance/sv-tests/README.md | 15 +- conformance/sv-tests/expected.tsv | 36 +- crates/celox-sv-analyzer/src/ast.rs | 3 + crates/celox-sv-analyzer/src/ast/classes.rs | 144 +++++++- .../celox-sv-analyzer/src/ast/declarations.rs | 5 + .../src/ast/dimensions/discovery.rs | 32 +- .../src/ast/expression_binding.rs | 4 +- .../src/ast/expression_binding/direct.rs | 60 ++-- .../src/ast/expression_binding/objects.rs | 275 ++++++++++----- crates/celox-sv-analyzer/src/ast/imports.rs | 8 + .../celox-sv-analyzer/src/ast/procedural.rs | 315 +++++++++++++----- crates/celox-test-suite/LIMITATIONS.md | 1 + .../celox-test-suite/src/sv/cases/class.vtest | 83 +++++ .../verification/sv/icarus/class.json | 34 ++ .../verification/sv/limitations.json | 17 + .../verification/sv/limitations/icarus.json | 10 +- .../verification/sv/verilator/class.json | 22 ++ .../tests/frontends/systemverilog/class.rs | 30 ++ docs/guide/systemverilog-reference.md | 10 +- docs/ja/guide/systemverilog-reference.md | 6 +- 20 files changed, 865 insertions(+), 245 deletions(-) diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 96c8486ebd1..731745d973d 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -158,8 +158,19 @@ cases in 2state and 526 in 4state. No passing case regresses: classes that are declared but never constructed, interface classes and pure virtual methods are not lowered. `8.7--constructor` keeps failing because it initializes an implicitly static procedural variable without the `static` keyword, which IEEE -1800-2023 6.21 requires. Inheritance with constructors, `super`, static members, -virtual dispatch and parameterized classes stay unsupported. +1800-2023 6.21 requires; `8.7--constructor_param` fails for the same reason. + +Base constructors, `super`, static members and `C::` scope resolution update +eighteen more rows: both state modes for `8.7--constructor_super`, +`8.8--typed_constructor`, `8.9--static_properties`, `8.10--static_methods`, +`8.13--inheritance`, `8.14--override_member`, `8.15--super`, +`8.17--constructor_const_arg` and `8.23--scope_resolution` change from fail to +pass. Each was simulated and its displayed values checked, including the base +method that a base-class handle calls in `8.14--override_member`. Full official +runs at the pinned revision report 534 passing cases in 2state and 536 in +4state, with no passing case regressing. Virtual dispatch, abstract and +interface classes, classes in packages, parameterized classes and shallow copies +stay unsupported. The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 0631e5f6113..c63919786c8 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1461,26 +1461,26 @@ chapter-7/unions/tagged/packed.sv 2state fail chapter-7/unions/tagged/packed.sv 4state fail chapter-7/unions/unpacked/basic.sv 2state fail chapter-7/unions/unpacked/basic.sv 4state fail -chapter-8/8.10--static_methods.sv 2state fail -chapter-8/8.10--static_methods.sv 4state fail +chapter-8/8.10--static_methods.sv 2state pass +chapter-8/8.10--static_methods.sv 4state pass chapter-8/8.11--this.sv 2state pass chapter-8/8.11--this.sv 4state pass chapter-8/8.12--assignment.sv 2state pass chapter-8/8.12--assignment.sv 4state pass chapter-8/8.12--shallow_copy.sv 2state fail chapter-8/8.12--shallow_copy.sv 4state fail -chapter-8/8.13--inheritance.sv 2state fail -chapter-8/8.13--inheritance.sv 4state fail -chapter-8/8.14--override_member.sv 2state fail -chapter-8/8.14--override_member.sv 4state fail +chapter-8/8.13--inheritance.sv 2state pass +chapter-8/8.13--inheritance.sv 4state pass +chapter-8/8.14--override_member.sv 2state pass +chapter-8/8.14--override_member.sv 4state pass chapter-8/8.15--super-default-new.sv 2state fail chapter-8/8.15--super-default-new.sv 4state fail -chapter-8/8.15--super.sv 2state fail -chapter-8/8.15--super.sv 4state fail +chapter-8/8.15--super.sv 2state pass +chapter-8/8.15--super.sv 4state pass chapter-8/8.16--cast_func.sv 2state fail chapter-8/8.16--cast_func.sv 4state fail -chapter-8/8.17--constructor_const_arg.sv 2state fail -chapter-8/8.17--constructor_const_arg.sv 4state fail +chapter-8/8.17--constructor_const_arg.sv 2state pass +chapter-8/8.17--constructor_const_arg.sv 4state pass chapter-8/8.18--var_local.sv 2state pass chapter-8/8.18--var_local.sv 4state pass chapter-8/8.18--var_protected.sv 2state pass @@ -1497,8 +1497,8 @@ chapter-8/8.21--abstract_class_inst.sv 2state pass chapter-8/8.21--abstract_class_inst.sv 4state pass chapter-8/8.22--dynamic_method_lookup.sv 2state fail chapter-8/8.22--dynamic_method_lookup.sv 4state fail -chapter-8/8.23--scope_resolution.sv 2state fail -chapter-8/8.23--scope_resolution.sv 4state fail +chapter-8/8.23--scope_resolution.sv 2state pass +chapter-8/8.23--scope_resolution.sv 4state pass chapter-8/8.24--out_of_block_methods.sv 2state pass chapter-8/8.24--out_of_block_methods.sv 4state pass chapter-8/8.25--parametrized_class_extend.sv 2state fail @@ -1559,14 +1559,14 @@ chapter-8/8.7--constructor.sv 2state fail chapter-8/8.7--constructor.sv 4state fail chapter-8/8.7--constructor_param.sv 2state fail chapter-8/8.7--constructor_param.sv 4state fail -chapter-8/8.7--constructor_super.sv 2state fail -chapter-8/8.7--constructor_super.sv 4state fail -chapter-8/8.8--typed_constructor.sv 2state fail -chapter-8/8.8--typed_constructor.sv 4state fail +chapter-8/8.7--constructor_super.sv 2state pass +chapter-8/8.7--constructor_super.sv 4state pass +chapter-8/8.8--typed_constructor.sv 2state pass +chapter-8/8.8--typed_constructor.sv 4state pass chapter-8/8.8--typed_constructor_param.sv 2state fail chapter-8/8.8--typed_constructor_param.sv 4state fail -chapter-8/8.9--static_properties.sv 2state fail -chapter-8/8.9--static_properties.sv 4state fail +chapter-8/8.9--static_properties.sv 2state pass +chapter-8/8.9--static_properties.sv 4state pass chapter-9/9.2.1--initial.sv 2state pass chapter-9/9.2.1--initial.sv 4state pass chapter-9/9.2.2.1--always.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 0f5545a9def..6ab988df73b 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2734,6 +2734,8 @@ struct PackedDimensions { /// assignment patterns passed as arguments. subroutine_param_shapes: Arc>>, subroutine_param_names: Arc>>, + /// The class whose method is being bound. + class_scope: Option, } impl PackedDimensions { @@ -2756,6 +2758,7 @@ impl PackedDimensions { type_query: false, subroutine_param_shapes: Arc::default(), subroutine_param_names: Arc::default(), + class_scope: None, } } } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 9b3aefc0111..c4d9aafde87 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -28,6 +28,19 @@ pub(super) struct Property { pub initializer: Option, } +/// A static property of a class: one variable of the module that declares +/// the class, shared by all of its objects (IEEE 1800-2023 8.9). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct StaticProperty { + pub name: String, + /// The class that declares the property. + pub owner: String, + pub r#type: Type, + /// The name of the variable that holds the property. + pub variable: String, + pub initializer: Option, +} + /// A method of a class. #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Method { @@ -47,6 +60,10 @@ pub(super) struct Class { pub base: Option, /// Properties of the class and its bases, bases first. pub properties: Vec, + /// How many of `properties` the bases declare. + pub base_properties: usize, + /// Static properties of the class and its bases. + pub statics: Vec, /// Methods visible in the class, overrides replacing inherited ones. pub methods: Vec, /// Bytes of an object. @@ -63,14 +80,58 @@ impl Class { .find(|property| property.name == name) } + pub fn static_property(&self, name: &str) -> Option<&StaticProperty> { + self.statics.iter().find(|property| property.name == name) + } + pub fn method(&self, name: &str) -> Option<&Method> { self.methods.iter().find(|method| method.name == name) } - /// The subroutine name of `method` of `owner`. + /// The properties the class itself declares. + pub fn own_properties(&self) -> &[Property] { + &self.properties[self.base_properties..] + } + + /// The number of formals of the constructor, which takes the handle of + /// the object it initializes before them. + pub fn constructor_formals(&self, native: &celox_sv_syntax::Declarations) -> usize { + self.method("new").map_or(0, |method| { + native + .subroutine(method.native) + .ports + .as_ref() + .map_or(0, Vec::len) + }) + } + + /// The subroutine name of `method` of `owner`, and the variable name of + /// its static property `method`. pub fn subroutine_name(owner: &str, method: &str) -> String { format!("{owner}::{method}") } + + /// An allocation of an uninitialized object of the class. + pub fn allocation(&self) -> Expr { + let handles = self + .properties + .iter() + .filter_map(|property| { + property + .field + .handle + .map(|handle| (property.field.offset, handle)) + }) + .collect(); + object_call( + ObjectOp::New { + class: self.id, + size: self.size, + handles, + }, + Vec::new(), + ) + } } /// The declaration of class `name`, if one exists. @@ -110,11 +171,12 @@ pub(super) fn item_classes( /// The methods that class `name` implements, with their definitions: the /// method itself or, for an `extern` method, its out-of-block definition. -/// A pure virtual method has none (IEEE 1800-2023 8.21). +/// A pure virtual method has none (IEEE 1800-2023 8.21). Each comes with +/// whether it is static. pub(super) fn declared_methods( tree: &AnalysisContext<'_>, name: &str, -) -> Converted> { +) -> Converted> { let Some(declaration) = declaration(tree, name) else { return Ok(Vec::new()); }; @@ -126,18 +188,55 @@ pub(super) fn declared_methods( .map(|method| { let subroutine = native.subroutine(method.subroutine); if !subroutine.prototype { - return Ok(method.subroutine); + return Ok((method.subroutine, method.qualifiers.is_static)); } let method_name = instances::normalize_identifier(&subroutine.name.spelling); - out_of_block_definition(tree, name, &method_name).ok_or_else(|| { - unsupported(format!( - "extern method `{name}::{method_name}` without a body" - )) - }) + out_of_block_definition(tree, name, &method_name) + .map(|id| (id, method.qualifiers.is_static)) + .ok_or_else(|| { + unsupported(format!( + "extern method `{name}::{method_name}` without a body" + )) + }) }) .collect() } +/// The static properties that the classes of body item `item` declare, +/// which are variables of the module (IEEE 1800-2023 8.9). A class that +/// cannot be laid out declares none here; its uses report why. +pub(super) fn item_statics( + item: celox_sv_syntax::BodyItemId, + tree: &AnalysisContext<'_>, + env: &HashMap, + aliases: &HashMap, +) -> Vec { + item_classes(item, tree) + .into_iter() + .filter_map(|name| { + let class = class(tree, &name, env, aliases).ok()?; + Some( + class + .statics + .iter() + .filter(|property| property.owner == name) + .cloned() + .collect::>(), + ) + }) + .flatten() + .collect() +} + +/// The arguments that the `extends` clause of class `name` passes to the +/// constructor of its base (IEEE 1800-2023 8.17). +pub(super) fn base_arguments<'a>( + tree: &'a AnalysisContext<'_>, + name: &str, +) -> Option<&'a [celox_sv_syntax::Argument]> { + declaration(tree, name)?.base.as_ref()?.arguments.as_deref() +} + /// The handle type of class `name`, if it is a class. pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option { declaration(tree, name)?; @@ -179,11 +278,13 @@ pub(super) fn class( .as_ref() .map(|base| base.properties.clone()) .unwrap_or_default(); + let base_properties = properties.len(); + let mut statics = base + .as_ref() + .map(|base| base.statics.clone()) + .unwrap_or_default(); let mut size = base.as_ref().map_or(0, |base| base.size); for property in &declaration.properties { - if property.qualifiers.is_static { - return Err(unsupported("static class property")); - } let ty = type_binding::procedural_type( property.declaration.data_type, native, @@ -196,7 +297,19 @@ pub(super) fn class( if !variable.dimensions.is_empty() { return Err(unsupported("class property with unpacked dimensions")); } - let name = instances::normalize_identifier(&variable.name.spelling); + let property_name = instances::normalize_identifier(&variable.name.spelling); + if property.qualifiers.is_static { + statics.retain(|known| known.name != property_name); + statics.push(StaticProperty { + variable: Class::subroutine_name(name, &property_name), + name: property_name, + owner: name.to_owned(), + r#type: ty.clone(), + initializer: variable.value, + }); + continue; + } + let name = property_name; let field = field(&tree.state, &ty, env, size)?; size = field.offset + field.bytes(); properties.push(Property { @@ -207,10 +320,13 @@ pub(super) fn class( }); } } + // A constructor is not inherited: a class without one has an implicit + // constructor (IEEE 1800-2023 8.7). let mut methods = base .as_ref() .map(|base| base.methods.clone()) .unwrap_or_default(); + methods.retain(|method| method.name != "new"); for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); @@ -241,6 +357,8 @@ pub(super) fn class( id: class_id(name), base: base.map(|base| base.name.clone()), properties, + base_properties, + statics, methods, size: size.max(1), }); diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 6c4af50f31b..aa2cb256ead 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -375,6 +375,11 @@ pub(super) fn signals_from_body_item( } values } + BodyItemKind::Unconverted { .. } => classes::item_statics(id, tree, env, aliases) + .into_iter() + .filter(|property| selected_name.is_none_or(|selected| selected == property.variable)) + .map(|property| Signal::new(property.variable, property.r#type)) + .collect(), _ => Vec::new(), }; substitute_signal_local_constants(&mut declared, env); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index ce1ddd82ae2..775b26fc042 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -405,10 +405,10 @@ fn return_type( } Ok(Some(ty)) } -/// The methods of `class` as subroutines `class::method`: a method takes -/// the handle `this` before its formals, and the constructor, declared or -/// implicit, returns the handle of the object it creates (IEEE 1800-2023 -/// 8.6, 8.7). +/// The methods of `class` as subroutines `class::method`: a method that is +/// not static takes the handle `this` before its formals, and the +/// constructor, declared or implicit, returns `this` once it has +/// initialized it (IEEE 1800-2023 8.6, 8.7, 8.10). fn class_signatures( class: &celox_sv_syntax::ClassDeclaration, tree: &AnalysisContext<'_>, @@ -418,25 +418,25 @@ fn class_signatures( let Some(handle) = classes::handle_type(tree, &class_name) else { return Ok(()); }; + let this = ( + FunctionArgumentMetadata { + name: classes::THIS.into(), + direction: ParamDirection::Input, + has_default: false, + }, + handle.clone(), + ); let mut constructor = false; for method in &class.methods { let subroutine = tree.declarations().subroutine(method.subroutine); let mut formals = formal_types(subroutine, tree, context)?; + if !method.qualifiers.is_static { + formals.insert(0, this.clone()); + } let result = if subroutine.kind == SubroutineKind::Constructor { constructor = true; Some(Some(handle.clone())) } else { - formals.insert( - 0, - ( - FunctionArgumentMetadata { - name: classes::THIS.into(), - direction: ParamDirection::Input, - has_default: false, - }, - handle.clone(), - ), - ); return_type(subroutine, tree, context)? }; publish_signature( @@ -450,7 +450,7 @@ fn class_signatures( if !constructor { publish_signature( classes::Class::subroutine_name(&class_name, "new"), - Vec::new(), + vec![this], Some(Some(handle)), tree, context, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 54768b99b7d..79354194004 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -15,8 +15,8 @@ pub(super) use direct::{ }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ - constructor as object_constructor, method as object_method, property as object_property, - receiver as object_receiver, this as object_this, + Receiver as ObjectReceiver, constructor as object_constructor, method as object_method, + property as object_property, receiver as object_receiver, this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index a93b9505792..ebc5adcd21b 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -233,16 +233,13 @@ enum Finish { /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), /// A read of property `property` of the object handle child. - ObjectLoad { - class: String, - property: String, - }, + ObjectLoad(crate::ast::classes::Property), /// A call of method subroutine `name` with `formals` formals; the first - /// child is the receiver unless `this` passes the enclosing method's own. + /// child is the object handle when `receiver` is one. MethodCall { name: String, formals: usize, - this: bool, + receiver: objects::Receiver, }, } @@ -419,8 +416,10 @@ pub(in crate::ast) fn bind_value( if args.len() > formals || args.iter().any(|arg| arg.name.is_some()) { return Err(unsupported(format!("arguments of method `{name}`"))); } - let mut children: Vec<_> = - receiver.into_iter().map(|id| (id, None)).collect(); + let mut children = Vec::new(); + if let objects::Receiver::Handle(handle) = receiver { + children.push((handle, None)); + } for arg in args { let Some(value) = arg.value else { return Err(unsupported(format!( @@ -433,7 +432,7 @@ pub(in crate::ast) fn bind_value( Finish::MethodCall { name, formals, - this: receiver.is_none(), + receiver, }, children, ) @@ -712,22 +711,20 @@ pub(in crate::ast) fn bind_value( vec![(*expression, None), (index, None)], ) } - ExprKind::Member { - expression, - separator, - name, - } if separator == "." - && objects::native_class(tree, *expression, native, dimensions) - .is_some() => + ExprKind::Member { .. } + if objects::property(tree, id, native, dimensions)?.is_some() => { - ( - Finish::ObjectLoad { - class: objects::native_class(tree, *expression, native, dimensions) - .expect("checked by the guard"), - property: instances::normalize_identifier(&name.spelling), - }, - vec![(*expression, None)], - ) + let (property, receiver) = objects::property(tree, id, native, dimensions)? + .expect("checked by the guard"); + match receiver { + Some(receiver) => { + (Finish::ObjectLoad(property), vec![(receiver, None)]) + } + None => { + values.push(objects::load(&property, objects::this())); + continue; + } + } } ExprKind::Member { .. } | ExprKind::Select { .. } => { values.push(selected_value(id, native, tree, dimensions)?); @@ -893,22 +890,23 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } - Finish::ObjectLoad { class, property } => { + Finish::ObjectLoad(property) => { let handle = operands.pop().ok_or_else(disagreement)?; - objects::load(tree, dimensions, &class, &property, handle)? + objects::load(&property, handle) } Finish::MethodCall { name, formals, - this, + receiver, } => { let mut args: Vec> = Vec::with_capacity(formals + 1); - if this { + if receiver == objects::Receiver::This { args.push(Some(objects::this())); } + let handles = usize::from(receiver != objects::Receiver::Static); args.extend(operands.into_iter().map(Some)); // Omitted trailing arguments take their defaults. - args.resize(formals + 1, None); + args.resize(formals + handles, None); Expr::Call { callee: Callee::Subroutine(name), args, @@ -1213,6 +1211,10 @@ fn path( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted<(Vec, Option)> { + // A static class property is a variable of the module. + if let Some(variable) = objects::static_property(tree, root, native, dimensions)? { + return Ok((vec![variable], None)); + } let mut parts = Vec::new(); let mut qualified = None; loop { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 109c10d885e..5a23baf7cb6 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -28,10 +28,14 @@ pub(in crate::ast) fn native_class( native: &Declarations, dimensions: &PackedDimensions, ) -> Option { - if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind - && let Some(ty) = dimensions.get(&instances::normalize_identifier(&name.spelling)) - { - return ty.class.clone(); + if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind { + let name = instances::normalize_identifier(&name.spelling); + if let Some(ty) = dimensions.get(&name) { + return ty.class.clone(); + } + if name == "super" { + return super_class(tree, dimensions); + } } let (property, _) = property(tree, id, native, dimensions).ok()??; property.r#type.class().map(str::to_owned) @@ -40,7 +44,68 @@ pub(in crate::ast) fn native_class( /// The class whose method is being bound, whose properties and methods /// unqualified names may refer to. pub(in crate::ast) fn scope_class(dimensions: &PackedDimensions) -> Option { - dimensions.get(THIS).and_then(|ty| ty.class.clone()) + dimensions.class_scope.clone() +} + +/// The base of the scope class, which `super` refers to inside a method that +/// has an object (IEEE 1800-2023 8.15). +fn super_class(tree: &AnalysisContext<'_>, dimensions: &PackedDimensions) -> Option { + dimensions.get(THIS)?; + class(tree, dimensions, &scope_class(dimensions)?) + .ok()? + .base + .clone() +} + +/// Whether native expression `id` is `super`, which passes the enclosing +/// method's `this`. +fn is_super(id: ExprId, native: &Declarations) -> bool { + matches!(&native.expression(ungroup(id, native)).kind, + ExprKind::Name(name) if name.spelling == "super") +} + +/// The class that native expression `id` names, as the scope of `C::name`. +fn named_class( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option { + let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind else { + return None; + }; + let name = instances::normalize_identifier(&name.spelling); + (dimensions.get(&name).is_none() && classes::handle_type(tree, &name).is_some()).then_some(name) +} + +/// The variable of the static property that native expression `id` names: +/// `h.p` or `C::p` (IEEE 1800-2023 8.9, 8.23). An unqualified name inside a +/// method of the class is renamed to it where the method's scope begins. +pub(in crate::ast) fn static_property( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted> { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(ungroup(id, native)).kind + else { + return Ok(None); + }; + let class_name = match separator.as_str() { + "." => native_class(tree, *expression, native, dimensions), + "::" => named_class(tree, *expression, native, dimensions), + _ => None, + }; + let Some(class_name) = class_name else { + return Ok(None); + }; + Ok(class(tree, dimensions, &class_name)? + .static_property(&instances::normalize_identifier(&name.spelling)) + .map(|property| property.variable.clone())) } /// The property that native expression `id` names, `h.p` or an unqualified @@ -58,7 +123,11 @@ pub(in crate::ast) fn property( separator, name, } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) => (class, name, Some(*expression)), + Some(class) => ( + class, + name, + (!is_super(*expression, native)).then_some(*expression), + ), None => return Ok(None), }, ExprKind::Name(name) => { @@ -76,9 +145,16 @@ pub(in crate::ast) fn property( _ => return Ok(None), }; let class = class(tree, dimensions, &class_name)?; - Ok(class - .property(&instances::normalize_identifier(&name.spelling)) - .map(|property| (property.clone(), receiver))) + let Some(property) = class.property(&instances::normalize_identifier(&name.spelling)) else { + return Ok(None); + }; + if receiver.is_none() && dimensions.get(THIS).is_none() { + return Err(unsupported(format!( + "non-static property `{}` in a static method", + property.name + ))); + } + Ok(Some((property.clone(), receiver))) } /// The handle of the object that `receiver` of [`property`] refers to. @@ -94,22 +170,9 @@ pub(in crate::ast) fn receiver( } } -/// A read of property `property` of the object `handle` of class `class`. -pub(in crate::ast) fn load( - tree: &AnalysisContext<'_>, - dimensions: &PackedDimensions, - class_name: &str, - property: &str, - handle: Expr, -) -> Converted { - let class = class(tree, dimensions, class_name)?; - let property = class - .property(property) - .ok_or_else(|| unsupported(format!("property `{property}` of class `{class_name}`")))?; - Ok(classes::object_call( - ObjectOp::Load(property.field), - vec![handle], - )) +/// A read of property `property` of the object `handle`. +pub(in crate::ast) fn load(property: &classes::Property, handle: Expr) -> Expr { + classes::object_call(ObjectOp::Load(property.field), vec![handle]) } /// The unqualified name `name` inside a method of the scope class, when it @@ -126,60 +189,104 @@ pub(in crate::ast) fn unqualified_property( return Ok(None); }; let class = class(tree, dimensions, &class_name)?; - Ok(class.property(name).map(|property| { - classes::object_call( - ObjectOp::Load(property.field), - vec![Expr::Ident(THIS.into())], - ) - })) + let Some(property) = class.property(name) else { + return Ok(None); + }; + if dimensions.get(THIS).is_none() { + return Err(unsupported(format!( + "non-static property `{name}` in a static method" + ))); + } + Ok(Some(load(property, this()))) +} + +/// The object a method is called on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::ast) enum Receiver { + /// The object of a handle expression. + Handle(ExprId), + /// The object of the enclosing method. + This, + /// None: a static method (IEEE 1800-2023 8.10). + Static, } /// The method that native callee expression `id` names: through a handle -/// (`h.m`), `this.m`, or unqualified inside a method. Returns the method's -/// subroutine, its number of formals, and the receiver to pass as `this`, -/// `None` for the enclosing method's own `this`. +/// (`h.m`), `this.m`, `super.m`, `C::m`, or unqualified inside a method. +/// Returns the method's subroutine, its number of formals, and the object +/// it is called on. pub(in crate::ast) fn method( tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, -) -> Converted)>> { +) -> Converted> { let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind { ExprKind::Member { expression, separator, name, } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) => (class, name, Some(*expression)), + Some(class) if is_super(*expression, native) => (class, name, Receiver::This), + Some(class) => (class, name, Receiver::Handle(*expression)), None => return Ok(None), }, - ExprKind::Name(name) if dimensions.get(THIS).is_some() => { + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" => match named_class(tree, *expression, native, dimensions) { + Some(class) => (class, name, Receiver::Static), + None => return Ok(None), + }, + ExprKind::Name(name) => { let normalized = instances::normalize_identifier(&name.spelling); if dimensions.get(&normalized).is_some() { return Ok(None); } match scope_class(dimensions) { - Some(class) => (class, name, None), + Some(class) => (class, name, Receiver::This), None => return Ok(None), } } _ => return Ok(None), }; let class = class(tree, dimensions, &class_name)?; - let Some(method) = class.method(&instances::normalize_identifier(&method_name.spelling)) else { + let method_name = instances::normalize_identifier(&method_name.spelling); + if method_name == "new" { + return match receiver { + // `C::new` is a constructor call, see [`constructor`]. + Receiver::Static => Ok(None), + _ => Err(unsupported( + "`super.new` that is not the first statement of a constructor", + )), + }; + } + let Some(method) = class.method(&method_name) else { return Ok(None); }; - if method.qualifiers.is_static || method.qualifiers.is_virtual { - return Err(unsupported(format!( - "{} method `{}`", - if method.qualifiers.is_static { - "static" - } else { - "virtual" - }, - method.name - ))); + if method.qualifiers.is_virtual { + return Err(unsupported(format!("virtual method `{}`", method.name))); } + let receiver = if method.qualifiers.is_static { + Receiver::Static + } else { + match receiver { + Receiver::This if dimensions.get(THIS).is_none() => { + return Err(unsupported(format!( + "non-static method `{}` called from a static method", + method.name + ))); + } + Receiver::Static => { + return Err(unsupported(format!( + "non-static method `{}` called through its class scope", + method.name + ))); + } + receiver => receiver, + } + }; let formals = native .subroutine(method.native) .ports @@ -197,8 +304,11 @@ pub(in crate::ast) fn this() -> Expr { Expr::Ident(THIS.into()) } -/// The constructor call that `new` or `new(args)` in native expression -/// `id` makes for an object of class `class_name`, if `id` is one. +/// The constructor call that native expression `id` makes when it is `new`, +/// `new(args)`, `C::new` or `C::new(args)`, the plain forms creating an +/// object of class `class_name` (IEEE 1800-2023 8.7, 8.8). The call +/// allocates the object and passes it to the constructor, which initializes +/// it and returns it. pub(in crate::ast) fn constructor( tree: &AnalysisContext<'_>, id: ExprId, @@ -206,48 +316,51 @@ pub(in crate::ast) fn constructor( dimensions: &PackedDimensions, class_name: &str, ) -> Converted> { - let arguments: &[celox_sv_syntax::Argument] = match &native.expression(ungroup(id, native)).kind - { - ExprKind::Name(name) if name.spelling == "new" => &[], - ExprKind::Call { + let (callee, arguments): (ExprId, &[celox_sv_syntax::Argument]) = + match &native.expression(ungroup(id, native)).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments), + _ => (id, &[]), + }; + let class_name = match &native.expression(ungroup(callee, native)).kind { + ExprKind::Name(name) if name.spelling == "new" => class_name.to_owned(), + ExprKind::Member { expression, - arguments, - } if matches!(&native.expression(ungroup(*expression, native)).kind, - ExprKind::Name(name) if name.spelling == "new") => - { - arguments + separator, + name, + } if separator == "::" && name.spelling == "new" => { + match named_class(tree, *expression, native, dimensions) { + Some(class) => class, + None => return Ok(None), + } } _ => return Ok(None), }; - let class = class(tree, dimensions, class_name)?; - let formals = class.method("new").map_or(0, |method| { - native - .subroutine(method.native) - .ports - .as_ref() - .map_or(0, Vec::len) - }); - let mut args = arguments - .iter() - .map(|argument| { - if argument.name.is_some() { - return Err(unsupported("named constructor argument")); - } + let class = class(tree, dimensions, &class_name)?; + let formals = class.constructor_formals(native); + let mut args = vec![Some(class.allocation())]; + for argument in arguments { + if argument.name.is_some() { + return Err(unsupported("named constructor argument")); + } + args.push( argument .value .map(|value| bind_value(value, native, tree, dimensions, None)) - .transpose() - }) - .collect::, _>>()?; - if args.len() > formals { + .transpose()?, + ); + } + if args.len() > formals + 1 { return Err(unsupported(format!( "constructor of class `{class_name}` with {} arguments", - args.len() + args.len() - 1 ))); } - args.resize(formals, None); + args.resize(formals + 1, None); Ok(Some(Expr::Call { - callee: Callee::Subroutine(Class::subroutine_name(class_name, "new")), + callee: Callee::Subroutine(Class::subroutine_name(&class_name, "new")), args, arg_order: Vec::new(), })) diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 8b6b6f83e0c..9e7c4882027 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -121,6 +121,14 @@ impl ScopeImports { if package == "std" && normalize_identifier(&name.spelling) == "randomize" { continue; } + // `C::name` names a member of class `C` (IEEE 1800-2023 8.23). + if native + .classes + .iter() + .any(|class| normalize_identifier(&class.name.spelling) == package) + { + continue; + } if !nested.iter().any(|(start, end, names)| { (*start..*end).contains(&expression.tokens.start) && names.contains(&package) }) { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index d58ec3ad6f7..0f1ff9d0e7c 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -265,7 +265,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// Hide the module-scope names that the properties of `class` shadow /// inside its methods (IEEE 1800-2023 8.5), until the scope ends. + /// A static property's name is renamed to the module variable that holds + /// it (IEEE 1800-2023 8.9). fn enter_class_scope(&mut self, class: &classes::Class) { + self.dims.class_scope = Some(class.name.clone()); for property in &class.properties { let entry = self.take_binding(&property.name, None, 0); self.scopes @@ -274,6 +277,25 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .entries .push(entry); } + for property in &class.statics { + let entry = self.take_binding( + &property.name, + Some(property.variable.clone()), + property.r#type.packed_ranges.len(), + ); + self.dims.insert( + property.name.clone(), + dimensions_from_type(&property.r#type), + ); + self.dims + .expression_signedness + .insert(property.name.clone(), property.r#type.is_signed()); + self.scopes + .last_mut() + .expect("a body always has a scope") + .entries + .push(entry); + } } fn lookup(&self, source: &str) -> Option<&str> { @@ -619,6 +641,18 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } value = expression_binding::string_operand(value, &self.dims); } + self.property_store(&property, handle, op, value).map(Some) + } + + /// `h.p op value`: a store of `value` into property `property` of the + /// object `handle`, combined with its old value by a compound `op`. + fn property_store( + &self, + property: &classes::Property, + handle: Expr, + op: &str, + mut value: Expr, + ) -> Result { if op != "=" { let operator = match op.strip_suffix('=') { Some("+") => BinaryOp::Add, @@ -648,7 +682,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { vec![handle, value], ); self.rename_expr(&mut store); - Ok(Some(Stmt::Eval(store))) + Ok(Stmt::Eval(store)) } /// A call of a class method as a statement, `h.m(args)`, `h.m`, or an @@ -674,14 +708,19 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { else { return Ok(None); }; - let receiver = match receiver { - Some(receiver) => { - expression_binding::value(receiver, native, self.tree, &self.dims)? + let mut args = match receiver { + expression_binding::ObjectReceiver::Handle(receiver) => vec![Some( + expression_binding::value(receiver, native, self.tree, &self.dims)?, + )], + expression_binding::ObjectReceiver::This => { + vec![Some(expression_binding::object_this())] } - None => expression_binding::object_this(), + expression_binding::ObjectReceiver::Static => Vec::new(), }; - let mut args = vec![Some(receiver)]; - args.resize(formals + 1, None); + args.resize( + formals + usize::from(receiver != expression_binding::ObjectReceiver::Static), + None, + ); Expr::Call { callee: Callee::Subroutine(name), args, @@ -770,6 +809,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { "--" => "-=", _ => return Err(unsupported("increment or decrement operator")), }; + let native = self.tree.declarations(); + if let Some((property, receiver)) = + expression_binding::object_property(self.tree, *expression, native, &self.dims)? + { + if property.field.handle.is_some() { + return Err(unsupported(format!("operator `{operator}` on a handle"))); + } + let handle = + expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + return self.property_store(&property, handle, op, Expr::Literal("1".into())); + } let (written, lhs) = self.native_lvalue(*expression)?; let mut rhs = assignment_op_expr( &self.tree.state, @@ -1485,21 +1535,18 @@ pub(super) fn subroutine_argument_names( let handle = classes::handle_type(tree, &class) .ok_or_else(|| unsupported(format!("class `{class}`")))?; let mut constructor = false; - for native_id in classes::declared_methods(tree, &class)? { + let this = ( + classes::THIS.to_owned(), + ParamDirection::Input, + handle.clone(), + None, + ); + for (native_id, is_static) in classes::declared_methods(tree, &class)? { let native = tree.declarations().subroutine(native_id); let mut params = subroutine_param_declarations(native, tree, &item.env, &aliases)?; - if native.kind == celox_sv_syntax::SubroutineKind::Constructor { - constructor = true; - } else { - params.insert( - 0, - ( - classes::THIS.to_owned(), - ParamDirection::Input, - handle.clone(), - None, - ), - ); + constructor |= native.kind == celox_sv_syntax::SubroutineKind::Constructor; + if !is_static { + params.insert(0, this.clone()); } let qualified = item.name(&classes::Class::subroutine_name( &class, @@ -1525,9 +1572,12 @@ pub(super) fn subroutine_argument_names( } if !constructor { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); - directions.insert(qualified.clone(), Vec::new()); - shapes.insert(qualified.clone(), Vec::new()); - names.insert(qualified, Vec::new()); + directions.insert(qualified.clone(), vec![ParamDirection::Input]); + shapes.insert( + qualified.clone(), + vec![dimensions_from_type(&scoped_type(handle, &item.env))], + ); + names.insert(qualified, vec![classes::THIS.to_owned()]); } } } @@ -1701,6 +1751,12 @@ pub(super) fn lower_subroutine( let native = tree.declarations().subroutine(native_id); let name = instances::normalize_identifier(&native.name.spelling); let constructor = native.kind == celox_sv_syntax::SubroutineKind::Constructor; + let is_static = class.is_some_and(|class| { + class + .methods + .iter() + .any(|method| method.native == native_id && method.qualifiers.is_static) + }); let handle = class .map(|class| { classes::handle_type(tree, &class.name) @@ -1779,9 +1835,9 @@ pub(super) fn lower_subroutine( .collect::, _>>()?; let mut lowered_params = Vec::new(); let mut formal_types = HashMap::default(); - // A method receives the handle of its object first, and a constructor - // returns the handle of the object it creates. - let this = handle.clone().filter(|_| !constructor).map(|handle| { + // A method that is not static receives the handle of its object first, + // and a constructor returns the handle of the object it initializes. + let this = handle.clone().filter(|_| !is_static).map(|handle| { ( classes::THIS.to_owned(), ParamDirection::Input, @@ -1811,21 +1867,42 @@ pub(super) fn lower_subroutine( default, }); } - let return_var = return_type.as_ref().map(|r#type| { - builder.declare( - if constructor { classes::THIS } else { &name }, - r#type.clone(), - ) - }); + let return_var = return_type + .as_ref() + .map(|r#type| builder.declare(&name, r#type.clone())); if let (Some(name), Some(ty)) = (&return_var, &return_type) { formal_types.insert(name.clone(), scoped_type(ty.clone(), declaration_env)); } let parameter_locals_end = builder.state.locals.len(); - let mut body = match (class, &return_var) { - (Some(class), Some(this)) if constructor => builder.constructor_prologue(class, this)?, - _ => Vec::new(), - }; - body.extend(builder.native_body(&native.items, &native.authored_statements)?); + let mut items = native.items.clone(); + let mut prologue = Vec::new(); + if let (Some(class), Some(result), Some(this)) = (class, &return_var, lowered_params.first()) + && constructor + { + // An explicit `super.new` call is made before the property + // initializers, with the base call the prologue makes. + let arguments = match ( + super_new(tree.declarations(), &items), + classes::base_arguments(tree, &class.name), + ) { + (Some(_), Some(_)) => { + return Err(unsupported( + "`super.new` in a class whose `extends` passes constructor arguments", + )); + } + (Some(_), None) if class.base.is_none() => { + return Err(unsupported("`super.new` in a class without a base")); + } + (Some((index, arguments)), None) => { + items.remove(index); + arguments + } + (None, arguments) => arguments.unwrap_or_default(), + }; + prologue = builder.constructor_prologue(class, &this.name, result, arguments)?; + } + let mut body = prologue; + body.extend(builder.native_body(&items, &native.authored_statements)?); builder.pop_scope(); let static_types: HashMap = builder .state @@ -1978,35 +2055,103 @@ pub(super) fn lower_subroutine( Ok(subroutine) } +/// The `super.new(args)` call that starts constructor body `items`, as its +/// index in `items` and its arguments (IEEE 1800-2023 8.15, 8.17). +fn super_new<'a>( + native: &'a celox_sv_syntax::Declarations, + items: &[celox_sv_syntax::StatementId], +) -> Option<(usize, &'a [celox_sv_syntax::Argument])> { + use celox_sv_syntax::{ExprKind, StatementKind}; + let (index, statement) = items.iter().enumerate().find(|(_, id)| { + !matches!( + native.statement(**id).kind, + StatementKind::Declaration(_) | StatementKind::Empty + ) + })?; + let StatementKind::Expression(root) = native.statement(*statement).kind else { + return None; + }; + let root = expression_binding::ungroup(root, native); + let (callee, arguments) = match &native.expression(root).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (root, &[][..]), + }; + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(callee).kind + else { + return None; + }; + (separator == "." + && name.spelling == "new" + && matches!(&native.expression(*expression).kind, + ExprKind::Name(name) if name.spelling == "super")) + .then_some((index, arguments)) +} + impl BodyBuilder<'_, '_, '_> { - /// The statements a constructor of `class` runs before its body: create - /// the object into `this` and initialize the properties that have - /// initializers (IEEE 1800-2023 8.7, 8.8). - fn constructor_prologue(&mut self, class: &classes::Class, this: &str) -> Converted> { + /// The statements a constructor of `class` runs before its body, on the + /// object `this` its caller allocated: return `this` as `result`, call + /// the constructor of the base with `arguments`, and initialize the + /// properties the class declares (IEEE 1800-2023 8.7, 8.8, 8.17). + fn constructor_prologue( + &mut self, + class: &classes::Class, + this: &str, + result: &str, + arguments: &[celox_sv_syntax::Argument], + ) -> Converted> { let native = self.tree.declarations(); - let handles = class - .properties - .iter() - .filter_map(|property| { - property - .field - .handle - .map(|handle| (property.field.offset, handle)) - }) - .collect(); let mut body = vec![Stmt::Assign { - lhs: LValue::Ident(this.to_owned()), - rhs: classes::object_call( - system_functions::ObjectOp::New { - class: class.id, - size: class.size, - handles, - }, - Vec::new(), - ), + lhs: LValue::Ident(result.to_owned()), + rhs: Expr::Ident(this.to_owned()), nonblocking: false, }]; - for property in &class.properties { + if let Some(base) = &class.base { + let base = classes::class( + self.tree, + base, + &self.dims.const_env, + &self.dims.type_aliases, + )?; + let formals = base.constructor_formals(native); + if arguments.len() > formals { + return Err(unsupported(format!( + "constructor of class `{}` with {} arguments", + base.name, + arguments.len() + ))); + } + let mut args = vec![Some(Expr::Ident(this.to_owned()))]; + for argument in arguments { + if argument.name.is_some() { + return Err(unsupported("named constructor argument")); + } + args.push( + argument + .value + .map(|value| { + let mut value = + expression_binding::value(value, native, self.tree, &self.dims)?; + self.rename_expr(&mut value); + Ok::<_, AnalyzerError>(value) + }) + .transpose()?, + ); + } + args.resize(formals + 1, None); + body.push(Stmt::Call { + name: classes::Class::subroutine_name(&base.name, "new"), + args, + arg_order: Vec::new(), + }); + } + for property in class.own_properties() { let Some(initializer) = property.initializer else { continue; }; @@ -2057,16 +2202,9 @@ fn lower_class( item: &generate::Item, ) -> Converted> { let class = classes::class(tree, name, declaration_env, type_aliases)?; - if let Some(base) = &class.base - && classes::class(tree, base, declaration_env, type_aliases)? - .method("new") - .is_some() - { - return Err(unsupported("class extending a class with a constructor")); - } let mut subroutines = Vec::new(); let mut constructor = false; - for id in classes::declared_methods(tree, name)? { + for (id, _) in classes::declared_methods(tree, name)? { constructor |= tree.declarations().subroutine(id).kind == celox_sv_syntax::SubroutineKind::Constructor; subroutines.push(lower_subroutine( @@ -2084,6 +2222,13 @@ fn lower_class( if !constructor { let handle = classes::handle_type(tree, name) .ok_or_else(|| unsupported(format!("class `{name}`")))?; + let ir_type = crate::ir::Type::from_ast( + scoped_type(handle.clone(), declaration_env), + &const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }, + ); let mut builder = BodyBuilder::new( tree, item_dimensions, @@ -2095,7 +2240,13 @@ fn lower_class( builder.push_scope(); builder.enter_class_scope(&class); let this = builder.declare(classes::THIS, handle.clone()); - let body = builder.constructor_prologue(&class, &this)?; + let result = builder.declare("new", handle); + let body = builder.constructor_prologue( + &class, + &this, + &result, + classes::base_arguments(tree, name).unwrap_or_default(), + )?; builder.pop_scope(); let mut subroutine = Subroutine { name: item.name(&classes::Class::subroutine_name(name, "new")), @@ -2105,15 +2256,15 @@ fn lower_class( .map(|local| local.name.clone()) .collect(), persistent_locals: Vec::new(), - return_type: Some(crate::ir::Type::from_ast( - scoped_type(handle, declaration_env), - &const_functions::Environment { - constants: &*item.env, - functions: &tree.state.const_functions, - }, - )), - params: Vec::new(), - return_var: Some(this), + return_type: Some(ir_type.clone()), + params: vec![SubroutineParam { + name: this, + source_name: classes::THIS.to_owned(), + direction: ParamDirection::Input, + r#type: ir_type, + default: None, + }], + return_var: Some(result), body, sensitivity_body: Vec::new(), }; @@ -2208,6 +2359,12 @@ pub(super) fn initial_processes_from_scope( } } } + // Static class properties are initialized like variables. + for property in classes::item_statics(item.id, tree, &item.env, &type_aliases) { + if let Some(value) = property.initializer { + assignments.push((property.variable, value)); + } + } if !assignments.is_empty() { let (item_dimensions, literals) = views.get(item); let mut body = Vec::new(); diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index ebc1d9d5ed4..5f9554fe29c 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -492,6 +492,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | | `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | +| `sv_icarus_class_scope_resolution` | compile | icarus | 1 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case. | | `sv_verilator_class_property_string_methods` | compile | verilator | 1 | Verilator 5.052 stops with an internal error ("AstNode is not of expected type, but instead has type 'MEMBERSEL'") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index e0a62bceba1..98c2d18e311 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -229,3 +229,86 @@ module Top(output int result, output bit same, output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq same 1) (assert_eq result 6281)) + +(case static_properties_and_methods + (source "class.sv" #" +module Top(output bit done); + class Counter; + static int created = 0; + static string last = "none"; + int id; + function new(); + created++; + id = created; + endfunction + static function int next(int by = 1); + created += by; + return created; + endfunction + function int peek(); + return created * 10 + id; + endfunction + endclass + Counter a, b; + initial begin + a = new; + b = new; + $display("created=%0d a=%0d b=%0d", Counter::created, a.id, b.id); + a.created = 7; + $display("b.created=%0d peek=%0d", b.created, b.peek()); + $display("next=%0d next=%0d", Counter::next(), a.next(3)); + Counter::last = "set"; + $display("last=%s", b.last); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "created=2 a=1 b=2\nb.created=7 peek=72\nnext=8 next=11\nlast=set\n")) + +(case constructors_chain_to_base + (source "class.sv" #" +module Top(output bit done); + class Base; + int a = 1; + int b; + function new(int b = 2); + this.b = b + a; + endfunction + function int sum(); + return a + b; + endfunction + endclass + class Derived extends Base; + int c = a * 100; + function new(int c0); + super.new(c0 * 2); + c += c0; + endfunction + function int sum(); + return super.sum() * 1000 + c + super.b; + endfunction + endclass + class Fixed extends Base(40); + endclass + class Default extends Base; + int d = b; + endclass + Derived d; + Base b; + Fixed f; + Default e; + initial begin + d = new(3); + b = d; + $display("a=%0d b=%0d c=%0d", d.a, d.b, d.c); + $display("derived=%0d base=%0d", d.sum(), b.sum()); + f = new; + e = Default::new; + $display("fixed=%0d default=%0d", f.b, e.d); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "a=1 b=7 c=103\nderived=8110 base=8\nfixed=41 default=3\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 3d6ebc71698..02c99aaf1a5 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::constructors_chain_to_base", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -137,6 +148,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_scope_resolution", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "upstream": [] + }, + "name": "class::static_properties_and_methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 does not support extern methods (\"sorry: External methods are not yet supported\") or string methods called on a class property (\"Can't find task itoa in class Named\") or comparisons of class handles (\"SORRY: Compare class handles not implemented\"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 42048791a99..f2c69d158b0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1864,6 +1864,23 @@ ] } }, + { + "id": "sv_icarus_class_scope_resolution", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::static_properties_and_methods" + ] + } + }, { "id": "sv_verilator_class_property_string_methods", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index d976c61d989..2d569e682de 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 15, "emission_error": 0, - "compile_error": 112, + "compile_error": 113, "runtime_error": 7, "unsupported": 0, "ignored": 0 @@ -1271,6 +1271,14 @@ "name": "class::inherited_properties_and_methods", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:23: syntax error\n/source_0.sv:23: error: Malformed statement\n/source_0.sv:26: syntax error\n/source_0.sv:26: error: Malformed statement\n/source_0.sv:27: syntax error\n/source_0.sv:27: Syntax in assignment statement l-value.\n", + "expectation": "Simulation", + "name": "class::static_properties_and_methods", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index ddf65590565..72774285008 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::constructors_chain_to_base", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -77,6 +88,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::static_properties_and_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Verilator 5.052 stops with an internal error (\"AstNode is not of expected type, but instead has type 'MEMBERSEL'\") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes.", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 6b821e0d979..4d2e3a2f413 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -14,6 +14,8 @@ sv_backends! { fn class_string_methods_on_properties(sim) { @case "class::string_methods_on_properties"; } fn class_derived_properties_hide_base_properties(sim) { @case "class::derived_properties_hide_base_properties"; } fn class_inherited_properties_and_methods(sim) { @case "class::inherited_properties_and_methods"; } + fn class_static_properties_and_methods(sim) { @case "class::static_properties_and_methods"; } + fn class_constructors_chain_to_base(sim) { @case "class::constructors_chain_to_base"; } } sv_backends! { @@ -87,3 +89,31 @@ fn four_state_properties_are_rejected() { let error = error.to_string(); assert!(error.contains("4-state class property"), "{error}"); } + +#[test] +fn misplaced_super_new_and_static_misuse_are_rejected() { + for (body, want) in [ + ( + "class B; endclass class C extends B; int x; function new(); x = 1; super.new(); endfunction endclass", + "`super.new` that is not the first statement", + ), + ( + "class C; int x; static function int f(); return x; endfunction endclass", + "non-static property `x` in a static method", + ), + ( + "class C; function int g(); return 1; endfunction static function int f(); return g(); endfunction endclass", + "non-static method `g` called from a static method", + ), + ] { + let source = format!("module Top; {body} C c; initial c = new; endmodule"); + let Err(error) = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("class.sv"))], "Top") + .build_cranelift() + else { + panic!("`{body}` is rejected"); + }; + let error = error.to_string(); + assert!(error.contains(want), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7a776ac9a3c..6bf041d4ce4 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -30,7 +30,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and non-virtual methods from a base class without a constructor. See [classes](#classes) | +| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and non-virtual methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; static properties and methods; `C::` scope resolution of static members and `C::new`. See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -128,7 +128,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): constructors of base classes and `super`, virtual method calls, static properties and methods, `C::` scope resolution, parameterized classes, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. +- Class features beyond those [listed](#classes): virtual method calls, abstract and interface classes, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. @@ -232,6 +232,12 @@ calls are bound to the method of the variable's class (IEEE 1800-2023 8.6). Reading or writing a property or calling a method through `null` is a runtime error. +A constructor calls the constructor of the base class first, with the +arguments of `super.new(...)` or of the `extends` clause, then runs the +initializers of the properties its class declares, then its body (IEEE +1800-2023 8.17). A static property is a variable of the module that declares +the class, so each instance of the module has its own. + Checkpoints keep objects. State files record strings but not objects, so saving a state file fails while any variable holds an object. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7bce8fc86df..b67333b1c30 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,7 +28,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、コンストラクタのない基底クラスからのプロパティと非 virtual メソッドの継承。[クラス](#classes)を参照 | +| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティと非 virtual メソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -118,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:基底クラスのコンストラクタと `super`、virtual メソッドの呼び出し、static プロパティとメソッド、`C::` によるスコープ解決、パラメータ付きクラス、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:virtual メソッドの呼び出し、抽象クラスと interface クラス、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -169,6 +169,8 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。 +コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。 + チェックポイントはオブジェクトを保持します。状態ファイルは文字列を記録しますがオブジェクトは記録しないため、オブジェクトを持つ変数があると状態ファイルの保存は失敗します。 ### インスタンス配列の要素 From a95ad5eadbdf22a0267d68eaa64308c0457063c7 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 10:56:11 +0900 Subject: [PATCH 11/11] feat(sv): support virtual methods, abstract classes and interface class implementation A virtual method gets a dispatcher subroutine that calls the override for the class of `this` (IEEE 1800-2023 8.20); calls through handles and unqualified calls inside methods go through it, `super.m` calls the base's implementation directly. A call through `null` is a runtime error. `virtual class` cannot be constructed and a class that is not abstract must implement every pure virtual method (8.21). A class that `implements` interface classes implements each of their methods with the same return type, or re-declares it pure when it is abstract (8.26); the parser now keeps the `implements` list. Methods called on elements of arrays of class handles and `new` assigned to such an element are bound with the element's class. Change-Id: I1f9a009a084e52b208ecd286d6d89ebe23ac40fd --- conformance/sv-tests/README.md | 15 ++ conformance/sv-tests/expected.tsv | 36 +-- crates/celox-sv-analyzer/src/ast/classes.rs | 187 ++++++++++++++- .../src/ast/dimensions/discovery.rs | 10 + .../src/ast/expression_binding.rs | 17 +- .../src/ast/expression_binding/objects.rs | 49 +++- crates/celox-sv-analyzer/src/ast/functions.rs | 1 + .../celox-sv-analyzer/src/ast/procedural.rs | 135 ++++++++++- crates/celox-sv-syntax/src/nodes.rs | 3 + crates/celox-sv-syntax/src/parser/classes.rs | 9 +- crates/celox-test-suite/LIMITATIONS.md | 2 + .../celox-test-suite/src/sv/cases/class.vtest | 214 ++++++++++++++++++ .../verification/repros/virtual_dispatch.sv | 41 ++++ .../repros/virtual_dispatch_icarus.json | 42 ++++ .../verification/sv/icarus/class.json | 93 ++++++++ .../verification/sv/limitations.json | 37 +++ .../verification/sv/limitations/icarus.json | 36 ++- .../verification/sv/verilator/class.json | 44 ++++ .../tests/frontends/systemverilog/class.rs | 43 +++- docs/guide/systemverilog-reference.md | 14 +- docs/ja/guide/systemverilog-reference.md | 6 +- 21 files changed, 972 insertions(+), 62 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/virtual_dispatch.sv create mode 100644 crates/celox-test-suite/verification/repros/virtual_dispatch_icarus.json diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 731745d973d..a0c9b0c88e3 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -172,6 +172,21 @@ runs at the pinned revision report 534 passing cases in 2state and 536 in interface classes, classes in packages, parameterized classes and shallow copies stay unsupported. +Virtual methods, abstract classes and classes implementing interface classes +update eighteen more rows: both state modes for `8.15--super-default-new`, +`8.20--virtual_method`, `8.21--abstract_class`, `8.22--dynamic_method_lookup`, +`8.26.2--implements`, `8.26.2--implements_extends`, +`8.26.2--implements_multiple`, `8.26.6.1--name_conflict_resolved` and +`8.26.7--partial_implementation` change from fail to pass. Each was simulated +and its displayed values checked: the override of the object's class runs +through base-class handles and an array of them, and the shadowed property of +`8.20--virtual_method` reads the derived class's value. Full official runs at +the pinned revision report 543 passing cases in 2state and 545 in 4state, with +no passing case regressing. `8.26.6.1--name_conflict_unresolved` stays a +passing negative case: its return types conflict, which is rejected. Calls +through interface class handles, `$cast`, parameterized classes and shallow +copies stay unsupported. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c63919786c8..df6b904eb10 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1473,8 +1473,8 @@ chapter-8/8.13--inheritance.sv 2state pass chapter-8/8.13--inheritance.sv 4state pass chapter-8/8.14--override_member.sv 2state pass chapter-8/8.14--override_member.sv 4state pass -chapter-8/8.15--super-default-new.sv 2state fail -chapter-8/8.15--super-default-new.sv 4state fail +chapter-8/8.15--super-default-new.sv 2state pass +chapter-8/8.15--super-default-new.sv 4state pass chapter-8/8.15--super.sv 2state pass chapter-8/8.15--super.sv 4state pass chapter-8/8.16--cast_func.sv 2state fail @@ -1489,14 +1489,14 @@ chapter-8/8.19--global_constant.sv 2state pass chapter-8/8.19--global_constant.sv 4state pass chapter-8/8.19--instance_constant.sv 2state pass chapter-8/8.19--instance_constant.sv 4state pass -chapter-8/8.20--virtual_method.sv 2state fail -chapter-8/8.20--virtual_method.sv 4state fail -chapter-8/8.21--abstract_class.sv 2state fail -chapter-8/8.21--abstract_class.sv 4state fail +chapter-8/8.20--virtual_method.sv 2state pass +chapter-8/8.20--virtual_method.sv 4state pass +chapter-8/8.21--abstract_class.sv 2state pass +chapter-8/8.21--abstract_class.sv 4state pass chapter-8/8.21--abstract_class_inst.sv 2state pass chapter-8/8.21--abstract_class_inst.sv 4state pass -chapter-8/8.22--dynamic_method_lookup.sv 2state fail -chapter-8/8.22--dynamic_method_lookup.sv 4state fail +chapter-8/8.22--dynamic_method_lookup.sv 2state pass +chapter-8/8.22--dynamic_method_lookup.sv 4state pass chapter-8/8.23--scope_resolution.sv 2state pass chapter-8/8.23--scope_resolution.sv 4state pass chapter-8/8.24--out_of_block_methods.sv 2state pass @@ -1507,12 +1507,12 @@ chapter-8/8.25.1--parametrized_class_invalid_scope_resolution.sv 2state pass chapter-8/8.25.1--parametrized_class_invalid_scope_resolution.sv 4state pass chapter-8/8.25.1--parametrized_class_scope_resolution.sv 2state fail chapter-8/8.25.1--parametrized_class_scope_resolution.sv 4state fail -chapter-8/8.26.2--implements.sv 2state fail -chapter-8/8.26.2--implements.sv 4state fail -chapter-8/8.26.2--implements_extends.sv 2state fail -chapter-8/8.26.2--implements_extends.sv 4state fail -chapter-8/8.26.2--implements_multiple.sv 2state fail -chapter-8/8.26.2--implements_multiple.sv 4state fail +chapter-8/8.26.2--implements.sv 2state pass +chapter-8/8.26.2--implements.sv 4state pass +chapter-8/8.26.2--implements_extends.sv 2state pass +chapter-8/8.26.2--implements_extends.sv 4state pass +chapter-8/8.26.2--implements_multiple.sv 2state pass +chapter-8/8.26.2--implements_multiple.sv 4state pass chapter-8/8.26.3--type_access_extends.sv 2state pass chapter-8/8.26.3--type_access_extends.sv 4state pass chapter-8/8.26.3--type_access_implements.sv 2state fail @@ -1529,8 +1529,8 @@ chapter-8/8.26.5--implemented_class_handle.sv 2state pass chapter-8/8.26.5--implemented_class_handle.sv 4state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 2state pass chapter-8/8.26.5--invalid_interface_instantiation.sv 4state pass -chapter-8/8.26.6.1--name_conflict_resolved.sv 2state fail -chapter-8/8.26.6.1--name_conflict_resolved.sv 4state fail +chapter-8/8.26.6.1--name_conflict_resolved.sv 2state pass +chapter-8/8.26.6.1--name_conflict_resolved.sv 4state pass chapter-8/8.26.6.1--name_conflict_unresolved.sv 2state pass chapter-8/8.26.6.1--name_conflict_unresolved.sv 4state pass chapter-8/8.26.6.2--parameter_type_conflict.sv 2state pass @@ -1541,8 +1541,8 @@ chapter-8/8.26.6.3--diamond_relationship.sv 2state pass chapter-8/8.26.6.3--diamond_relationship.sv 4state pass chapter-8/8.26.6.3--diamond_relationship_parametrized.sv 2state fail chapter-8/8.26.6.3--diamond_relationship_parametrized.sv 4state fail -chapter-8/8.26.7--partial_implementation.sv 2state fail -chapter-8/8.26.7--partial_implementation.sv 4state fail +chapter-8/8.26.7--partial_implementation.sv 2state pass +chapter-8/8.26.7--partial_implementation.sv 4state pass chapter-8/8.27--forward_declaration.sv 2state pass chapter-8/8.27--forward_declaration.sv 4state pass chapter-8/8.4--instantiation.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index c4d9aafde87..55eff2a48e9 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -47,8 +47,19 @@ pub(super) struct Method { pub name: String, /// The class that declares the method. pub owner: String, + /// The definition, or the prototype of a pure virtual method. pub native: celox_sv_syntax::SubroutineId, pub qualifiers: celox_sv_syntax::ClassQualifiers, + /// Declared `virtual` here or in a base: a call through a handle runs + /// the override of the object's class (IEEE 1800-2023 8.20). + pub is_virtual: bool, +} + +impl Method { + /// A pure virtual method, which has no implementation (8.21). + pub fn is_pure(&self) -> bool { + self.qualifiers.is_pure + } } /// A class with the layout of its objects. @@ -58,6 +69,8 @@ pub(super) struct Class { /// Identifies the class at run time; stable across modules and runs. pub id: u32, pub base: Option, + /// A `virtual class`, which cannot be constructed (IEEE 1800-2023 8.21). + pub is_abstract: bool, /// Properties of the class and its bases, bases first. pub properties: Vec, /// How many of `properties` the bases declare. @@ -111,6 +124,40 @@ impl Class { format!("{owner}::{method}") } + /// The subroutine that calls the override of virtual method `method` + /// of `owner` for the class of its `this` (IEEE 1800-2023 8.20). + pub fn dispatcher_name(owner: &str, method: &str) -> String { + format!("{owner}::{method}$virtual") + } + + /// The virtual methods the class itself declares, each with a + /// dispatcher. + pub fn dispatched_methods(&self) -> impl Iterator { + self.methods + .iter() + .filter(|method| method.owner == self.name && method.is_virtual) + } + + /// Whether the class is `ancestor` or derives from it. + pub fn derives_from( + &self, + tree: &AnalysisContext<'_>, + ancestor: &str, + env: &HashMap, + aliases: &HashMap, + ) -> bool { + let mut class = Some(self.name.clone()); + while let Some(name) = class { + if name == ancestor { + return true; + } + class = self::class(tree, &name, env, aliases) + .ok() + .and_then(|class| class.base.clone()); + } + false + } + /// An allocation of an uninitialized object of the class. pub fn allocation(&self) -> Expr { let handles = self @@ -330,12 +377,14 @@ pub(super) fn class( for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); - // A pure virtual method has no implementation to call; calls of - // virtual methods are rejected where they are bound. - if method.qualifiers.is_pure { - continue; - } - let native_id = if subroutine.prototype { + // A method overriding a virtual method is virtual (8.20). + let is_virtual = method.qualifiers.is_virtual + || methods + .iter() + .any(|known| known.name == method_name && known.is_virtual); + let native_id = if method.qualifiers.is_pure { + method.subroutine + } else if subroutine.prototype { out_of_block_definition(tree, name, &method_name).ok_or_else(|| { unsupported(format!( "extern method `{name}::{method_name}` without a body" @@ -350,12 +399,55 @@ pub(super) fn class( owner: name.to_owned(), native: native_id, qualifiers: method.qualifiers, + is_virtual, }); } + // A method of an implemented interface class is virtual, and the class + // implements it with the same return type (8.26.2, 8.26.6.1). An + // abstract class may instead re-declare it pure (8.26.7). + let mut required = Vec::new(); + for &interface in &declaration.interfaces { + interface_methods(tree, interface, env, aliases, &mut required)?; + } + for (method_name, prototype) in required { + match methods.iter_mut().find(|method| method.name == method_name) { + Some(method) => { + if !method.is_virtual && method.owner != name { + return Err(unsupported(format!( + "interface class method `{method_name}` implemented by a non-virtual method of a base class" + ))); + } + if return_type(tree, method.native, env, aliases)? + != return_type(tree, prototype, env, aliases)? + { + return Err(unsupported(format!( + "method `{method_name}` of class `{name}` whose return type differs from its interface class" + ))); + } + method.is_virtual = true; + } + None => { + return Err(unsupported(format!( + "class `{name}` that does not implement interface class method `{method_name}`" + ))); + } + } + } + // A class that is not abstract implements every pure virtual method + // (8.21). + if !declaration.virtual_class + && let Some(method) = methods.iter().find(|method| method.is_pure()) + { + return Err(unsupported(format!( + "class `{name}` that does not implement pure virtual method `{}`", + method.name + ))); + } let class = Rc::new(Class { name: name.to_owned(), id: class_id(name), base: base.map(|base| base.name.clone()), + is_abstract: declaration.virtual_class, properties, base_properties, statics, @@ -369,6 +461,48 @@ pub(super) fn class( Ok(class) } +/// The methods that interface class type `interface` declares or inherits, +/// with their prototypes, appended to `methods` (IEEE 1800-2023 8.26). A +/// name that several interface classes declare appears once for each. +fn interface_methods( + tree: &AnalysisContext<'_>, + interface: celox_sv_syntax::TypeId, + env: &HashMap, + aliases: &HashMap, + methods: &mut Vec<(String, celox_sv_syntax::SubroutineId)>, +) -> Converted<()> { + let native = tree.declarations(); + let name = type_binding::procedural_type(interface, native, tree, env, aliases)? + .and_then(|ty| ty.class.clone()) + .ok_or_else(|| unsupported("implemented interface class type"))?; + let declaration = declaration(tree, &name) + .filter(|declaration| declaration.interface) + .ok_or_else(|| unsupported(format!("`implements` of `{name}`, not an interface class")))?; + for method in &declaration.methods { + let method_name = + instances::normalize_identifier(&native.subroutine(method.subroutine).name.spelling); + methods.push((method_name, method.subroutine)); + } + for &base in &declaration.interfaces { + interface_methods(tree, base, env, aliases, methods)?; + } + Ok(()) +} + +/// The return type of subroutine `id`, `None` for a task or `void`. +fn return_type( + tree: &AnalysisContext<'_>, + id: celox_sv_syntax::SubroutineId, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + match native.subroutine(id).return_type { + Some(ty) => type_binding::procedural_type(ty, native, tree, env, aliases), + None => Ok(None), + } +} + /// The definition `function ... class::method` outside class `class`. fn out_of_block_definition( tree: &AnalysisContext<'_>, @@ -428,6 +562,47 @@ fn class_id(name: &str) -> u32 { hash.max(1) } +/// The overrides that dispatcher `Class::dispatcher_name(owner, method)` +/// calls: each implementation of the method with the classes, deriving from +/// `owner` and not abstract, whose objects run it. +pub(super) fn dispatch_targets( + tree: &AnalysisContext<'_>, + owner: &str, + method: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted)>> { + let mut targets: Vec<(String, Vec)> = Vec::new(); + let mut ids = HashMap::default(); + for declaration in &tree.declarations().classes { + if declaration.interface || declaration.virtual_class { + continue; + } + let name = instances::normalize_identifier(&declaration.name.spelling); + // A class that cannot be laid out has no objects. + let Ok(class) = class(tree, &name, env, aliases) else { + continue; + }; + if !class.derives_from(tree, owner, env, aliases) { + continue; + } + if let Some(other) = ids.insert(class.id, name.clone()) { + return Err(unsupported(format!( + "classes `{other}` and `{name}` with the same run-time identifier" + ))); + } + let Some(implementation) = class.method(method) else { + continue; + }; + let target = Class::subroutine_name(&implementation.owner, method); + match targets.iter_mut().find(|(known, _)| *known == target) { + Some((_, classes)) => classes.push(class.id), + None => targets.push((target, vec![class.id])), + } + } + Ok(targets) +} + /// A call of object operation `op`. pub(super) fn object_call(op: ObjectOp, args: Vec) -> Expr { Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 775b26fc042..d15c8400ea1 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -439,6 +439,16 @@ fn class_signatures( } else { return_type(subroutine, tree, context)? }; + // A method that may be virtual also has a dispatcher (8.20). + if !method.qualifiers.is_static && subroutine.kind != SubroutineKind::Constructor { + publish_signature( + classes::Class::dispatcher_name(&class_name, &name(&subroutine.name)), + formals.clone(), + result.clone(), + tree, + context, + ); + } publish_signature( classes::Class::subroutine_name(&class_name, &name(&subroutine.name)), formals, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 79354194004..065187f34ae 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -42,8 +42,21 @@ pub(super) fn expression( LValue::Ident(name) => dimensions.get(name), _ => None, }; - // `new` creates an object of the variable's class (IEEE 1800-2023 8.7). - if let Some(class) = shape.and_then(|shape| shape.class.as_deref()) + // `new` creates an object of the class of the variable or of the + // element of an array of handles (IEEE 1800-2023 8.7). + let class = match lhs { + LValue::Ident(_) => shape.and_then(|shape| shape.class.as_deref()), + LValue::Select { + name, + array_slice_width: None, + .. + } => dimensions + .get(name) + .filter(|shape| !shape.unpacked.is_empty()) + .and_then(|shape| shape.class.as_deref()), + LValue::Select { .. } => None, + }; + if let Some(class) = class && let Some(call) = objects::constructor(tree, root, native, dimensions, class)? { return Ok(call); diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 5a23baf7cb6..7665af7a0b4 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -21,14 +21,26 @@ pub(in crate::ast) fn class( } /// The class of native expression `id` when it is an object handle, judged -/// before it is bound: a handle variable, or a handle property. +/// before it is bound: a handle variable, an element of an array of +/// handles, or a handle property. pub(in crate::ast) fn native_class( tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Option { - if let ExprKind::Name(name) = &native.expression(ungroup(id, native)).kind { + let expression = native.expression(ungroup(id, native)); + if let ExprKind::Select { + expression, + dimension, + } = &expression.kind + && matches!(dimension.kind, celox_sv_syntax::DimensionKind::Index(_)) + && let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind + { + let ty = dimensions.get(&instances::normalize_identifier(&name.spelling))?; + return ty.class.clone().filter(|_| !ty.unpacked.is_empty()); + } + if let ExprKind::Name(name) = &expression.kind { let name = instances::normalize_identifier(&name.spelling); if let Some(ty) = dimensions.get(&name) { return ty.class.clone(); @@ -214,20 +226,26 @@ pub(in crate::ast) enum Receiver { /// The method that native callee expression `id` names: through a handle /// (`h.m`), `this.m`, `super.m`, `C::m`, or unqualified inside a method. /// Returns the method's subroutine, its number of formals, and the object -/// it is called on. +/// it is called on. A virtual method is called through its dispatcher, +/// except as `super.m`, which names the base's implementation (IEEE +/// 1800-2023 8.15, 8.20). pub(in crate::ast) fn method( tree: &AnalysisContext<'_>, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { + let mut through_super = false; let (class_name, method_name, receiver) = match &native.expression(ungroup(id, native)).kind { ExprKind::Member { expression, separator, name, } if separator == "." => match native_class(tree, *expression, native, dimensions) { - Some(class) if is_super(*expression, native) => (class, name, Receiver::This), + Some(class) if is_super(*expression, native) => { + through_super = true; + (class, name, Receiver::This) + } Some(class) => (class, name, Receiver::Handle(*expression)), None => return Ok(None), }, @@ -265,8 +283,11 @@ pub(in crate::ast) fn method( let Some(method) = class.method(&method_name) else { return Ok(None); }; - if method.qualifiers.is_virtual { - return Err(unsupported(format!("virtual method `{}`", method.name))); + if through_super && method.is_pure() { + return Err(unsupported(format!( + "pure virtual method `{}` called through `super`", + method.name + ))); } let receiver = if method.qualifiers.is_static { Receiver::Static @@ -292,11 +313,12 @@ pub(in crate::ast) fn method( .ports .as_ref() .map_or(0, Vec::len); - Ok(Some(( - Class::subroutine_name(&method.owner, &method.name), - formals, - receiver, - ))) + let subroutine = if method.is_virtual && !through_super && receiver != Receiver::Static { + Class::dispatcher_name(&method.owner, &method.name) + } else { + Class::subroutine_name(&method.owner, &method.name) + }; + Ok(Some((subroutine, formals, receiver))) } /// The receiver of an unqualified method call inside a method. @@ -339,6 +361,11 @@ pub(in crate::ast) fn constructor( _ => return Ok(None), }; let class = class(tree, dimensions, &class_name)?; + if class.is_abstract { + return Err(unsupported(format!( + "object of abstract class `{class_name}`" + ))); + } let formals = class.constructor_formals(native); let mut args = vec![Some(class.allocation())]; for argument in arguments { diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 2112b88a286..65393bef9c8 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -100,6 +100,7 @@ pub(super) fn native_functions( &mut state, item, None, + None, ) { Ok(subroutine) => { let has_real = subroutine.return_type.as_ref().is_some_and(|ty| { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 0f1ff9d0e7c..6d1661eb256 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1541,17 +1541,38 @@ pub(super) fn subroutine_argument_names( handle.clone(), None, ); - for (native_id, is_static) in classes::declared_methods(tree, &class)? { + let mut methods = classes::declared_methods(tree, &class)? + .into_iter() + .map(|(native_id, is_static)| { + let name = instances::normalize_identifier( + &tree.declarations().subroutine(native_id).name.spelling, + ); + ( + classes::Class::subroutine_name(&class, &name), + native_id, + is_static, + ) + }) + .collect::>(); + // A class that cannot be laid out reports why where it is + // lowered. + if let Ok(layout) = classes::class(tree, &class, &item.env, &aliases) { + methods.extend(layout.dispatched_methods().map(|method| { + ( + classes::Class::dispatcher_name(&class, &method.name), + method.native, + false, + ) + })); + } + for (name, native_id, is_static) in methods { let native = tree.declarations().subroutine(native_id); let mut params = subroutine_param_declarations(native, tree, &item.env, &aliases)?; constructor |= native.kind == celox_sv_syntax::SubroutineKind::Constructor; if !is_static { params.insert(0, this.clone()); } - let qualified = item.name(&classes::Class::subroutine_name( - &class, - &instances::normalize_identifier(&native.name.spelling), - )); + let qualified = item.name(&name); directions.insert( qualified.clone(), params.iter().map(|(_, direction, ..)| *direction).collect(), @@ -1685,6 +1706,7 @@ pub(super) fn subroutines_with_symbolic_parameters( state, item, None, + None, ); let subroutine = match (lowered, rejected.as_deref_mut()) { (Ok(subroutine), _) => subroutine, @@ -1747,16 +1769,18 @@ pub(super) fn lower_subroutine( state: &mut BodyState<'_>, item: &generate::Item, class: Option<&classes::Class>, + dispatch: Option<&[(String, Vec)]>, ) -> Converted { let native = tree.declarations().subroutine(native_id); let name = instances::normalize_identifier(&native.name.spelling); let constructor = native.kind == celox_sv_syntax::SubroutineKind::Constructor; - let is_static = class.is_some_and(|class| { - class - .methods - .iter() - .any(|method| method.native == native_id && method.qualifiers.is_static) - }); + let is_static = dispatch.is_none() + && class.is_some_and(|class| { + class + .methods + .iter() + .any(|method| method.native == native_id && method.qualifiers.is_static) + }); let handle = class .map(|class| { classes::handle_type(tree, &class.name) @@ -1902,7 +1926,14 @@ pub(super) fn lower_subroutine( prologue = builder.constructor_prologue(class, &this.name, result, arguments)?; } let mut body = prologue; - body.extend(builder.native_body(&items, &native.authored_statements)?); + match dispatch { + Some(targets) => body.push(dispatch_body( + targets, + &lowered_params, + return_var.as_deref(), + )), + None => body.extend(builder.native_body(&items, &native.authored_statements)?), + } builder.pop_scope(); let static_types: HashMap = builder .state @@ -1923,6 +1954,9 @@ pub(super) fn lower_subroutine( } let mut subroutine = Subroutine { name: item.name(&match class { + Some(class) if dispatch.is_some() => { + classes::Class::dispatcher_name(&class.name, &name) + } Some(class) => classes::Class::subroutine_name(&class.name, &name), None => name, }), @@ -2055,6 +2089,66 @@ pub(super) fn lower_subroutine( Ok(subroutine) } +/// The body of a dispatcher of a virtual method: a call of the override in +/// `targets` for the class of `this`, the first of `params`, passing the +/// formals on (IEEE 1800-2023 8.20). Every class an object can have is in +/// `targets`, so any other class is that of `null`, whose dereference is an +/// error (8.4). +fn dispatch_body( + targets: &[(String, Vec)], + params: &[SubroutineParam], + result: Option<&str>, +) -> Stmt { + let this = Expr::Ident(params[0].name.clone()); + let args = params + .iter() + .map(|param| Some(Expr::Ident(param.name.clone()))) + .collect::>(); + let items = targets + .iter() + .map(|(target, classes)| { + let call = match result { + Some(result) => Stmt::Assign { + lhs: LValue::Ident(result.to_owned()), + rhs: Expr::Call { + callee: Callee::Subroutine(target.clone()), + args: args.clone(), + arg_order: Vec::new(), + }, + nonblocking: false, + }, + None => Stmt::Call { + name: target.clone(), + args: args.clone(), + arg_order: Vec::new(), + }, + }; + CaseItemBase { + labels: classes + .iter() + .map(|id| CaseLabel::Value(Expr::Literal(format!("32'd{id}")))) + .collect(), + body: vec![call], + } + }) + .collect(); + let null_dereference = classes::object_call( + system_functions::ObjectOp::Load(system_functions::ObjectField { + offset: 0, + width: 8, + signed: false, + handle: None, + }), + vec![this.clone()], + ); + Stmt::Case { + kind: CaseKind::Exact, + selector: classes::object_call(system_functions::ObjectOp::ClassOf, vec![this]), + items, + default: Some(vec![Stmt::Eval(null_dereference)]), + } +} + /// The `super.new(args)` call that starts constructor body `items`, as its /// index in `items` and its arguments (IEEE 1800-2023 8.15, 8.17). fn super_new<'a>( @@ -2217,6 +2311,23 @@ fn lower_class( state, item, Some(&class), + None, + )?); + } + for method in class.dispatched_methods() { + let targets = + classes::dispatch_targets(tree, name, &method.name, declaration_env, type_aliases)?; + subroutines.push(lower_subroutine( + method.native, + tree, + declaration_env, + type_aliases, + item_dimensions, + literals, + state, + item, + Some(&class), + Some(&targets), )?); } if !constructor { diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index f857274c2ca..e72c9d6fcee 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -954,6 +954,9 @@ pub struct ClassDeclaration { pub interface: bool, /// `extends` of a class, not of an interface class. pub base: Option, + /// The interface classes of `implements`, or those an interface class + /// extends (8.26). + pub interfaces: Vec, pub properties: Vec, pub methods: Vec, pub tokens: TokenRange, diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index 0de82cbbff9..e9ea1f3df5f 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -155,6 +155,7 @@ impl Parser<'_> { } let name = self.name()?; let mut base = None; + let mut interfaces = Vec::new(); if self.eat("#") { let start = self.at; self.expect("(")?; @@ -173,8 +174,9 @@ impl Parser<'_> { if self.eat("extends") { let data_type = self.class_base(interface)?; if interface { + interfaces.push(data_type); while self.eat(",") { - self.class_base(true)?; + interfaces.push(self.class_base(true)?); } } else { let arguments = if self.peek() == "(" { @@ -192,9 +194,9 @@ impl Parser<'_> { } } if !interface && self.eat("implements") { - self.class_base(true)?; + interfaces.push(self.class_base(true)?); while self.eat(",") { - self.class_base(true)?; + interfaces.push(self.class_base(true)?); } } self.expect(";")?; @@ -203,6 +205,7 @@ impl Parser<'_> { virtual_class, interface, base, + interfaces, properties: Vec::new(), methods: Vec::new(), tokens: TokenRange { start, end: start }, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 5f9554fe29c..287bdccd714 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -493,6 +493,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | | `sv_icarus_class_scope_resolution` | compile | icarus | 1 | Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = "set"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case. | +| `sv_icarus_virtual_dispatch` | execute | icarus | 1 | Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case. | +| `sv_icarus_abstract_and_interface_classes` | compile | icarus | 3 | Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors ("Invalid class item", "Invalid module item") and fails code generation without a diagnostic ("Code generation had 2 error(s)") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases. | | `sv_verilator_class_property_string_methods` | compile | verilator | 1 | Verilator 5.052 stops with an internal error ("AstNode is not of expected type, but instead has type 'MEMBERSEL'") on a string method called on a class property, n.name.itoa(42), which IEEE 1800-2023 6.16 and 8.5 permit. Icarus rejects the case too, see sv_icarus_classes. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 98c2d18e311..c7470fd436a 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -312,3 +312,217 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "a=1 b=7 c=103\nderived=8110 base=8\nfixed=41 default=3\n")) + +(case virtual_methods_dispatch_on_object_class + (source "class.sv" #" +module Top(output bit done); + class Shape; + int id; + function new(int id); + this.id = id; + endfunction + virtual function int area(); + return 0; + endfunction + function int describe(); + return id * 1000 + area(); + endfunction + virtual task scale(input int by, output int result); + result = by; + endtask + function int plain(); + return 1; + endfunction + endclass + class Square extends Shape; + int side; + function new(int id, int side); + super.new(id); + this.side = side; + endfunction + function int area(); + return side * side; + endfunction + task scale(input int by, output int result); + result = area() * by; + endtask + function int plain(); + return 2; + endfunction + endclass + class Cube extends Square; + function new(int id, int side); + super.new(id, side); + endfunction + function int area(); + return super.area() * 6; + endfunction + endclass + class Unchanged extends Shape; + function new(); + super.new(9); + endfunction + endclass + Shape shapes[4]; + Shape shape; + Square square; + Cube cube; + Unchanged unchanged; + int scaled; + initial begin + square = new(1, 3); + cube = new(2, 2); + unchanged = new; + shapes[0] = square; + shapes[1] = cube; + shapes[2] = unchanged; + shapes[3] = new(4); + foreach (shapes[i]) begin + shape = shapes[i]; + shape.scale(10, scaled); + $display("%0d area=%0d describe=%0d scaled=%0d plain=%0d", i, + shape.area(), shape.describe(), scaled, shape.plain()); + end + square = cube; + $display("square area=%0d plain=%0d", square.area(), square.plain()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "0 area=9 describe=1009 scaled=90 plain=1\n1 area=24 describe=2024 scaled=240 plain=1\n2 area=0 describe=9000 scaled=10 plain=1\n3 area=0 describe=4000 scaled=10 plain=1\nsquare area=24 plain=2\n")) + +(case abstract_classes_and_pure_virtual_methods + (source "class.sv" #" +module Top(output bit done); + virtual class Animal; + string name; + function new(string name); + this.name = name; + endfunction + pure virtual function string sound(); + function string speak(); + return {name, " says ", sound()}; + endfunction + endclass + class Dog extends Animal; + function new(); + super.new("dog"); + endfunction + virtual function string sound(); + return "woof"; + endfunction + endclass + virtual class Bird extends Animal; + function new(string name); + super.new(name); + endfunction + endclass + class Crow extends Bird; + function new(); + super.new("crow"); + endfunction + function string sound(); + return "caw"; + endfunction + endclass + Animal animal; + Dog dog; + Crow crow; + initial begin + dog = new; + crow = new; + animal = dog; + $display("%s", animal.speak()); + animal = crow; + $display("%s / %s", animal.speak(), animal.sound()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "dog says woof\ncrow says caw / caw\n")) + +(case methods_of_handle_array_elements + (source "class.sv" #" +module Top(output bit done); + class Item; + int value; + function new(int value); + this.value = value; + endfunction + virtual function int get(); + return value; + endfunction + endclass + class Twice extends Item; + function new(int value); + super.new(value); + endfunction + function int get(); + return value * 2; + endfunction + endclass + Item items[3]; + Twice twice; + int sum; + initial begin + items[0] = new(1); + twice = new(5); + items[1] = twice; + items[2] = new(7); + foreach (items[i]) sum = sum * 100 + items[i].get(); + $display("%0d %0d %0d", items[1].get(), items[1].value, sum); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "10 5 11007\n")) + +(case classes_implementing_interface_classes + (source "class.sv" #" +module Top(output bit done); + interface class Named; + pure virtual function int code(); + endclass + interface class Sized extends Named; + pure virtual function int size(); + endclass + virtual class Partial implements Sized; + pure virtual function int code(); + function int size(); + return code() * 2; + endfunction + endclass + class Box extends Partial; + int n; + function new(int n); + this.n = n; + endfunction + function int code(); + return n; + endfunction + endclass + class Crate extends Box; + function new(); + super.new(4); + endfunction + function int code(); + return 100; + endfunction + endclass + Box box; + Crate crate; + initial begin + box = new(3); + crate = new; + $display("%0d %0d", box.code(), box.size()); + box = crate; + $display("%0d %0d", box.code(), box.size()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "3 6\n100 200\n")) diff --git a/crates/celox-test-suite/verification/repros/virtual_dispatch.sv b/crates/celox-test-suite/verification/repros/virtual_dispatch.sv new file mode 100644 index 00000000000..1826c5f1756 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/virtual_dispatch.sv @@ -0,0 +1,41 @@ +// A virtual function called through a base-class handle runs the override of +// the object's class (IEEE 1800-2023 8.20). Expected output: 2 3 4 4. +module Top; + class A; + virtual function int f(); + return 1; + endfunction + endclass + class B extends A; + function int f(); + return 2; + endfunction + endclass + class C extends A; + virtual function int f(); + return 3; + endfunction + endclass + class D extends C; + function int f(); + return 4; + endfunction + endclass + A a; + B b; + C c; + D d; + initial begin + b = new; + c = new; + d = new; + a = b; + $write("%0d ", a.f()); + a = c; + $write("%0d ", a.f()); + a = d; + $write("%0d ", a.f()); + c = d; + $display("%0d", c.f()); + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/virtual_dispatch_icarus.json b/crates/celox-test-suite/verification/repros/virtual_dispatch_icarus.json new file mode 100644 index 00000000000..691c18acbf1 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/virtual_dispatch_icarus.json @@ -0,0 +1,42 @@ +{ + "schema_version": 3, + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0", + "cases": [ + { + "category": "Types", + "detail": "class::virtual_methods_dispatch_on_object_class at 393:3: expect_output: expected [48, 32, 97, 114, 101, 97, 61, 57, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 49, 48, 48, 57, 32, 115, 99, 97, 108, 101, 100, 61, 57, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 49, 32, 97, 114, 101, 97, 61, 50, 52, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 50, 48, 50, 52, 32, 115, 99, 97, 108, 101, 100, 61, 50, 52, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 50, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 57, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 51, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 52, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 115, 113, 117, 97, 114, 101, 32, 97, 114, 101, 97, 61, 50, 52, 32, 112, 108, 97, 105, 110, 61, 50, 10], got [48, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 49, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 49, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 50, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 50, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 57, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 51, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 52, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 115, 113, 117, 97, 114, 101, 32, 97, 114, 101, 97, 61, 52, 32, 112, 108, 97, 105, 110, 61, 50, 10]", + "expectation": "Simulation", + "name": "class::virtual_methods_dispatch_on_object_class", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "passed": 0, + "mismatch": 1, + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "include_ignored": true, + "exclude_stronger_than_sv": false, + "standard": "IEEE 1800-2023 8.20: a virtual method called through a base-class handle runs the override of the object's class; an override is virtual whether or not it repeats the keyword.", + "adapter_free": { + "source": "verification/repros/virtual_dispatch.sv", + "icarus_command": "iverilog -g2012 -s Top -o virtual_dispatch.sv; vvp ", + "icarus_version": "Icarus Verilog version 13.0", + "icarus_output": "1 1 1 3", + "verilator_command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir virtual_dispatch.sv", + "verilator_output": "2 3 4 4", + "expected_output": "2 3 4 4" + } +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 02c99aaf1a5..2c488fd85ce 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -1,5 +1,51 @@ { "cases": [ + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "upstream": [] + }, + "name": "class::abstract_classes_and_pure_virtual_methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "upstream": [] + }, + "name": "class::classes_implementing_interface_classes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -91,6 +137,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_abstract_and_interface_classes", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "upstream": [] + }, + "name": "class::methods_of_handle_array_elements", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -193,6 +262,30 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/virtual_dispatch_icarus.json", + "verification/repros/virtual_dispatch.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_virtual_dispatch", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case.", + "upstream": [] + }, + "name": "class::virtual_methods_dispatch_on_object_class", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index f2c69d158b0..cd5e9eb793d 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1881,6 +1881,43 @@ ] } }, + { + "id": "sv_icarus_virtual_dispatch", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case.", + "upstream": [], + "evidence": [ + "verification/repros/virtual_dispatch_icarus.json", + "verification/repros/virtual_dispatch.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::virtual_methods_dispatch_on_object_class" + ] + } + }, + { + "id": "sv_icarus_abstract_and_interface_classes", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects pure virtual method declarations and interface classes with syntax errors (\"Invalid class item\", \"Invalid module item\") and fails code generation without a diagnostic (\"Code generation had 2 error(s)\") for a method called on an element of an array of class handles. IEEE 1800-2023 8.21 and 8.26 define pure virtual methods and interface classes, and 7.4 and 8.4 permit arrays of class handles. Verilator passes all three cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::abstract_classes_and_pure_virtual_methods", + "class::methods_of_handle_array_elements", + "class::classes_implementing_interface_classes" + ] + } + }, { "id": "sv_verilator_class_property_string_methods", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 2d569e682de..bcde8372c4e 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -7,9 +7,9 @@ "passed": 0, "rejected": 0, "unexpected_accept": 1, - "mismatch": 15, + "mismatch": 16, "emission_error": 0, - "compile_error": 113, + "compile_error": 116, "runtime_error": 7, "unsupported": 0, "ignored": 0 @@ -1279,6 +1279,38 @@ "name": "class::static_properties_and_methods", "phase": "compile", "status": "compile_error" + }, + { + "category": "Types", + "detail": "class::virtual_methods_dispatch_on_object_class at 393:3: expect_output: expected [48, 32, 97, 114, 101, 97, 61, 57, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 49, 48, 48, 57, 32, 115, 99, 97, 108, 101, 100, 61, 57, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 49, 32, 97, 114, 101, 97, 61, 50, 52, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 50, 48, 50, 52, 32, 115, 99, 97, 108, 101, 100, 61, 50, 52, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 50, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 57, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 51, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 52, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 115, 113, 117, 97, 114, 101, 32, 97, 114, 101, 97, 61, 50, 52, 32, 112, 108, 97, 105, 110, 61, 50, 10], got [48, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 49, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 49, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 50, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 50, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 57, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 51, 32, 97, 114, 101, 97, 61, 48, 32, 100, 101, 115, 99, 114, 105, 98, 101, 61, 52, 48, 48, 48, 32, 115, 99, 97, 108, 101, 100, 61, 49, 48, 32, 112, 108, 97, 105, 110, 61, 49, 10, 115, 113, 117, 97, 114, 101, 32, 97, 114, 101, 97, 61, 52, 32, 112, 108, 97, 105, 110, 61, 50, 10]", + "expectation": "Simulation", + "name": "class::virtual_methods_dispatch_on_object_class", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid class item.\n", + "expectation": "Simulation", + "name": "class::abstract_classes_and_pure_virtual_methods", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 1; see /build.log\nerror: Code generation had 2 error(s).\n", + "expectation": "Simulation", + "name": "class::methods_of_handle_array_elements", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 25; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:5: syntax error\n/source_0.sv:6: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:9: error: Invalid module item.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Invalid module item.\n/source_0.sv:14: syntax error\n/source_0.sv:15: error: Invalid module item.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: I give up on this function definition.\n/source_0.sv:23: syntax error\n/source_0.sv:24: error: Invalid module item.\n/source_0.sv:25: syntax error\n/source_0.sv:25: error: I give up on this function definition.\n/source_0.sv:28: error: 'code' has already been declared in this scope.\n/source_0.sv:20: : It was declared here as a function.\n/source_0.sv:31: syntax error\n/source_0.sv:32: error: Invalid module item.\n/source_0.sv:33: syntax error\n/source_0.sv:33: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "class::classes_implementing_interface_classes", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 72774285008..736c8fff273 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -1,5 +1,27 @@ { "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::abstract_classes_and_pure_virtual_methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::classes_implementing_interface_classes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -55,6 +77,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::methods_of_handle_array_elements", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", @@ -121,6 +154,17 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::virtual_methods_dispatch_on_object_class", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 4d2e3a2f413..a70bfda6206 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -16,6 +16,10 @@ sv_backends! { fn class_inherited_properties_and_methods(sim) { @case "class::inherited_properties_and_methods"; } fn class_static_properties_and_methods(sim) { @case "class::static_properties_and_methods"; } fn class_constructors_chain_to_base(sim) { @case "class::constructors_chain_to_base"; } + fn class_virtual_methods_dispatch_on_object_class(sim) { @case "class::virtual_methods_dispatch_on_object_class"; } + fn class_abstract_classes_and_pure_virtual_methods(sim) { @case "class::abstract_classes_and_pure_virtual_methods"; } + fn class_methods_of_handle_array_elements(sim) { @case "class::methods_of_handle_array_elements"; } + fn class_classes_implementing_interface_classes(sim) { @case "class::classes_implementing_interface_classes"; } } sv_backends! { @@ -37,6 +41,26 @@ sv_backends! { assert!(error.contains("null object handle"), "{error}"); } + fn virtual_calls_through_null_are_runtime_errors(sim) { + @setup { + let source = r#"module Top(output int value, output bit done); + class C; + virtual function int f(); + return 1; + endfunction + endclass + C c; + initial begin + value = c.f(); + done = 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("null.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); + } + fn checkpoints_keep_objects_that_state_files_cannot_record(sim) { @setup { let source = r#"module Top(output int value); @@ -91,7 +115,7 @@ fn four_state_properties_are_rejected() { } #[test] -fn misplaced_super_new_and_static_misuse_are_rejected() { +fn misplaced_super_new_static_misuse_and_unimplemented_methods_are_rejected() { for (body, want) in [ ( "class B; endclass class C extends B; int x; function new(); x = 1; super.new(); endfunction endclass", @@ -105,6 +129,23 @@ fn misplaced_super_new_and_static_misuse_are_rejected() { "class C; function int g(); return 1; endfunction static function int f(); return g(); endfunction endclass", "non-static method `g` called from a static method", ), + ( + "virtual class C; pure virtual function int f(); endclass class D extends C; endclass", + "does not implement pure virtual method `f`", + ), + ( + "virtual class B; pure virtual function int f(); endclass class C extends B; function int f(); return super.f(); endfunction endclass", + "pure virtual method `f` called through `super`", + ), + ("virtual class C; endclass", "object of abstract class `C`"), + ( + "interface class I; pure virtual function int f(); endclass virtual class B implements I; endclass class C extends B; endclass", + "does not implement interface class method `f`", + ), + ( + "interface class I; pure virtual function int f(); endclass interface class J; pure virtual function void f(); endclass class C implements I, J; function int f(); return 1; endfunction endclass", + "whose return type differs from its interface class", + ), ] { let source = format!("module Top; {body} C c; initial c = new; endmodule"); let Err(error) = diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6bf041d4ce4..d3358f3d560 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -30,7 +30,7 @@ synthesis and is tested at the design level. | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | -| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and non-virtual methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; static properties and methods; `C::` scope resolution of static members and `C::new`. See [classes](#classes) | +| Classes | classes declared in a module: properties of 2-state integral types up to 64 bits, `string` and class handle types, with initializers; `new` with and without arguments, implicit and explicit constructors; methods (`function` and `task`, also `extern` with an out-of-block body) called through a handle or unqualified inside the class; `this`, `null`, handle assignment and comparison; inheritance of properties and methods, with base constructors called by `super.new(...)` or `extends Base(...)`; `super.` members; virtual methods, abstract (`virtual`) classes and pure virtual methods; classes that implement interface classes; static properties and methods; `C::` scope resolution of static members and `C::new`; arrays of handles. See [classes](#classes) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -128,7 +128,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): virtual method calls, abstract and interface classes, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. +- Class features beyond those [listed](#classes): method calls through an interface class handle, `$cast`, classes declared in packages, parameterized classes, named constructor arguments, shallow copies (`new h`), and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. - Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. @@ -229,8 +229,14 @@ object call into the runtime. Objects that no variable or other object refers to are collected between time slots and after each `tick`. A method is called with the object it was called on, so it can be a function or a task, and calls are bound to the method of the variable's class (IEEE 1800-2023 8.6). -Reading or writing a property or calling a method through `null` is a runtime -error. +A call of a virtual method runs the override of the object's class instead, +except `super.m(...)`, which runs the base's implementation (8.15, 8.20); it +selects the override by the class of the object, so it costs one more call +into the runtime. Reading or writing a property or calling a method through +`null` is a runtime error. Constructing an abstract class and a class that +leaves a pure virtual method unimplemented are rejected (8.21). A class that +implements an interface class implements each of its methods with the same +return type, or, if it is abstract, re-declares it pure (8.26). A constructor calls the constructor of the base class first, with the arguments of `super.new(...)` or of the `extends` clause, then runs the diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index b67333b1c30..7667500252d 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,7 +28,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティと非 virtual メソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決。[クラス](#classes)を参照 | +| クラス | モジュール内で宣言したクラス。64 ビット以下の 2 値整数型・`string`・クラスハンドル型のプロパティ(初期値つきも可)、引数あり・なしの `new`、暗黙と明示のコンストラクタ、ハンドル経由またはクラス内から修飾なしで呼ぶメソッド(`function` と `task`、本体をクラス外に書く `extern` も可)、`this`、`null`、ハンドルの代入と比較、プロパティとメソッドの継承(基底クラスのコンストラクタは `super.new(...)` か `extends Base(...)` で呼ぶ)、`super.` によるメンバ参照、virtual メソッド、抽象クラス(`virtual class`)と pure virtual メソッド、interface クラスを実装するクラス、static プロパティとメソッド、static メンバと `C::new` の `C::` によるスコープ解決、ハンドルの配列。[クラス](#classes)を参照 | | 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | @@ -118,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:virtual メソッドの呼び出し、抽象クラスと interface クラス、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:interface クラスのハンドルを通したメソッド呼び出し、`$cast`、package 内で宣言したクラス、パラメータ付きクラス、名前付きのコンストラクタ引数、浅いコピー(`new h`)、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 @@ -167,7 +167,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ### クラス {#classes} -クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。 +クラス型の変数はシミュレータのヒープ上のオブジェクトへのハンドルを持ち、コンストラクタを呼ぶまでは `null` です。文字列と同じく、ハンドルのコピーと比較は 32 ビット整数と同じコストで、プロパティの読み書きとオブジェクトの生成だけがランタイムを呼び出します。どの変数・オブジェクトからも参照されないオブジェクトは、タイムスロットの間と各 `tick` の後に回収されます。メソッドは呼び出したオブジェクトを受け取るので function でも task でもよく、呼び出しは変数のクラスのメソッドに結び付きます(IEEE 1800-2023 8.6)。virtual メソッドの呼び出しは、代わりにオブジェクトのクラスの override を実行します。ただし `super.m(...)` は基底クラスの実装を実行します(8.15、8.20)。override はオブジェクトのクラスで選ぶので、ランタイムの呼び出しが 1 回増えます。`null` を通したプロパティの読み書きやメソッド呼び出しは実行時エラーです。抽象クラスの生成と、pure virtual メソッドを実装しないクラスはエラーになります(8.21)。interface クラスを実装するクラスは、そのメソッドをすべて同じ戻り値型で実装するか、抽象クラスなら pure として宣言し直します(8.26)。 コンストラクタは、まず `super.new(...)` または `extends` 節の引数で基底クラスのコンストラクタを呼び、次に自クラスが宣言するプロパティの初期値を設定し、最後に本体を実行します(IEEE 1800-2023 8.17)。static プロパティはクラスを宣言したモジュールの変数なので、モジュールのインスタンスごとに 1 つずつあります。