From 0e87db6d9020b7400b1697ae3296177ed062e8e8 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 13:17:33 +0900 Subject: [PATCH 1/6] perf(runtime)!: compare counted wait baselines in place A wait term on a counted signal kept the signal's value at the last check as a pair of BigUints: every check read the signal into new BigUints and compared them. Like an uncounted plain signal, it now keeps the signal's plane image (Baseline::RawCounter) and compares it with the state in place. Counter remains for signals without a plane image and for baselines loaded from a state file, which become RawCounter at their first check; a RawCounter saves as the same Counter record. BREAKING CHANGE: celox_runtime::timing::Baseline has a new variant, RawCounter. Change-Id: Icaf42a4570d829af240927beaeafcb3642cf245b --- crates/celox-runtime/src/simulation/wait.rs | 68 ++++++++++++++++----- crates/celox/src/simulator/state_file.rs | 26 +++++--- 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index f8497a81a6d..1bb95a744e9 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -48,9 +48,24 @@ impl SimulationState { for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { match term.counter { Some(counter) => { - *baseline = Baseline::Counter { - seen: backend.get_as(counter), - value: read(backend, term.signal), + let seen = backend.get_as(counter); + match planes(backend, term.signal) { + Some(image) => { + if let Baseline::RawCounter { seen: last, raw } = baseline { + *last = seen; + copy_planes(raw, image, term.signal.width); + } else { + let mut raw = Vec::with_capacity(image.len()); + copy_planes(&mut raw, image, term.signal.width); + *baseline = Baseline::RawCounter { seen, raw }; + } + } + None => { + *baseline = Baseline::Counter { + seen, + value: read(backend, term.signal), + } + } } } None => match planes(backend, term.signal) { @@ -128,20 +143,40 @@ impl SimulationState { continue; } let baseline = &mut waiter.baselines[index]; + // The common term: a plain signal no counter counts. + if let Baseline::Raw(last) = baseline { + let now = state.planes(term.signal).expect("a plain signal"); + wake |= Self::advance(term.kind, last, now, term.signal.width); + continue; + } + let counted = |seen: u32| { + term.counter + .is_some_and(|counter| backend.get_as::(counter) != seen) + }; wake |= match baseline { - Baseline::Counter { seen, value } => { - let counted = term - .counter - .is_some_and(|counter| backend.get_as::(counter) != *seen); - let now = read(backend, term.signal); - let changed = occurs(term.kind, value, &now); - *value = now; - counted || changed - } - Baseline::Raw(last) => { + Baseline::RawCounter { seen, raw } => { let now = state.planes(term.signal).expect("a plain signal"); - Self::advance(term.kind, last, now, term.signal.width) + let changed = Self::advance(term.kind, raw, now, term.signal.width); + counted(*seen) || changed } + Baseline::Counter { seen, value } => match state.planes(term.signal) { + // A baseline loaded from a state file. + Some(now) => { + let seen = *seen; + let mut raw = encode_planes(value, term.signal.width, now.len()); + let changed = + Self::advance(term.kind, &mut raw, now, term.signal.width); + *baseline = Baseline::RawCounter { seen, raw }; + counted(seen) || changed + } + None => { + let now = read(backend, term.signal); + let changed = occurs(term.kind, value, &now); + *value = now; + counted(*seen) || changed + } + }, + Baseline::Raw(_) => unreachable!("tested above"), Baseline::Value(last) => match state.planes(term.signal) { // A baseline loaded from a state file. Some(now) => { @@ -191,7 +226,7 @@ impl SimulationState { } match baseline { // Counters are bumped by the write itself. - Baseline::Counter { .. } => {} + Baseline::Counter { .. } | Baseline::RawCounter { .. } => {} Baseline::Raw(last) => { let now = encode_planes(value, signal.width, last.len()); wake |= Self::advance(term.kind, last, &now, signal.width); @@ -224,6 +259,9 @@ pub enum Baseline { /// (see [`planes`]) with the bits above its width cleared. Checks /// compare it with the state in place. Raw(Vec), + /// Like `Counter`, with the signal's state at the last check kept as + /// in [`Baseline::Raw`]. + RawCounter { seen: u32, raw: Vec }, } /// A process suspended at a wait. diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 50b7218fed1..ecf643082d2 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -533,6 +533,13 @@ impl Simulator { .collect() }) .unwrap_or_default(); + let split = |term: usize, image: &[u8]| { + let bytes = widths + .get(term) + .map_or(image.len(), |width| width.div_ceil(8).max(1)) + .min(image.len()); + (image[..bytes].to_vec(), image[bytes..].to_vec()) + }; WaiterRecord { process: process(index), site: waiter.site as u64, @@ -554,13 +561,18 @@ impl Simulator { mask: mask.to_bytes_le(), }, Baseline::Raw(image) => { - let bytes = widths - .get(term) - .map_or(image.len(), |width| width.div_ceil(8).max(1)) - .min(image.len()); - BaselineRecord::Value { - value: image[..bytes].to_vec(), - mask: image[bytes..].to_vec(), + let (value, mask) = split(term, image); + BaselineRecord::Value { value, mask } + } + Baseline::RawCounter { seen, raw } => { + // The bytes a `Counter` baseline's value saves as. + let (value, mask) = split(term, raw); + let number = + |bytes: &[u8]| BigUint::from_bytes_le(bytes).to_bytes_le(); + BaselineRecord::Counter { + seen: *seen, + value: number(&value), + mask: number(&mask), } } }) From dcebf338a554a790511661d5d52331952987e74d Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 13:17:33 +0900 Subject: [PATCH 2/6] test(sv): keep counted wait baselines across a state file Change-Id: I1a6d04d2baedc95cd44502fe1d7c769680f54ec2 --- .../tests/frontends/systemverilog/timing.rs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 204f36c4992..9a1070623df 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -748,3 +748,88 @@ fn runtime_error_before_a_commit_leaves_no_held_writes() { } } } + +/// The baselines of waits on a counted variable survive a state file: a +/// simulation loaded between two pulses of `y` wakes the waiters as the +/// uninterrupted one does, and saves the same baselines again. +#[test] +fn counted_wait_baselines_survive_a_state_file() { + let source = r#" + module Top(output int n, r); + timeunit 1ns / 1ns; + bit a, b, c; + logic y; + always_comb begin y = 0; if (a) y = 1; c = b; end + initial #1 forever begin @(y); n++; end + initial #1 forever begin @(posedge y); r++; end + initial begin + #2 a = 1; + #1 b = 1; + #1 b = 0; + #1 b = 1; + #1 a = 0; + end + endmodule + "#; + let build = |four_state: bool| { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("counted_state.sv"))], + "Top", + ) + .four_state(four_state) + .build() + .unwrap() + }; + let through_bytes = |file: &celox::StateFile| { + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + celox::StateFile::read_from(bytes.as_slice()).unwrap() + }; + for four_state in [false, true] { + let counts = |sim: &mut celox::Simulation| { + ["n", "r"].map(|name| { + let signal = sim.signal(name); + sim.get(signal) + }) + }; + let mut whole = build(four_state); + whole.run_until(10).unwrap(); + let expected = counts(&mut whole); + assert_eq!( + expected, + [5u32.into(), 4u32.into()], + "four_state={four_state}" + ); + + let mut first = build(four_state); + first.run_until(3).unwrap(); + let file = through_bytes(&first.save_state().unwrap()); + assert!( + file.schedule + .as_ref() + .unwrap() + .processes + .waiters + .iter() + .flat_map(|waiter| &waiter.baselines) + .any(|baseline| matches!(baseline, celox::BaselineRecord::Counter { .. })), + "four_state={four_state}: `y` is counted" + ); + let mut loaded = build(four_state); + loaded.load_state(&file).unwrap(); + assert_eq!( + through_bytes(&loaded.save_state().unwrap()), + file, + "four_state={four_state}" + ); + loaded.run_until(10).unwrap(); + assert_eq!(counts(&mut loaded), expected, "four_state={four_state}"); + // A baseline taken at a check in this run saves as the loaded one. + first.run_until(4).unwrap(); + loaded = build(four_state); + let file = through_bytes(&first.save_state().unwrap()); + loaded.load_state(&file).unwrap(); + loaded.run_until(10).unwrap(); + assert_eq!(counts(&mut loaded), expected, "four_state={four_state}"); + } +} From 5b5ab7b53e98642c8afa3cf1c039c7a929e293ed Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 3/6] fix(sv): reject edge event controls on reals A real has no least significant bit to judge an edge on, and IEEE 1800-2023 6.12 prohibits posedge, negedge and edge of a real. A process waiting on one was accepted and never woke; it is now an error. Change-Id: If5c69702c6a335e0ca9a8f0621451d23335be3fa --- crates/celox-frontend-sv/src/lowering/ff.rs | 11 +++++++ crates/celox-sv-analyzer/src/lib.rs | 4 +++ .../tests/frontends/systemverilog/timing.rs | 33 +++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ba395190ed5..21b4c83ce8b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4626,6 +4626,17 @@ impl Ff<'_, '_> { let mut samples = Vec::new(); for item in items { let expr = self.propagate(&item.expr); + let edge = match item.edge { + sv::ir::EventEdge::Any => None, + sv::ir::EventEdge::Pos => Some("posedge"), + sv::ir::EventEdge::Neg => Some("negedge"), + sv::ir::EventEdge::Both => Some("edge"), + }; + if let Some(edge) = edge + && self.m.expr_float_precision(&expr).is_some() + { + return Err(sv::AnalyzerError::RealEdgeEvent { edge }); + } let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { Some(id) if !self.m.is_hidden(id) => id, diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 6cb234e623f..76c037db994 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -158,6 +158,10 @@ pub enum AnalyzerError { actual: String, target: String, }, + /// `posedge`, `negedge` or `edge` of a real expression, which has no + /// least significant bit to judge the edge on (IEEE 1800-2023 6.12). + #[error("`{edge}` of a real expression: edge event controls do not apply to reals")] + RealEdgeEvent { edge: &'static str }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 204f36c4992..eed894ee5aa 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -536,6 +536,39 @@ fn unimplemented_timing_features_are_rejected() { } } +/// A real has no least significant bit, so no edge event control applies to +/// one (IEEE 1800-2023 6.12); a change of its value is an event. +#[test] +fn edge_events_of_reals_are_errors() { + for (body, edge) in [ + ("real r; initial @(posedge r);", "posedge"), + ("real r; int n; always @(negedge r) n++;", "negedge"), + ("real r; initial @(edge (r * 2.0));", "edge"), + ( + "shortreal r; bit c; int n; always @(posedge c or posedge r) n++;", + "posedge", + ), + ] { + let source = format!("module Top; {body} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("real_edge.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`{body}` must be rejected")) + .to_string(); + assert!( + error.contains(&format!("`{edge}` of a real expression")), + "{body}: {error}" + ); + } + let source = "module Top; real r; initial @(r); endmodule"; + celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("real.sv"))], "Top") + .build() + .expect("a change of a real is an event"); +} + /// Only `initial` and `always` processes may suspend (IEEE 1800-2023 /// 9.2.2.2, 9.2.2.4 and 13.4); a timing control elsewhere is an error. #[test] From e512f6dbe68557ef8218802726c69965b1a8f175 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 4/6] feat(sv): run plain always blocks without the flip-flop shape as processes IEEE 1800-2023 9.2.2.4 restricts only always_ff to the shape of a flip-flop. A plain always whose event control is not a clock and asynchronous resets of one-bit variables now runs as a process waiting on the same event control, instead of being rejected: an edge of a select or an expression, `edge`, an item without an edge next to edges, a multi-bit edge signal (judged on its least significant bit), and several edges of which the body tests none as a reset. Blocks of the flip-flop shape stay on the flip-flop path, lowered as before. always_ff of the other shapes stays rejected. Fixes #1708. Change-Id: Ic4652f6e110243b39566bbf2ed1d2ab3f81a2f7e --- crates/celox-frontend-sv/src/lowering.rs | 74 ++++++++++++++---- .../celox-sv-analyzer/src/ast/ff_process.rs | 34 ++++++-- .../celox-sv-analyzer/src/ast/procedural.rs | 3 +- .../celox-sv-analyzer/src/ast/validation.rs | 5 +- crates/celox-sv-analyzer/src/ir.rs | 18 ++++- .../src/sv/cases/timing.vtest | 77 +++++++++++++++++++ .../verification/sv/icarus/timing.json | 33 ++++++++ .../verification/sv/verilator/timing.json | 33 ++++++++ .../tests/frontends/systemverilog/timing.rs | 11 ++- 9 files changed, 258 insertions(+), 30 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index ce9eeda9600..e88c58796ab 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -2712,6 +2712,31 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, ) -> Result { + let parameter_types = module + .imported_parameters() + .iter() + .chain(module.parameters()) + .filter_map(|parameter| { + Some(( + parameter.name().to_string(), + ( + parameter.resolved_width()?, + parameter.resolved_signed().unwrap_or(false), + ), + )) + }) + .collect(); + let constants = module_constants_with_overrides(module, parameter_overrides); + let fallbacks = module + .ff_processes() + .iter() + .any(|process| runs_as_process(module, process, &constants, ¶meter_types)) + .then(|| { + module.clone().run_edge_processes_as_processes(|process| { + runs_as_process(module, process, &constants, ¶meter_types) + }) + }); + let module = fallbacks.as_ref().unwrap_or(module); let mut ff_event_roles = Vec::new(); for process in module.ff_processes() { let clock = clock_event_from_ff_process(process) @@ -2734,21 +2759,6 @@ fn lower_module_with_overrides( }); } } - let parameter_types = module - .imported_parameters() - .iter() - .chain(module.parameters()) - .filter_map(|parameter| { - Some(( - parameter.name().to_string(), - ( - parameter.resolved_width()?, - parameter.resolved_signed().unwrap_or(false), - ), - )) - }) - .collect(); - let constants = module_constants_with_overrides(module, parameter_overrides); let shared_memories = shared_edge_memories(module, &constants, ¶meter_types, warnings); validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; let scheduled = module @@ -8392,6 +8402,40 @@ fn insert_or_merge_ff_unit( } } +/// A plain `always` sensitive to edges is a flip-flop only in the shape of +/// one: a clock and asynchronous resets, each a one-bit variable. Any other +/// edge-sensitive `always` runs as a process waiting on the same events. +fn runs_as_process( + module: &sv::ir::Module, + process: &sv::ir::FfProcess, + constants: &HashMap, + parameter_types: &HashMap, +) -> bool { + let multi_bit = |name: &str| { + let r#type = module + .ports() + .iter() + .find(|port| port.name() == name) + .map(sv::ir::Port::r#type) + .or_else(|| { + module + .signals() + .iter() + .find(|signal| signal.name() == name) + .map(sv::ir::Signal::r#type) + }); + r#type + .and_then(|r#type| signal_type_from_sv(r#type, constants, parameter_types).ok()) + .is_some_and(|type_info| type_info.width != 1) + }; + !process.is_always_ff() + && (clock_event_from_ff_process(process).is_none() + || process + .events() + .iter() + .any(|event| multi_bit(event.signal()))) +} + fn clock_event_from_ff_process(process: &sv::ir::FfProcess) -> Option<&sv::ir::FfEvent> { let clock = process.events().first()?; if process.events().len() == 1 { diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 944550c2926..c4b8cb131dd 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -66,8 +66,12 @@ fn ff_process_from_procedure( if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff { return Ok(None); } - let root = procedure.body; - let (events, body) = ff_event_control_and_body(root, syntax_tree)?; + let Some((events, body)) = ff_event_control_and_body(procedure.body, syntax_tree)? else { + if procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf { + return Err(unsupported("always_ff event expression")); + } + return Ok(None); + }; let mut local_dimensions = packed_dimensions.clone(); local_dimensions.const_env = const_env.clone().into(); let mut builder = procedural::BodyBuilder::new( @@ -93,12 +97,26 @@ fn ff_process_from_procedure( })) } +/// A plain `always` sensitive to edges runs as a process when its events are +/// not all `posedge` or `negedge` of a variable, such as `@(posedge v[0])`, +/// `@(edge a)` or `@(posedge clk or a)`. Only `always_ff` must have this shape +/// (IEEE 1800-2023 9.2.2.4). +pub(super) fn always_falls_back_to_process( + procedure: &celox_sv_syntax::Procedure, + tree: &AnalysisContext<'_>, +) -> Result { + Ok(procedure.kind == celox_sv_syntax::ProcedureKind::Always + && always_kind(procedure, tree.declarations())? == AlwaysKind::Ff + && ff_event_control_and_body(procedure.body, tree)?.is_none()) +} + +/// The events of a flip-flop shaped event control and the body it controls, +/// or `None` when an event is not an edge of a variable. fn ff_event_control_and_body( root: celox_sv_syntax::StatementId, tree: &AnalysisContext<'_>, -) -> Result<(Vec, celox_sv_syntax::StatementId), AnalyzerError> { +) -> Result, celox_sv_syntax::StatementId)>, AnalyzerError> { use celox_sv_syntax::{EventControl, StatementKind, TimingControlKind, TimingEdge}; - let unsupported_event = || unsupported("always_ff event expression"); let native = tree.declarations(); let StatementKind::Timing { control, body } = native.statement(root).kind else { return Err(timing::disagreement()); @@ -115,12 +133,14 @@ fn ff_event_control_and_body( let edge = match item.edge { TimingEdge::Pos => FfEdge::Pos, TimingEdge::Neg => FfEdge::Neg, - _ => return Err(unsupported_event()), + _ => return Ok(None), }; let expression = expression_binding::value(item.expression, native, tree, &PackedDimensions::default())?; - let signal = expr_ident_name(&expression).ok_or_else(unsupported_event)?; + let Some(signal) = expr_ident_name(&expression) else { + return Ok(None); + }; events.push(FfEvent::new(edge, signal)); } - Ok((events, body)) + Ok(Some((events, body))) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 7fb788f706d..f749276459d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -2701,7 +2701,8 @@ pub(super) fn initial_processes_from_scope( celox_sv_syntax::ProcedureKind::Initial => false, celox_sv_syntax::ProcedureKind::Always if validation::always_kind(procedure, tree.declarations())? - == validation::AlwaysKind::Process => + == validation::AlwaysKind::Process + || ff_process::always_falls_back_to_process(procedure, tree)? => { true } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index fd6a43b40ab..1ccf521aeb4 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -14,7 +14,10 @@ pub(super) enum AlwaysKind { /// `always_comb` and `always @*` are combinational; `always_ff` and an /// `always` sensitive to clock edges are sequential, as long as their body -/// has no timing control of its own. Every other `always` is a process. +/// has no timing control of its own. Every other `always` is a process, and +/// so is an edge-sensitive `always` whose events are not edges of variables +/// (`ff_process::always_falls_back_to_process`). The frontend runs one whose +/// events are not a one-bit clock and resets as a process too. /// `always_latch` has the execution and sensitivity rules of `always_comb`. pub(super) fn always_kind( procedure: &celox_sv_syntax::Procedure, diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 9a02e684932..3fabbdb7eb8 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -77,7 +77,21 @@ pub struct Module { impl Module { /// Represent selected edge procedures as scheduled processes. A host /// request must finish synchronously before the following statement runs. - pub fn schedule_edge_processes(mut self, mut select: impl FnMut(&FfProcess) -> bool) -> Self { + pub fn schedule_edge_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self { + self.edge_processes_as_processes(select, true) + } + + /// Run selected plain `always` edge procedures as ordinary processes that + /// wait on the same events, for those that do not fit the flip-flop shape. + pub fn run_edge_processes_as_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self { + self.edge_processes_as_processes(select, false) + } + + fn edge_processes_as_processes( + mut self, + mut select: impl FnMut(&FfProcess) -> bool, + scheduled_edge: bool, + ) -> Self { let mut retained = Vec::new(); for process in std::mem::take(&mut self.ff_processes) { if !select(&process) { @@ -101,7 +115,7 @@ impl Module { self.initial_processes.push(InitialProcess { creation_order: process.creation_order, site: process.site, - scheduled_edge: true, + scheduled_edge, condition: None, body: vec![Stmt::Loop { kind: LoopKind::Forever, diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index d696896ac9a..1b446580399 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2082,3 +2082,80 @@ 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 "q=2 r=1 s=1\n")) + +(case plain_always_expression_edges_run_as_processes + ; IEEE 1800-2023 9.2.2.4 restricts only always_ff to the flip-flop shape. + ; A plain always waits on its event control like any other process: an + ; edge of a select or an expression, or `edge` (9.4.2). + (source "always_expression_edges.sv" #" + module Top(output bit [7:0] selected, both, any); + bit [3:0] v; + bit a, b; + always @(posedge v[1]) selected = selected + 8'd1; + always @(posedge (a & b)) both = both + 8'd1; + always @(edge a) any = any + 8'd1; + initial begin + #1; v = 4'b0010; a = 1; + #1; b = 1; + #1; v = 4'b0000; a = 0; + #1; v = 4'b0010; a = 1; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq selected 1) + (assert_eq both 0) + (assert_eq any 1) + (run_until 2) + (assert_eq both 1 "a & b rose") + (run_until 4) + (assert_eq selected 2) + (assert_eq both 2) + (assert_eq any 3 "a rose, fell and rose")) + +(case plain_always_multi_bit_edges_follow_the_lsb + ; Table 9-2 judges the edge of a multi-bit expression on its least + ; significant bit. + (source "always_multi_bit_edge.sv" #" + module Top(output bit [7:0] count); + bit [3:0] bus; + always @(posedge bus) count = count + 8'd1; + initial begin + #1; bus = 4'b0010; + #1; bus = 4'b0011; + #1; bus = 4'b0000; + #1; bus = 4'b0001; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0 "the least significant bit stayed 0") + (run_until 2) + (assert_eq count 1) + (run_until 4) + (assert_eq count 2)) + +(case plain_always_edges_without_a_reset_run_as_processes + ; Neither edge is tested in the body, so neither is an asynchronous + ; reset: the process wakes on each of them. + (source "always_two_edges.sv" #" + module Top(output bit [7:0] count); + bit c, d; + always @(posedge c or posedge d) count <= count + 8'd1; + initial begin + #1; c = 1; + #1; d = 1; + #1; c = 0; d = 0; + #1; c = 1; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 1) + (run_until 2) + (assert_eq count 2) + (run_until 4) + (assert_eq count 3)) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 8c54f5c6013..b6998ae9588 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -673,6 +673,39 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_edges_without_a_reset_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_expression_edges_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_multi_bit_edges_follow_the_lsb", + "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 07c3f4d070c..7a14137d3b9 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -781,6 +781,39 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_edges_without_a_reset_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_expression_edges_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_multi_bit_edges_follow_the_lsb", + "phase": "execute", + "status": "passed", + "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 eed894ee5aa..809fe25b00b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -160,6 +160,9 @@ timed_cases! { fn blocking_write_waiters_run_before_nonblocking_updates = "timing::blocking_write_waiters_run_before_nonblocking_updates"; fn blocking_write_waiters_rearm_before_nonblocking_updates = "timing::blocking_write_waiters_rearm_before_nonblocking_updates"; fn blocking_write_edges_read_values_before_nonblocking_updates = "timing::blocking_write_edges_read_values_before_nonblocking_updates"; + fn plain_always_expression_edges_run_as_processes = "timing::plain_always_expression_edges_run_as_processes"; + fn plain_always_multi_bit_edges_follow_the_lsb = "timing::plain_always_multi_bit_edges_follow_the_lsb"; + fn plain_always_edges_without_a_reset_run_as_processes = "timing::plain_always_edges_without_a_reset_run_as_processes"; } #[test] @@ -474,19 +477,19 @@ fn unimplemented_timing_features_are_rejected() { "delayed continuous assignment", 444, ), - // #1708: a plain `always` that is not a flip-flop runs as a process. + // A plain `always` of these forms runs as a process. ( - "bit [3:0] v; int n; always @(posedge v[0]) n++;", + "bit [3:0] v; int n; always_ff @(posedge v[0]) n <= n + 1;", "always_ff event expression", 464, ), ( - "bit [3:0] v; int n; always @(posedge v) n++;", + "bit [3:0] v; int n; always_ff @(posedge v) n <= n + 1;", "multi-bit always_ff event signal", 88, ), ( - "bit a, b; int n; always @(posedge a or posedge b) n <= n + 1;", + "bit a, b; int n; always_ff @(posedge a or posedge b) n <= n + 1;", "always_ff event control", 88, ), From 554f20493b4ed4d734940e22114e119d9722e35e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 5/6] docs(sv): describe plain always blocks that run as processes Change-Id: I8638596a6f136bca76c8d2cfa844f258f36c3d38 --- docs/guide/systemverilog-reference.md | 19 ++++++++++++------- docs/ja/guide/systemverilog-reference.md | 13 ++++++++----- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index cd74c47a430..68085540f6b 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -62,9 +62,15 @@ both `Simulator` and `Simulation`: `always @(a or b) y = a + b;` or or a nonblocking assignment. Any other sensitivity list without edges runs as a process: `always @(a) y = a + b;` leaves `y` unchanged when only `b` changes. So does a list that, as `always @*`, would close a combinational -loop with other logic. A `Simulator` runs no processes, so building one for -such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation`; use -`Simulation`, or write `always @*` or `always_comb`. +loop with other logic. So does an edge-sensitive `always` +that does not have the shape of a flip-flop: one with an edge of a select or +an expression (`@(posedge v[0])`, `@(posedge (a & b))`), an `edge`, an item +without an edge next to edges, a multi-bit edge signal (its least significant +bit decides the edge), or several edges of which the body tests none as an +asynchronous reset. Only `always_ff` must have that shape. A `Simulator` runs +no processes, so building one for such a design fails with +`SimulatorErrorKind::ProcessRequiresSimulation`; use `Simulation`, or write +`always @*` or `always_comb`. ### Timed task calls @@ -147,10 +153,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs and `real`. -- Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a - plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. A plain `always` with - such an edge, a multi-bit edge signal, or several edges without a reset is - rejected too, until it runs as a process ([#1708](https://github.com/celox-sim/celox/issues/1708)). +- Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) in event lists, and in + `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit + edge signals, and several edges without an asynchronous reset. - Combinational processes: nonblocking assignments inside `always_comb` ([#453](https://github.com/celox-sim/celox/issues/453)). - Loops: a procedural loop unrolls at most 10,000 iterations; a combinational diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f4a3e96b0a5..ee9a7dc32b9 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -60,7 +60,11 @@ outline: [2, 3] 文にはタイミング制御とノンブロッキング代入を含められません。エッジを持たないそれ以外の センシティビティリストを持つ `always` はプロセスとして実行します。`always @(a) y = a + b;` は `b` だけが変化しても `y` を更新しません。`always @*` として扱うと他の論理と組み合わせループを作るリストも -プロセスとして実行します。`Simulator` はプロセスを実行しないため、このようなデザインでは +プロセスとして実行します。フリップフロップの形をしていないエッジ駆動の `always` も同様です。 +選択や式のエッジ(`@(posedge v[0])`、`@(posedge (a & b))`)、`edge`、エッジと並んだエッジなしの項目、 +複数ビットのエッジ信号(最下位ビットでエッジを判定)、本体がどれも非同期リセットとして判定しない +複数のエッジを持つものがこれに当たります。この形でなければならないのは `always_ff` だけです。 +`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗します。`Simulation` を使うか、 `always @*` / `always_comb` で記述してください。 @@ -135,10 +139,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 -- 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ - オペランド([#464](https://github.com/celox-sim/celox/issues/464))。このようなエッジ、複数ビットのエッジ信号、リセットを持たない - 複数のエッジを持つ通常の `always` も、プロセスとして実行できるようになるまで拒否します - ([#1708](https://github.com/celox-sim/celox/issues/1708))。 +- 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での + 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 + 非同期リセットを持たない複数のエッジ。 - 組み合わせ回路のプロセス:`always_comb` 内のノンブロッキング代入([#453](https://github.com/celox-sim/celox/issues/453))。 - ループ:手続き的なループの展開は 10,000 回までです。反復回数が実行時に決まる組み合わせ 回路のループは、カウンタ形式の `for` である必要があります。loop-generate は 10,000 回を From d8d628e65550d60570f34500f4dc7c64a9966a1d Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 6/6] test(sv): expect sv-tests event_control_edge to pass Change-Id: Ic07f6d1941094224ee0e090dc8381f0a424f3198 --- conformance/sv-tests/expected.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 6e2efb757e4..535226b7930 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1607,8 +1607,8 @@ chapter-9/9.4.1--delay_control-two-blocks-sim.sv 2state pass chapter-9/9.4.1--delay_control-two-blocks-sim.sv 4state pass chapter-9/9.4.1--delay_control.sv 2state pass chapter-9/9.4.1--delay_control.sv 4state pass -chapter-9/9.4.2--event_control_edge.sv 2state fail -chapter-9/9.4.2--event_control_edge.sv 4state fail +chapter-9/9.4.2--event_control_edge.sv 2state pass +chapter-9/9.4.2--event_control_edge.sv 4state pass chapter-9/9.4.2--event_control_negedge.sv 2state pass chapter-9/9.4.2--event_control_negedge.sv 4state pass chapter-9/9.4.2--event_control_posedge.sv 2state pass