From cd1cf40c44b235ffe6d66e7af25d853ad25eb2fa Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 06:19:25 +0900 Subject: [PATCH 1/6] fix(sim): list only named events An event domain whose variable no path names, such as a hidden copy of a clock, has no name to list in named_events, as named_signals, the hierarchy, and VCD descriptions already omit such variables. --- crates/celox/src/simulator.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 8c7393b161a..268dc93252b 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1803,6 +1803,11 @@ mod host { pub fn named_events(&self) -> Vec> { let mut result = Vec::new(); for (id, addr) in self.backend.id_to_addr_slice().iter().enumerate() { + // A hidden event, such as the copy of a clock sensed at its + // other edge, has no name to list. + if !self.event_is_named(addr) { + continue; + } let name = self.program.get_path(addr); if let Some(ev) = self.backend.resolve_event_opt(addr) { result.push(NamedEvent { @@ -1815,6 +1820,19 @@ mod host { result } + /// Whether the event at `addr` is a variable a path names. + fn event_is_named(&self, addr: &crate::ir::AbsoluteAddr) -> bool { + self.program + .design + .instance(addr.instance_id) + .is_some_and(|instance| { + self.program + .design + .variable(addr) + .is_some_and(|variable| instance.resolves_path_to(&variable.path, *addr)) + }) + } + /// Triggers a clock/event by its numeric ID. /// /// # Errors From 3088b1ca52512a347fa8192040c2f6a2c04993d7 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 06:19:25 +0900 Subject: [PATCH 2/6] feat(sv): support both edges of one clock or reset A variable carries one domain kind, so always_ff processes sensing one signal at both edges, or as a clock and as an asynchronous reset, were rejected. The frontend now senses the signal on itself at one kind (rising clock first) and at every other kind on a hidden one-bit whole-variable copy, which clock-domain unification keeps in the signal's domain when the edges agree and otherwise runs as a clock derived from the signal. Designs that sense one kind per signal are unchanged. Closes #443. Closes #471. --- crates/celox-frontend-sv/src/lowering.rs | 278 +++++++----- .../src/lowering/procedural.rs | 35 ++ crates/celox-sv-analyzer/src/lib.rs | 2 - crates/celox/tests/both_clock_edges.rs | 395 ++++++++++++++++++ .../systemverilog/review_regressions.rs | 117 ++++-- docs/guide/systemverilog.md | 5 +- docs/ja/guide/systemverilog.md | 5 +- 7 files changed, 686 insertions(+), 151 deletions(-) create mode 100644 crates/celox/tests/both_clock_edges.rs diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0ca7bcdd834..2cdca5a2933 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -105,6 +105,8 @@ pub(crate) struct LoweredSvModule { pub instances: Vec, /// Variables that denote a package variable, with its package and name. package_variables: Vec<(SourceVarId, String, String)>, + /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. + event_copies: Vec<(SourceVarId, SourceVarId)>, } #[derive(Clone)] @@ -1242,6 +1244,8 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( parameter_types: HashMap::default(), instances: Vec::new(), package_variables: Vec::new(), + // The foreign module's own combinational blocks carry its copies. + event_copies: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -1941,6 +1945,7 @@ fn lower_module_with_overrides( eval_apply_ff_blocks, reset_clock_map, parallel_ff_parts, + event_vars, ), mut runtime_event_sites, mut runtime_errors, @@ -1962,7 +1967,7 @@ fn lower_module_with_overrides( std::mem::take(&mut pm.extern_functions), ) }; - mark_ff_event_domains(module, &mut variables, &name_to_id); + mark_ff_event_domains(&event_vars, &mut variables); let (initial_values, processes) = lower_initial_processes( module, &mut variables, @@ -2075,44 +2080,22 @@ fn lower_module_with_overrides( parameter_types, instances, package_variables, + event_copies: event_vars.copies, }) } fn mark_ff_event_domains( - module: &sv::ir::Module, + event_vars: &FfEventVars, variables: &mut HashMap, - name_to_id: &HashMap, ) { - for process in module.ff_processes() { - let Some(clock) = clock_event_from_ff_process(process) else { - continue; - }; - if let Some(id) = name_to_id.get(clock.signal()).copied() - && let Some(variable) = variables.get_mut(&id) - { - variable.domain_kind = match clock.edge() { - sv::ir::FfEdge::Pos => DomainKind::ClockPosedge, - sv::ir::FfEdge::Neg => DomainKind::ClockNegedge, + for (id, kind) in event_vars.kinds() { + if let Some(variable) = variables.get_mut(&id) { + variable.domain_kind = kind; + variable.type_kind = match kind { + DomainKind::ResetAsyncHigh => PortTypeKind::ResetAsyncHigh, + DomainKind::ResetAsyncLow => PortTypeKind::ResetAsyncLow, + _ => PortTypeKind::Clock, }; - variable.type_kind = PortTypeKind::Clock; - } - for event in process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - { - if let Some(id) = name_to_id.get(event.signal()).copied() - && let Some(variable) = variables.get_mut(&id) - { - variable.domain_kind = match event.edge() { - sv::ir::FfEdge::Pos => DomainKind::ResetAsyncHigh, - sv::ir::FfEdge::Neg => DomainKind::ResetAsyncLow, - }; - variable.type_kind = match event.edge() { - sv::ir::FfEdge::Pos => PortTypeKind::ResetAsyncHigh, - sv::ir::FfEdge::Neg => PortTypeKind::ResetAsyncLow, - }; - } } } } @@ -2438,6 +2421,8 @@ pub(crate) fn attach_instance_glue( 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); module.comb_blocks = comb_blocks; module.arena = arena; @@ -2964,6 +2949,46 @@ fn lower_comb_processes( Ok((comb_blocks, arena, created, observers, sites)) } +/// The continuous assignments `copy = signal` of the hidden event copies of +/// [`FfEventVars`]: a whole-variable copy, which clock-domain unification +/// keeps in the signal's domain unless the copy is sensed at the other edge. +fn push_event_copies( + copies: &[(SourceVarId, SourceVarId)], + comb_blocks: &mut Vec>, + arena: &mut SLTNodeArena, +) -> Result<(), ParserError> { + for &(copy, signal) in copies { + let access = BitAccess::new(0, 0); + let expr = arena + .alloc(SLTNode::Input { + variable: signal, + signed: false, + index: Vec::new(), + access, + }) + .map_err(|error| { + ParserError::illegal_context( + "systemverilog always_ff event copy", + error.to_string(), + None, + ) + })?; + comb_blocks.push(LogicPath { + target: LogicPathTarget::Var(VarAtomBase::new(copy, 0, 0)), + sources: std::iter::once(VarAtomBase::new(signal, 0, 0)).collect(), + previous_sources: HashSet::default(), + address_sources: HashSet::default(), + local_inputs: Vec::new(), + order_before: HashSet::default(), + comb_capture_enable_sites: Vec::new(), + comb_capture_enable_always: false, + pre_lower_nodes: Vec::new(), + expr, + }); + } + Ok(()) +} + /// The bit boundaries at which combinational processes write or statically /// read each variable. Flattening splits paths at these boundaries (and at /// those propagated through ports), so bit-disjoint dependencies on one @@ -6176,8 +6201,89 @@ type SvFfBlocks = ( TriggerSet, Vec>, >, + FfEventVars, ); +/// The variables `always_ff` event controls are sensed on. +/// +/// A variable carries one domain kind, the edge and role of its event, so a +/// signal is sensed on itself at one edge and role, and at any other on a +/// hidden copy of the signal: `negedge clk` beside `posedge clk`, or +/// `posedge rst` as a clock beside `negedge rst` as an asynchronous reset. +/// Each copy is a whole-variable continuous assignment of the signal, so it +/// changes in the same time step as the signal and is a clock derived from +/// it; only domains sensed on a copy pay for it. +/// +/// The signal itself keeps the first of rising clock, falling clock, active +/// high reset, active low reset that it is sensed as, independent of the +/// order of the processes: a clock port stays in the domain of the rising +/// clock that drives it, and `Simulator::tick` of the signal is its rising +/// edge whenever a process uses that. +#[derive(Clone, Default)] +pub(crate) struct FfEventVars { + /// Per signal, the domain kinds it is sensed at and their variables. + sensed: HashMap>, + /// The `(copy, signal)` pairs of the hidden copies, in creation order. + copies: Vec<(SourceVarId, SourceVarId)>, +} + +impl FfEventVars { + /// Sense each signal of `events` on itself at its first kind in + /// priority order. + fn new(events: impl Iterator) -> Self { + let priority = |kind: DomainKind| match kind { + DomainKind::ClockPosedge => 0, + DomainKind::ClockNegedge => 1, + DomainKind::ResetAsyncHigh => 2, + DomainKind::ResetAsyncLow => 3, + DomainKind::Other => 4, + }; + let mut primary = HashMap::::default(); + for (signal, kind) in events { + primary + .entry(signal) + .and_modify(|primary| { + if priority(kind) < priority(*primary) { + *primary = kind; + } + }) + .or_insert(kind); + } + Self { + sensed: primary + .into_iter() + .map(|(signal, kind)| (signal, vec![(kind, signal)])) + .collect(), + copies: Vec::new(), + } + } + + /// The variable on which `signal` is sensed as `kind`. + fn sensed( + &mut self, + pm: &mut procedural::ProcModule<'_>, + signal: SourceVarId, + kind: DomainKind, + ) -> SourceVarId { + let sensed = self.sensed.entry(signal).or_default(); + if let Some(&(_, var)) = sensed.iter().find(|(sensed_kind, _)| *sensed_kind == kind) { + return var; + } + let copy = pm.event_copy(signal, kind); + self.copies.push((copy, signal)); + sensed.push((kind, copy)); + copy + } + + /// Every sensed variable with its domain kind. + fn kinds(&self) -> impl Iterator + '_ { + self.sensed + .values() + .flatten() + .map(|&(kind, var)| (var, kind)) + } +} + fn lower_ff_processes( module: &sv::ir::Module, pm: &mut procedural::ProcModule<'_>, @@ -6188,71 +6294,58 @@ fn lower_ff_processes( let mut apply_ff_blocks = HashMap::default(); let mut eval_apply_ff_blocks = HashMap::default(); let mut reset_clock_map = HashMap::default(); - let mut clock_edges = HashMap::default(); - let mut reset_edges = HashMap::default(); - let random_seeds = process_random_seeds(module); - for (index, process) in module.ff_processes().iter().enumerate() { + // Every event of every process, as (signal, domain kind): the clock, then + // the resets. + let mut process_events = Vec::new(); + for process in module.ff_processes() { let clock = clock_event_from_ff_process(process) .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; - let clock_id = pm - .id(clock.signal()) - .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; - if pm - .variables - .get(&clock_id) - .is_some_and(|variable| variable.width != 1) - { - return Err(sv::AnalyzerError::Unsupported( - "multi-bit always_ff event signal".to_string(), - )); - } - if reset_edges.contains_key(&clock_id) { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock/reset-edge polarities for one signal".to_string(), - )); - } - if clock_edges - .insert(clock_id, clock.edge()) - .is_some_and(|edge| edge != clock.edge()) - { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock-edge polarities for one signal".to_string(), - )); - } - for reset in process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - { - let reset_id = pm.id(reset.signal()).ok_or_else(|| { + let event_id = |event: &sv::ir::FfEvent| { + let id = pm.id(event.signal()).ok_or_else(|| { sv::AnalyzerError::Unsupported("always_ff event control".to_string()) })?; if pm .variables - .get(&reset_id) + .get(&id) .is_some_and(|variable| variable.width != 1) { return Err(sv::AnalyzerError::Unsupported( "multi-bit always_ff event signal".to_string(), )); } - if clock_edges.contains_key(&reset_id) { - return Err(sv::AnalyzerError::Unsupported( - "mixed clock/reset-edge polarities for one signal".to_string(), - )); - } - if reset_edges - .insert(reset_id, reset.edge()) - .is_some_and(|edge| edge != reset.edge()) - { - return Err(sv::AnalyzerError::Unsupported( - "mixed reset-edge polarities for one signal".to_string(), - )); - } + Ok(id) + }; + let clock_kind = match clock.edge() { + sv::ir::FfEdge::Pos => DomainKind::ClockPosedge, + sv::ir::FfEdge::Neg => DomainKind::ClockNegedge, + }; + let mut events = vec![(event_id(clock)?, clock_kind)]; + for reset in process + .events() + .iter() + .filter(|event| event.signal() != clock.signal()) + { + let reset_kind = match reset.edge() { + sv::ir::FfEdge::Pos => DomainKind::ResetAsyncHigh, + sv::ir::FfEdge::Neg => DomainKind::ResetAsyncLow, + }; + events.push((event_id(reset)?, reset_kind)); } - let trigger_set = trigger_set_from_ff_process(process, pm.name_to_id) - .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; + process_events.push(events); + } + let mut event_vars = FfEventVars::new(process_events.iter().flatten().copied()); + + let random_seeds = process_random_seeds(module); + for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { + let mut events = events + .into_iter() + .map(|(signal, kind)| event_vars.sensed(pm, signal, kind)); + let mut trigger_set = TriggerSet { + clock: events.next().expect("a process has a clock event"), + resets: Vec::new(), + }; + trigger_set.resets.extend(events); // A reset shared by several clock domains is associated with the // first; the association only names a clock for the reset signal. for reset in &trigger_set.resets { @@ -6299,6 +6392,7 @@ fn lower_ff_processes( eval_apply_ff_blocks, reset_clock_map, parallel_ff_parts, + event_vars, )) } @@ -6383,24 +6477,6 @@ fn expr_uses_ident_as_condition(expr: &sv::ir::Expr, name: &str) -> bool { } } -fn trigger_set_from_ff_process( - process: &sv::ir::FfProcess, - name_to_id: &HashMap, -) -> Option> { - let clock = clock_event_from_ff_process(process)?; - let clock_id = *name_to_id.get(clock.signal())?; - let resets = process - .events() - .iter() - .filter(|event| event.signal() != clock.signal()) - .filter_map(|event| name_to_id.get(event.signal()).copied()) - .collect(); - Some(TriggerSet { - clock: clock_id, - resets, - }) -} - fn seal_builder(mut builder: SIRBuilder) -> ExecutionUnit { builder.seal_block(SIRTerminator::Return); let (blocks, register_map, _) = builder.drain(); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 43f1660a05b..042f0064461 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -514,6 +514,41 @@ impl<'a> ProcModule<'a> { (id, name) } + /// A hidden one-bit copy of the event signal `signal`, sensed as `kind`. + /// It has no name a SystemVerilog identifier can denote, and is not + /// addressable by path. + pub fn event_copy(&mut self, signal: SourceVarId, kind: DomainKind) -> SourceVarId { + let source = &self.variables[&signal]; + let suffix = match kind { + DomainKind::ClockPosedge => "posedge", + DomainKind::ClockNegedge => "negedge", + DomainKind::ResetAsyncHigh => "reset_high", + DomainKind::ResetAsyncLow => "reset_low", + DomainKind::Other => "event", + }; + let mut path = source.path.clone(); + if let Some(last) = path.last_mut() { + last.push('@'); + last.push_str(suffix); + } + let variable = SvVariable { + path, + width: 1, + signed: false, + is_4state: source.is_4state, + packed_ranges: vec![(0, 0)], + array_dims: Vec::new(), + domain_kind: kind, + kind: VariableKind::Variable, + type_kind: source.type_kind, + source: None, + hidden: true, + }; + let id = next_var_id(&mut self.next_id); + self.variables.insert(id, variable); + id + } + pub fn subroutine(&self, name: &str) -> Option<&sv::ir::Subroutine> { self.subroutines.get(name) } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index b2bc2c7a56c..67765df9e85 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -137,7 +137,6 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ 440, ), ("wildcard port connection", 442), - ("mixed clock-edge polarities for one signal", 443), ("delayed continuous assignment", 444), ("duplicate internal signal", 445), ("streaming concatenation", 447), @@ -150,7 +149,6 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("undriven net declaration", 460), ("non-integer module parameter override", 461), ("always_ff event expression", 464), - ("mixed reset-edge polarities for one signal", 471), ("package net", 1146), ]; diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs new file mode 100644 index 00000000000..2e14eda8b01 --- /dev/null +++ b/crates/celox/tests/both_clock_edges.rs @@ -0,0 +1,395 @@ +//! `always_ff` processes sensed at both edges of one signal (#443). +//! +//! A signal carries one domain kind, so the frontend senses every further +//! edge or role of a signal on a hidden whole-variable copy of it, which runs +//! as a clock derived from the signal. These tests drive the timed +//! `Simulation` and check that each process runs at the edges IEEE 1800-2023 +//! 9.4.2 defines, evaluating against the state before the edge (4.4.2, +//! 10.4.2), and that the copy is invisible. +//! +//! Event-based `Simulator` tests with explicit edges belong here too, once the +//! `Simulator` can drive a falling edge: a `tick` is the rising edge only and +//! does not run falling-edge domains. + +#![cfg(feature = "systemverilog")] + +use celox::{BigUint, OptLevel, Simulation}; + +fn build(source: &str, four_state: bool) -> Simulation { + build_with(source, four_state, OptLevel::O1) +} + +fn build_with(source: &str, four_state: bool, opt_level: OptLevel) -> Simulation { + let path = std::path::Path::new("both_clock_edges.sv"); + Simulation::from_sv_sources(vec![(source, path)], "Top") + .four_state(four_state) + .opt_level(opt_level) + .build() + .unwrap() +} + +fn get(sim: &mut Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() +} + +/// Pulses `rst` high at time 0 with `clk` low, then applies `cycles` clock +/// periods of 10 (rising at 10, 20, ...; falling 5 later) and returns the +/// values of `outputs` after every edge, rising edge first. +fn run(sim: &mut Simulation, cycles: u64, outputs: &[&str]) -> Vec> { + sim.schedule("clk", 0, 0).unwrap(); + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + let mut observed = Vec::new(); + for cycle in 0..cycles { + for (offset, level) in [(10, 1), (15, 0)] { + sim.schedule("clk", cycle * 10 + offset, level).unwrap(); + sim.step().unwrap(); + observed.push(outputs.iter().map(|name| get(sim, name)).collect()); + } + } + observed +} + +/// `rise` and `fall` count the edges of `clk`; `at_fall` samples `rise` at +/// each falling edge and `at_rise` samples `fall` at each rising edge. +fn expected_counters(cycles: u64) -> Vec> { + (1..=cycles) + .flat_map(|k| [vec![k, k - 1, k - 1, k - 1], vec![k, k, k, k - 1]]) + .collect() +} + +const COUNTERS: [&str; 4] = ["rise", "fall", "at_fall", "at_rise"]; + +fn counters_source(negedge_first: bool) -> String { + let rise = "always_ff @(posedge clk or posedge rst) + if (rst) begin rise <= 0; at_rise <= 0; end + else begin rise <= rise + 1; at_rise <= fall; end"; + let fall = "always_ff @(negedge clk or posedge rst) + if (rst) begin fall <= 0; at_fall <= 0; end + else begin fall <= fall + 1; at_fall <= rise; end"; + let (first, second) = if negedge_first { + (fall, rise) + } else { + (rise, fall) + }; + format!( + "module Top(input logic clk, input logic rst, + output logic [7:0] rise, output logic [7:0] fall, + output logic [7:0] at_fall, output logic [7:0] at_rise); + {first} + {second} + endmodule" + ) +} + +#[test] +fn processes_at_both_edges_of_one_clock() { + for negedge_first in [false, true] { + for four_state in [false, true] { + for opt_level in [OptLevel::O0, OptLevel::O1, OptLevel::O2] { + let mut sim = build_with(&counters_source(negedge_first), four_state, opt_level); + assert_eq!( + run(&mut sim, 4, &COUNTERS), + expected_counters(4), + "negedge first: {negedge_first}, four-state: {four_state}, {opt_level:?}" + ); + } + } + } +} + +/// A child module senses both edges of its clock port, the falling edge in +/// its first process. The child's rising-edge register `c` samples the +/// parent's register `p` before the parent's rising edge commits, and the +/// falling edge runs on its own. +#[test] +fn both_edges_of_a_child_clock_port() { + let source = "module Child(input logic clk, input logic rst, input logic [7:0] p, + output logic [7:0] c, output logic [7:0] f); + always_ff @(negedge clk or posedge rst) if (rst) f <= 0; else f <= f + 1; + always_ff @(posedge clk or posedge rst) if (rst) c <= 0; else c <= p; + endmodule + module Top(input logic clk, input logic rst, + output logic [7:0] p, output logic [7:0] c, output logic [7:0] f); + always_ff @(posedge clk or posedge rst) if (rst) p <= 0; else p <= p + 1; + Child u(.clk(clk), .rst(rst), .p(p), .c(c), .f(f)); + endmodule"; + let expected: Vec> = (1..=4) + .flat_map(|k| [vec![k, k - 1, k - 1], vec![k, k - 1, k]]) + .collect(); + for four_state in [false, true] { + let mut sim = build(source, four_state); + assert_eq!( + run(&mut sim, 4, &["p", "c", "f"]), + expected, + "four-state: {four_state}" + ); + } +} + +/// Both edges reached through whole-variable copies of `clk`, and both edges +/// of one copy. +#[test] +fn both_edges_through_clock_copies() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] rise, output logic [7:0] fall, + output logic [7:0] at_fall, output logic [7:0] at_rise); + logic c1, c2; + assign c1 = clk; + assign c2 = c1; + always_ff @(posedge c2 or posedge rst) if (rst) rise <= 0; else rise <= rise + 1; + always_ff @(negedge c2 or posedge rst) if (rst) fall <= 0; else fall <= fall + 1; + always_ff @(negedge c1 or posedge rst) if (rst) at_fall <= 0; else at_fall <= rise; + always_ff @(posedge clk or posedge rst) if (rst) at_rise <= 0; else at_rise <= fall; + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + assert_eq!( + run(&mut sim, 4, &COUNTERS), + expected_counters(4), + "four-state: {four_state}" + ); + } +} + +/// One asynchronous reset sensed active high by one process and active low by +/// another. +#[test] +fn a_reset_at_both_edges() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] high, output logic [7:0] low); + always_ff @(posedge clk or posedge rst) if (rst) high <= 0; else high <= high + 1; + always_ff @(posedge clk or negedge rst) if (!rst) low <= 0; else low <= low + 1; + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + let mut observed = Vec::new(); + let mut time = 0; + let mut edge = |sim: &mut Simulation, port: &str, level: u64| { + sim.schedule(port, time, level).unwrap(); + sim.step().unwrap(); + time += 5; + (get(sim, "high"), get(sim, "low")) + }; + // `rst` high clears `high`; its fall clears `low`. + edge(&mut sim, "clk", 0); + observed.push(edge(&mut sim, "rst", 1)); + for _ in 0..2 { + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + observed.push(edge(&mut sim, "rst", 0)); + for _ in 0..2 { + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + observed.push(edge(&mut sim, "rst", 1)); + observed.push(edge(&mut sim, "clk", 1)); + // Before `rst` first falls, `low` is unknown, and stays unknown when + // incremented. + let low = |count: u64| if four_state { 0xff } else { count }; + assert_eq!( + observed, + vec![ + (0, low(0)), + (0, low(1)), + (0, low(2)), + (0, 0), + (1, 0), + (2, 0), + (0, 0), + (0, 1), + ], + "four-state: {four_state}" + ); + } +} + +/// One signal as the asynchronous reset of one process and the clock of +/// others, at the same and at the opposite edge. +#[test] +fn a_signal_as_reset_and_as_clock() { + let source = "module Top(input logic clk, input logic rst, + output logic [7:0] cnt, output logic [7:0] rises, output logic [7:0] falls); + always_ff @(posedge clk or posedge rst) if (rst) cnt <= 0; else cnt <= cnt + 1; + always_ff @(posedge rst) rises <= rises + 1; + always_ff @(negedge rst) falls <= falls + 1; + initial begin rises = 0; falls = 0; end + endmodule"; + for four_state in [false, true] { + let mut sim = build(source, four_state); + let mut time = 0; + let mut edge = |sim: &mut Simulation, port: &str, level: u64| { + sim.schedule(port, time, level).unwrap(); + sim.step().unwrap(); + time += 5; + (get(sim, "cnt"), get(sim, "rises"), get(sim, "falls")) + }; + edge(&mut sim, "clk", 0); + // A four-state `rst` starts unknown, and its move to 0 is a negedge + // (IEEE 1800-2023 Table 9-2); a two-state one starts at 0. + let (_, _, initial_falls) = edge(&mut sim, "rst", 0); + assert_eq!( + initial_falls, + u64::from(four_state), + "four-state: {four_state}" + ); + let mut observed = Vec::new(); + for _ in 0..2 { + observed.push(edge(&mut sim, "rst", 1)); + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + observed.push(edge(&mut sim, "rst", 0)); + observed.push(edge(&mut sim, "clk", 1)); + edge(&mut sim, "clk", 0); + } + let f = initial_falls; + assert_eq!( + observed, + vec![ + (0, 1, f), + (0, 1, f), + (0, 1, f + 1), + (1, 1, f + 1), + (0, 2, f + 1), + (0, 2, f + 1), + (0, 2, f + 2), + (1, 2, f + 2), + ], + "four-state: {four_state}" + ); + } +} + +/// Drives `d` through `levels` (value, unknown mask) and pulses `clk` after +/// each, so that the register `q` takes each level in turn, starting from +/// unknown. Returns the outputs `pos` and `neg` after each level. +fn register_edges(source: &str, levels: &[(u8, u8)]) -> Vec<(u64, u64)> { + let mut sim = build(source, true); + let d = sim.signal("d"); + sim.schedule("clk", 0, 0).unwrap(); + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + let mut time = 10; + let mut observed = Vec::new(); + for &(value, mask) in levels { + sim.modify(|io| io.set_four_state(d, BigUint::from(value), BigUint::from(mask))) + .unwrap(); + sim.schedule("clk", time, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("clk", time + 5, 0).unwrap(); + sim.step().unwrap(); + time += 10; + observed.push((get(&mut sim, "pos"), get(&mut sim, "neg"))); + } + observed +} + +fn register_source(posedge: bool, negedge: bool) -> String { + let pos = if posedge { + "always_ff @(posedge q or posedge rst) if (rst) pos <= 0; else pos <= pos + 1;" + } else { + "assign pos = 0;" + }; + let neg = if negedge { + "always_ff @(negedge q or posedge rst) if (rst) neg <= 0; else neg <= neg + 1;" + } else { + "assign neg = 0;" + }; + format!( + "module Top(input logic clk, input logic rst, input logic d, + output logic [7:0] pos, output logic [7:0] neg); + logic q; + always_ff @(posedge clk) q <= d; + {pos} + {neg} + endmodule" + ) +} + +const LOW: (u8, u8) = (0, 0); +const HIGH: (u8, u8) = (1, 0); +const X: (u8, u8) = (1, 1); +const Z: (u8, u8) = (0, 1); + +/// Both edges of a register that takes unknown and high-impedance values. +#[test] +fn both_edges_of_a_register_through_unknown_values() { + // `q` starts unknown. + let levels = [LOW, HIGH, LOW, X, LOW]; + assert_eq!( + register_edges(®ister_source(true, true), &levels), + vec![ + (0, 1), // x -> 0: negedge + (1, 1), // 0 -> 1: posedge + (1, 2), // 1 -> 0: negedge + (2, 2), // 0 -> x: posedge + (2, 3), // x -> 0: negedge + ] + ); + // Through every transition between 0, 1, x, and z, each process runs + // exactly when it runs in a design that senses only its edge of `q`. + let levels = [HIGH, X, HIGH, Z, HIGH, LOW, Z, LOW, X, Z, X, LOW, HIGH]; + let both = register_edges(®ister_source(true, true), &levels); + let pos = register_edges(®ister_source(true, false), &levels); + let neg = register_edges(®ister_source(false, true), &levels); + assert_eq!( + both, + pos.iter() + .zip(&neg) + .map(|(&(pos, _), &(_, neg))| (pos, neg)) + .collect::>() + ); +} + +/// The hidden copy is no signal, event, or trace variable of the design. +#[test] +fn the_edge_copy_is_hidden() { + let dir = tempfile::tempdir().unwrap(); + let vcd = dir.path().join("wave.vcd"); + let path = std::path::Path::new("both_clock_edges.sv"); + let source = counters_source(false); + let mut sim = Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top") + .vcd(&vcd) + .build() + .unwrap(); + let names: Vec<_> = sim + .named_signals() + .into_iter() + .map(|signal| signal.name) + .collect(); + assert!(names.iter().all(|name| !name.contains('@')), "{names:?}"); + assert!(names.iter().any(|name| name == "clk"), "{names:?}"); + let events: Vec<_> = sim + .named_events() + .into_iter() + .map(|event| event.name) + .collect(); + assert_eq!( + events.iter().filter(|name| name.contains("clk")).count(), + 1, + "{events:?}" + ); + assert!(events.iter().all(|name| !name.contains('@')), "{events:?}"); + let hierarchy = sim.named_hierarchy(); + assert!( + hierarchy + .signals + .iter() + .all(|signal| !signal.name.contains('@')), + "hierarchy lists a hidden copy" + ); + run(&mut sim, 2, &COUNTERS); + sim.dump(100); + sim.flush_vcd().unwrap(); + let wave = std::fs::read_to_string(&vcd).unwrap(); + assert!(!wave.contains('@'), "{wave}"); + assert!(wave.contains(" clk "), "{wave}"); + let addr = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sim.signal("clk@negedge"))); + assert!(addr.is_err(), "the copy resolves by name"); +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 53159dee475..437920ea798 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5486,15 +5486,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { module Top(input logic a, output wire y); assign #5 y = a; endmodule "#, ), - ( - "mixed clock-edge polarities for one signal", - r#" - module Top(input logic clk, a, b, output logic qa, qb); - always_ff @(posedge clk) qa <= a; - always_ff @(negedge clk) qb <= b; - endmodule - "#, - ), ( "streaming concatenation", r#" @@ -5732,39 +5723,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "mixed reset-edge polarities for one signal", - r#" - module Top(input logic clk1, clk2, rst, d, output logic q1, q2); - always_ff @(posedge clk1 or posedge rst) - if (rst) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or negedge rst) - if (!rst) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), - ( - "mixed clock/reset-edge polarities for one signal", - r#" - module Top(input logic sig, clk2, rst2, d, output logic q1, q2); - always_ff @(posedge sig or posedge rst2) - if (rst2) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or negedge sig) - if (!sig) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), - ( - "mixed clock/reset-edge polarities for one signal", - r#" - module Top(input logic sig, clk2, rst2, d, output logic q1, q2); - always_ff @(posedge sig or posedge rst2) - if (rst2) q1 <= 1'b0; else q1 <= d; - always_ff @(posedge clk2 or posedge sig) - if (sig) q2 <= 1'b0; else q2 <= d; - endmodule - "#, - ), ( "unsupported function formal data type", r#" @@ -8493,3 +8451,78 @@ fn commits_ff_output_actuals_whose_index_calls_a_function() { assert_eq!(sim.get_as::(bits), 4); } } + +/// The designs once rejected for sensing one signal at two edges or in two +/// roles (#443, #471) run each process at its own edge. +#[test] +fn runs_processes_sensing_one_signal_at_two_edges_or_roles() { + const BOTH_EDGES: &str = "module Top(input logic clk, a, b, output logic qa, qb); + always_ff @(posedge clk) qa <= a; + always_ff @(negedge clk) qb <= b; + endmodule"; + // The source, its data inputs (driven to 1), the scheduled event levels in + // order, and the outputs with their values afterwards. + type Case<'a> = ( + &'a str, + &'a [&'a str], + &'a [(&'a str, u64)], + [(&'a str, u64); 2], + ); + let cases: [Case; 4] = [ + ( + BOTH_EDGES, + &["a", "b"], + &[("clk", 1)], + [("qa", 1), ("qb", 0)], + ), + ( + BOTH_EDGES, + &["a", "b"], + &[("clk", 1), ("clk", 0)], + [("qa", 1), ("qb", 1)], + ), + ( + "module Top(input logic clk1, clk2, rst, d, output logic q1, q2); + always_ff @(posedge clk1 or posedge rst) + if (rst) q1 <= 1'b0; else q1 <= d; + always_ff @(posedge clk2 or negedge rst) + if (!rst) q2 <= 1'b0; else q2 <= d; + endmodule", + &["d"], + // `q2` loads at `clk2` while `rst` is high, then `rst` falls; + // `q1` loads at `clk1` once `rst` is low. + &[("rst", 1), ("clk2", 1), ("rst", 0), ("clk1", 1)], + [("q1", 1), ("q2", 0)], + ), + ( + "module Top(input logic sig, clk2, rst2, d, output logic q1, q2); + always_ff @(posedge sig or posedge rst2) + if (rst2) q1 <= 1'b0; else q1 <= d; + always_ff @(posedge clk2 or negedge sig) + if (!sig) q2 <= 1'b0; else q2 <= d; + endmodule", + &["d"], + &[("sig", 1), ("clk2", 1), ("sig", 0)], + [("q1", 1), ("q2", 0)], + ), + ]; + for (source, inputs, stimulus, expected) in cases { + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("both_edges.sv"))], "Top") + .build() + .unwrap(); + for input in inputs { + let signal = sim.signal(input); + sim.modify(|io| io.set(signal, 1u8)).unwrap(); + } + for (index, &(port, level)) in stimulus.iter().enumerate() { + sim.schedule(port, index as u64 * 10 + 10, level).unwrap(); + sim.step().unwrap(); + } + let observed = expected.map(|(name, _)| { + let signal = sim.signal(name); + (name, u64::try_from(sim.get(signal)).unwrap()) + }); + assert_eq!(observed, expected, "{source}"); + } +} diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 23af8333ba1..4a1702b0063 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -76,7 +76,7 @@ synthesis and is tested at the design level. | Interfaces | interfaces with parameters, `localparam`s, `typedef`s, variables and nets, logic (`assign`, `always_comb`, `always_ff`, generate) and functions; interface instances and instance arrays, also inside generate blocks; interface ports with or without a modport, generic `interface` and `interface.mp` ports, and arrays of interface ports; modport `input` / `output` members and imported functions; access to members, parameters and functions through an instance or port (`h[i].m`, `h.P`, `h.f(...)`) | | Continuous logic | `assign`, `wire w = expr;` | | Combinational processes | `always_comb`, `always @*`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | -| Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains | +| Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | | Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate assertions | | Functions | `function` and `task` (without timing) with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | @@ -136,8 +136,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: descending ([#438](https://github.com/celox-sim/celox/issues/438)), internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs, strings 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, and both edges of one clock ([#443](https://github.com/celox-sim/celox/issues/443)) or one - reset ([#471](https://github.com/celox-sim/celox/issues/471)) across processes. + plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. - 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.md b/docs/ja/guide/systemverilog.md index f564c966a54..dc176b63d4a 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -62,7 +62,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | -| 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット | +| 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | | initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しない) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、タイミング制御のない `task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | @@ -102,8 +102,7 @@ package・interface の手続きは宣言元の時間単位と精度を保持し - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、0 起点の降順でない 多次元 packed 範囲([#438](https://github.com/celox-sim/celox/issues/438))、ドライバを持たない内部ネット([#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))、プロセスをまたいだ同一クロック([#443](https://github.com/celox-sim/celox/issues/443))・同一リセット - ([#471](https://github.com/celox-sim/celox/issues/471))の両エッジの使用。 + オペランド([#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 71d27b74c64488315f92a26a858130c77fbbc492 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 06:31:17 +0900 Subject: [PATCH 3/6] test(sv): cover always_ff at both edges in the shared suite Both edges of a divided clock, of a child clock port, and one register as an asynchronous reset at both edges and as a clock at both edges. Verified against Verilator and Icarus with no mismatches. --- .../src/sv/cases/procedural.vtest | 91 +++++++++++++++++++ .../frontends/systemverilog/procedural.rs | 12 +++ 2 files changed, 103 insertions(+) diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index e4bbab47695..c7817aab5be 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -517,3 +517,94 @@ (assert_eq known 0xa) (assert_eq partial (fourstate 0xd 0x5)) (assert_eq unset (fourstate 0xf 0xf))) + +; Processes at the rising and the falling edge of one clock, here a divided +; clock `q`, each evaluate against the state before their edge +; (IEEE 1800-2023 9.4.2, 10.4.2). +(case always_ff_at_both_edges_of_one_clock + (source "both_edges.sv" #" + module Top(input logic clk, output logic [7:0] rise, fall, at_rise, at_fall); + logic q = 1'b0; + logic [7:0] r = 8'd0, f = 8'd0, ar = 8'd0, af = 8'd0; + always_ff @(posedge clk) q <= ~q; + always_ff @(negedge q) begin f <= f + 8'd1; af <= r; end + always_ff @(posedge q) begin r <= r + 8'd1; ar <= f; end + assign rise = r; + assign fall = f; + assign at_rise = ar; + assign at_fall = af; + endmodule + "#) + (top Top) + (for k (list 1 2 3) + (tick clk) + (assert_eq rise k) + (assert_eq fall (- k 1)) + (assert_eq at_rise (- k 1)) + (tick clk) + (assert_eq fall k) + (assert_eq at_fall k))) + +; A child senses both edges of its clock port; its rising-edge register +; samples the parent's before the parent's rising edge commits. +(case always_ff_at_both_edges_of_a_child_clock_port + (source "both_edges_child.sv" #" + module Child(input logic c, input logic [7:0] p, + output logic [7:0] sampled, falls); + logic [7:0] s = 8'd0, f = 8'd0; + always_ff @(negedge c) f <= f + 8'd1; + always_ff @(posedge c) s <= p; + assign sampled = s; + assign falls = f; + endmodule + module Top(input logic clk, output logic [7:0] parent, sampled, falls); + logic q = 1'b0; + logic [7:0] p = 8'd0; + always_ff @(posedge clk) q <= ~q; + always_ff @(posedge q) p <= p + 8'd1; + Child u(.c(q), .p(p), .sampled(sampled), .falls(falls)); + assign parent = p; + endmodule + "#) + (top Top) + (for k (list 1 2 3) + (tick clk) + (assert_eq parent k) + (assert_eq sampled (- k 1)) + (assert_eq falls (- k 1)) + (tick clk) + (assert_eq falls k))) + +; One asynchronous reset `r` sensed active high and active low, and also as a +; clock at both edges. +(case always_ff_reset_at_both_edges_and_as_a_clock + (source "both_edges_reset.sv" #" + module Top(input logic clk, d, output logic [7:0] high, low, rises, falls); + logic r = 1'b0; + logic [7:0] h = 8'd0, l = 8'd0, ri = 8'd0, fa = 8'd0; + always_ff @(posedge clk) r <= d; + always_ff @(posedge clk or posedge r) if (r) h <= 8'd0; else h <= h + 8'd1; + always_ff @(posedge clk or negedge r) if (!r) l <= 8'd0; else l <= l + 8'd1; + always_ff @(posedge r) ri <= ri + 8'd1; + always_ff @(negedge r) fa <= fa + 8'd1; + assign high = h; + assign low = l; + assign rises = ri; + assign falls = fa; + endmodule + "#) + (top Top) + (for (value h l ri fa) + (list + (0 1 0 0 0) + (1 0 0 1 0) + (1 0 1 1 0) + (1 0 2 1 0) + (0 0 0 1 1) + (0 1 0 1 1)) + (modify (set d value)) + (tick clk) + (assert_eq high h) + (assert_eq low l) + (assert_eq rises ri) + (assert_eq falls fa))) diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index f74e969ba81..bf0318df3a6 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -70,4 +70,16 @@ sv_backends! { fn declaration_initializers_keep_unknown_bits(sim) { @case "procedural::declaration_initializers_keep_unknown_bits"; } + + fn always_ff_at_both_edges_of_one_clock(sim) { + @case "procedural::always_ff_at_both_edges_of_one_clock"; + } + + fn always_ff_at_both_edges_of_a_child_clock_port(sim) { + @case "procedural::always_ff_at_both_edges_of_a_child_clock_port"; + } + + fn always_ff_reset_at_both_edges_and_as_a_clock(sim) { + @case "procedural::always_ff_reset_at_both_edges_and_as_a_clock"; + } } From 346fa153fe62af625435e22fb7a7d16df99acb17 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 07:32:39 +0900 Subject: [PATCH 4/6] test(sim): benchmark SystemVerilog counters at both clock edges Simulation::step of counters at the rising edge only, half at each edge of one clock, and half at the falling edge of a whole copy of the clock. --- crates/celox/benches/overhead.rs | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 07e553f1b28..2dfcaf89806 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -107,6 +107,55 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { }) }); } + + // Benchmark 3: Simulation::step of SystemVerilog counters at the rising + // edge only, half at each edge of `clk`, and half at the falling edge of + // a copy of `clk`. + #[cfg(feature = "systemverilog")] + for (name, falling) in [ + ("sv_simulation_step_posedge_x20000", "posedge clk"), + ("sv_simulation_step_both_edges_x20000", "negedge clk"), + ("sv_simulation_step_negedge_copy_x20000", "negedge c"), + ] { + let source = format!( + "module Top #(parameter int N = 1000) (input logic clk, input logic rst, + output logic [31:0] cnt [N]); + logic c; + assign c = clk; + for (genvar i = 0; i < N; i++) begin : g + if (i % 2 == 0) begin : rise + always_ff @(posedge clk or posedge rst) + if (rst) cnt[i] <= 0; else cnt[i] <= cnt[i] + 1; + end else begin : fall + always_ff @({falling} or posedge rst) + if (rst) cnt[i] <= 0; else cnt[i] <= cnt[i] + 1; + end + end + endmodule" + ); + let path = std::path::Path::new("overhead.sv"); + let mut sim = + match Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top").build() { + Ok(sim) => sim, + Err(error) => { + eprintln!("{name}: {error}"); + continue; + } + }; + sim.schedule("rst", 0, 1).unwrap(); + sim.step().unwrap(); + sim.schedule("rst", 1, 0).unwrap(); + sim.step().unwrap(); + sim.add_clock("clk", 10, 10); + + c.bench_function(name, |b| { + b.iter(|| { + for _ in 0..20000 { + sim.step().unwrap(); + } + }) + }); + } } criterion_group!(benches, benchmark_simulation_overhead); From b280ce46e26f0f80131b0abab83b17bd6226e465 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:49:01 +0000 Subject: [PATCH 5/6] fix(deps): update rust crate wasm-encoder to 0.262 --- Cargo.lock | 14 +++++++------- crates/celox-backend-wasm/Cargo.toml | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 53ff84aee25..4ca20c86ed5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,7 +512,7 @@ dependencies = [ "celox-state-layout", "fxhash", "num-bigint", - "wasm-encoder 0.261.0", + "wasm-encoder 0.262.0", "wasmtime", ] @@ -963,7 +963,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" dependencies = [ "serde", "termcolor", - "unicode-width 0.1.14", + "unicode-width 0.2.2", ] [[package]] @@ -4740,12 +4740,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.261.0" +version = "0.262.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" dependencies = [ "leb128fmt", - "wasmparser 0.261.0", + "wasmparser 0.262.0", ] [[package]] @@ -4786,9 +4786,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.261.0" +version = "0.262.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" dependencies = [ "bitflags 2.13.0", "indexmap", diff --git a/crates/celox-backend-wasm/Cargo.toml b/crates/celox-backend-wasm/Cargo.toml index 07908286898..0631000c68d 100644 --- a/crates/celox-backend-wasm/Cargo.toml +++ b/crates/celox-backend-wasm/Cargo.toml @@ -14,7 +14,7 @@ celox-design = { workspace = true } celox-sir = { workspace = true } celox-state-layout = { workspace = true } fxhash = { workspace = true } -wasm-encoder = "0.261" +wasm-encoder = "0.262" [dev-dependencies] celox-backend-cranelift = { workspace = true } From d40208fb7fda462c580d81ef1df93b073b60a75c Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 08:33:11 +0900 Subject: [PATCH 6/6] test(bench): build the both-edges benches unconditionally --- crates/celox/benches/overhead.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 2dfcaf89806..9a7393c1c66 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -134,14 +134,9 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { endmodule" ); let path = std::path::Path::new("overhead.sv"); - let mut sim = - match Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top").build() { - Ok(sim) => sim, - Err(error) => { - eprintln!("{name}: {error}"); - continue; - } - }; + let mut sim = Simulation::from_sv_sources(vec![(source.as_str(), path)], "Top") + .build() + .unwrap(); sim.schedule("rst", 0, 1).unwrap(); sim.step().unwrap(); sim.schedule("rst", 1, 0).unwrap();