From e6739101132dc44065069b7f2b386ceb3b66f9be Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 11:18:10 +0900 Subject: [PATCH 1/2] perf(sim): keep the inactive edge of a tick cheap when nothing can fire on it A tick of an event with derived clocks ran its inactive edge through the derived plan, which settles combinational logic although no domain fires on that edge for a gated (`clk & en`) or divided clock. Decide per event at build time whether the inactive edge can run a domain: the event's own, or one of a clock computed combinationally from the signal that the edge can move to its active edge, judged from how the gate program depends on the signal (positive, negative, independent or mixed). With nothing able to fire on that edge nothing commits, so no state-derived domain runs either. `EventEdge::inactive_runs` records it. `tick`, `tick_events` and the native testbench's `clk.next(n)` use it: when the inactive edge runs nothing they take the active edge and then only store the inactive level, marking combinational logic dirty when it reads the signal. If the active edge left combinational logic unsettled, the inactive edge still runs in full. Gated and divided designs keep the batched `clk.next(n)` path. Change-Id: Id9d21afbe418767912aa2adf08d018ec5899162e --- crates/celox-runtime/src/edge.rs | 193 ++++++++++++- crates/celox/src/simulator.rs | 73 +++-- crates/celox/src/testbench.rs | 2 +- crates/celox/tests/native_testbench.rs | 59 ++++ crates/celox/tests/tick_inactive_edge.rs | 337 +++++++++++++++++++++++ 5 files changed, 640 insertions(+), 24 deletions(-) create mode 100644 crates/celox/tests/tick_inactive_edge.rs diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 1b971593394..b6d82420df1 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -13,7 +13,7 @@ //! so the inactive edge of a clock that only clocks flip-flops costs no //! settle on the next active edge. -use celox_design::{DomainKind, EventTopology, edges::LEVEL_UNKNOWN}; +use celox_design::{DomainKind, EventTopology, GateOp, edges::LEVEL_UNKNOWN}; use crate::{ AbsoluteAddr, SignalRef, @@ -60,6 +60,12 @@ pub struct EventEdge { pub kind: Option, /// Combinational logic reads the signal. pub comb_read: bool, + /// The edge opposite to [`Self::active_edge`] can run a domain: the + /// event's own, or that of a clock computed combinationally from the + /// signal that this edge can move to its active edge. When it cannot, + /// nothing commits on that edge, so no domain clocked from state runs + /// either, and a host only needs to store the level. + pub inactive_runs: bool, } impl EventEdge { @@ -108,15 +114,128 @@ pub fn build_event_edges( .iter() .map(|address| { let canonical = events.canonical(*address); - EventEdge { + let kind = kinds.get(&canonical).copied(); + let mut info = EventEdge { signal: backend.resolve_signal(&canonical), - kind: kinds.get(&canonical).copied(), + kind, comb_read: events.combinationally_read.contains(&canonical), - } + inactive_runs: false, + }; + let inactive = info.active_edge().opposite(); + info.inactive_runs = info.can_fire(inactive) + || events + .combinational_derived + .get(&canonical) + .into_iter() + .flatten() + // A clock without a domain of its own runs nothing. + .filter(|clock| backend.resolve_event_opt(&clock.clock).is_some()) + .any(|clock| { + let moves = clock + .gate + .as_deref() + .and_then(dependence) + .unwrap_or(Dependence::Mixed); + moves.can_reach(inactive, kinds.get(&clock.clock).copied()) + }); + info }) .collect() } +/// How a gate program's value depends on its source's level, bitwise: +/// whether raising the source can only raise each bit, only lower it, or +/// either. The operations it treats as monotone also are over the order +/// 0 < x < 1 of four-state values, so it holds for four-state designs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dependence { + Independent, + Positive, + Negative, + Mixed, +} + +impl Dependence { + fn invert(self) -> Self { + match self { + Dependence::Positive => Dependence::Negative, + Dependence::Negative => Dependence::Positive, + other => other, + } + } + + /// A monotone function of both operands, such as `&` or `|`. + fn join(self, other: Self) -> Self { + match (self, other) { + (Dependence::Independent, other) | (other, Dependence::Independent) => other, + (lhs, rhs) if lhs == rhs => lhs, + _ => Dependence::Mixed, + } + } + + /// A function of the operands that is not monotone, such as `^`. + fn scramble(self, other: Self) -> Self { + if self == Dependence::Independent && other == Dependence::Independent { + Dependence::Independent + } else { + Dependence::Mixed + } + } + + /// Whether `edge` of the source can be an edge of a clock of `kind` + /// computed with this dependence. + fn can_reach(self, edge: Edge, kind: Option) -> bool { + let moves = match self { + Dependence::Independent => return false, + Dependence::Mixed => return true, + Dependence::Positive => edge, + Dependence::Negative => edge.opposite(), + }; + match kind { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => moves == Edge::Rising, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => moves == Edge::Falling, + _ => true, + } + } +} + +/// The [`Dependence`] of a gate program's value on its source, or `None` +/// for a malformed program. +fn dependence(ops: &[GateOp]) -> Option { + let mut stack: Vec = Vec::new(); + for op in ops { + let value = match op { + GateOp::Source => Dependence::Positive, + GateOp::Load { .. } | GateOp::Const(_) => Dependence::Independent, + GateOp::Not { .. } | GateOp::LogicNot => stack.pop()?.invert(), + GateOp::ReduceAnd { .. } | GateOp::ReduceOr | GateOp::Slice { .. } => stack.pop()?, + GateOp::ReduceXor => stack.pop()?.scramble(Dependence::Independent), + GateOp::And | GateOp::Or | GateOp::LogicAnd | GateOp::LogicOr => { + let rhs = stack.pop()?; + stack.pop()?.join(rhs) + } + GateOp::Xor | GateOp::Eq | GateOp::Ne => { + let rhs = stack.pop()?; + stack.pop()?.scramble(rhs) + } + GateOp::Mux => { + let otherwise = stack.pop()?; + let then = stack.pop()?; + match stack.pop()? { + // A fixed condition selects one of two monotone values. + Dependence::Independent => then.join(otherwise), + _ => Dependence::Mixed, + } + } + }; + stack.push(value); + } + match stack.as_slice() { + [value] => Some(*value), + _ => None, + } +} + /// What an edge did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EdgeOutcome { @@ -398,3 +517,69 @@ where } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + type Op = GateOp<()>; + + const LOAD: Op = GateOp::Load { + address: (), + lsb: 0, + width: 1, + }; + + #[test] + fn gates_follow_their_source_through_monotone_operations() { + use Dependence::*; + let cases: [(&[Op], Dependence); 8] = [ + (&[GateOp::Source, LOAD, GateOp::And], Positive), + (&[GateOp::Source, GateOp::Not { width: 1 }], Negative), + ( + &[GateOp::Source, GateOp::LogicNot, LOAD, GateOp::LogicOr], + Negative, + ), + (&[LOAD, GateOp::Const(1), GateOp::Or], Independent), + (&[GateOp::Source, LOAD, GateOp::Xor], Mixed), + ( + &[ + GateOp::Source, + GateOp::Source, + GateOp::Not { width: 1 }, + GateOp::Or, + ], + Mixed, + ), + ( + &[LOAD, GateOp::Source, GateOp::Const(0), GateOp::Mux], + Positive, + ), + ( + &[GateOp::Source, LOAD, GateOp::Const(0), GateOp::Mux], + Mixed, + ), + ]; + for (ops, expected) in cases { + assert_eq!(dependence(ops), Some(expected), "{ops:?}"); + } + assert_eq!(dependence::<()>(&[GateOp::And]), None); + assert_eq!(dependence::<()>(&[GateOp::Source, GateOp::Source]), None); + } + + #[test] + fn a_clock_is_reached_by_the_edges_its_dependence_allows() { + use DomainKind::*; + let posedge = Some(ClockPosedge); + let negedge = Some(ClockNegedge); + // The falling edge of a positive-edge clock's source. + let edge = Edge::Falling; + assert!(!Dependence::Positive.can_reach(edge, posedge)); + assert!(Dependence::Positive.can_reach(edge, negedge)); + assert!(Dependence::Negative.can_reach(edge, posedge)); + assert!(!Dependence::Negative.can_reach(edge, Some(ResetAsyncLow))); + assert!(Dependence::Positive.can_reach(edge, None)); + assert!(!Dependence::Independent.can_reach(edge, None)); + assert!(Dependence::Mixed.can_reach(edge, posedge)); + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 524a7281730..ae0fe401b20 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1724,11 +1724,13 @@ mod host { let info = self.event_edges[event.id()]; let active = info.active_edge(); let inactive = active.opposite(); - let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); - if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { + if info.inactive_runs || !self.host_watch.is_empty() { self.active_edge(event)?; return self.inactive_edge(event); } + if let Some(Some(_)) = self.derived_ticks.get(event.id()) { + return self.tick_derived_quiet(event); + } // Everything is read before the domain runs: right after its // kernel, loads of host tables can wait behind the kernel's // stores (4 KiB aliasing), which made a period cost almost two @@ -1755,6 +1757,25 @@ mod host { Ok(()) } + /// [`Self::tick`] of an event with derived domains whose inactive + /// edge runs nothing: the active edge, then only the inactive level. + #[inline(never)] + fn tick_derived_quiet(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + self.active_edge(event)?; + let info = self.event_edges[event.id()]; + if self.dirty { + // Combinational logic did not settle, so the inactive edge + // may still find a derived clock moved by the settle. + return self.inactive_edge(event); + } + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + Ok(()) + } + /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2037,22 +2058,39 @@ mod host { return self.tick(*event); } let only_active_edges = self.host_watch.is_empty() - && events.iter().all(|event| { - let info = self.event_edges[event.id()]; - !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) - && !info.can_fire(info.active_edge().opposite()) - }); - if !only_active_edges { + && events + .iter() + .all(|event| !self.event_edges[event.id()].inactive_runs); + let derived = events + .iter() + .any(|event| matches!(self.derived_ticks.get(event.id()), Some(Some(_)))); + if !only_active_edges || derived { + let edges = std::sync::Arc::clone(&self.event_edges); let moves = |edge: fn(celox_runtime::EventEdge) -> celox_runtime::Edge| { events .iter() - .map(|&event| (event, edge(self.event_edges[event.id()]))) + .map(|&event| (event, edge(edges[event.id()]))) .collect::>() }; let active = moves(|info| info.active_edge()); - let inactive = moves(|info| info.active_edge().opposite()); self.edges(&active)?; - return self.edges(&inactive); + if !only_active_edges || self.dirty { + let inactive = moves(|info| info.active_edge().opposite()); + return self.edges(&inactive); + } + // The inactive edges run nothing and only store. + for &event in events { + let info = self.event_edges[event.id()]; + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read { + self.dirty = true; + } + } + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + return Ok(()); } // The inactive edges run nothing and only store. let mut fired = Vec::with_capacity(events.len()); @@ -2190,14 +2228,11 @@ mod host { Ok(()) } - /// Whether a period of `event`'s signal, a rise and a fall, runs only - /// the event's own domain, once: no domain reacts to the other edge - /// and no clock derives from the signal. - pub(crate) fn period_runs_only_own_domain(&self, event: B::Event) -> bool { - let info = self.event_edges[event.id()]; - !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) - && !info.can_fire(info.active_edge().opposite()) - && self.host_watch.is_empty() + /// Whether a period of `event`'s signal, a rise and a fall, runs + /// domains only at its active edge: the event's own and those derived + /// from it, while the inactive edge runs nothing. + pub(crate) fn period_runs_only_active_edge(&self, event: B::Event) -> bool { + !self.event_edges[event.id()].inactive_runs && self.host_watch.is_empty() } /// Advance a run of identical deferred-comb ticks. Native code may keep diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index f1239aa8884..1f60c315077 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -2425,7 +2425,7 @@ fn clock_periods( event: B::Event, count: u64, ) -> (u64, Result<(), crate::RuntimeErrorCode>) { - if sim.period_runs_only_own_domain(event) { + if sim.period_runs_only_active_edge(event) { return sim.tick_deferred_comb_many(event, count); } let result = sim diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index a5df2eb8ac1..61cef16d016 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -105,6 +105,65 @@ fn test_native_testbench_ff_condition_reads_pre_edge_value_after_write() { ); } +/// `clk.next(n)` runs gated and divided domains on every period whose +/// inactive edge runs nothing, and leaves the clock low. +#[test] +fn test_native_testbench_next_runs_gated_and_divided_domains() { + let code = r#" + module Dut ( + clk: input '_ clock, + en : input '_ logic, + g : output '_ logic<8>, + d : output '_ logic<8>, + lvl: output '_ logic, + ) { + var a: logic<2>; + always_ff (clk) { + a = a + 2'd1; + } + let divided: '_ clock = a[0]; + always_ff (divided) { + d = d + 8'd1; + } + let gated: '_ clock = clk & en; + always_ff (gated) { + g = g + 8'd1; + } + assign lvl = clk; + } + + #[test(t)] + module t { + inst clk: $tb::clock_gen; + var en : logic; + var g : logic<8>; + var d : logic<8>; + var lvl: logic; + inst dut: Dut (clk, en, g, d, lvl); + + initial { + en = 1'b1; + clk.next(4); + $assert(g == 8'd4); + $assert(d == 8'd2); + $assert(lvl == 1'b0); + + en = 1'b0; + clk.next(3); + $assert(g == 8'd4); + $assert(d == 8'd4); + $assert(lvl == 1'b0); + $finish(); + } + } + "#; + + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + TestResult::Pass, + ); +} + #[test] fn test_native_testbench_overlapping_ff_writes_preserve_last_write() { let code = r#" diff --git a/crates/celox/tests/tick_inactive_edge.rs b/crates/celox/tests/tick_inactive_edge.rs new file mode 100644 index 00000000000..080ef91be09 --- /dev/null +++ b/crates/celox/tests/tick_inactive_edge.rs @@ -0,0 +1,337 @@ +//! The inactive edge of a tick stores only the level when nothing can run on +//! it, and still runs every domain that can. Each design is checked as +//! `tick_semantics` checks the host API: the timed `Simulation` of the +//! statements a host operation stands for must observe the same values, +//! unknown bits included, after every operation: +//! +//! - `set(x, v)` is `x = v;`, +//! - `edge(e, lvl)` is `s <= lvl;`, +//! - `tick(e)` is `s <= A; #H; s <= I; #L;`, +//! - `tick_events(e1..ek)` makes the moves of all their signals together. + +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{Edge, EventHandle, Simulation, Simulator}; +use num_bigint::BigUint; + +/// Inputs of every design, all one bit wide. +const INPUTS: [&str; 4] = ["clk", "clk2", "en", "rst"]; + +/// Event signals with their active levels. +const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst", 1)]; + +/// A gated clock clocking only rising edges, and combinational logic reading +/// the clock: the inactive edge of `clk` runs nothing. +const GATED: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] g, + output logic [7:0] c2, + output logic [7:0] lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge gclk or posedge rst) + if (rst) g <= 8'd0; + else g <= g + 8'd1; + always_ff @(posedge clk2 or posedge rst) + if (rst) c2 <= 8'd0; + else c2 <= c2 + 8'd1; + assign lvl = {6'd0, gclk, clk}; +endmodule +"#; + +/// A domain on the falling edge of a gated clock runs on the inactive edge. +const GATED_NEGEDGE: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] g, + output logic [7:0] ng, + output logic [7:0] lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge gclk or posedge rst) + if (rst) g <= 8'd0; + else g <= g + 8'd1; + always_ff @(negedge gclk or posedge rst) + if (rst) ng <= 8'd0; + else ng <= ng + 8'd1; + assign lvl = {7'd0, clk}; +endmodule +"#; + +/// The rising edge of `~clk` is the falling edge of `clk`. +const INVERTED: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] q, + output logic [7:0] lvl +); + logic nclk; + assign nclk = ~clk; + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge nclk or posedge rst) + if (rst) q <= 8'd0; + else q <= q + 8'd1; + assign lvl = {7'd0, clk}; +endmodule +"#; + +/// A register divider; with `en` low the divided clock stays where it is. +const DIVIDER: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] d, + output logic [7:0] lvl +); + logic div; + always_ff @(posedge clk or posedge rst) + if (rst) begin + p <= 8'd0; + div <= 1'b0; + end else begin + p <= p + 8'd1; + if (en) div <= ~div; + end + always_ff @(posedge div or posedge rst) + if (rst) d <= 8'd0; + else d <= d + 8'd1; + assign lvl = {6'd0, div, clk}; +endmodule +"#; + +#[derive(Clone, Copy, Debug)] +enum Op { + Set(&'static str, u8), + Edge(&'static str, u8), + Tick(&'static [&'static str]), +} + +fn active(name: &str) -> u8 { + EVENTS.iter().find(|(event, _)| *event == name).unwrap().1 +} + +/// The statements `op` stands for, with the half periods of a tick at 1. +fn statements(op: Op) -> String { + match op { + Op::Set(name, value) => format!("{name} = {value};"), + Op::Edge(name, level) => format!("{name} <= {level};"), + Op::Tick(names) => { + let moves = |level: fn(u8) -> u8| { + names + .iter() + .map(|name| format!("{name} <= {}; ", level(active(name)))) + .collect::() + }; + format!("{}#1; {}#1;", moves(|a| a), moves(|a| 1 - a)) + } + } +} + +type Values = Vec<(BigUint, BigUint)>; + +/// The outputs after each operation, from the timed simulation of the +/// operations' statements. Operation `k` starts at time `4k + 1`. +fn reference(dut: &str, outputs: &[&str], four_state: bool, ops: &[Op]) -> Vec { + let mut body = String::new(); + for (k, &op) in ops.iter().enumerate() { + body += &format!(" #({} - $time) {}\n", 4 * k + 1, statements(op)); + } + let top = format!( + r#" +`timescale 1ns/1ns +module Top; + logic {inputs}; + wire [7:0] {outputs}; + Dut u (.{ports}); + initial begin +{body} end +endmodule +"#, + inputs = INPUTS.join(", "), + outputs = outputs.join(", "), + ports = INPUTS + .iter() + .chain(outputs) + .copied() + .collect::>() + .join(", ."), + ); + let mut sim = Simulation::from_sv_sources( + vec![(dut, Path::new("dut.sv")), (&top, Path::new("top.sv"))], + "Top", + ) + .four_state(four_state) + .build() + .unwrap(); + (0..ops.len()) + .map(|k| { + sim.run_until(4 * k as u64 + 4).unwrap(); + outputs + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get_four_state(signal) + }) + .collect() + }) + .collect() +} + +fn hosted( + dut: &str, + outputs: &[&str], + four_state: bool, + inactive_runs: bool, + ops: &[Op], +) -> Vec { + let mut sim = Simulator::from_sv_sources(vec![(dut, Path::new("dut.sv"))], "Dut") + .four_state(four_state) + .build() + .unwrap(); + let clk = sim.event("clk"); + assert_eq!( + sim.event_edges()[clk.id()].inactive_runs, + inactive_runs, + "whether the inactive edge of clk can run a domain" + ); + ops.iter() + .map(|&op| { + match op { + Op::Set(name, value) => { + let signal = sim.signal(name); + sim.set(signal, value); + } + Op::Edge(name, level) => { + let event = sim.event(name); + let edge = if level == 1 { + Edge::Rising + } else { + Edge::Falling + }; + sim.edge(event, edge).unwrap(); + } + Op::Tick([name]) => { + let event = sim.event(name); + sim.tick(event).unwrap(); + } + Op::Tick(names) => { + let events: Vec<_> = names.iter().map(|name| sim.event(name)).collect(); + sim.tick_events(&events).unwrap(); + } + } + outputs + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get_four_state(signal) + }) + .collect() + }) + .collect() +} + +/// Operations before [`RESET`] leave the counters unknown, and the timed +/// simulation's start-up settle may already clock them; they are not +/// compared. +const RESET: usize = 4; + +fn check(dut: &str, outputs: &[&str], inactive_runs: bool, ops: &[Op]) { + for four_state in [false, true] { + let expected = reference(dut, outputs, four_state, ops); + let actual = hosted(dut, outputs, four_state, inactive_runs, ops); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate().skip(RESET) { + assert_eq!( + actual, expected, + "four_state {four_state}: after {:?} (operation {k}), outputs {outputs:?}", + ops[k] + ); + } + } +} + +/// Reset, then periods with the gate open, closed and open again. The clock +/// starts unknown in a four-state design. +const PERIODS: &[Op] = &[ + Op::Set("en", 0), + Op::Set("clk2", 0), + Op::Edge("rst", 1), + Op::Edge("rst", 0), + Op::Tick(&["clk"]), + Op::Set("en", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Set("en", 0), + Op::Tick(&["clk"]), + Op::Set("en", 1), + Op::Tick(&["clk"]), +]; + +/// A gated clock that clocks only rising edges: combinational logic reading +/// the clock and the gated clock sees both low after every tick, and ticks +/// coincident with another clock still gate. +#[test] +fn a_gated_rising_edge_domain_leaves_the_inactive_edge_quiet() { + let mut ops = PERIODS.to_vec(); + ops.extend([ + Op::Tick(&["clk", "clk2"]), + Op::Set("en", 0), + Op::Tick(&["clk", "clk2"]), + Op::Set("en", 1), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + ]); + check(GATED, &["p", "g", "c2", "lvl"], false, &ops); +} + +/// A domain on the falling edge of a gated clock runs on every tick that +/// opens the gate. +#[test] +fn a_gated_falling_edge_domain_runs_on_every_tick() { + check(GATED_NEGEDGE, &["p", "g", "ng", "lvl"], true, PERIODS); +} + +/// The rising edge of an inverted clock runs on the inactive edge. +#[test] +fn an_inverted_clock_domain_runs_on_the_inactive_edge() { + check(INVERTED, &["p", "q", "lvl"], true, PERIODS); +} + +/// A divided domain runs when the divider rises and not while the divider +/// holds. +#[test] +fn a_divided_domain_runs_only_when_the_divider_rises() { + check(DIVIDER, &["p", "d", "lvl"], false, PERIODS); +} From b49c5a495eac1090781cf77cbd168e1514a02c8d Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 13:22:14 +0900 Subject: [PATCH 2/2] perf(sim): run a plain tick as one domain run when its level stores are unobservable A plain tick stores the active level, runs the domain and stores the inactive level. When the signal already is at its known inactive level, no combinational logic and no flip-flop of the event's own domain reads it, and no comb observer or host watch is active, both stores are unobservable: the level is the inactive one before and after the call and nothing but the domain runs in between. `tick` then is exactly the domain run, as before ticks became clock periods. The frontend records at build time which event domains never read their own signal (`EventTopology::level_unread_by_domain`; a load or commit source of the signal or an external call counts as a read, and an absent entry means the level may be read). `EventEdge::level_read` combines it with `comb_read`. A first tick from an unknown or active level still moves the signal. Change-Id: I0ec005eafbfc07f8f8ff246be3e7f381436178a3 --- crates/celox-design/src/lib.rs | 7 +++ .../src/symbolic/assembly.rs | 26 +++++++++ crates/celox-runtime/src/edge.rs | 13 ++++- crates/celox-runtime/src/lib.rs | 4 +- crates/celox/src/simulator.rs | 9 +++ crates/celox/tests/tick_inactive_edge.rs | 48 ++++++++++++++++ crates/celox/tests/vcd.rs | 57 +++++++++++++++++++ 7 files changed, 161 insertions(+), 3 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 50e687c8a08..a632d935468 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -918,6 +918,12 @@ pub struct EventTopology { /// a signal needs a settle before its domains evaluate. #[serde(default)] pub combinationally_read: BTreeSet, + /// Canonical events whose own domain reads no level of their signal: its + /// flip-flops do not sample the signal as data. With + /// [`Self::combinationally_read`] it says whether a run of the domain + /// observes the signal's level. Absent means it may. + #[serde(default)] + pub level_unread_by_domain: BTreeSet, } /// A clock computed combinationally from an event's signal. @@ -1013,6 +1019,7 @@ impl Default for EventTopology { combinational_derived: BTreeMap::new(), independent_derived: BTreeSet::new(), combinationally_read: BTreeSet::new(), + level_unread_by_domain: BTreeSet::new(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 9e7edb1dc0c..836a229fa8d 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -924,6 +924,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( combinational_derived, independent_derived, combinationally_read, + level_unread_by_domain, } = timed_sub!( "analyze_clock_dependencies", analyze_clock_dependencies( @@ -1770,6 +1771,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(), independent_derived: independent_derived.into_iter().map(project).collect(), combinationally_read: combinationally_read.into_iter().map(project).collect(), + level_unread_by_domain: level_unread_by_domain.into_iter().map(project).collect(), combinational_derived: combinational_derived .into_iter() .map(|(event, clocks)| { @@ -4396,6 +4398,8 @@ struct ClockAnalysis { independent_derived: BTreeSet, /// Events whose signal combinational logic reads. combinationally_read: BTreeSet, + /// Events whose own domain does not read their signal. + level_unread_by_domain: BTreeSet, } fn analyze_clock_dependencies( @@ -4790,6 +4794,27 @@ fn analyze_clock_dependencies( } Some((reads, writes)) }; + // A domain reads its own clock's level when a flip-flop samples it as + // data. An external call may read anything. + let canonical = |address: AbsoluteAddr| clock_domains.get(&address).copied().unwrap_or(address); + let level_unread_by_domain: BTreeSet = eval_apply_ffs + .iter() + .filter(|(domain, units)| { + let domain = canonical(**domain); + !units + .iter() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .any(|instruction| match instruction { + SIRInstruction::Load(_, address, ..) | SIRInstruction::Commit(address, ..) => { + canonical(address.absolute_addr()) == domain + } + SIRInstruction::ExternCall { .. } => true, + _ => false, + }) + }) + .map(|(domain, _)| canonical(*domain)) + .collect(); let mut independent_derived = BTreeSet::new(); let combinationally_read: BTreeSet = comb_deps .values() @@ -4837,6 +4862,7 @@ fn analyze_clock_dependencies( combinational_derived, independent_derived, combinationally_read, + level_unread_by_domain, } } diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index b6d82420df1..1348822b39f 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -60,6 +60,9 @@ pub struct EventEdge { pub kind: Option, /// Combinational logic reads the signal. pub comb_read: bool, + /// A run of the event's own domain can observe the signal's level: + /// combinational logic or one of the domain's flip-flops reads it. + pub level_read: bool, /// The edge opposite to [`Self::active_edge`] can run a domain: the /// event's own, or that of a clock computed combinationally from the /// signal that this edge can move to its active edge. When it cannot, @@ -115,10 +118,12 @@ pub fn build_event_edges( .map(|address| { let canonical = events.canonical(*address); let kind = kinds.get(&canonical).copied(); + let comb_read = events.combinationally_read.contains(&canonical); let mut info = EventEdge { signal: backend.resolve_signal(&canonical), kind, - comb_read: events.combinationally_read.contains(&canonical), + comb_read, + level_read: comb_read || !events.level_unread_by_domain.contains(&canonical), inactive_runs: false, }; let inactive = info.active_edge().opposite(); @@ -293,6 +298,12 @@ pub fn set_level(backend: &mut B, signal: SignalRef, level: u8) { backend.set(signal, level); } +/// Whether `info`'s signal is at the known level `edge` leaves it at. +#[inline] +pub fn at_level(backend: &B, info: &EventEdge, edge: Edge) -> bool { + level(backend, info.signal) == edge.level() +} + /// Move `info`'s signal to the level of `edge` through `write`. Returns the /// level it had (`None` while unknown), or `None` when it already was at /// that level. diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index ecffa23e4b5..1b1bfdddcad 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -24,8 +24,8 @@ pub use derived_tick::{ EventDomain, Gate, GatedDomain, TickExecutor, build_derived_tick_plans, }; pub use edge::{ - Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal, - run_edge, run_edges, run_tick, set_level, + Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, at_level, build_event_edges, + move_signal, run_edge, run_edges, run_tick, set_level, }; pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site}; pub use event_buffer::RuntimeEventBuffer; diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ae0fe401b20..d475dd0eadc 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1736,6 +1736,15 @@ mod host { // stores (4 KiB aliasing), which made a period cost almost two // domain runs. The inactive edge runs nothing and only stores. let observers = !self.program.runtime_schema.comb_observers.is_empty(); + if !info.level_read + && !observers + && celox_runtime::at_level(&self.backend, &info, inactive) + { + // Nothing the domain runs reads the level, which is the + // inactive one before and after the period: both stores are + // unobservable, and the period is one run of the domain. + return self.fire(event); + } let moved = celox_runtime::move_signal( &mut self.backend, &info, diff --git a/crates/celox/tests/tick_inactive_edge.rs b/crates/celox/tests/tick_inactive_edge.rs index 080ef91be09..a2efcddd3dc 100644 --- a/crates/celox/tests/tick_inactive_edge.rs +++ b/crates/celox/tests/tick_inactive_edge.rs @@ -131,6 +131,26 @@ module Dut ( endmodule "#; +/// A plain clock nothing reads as data, and one a flip-flop samples. +const PLAIN: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst, + output logic [7:0] p, + output logic [7:0] q +); + always_ff @(posedge clk or posedge rst) + if (rst) p <= 8'd0; + else p <= p + 8'd1; + always_ff @(posedge clk2 or posedge rst) + if (rst) q <= 8'd0; + else q <= {6'd0, clk2, en}; +endmodule +"#; + #[derive(Clone, Copy, Debug)] enum Op { Set(&'static str, u8), @@ -335,3 +355,31 @@ fn an_inverted_clock_domain_runs_on_the_inactive_edge() { fn a_divided_domain_runs_only_when_the_divider_rises() { check(DIVIDER, &["p", "d", "lvl"], false, PERIODS); } + +/// A plain tick whose level stores nothing observes is one run of the +/// domain; a domain that samples its clock still sees it high. A tick from +/// an unknown or active level still moves the signal. +#[test] +fn a_plain_tick_skips_only_unobservable_level_stores() { + for four_state in [false, true] { + let sim = Simulator::from_sv_sources(vec![(PLAIN, Path::new("dut.sv"))], "Dut") + .four_state(four_state) + .build() + .unwrap(); + let level_read = |name| sim.event_edges()[sim.event(name).id()].level_read; + assert!(!level_read("clk"), "nothing reads the level of clk"); + assert!(level_read("clk2"), "a flip-flop samples clk2"); + } + let mut ops = PERIODS.to_vec(); + ops.extend([ + Op::Tick(&["clk2"]), + Op::Set("en", 1), + Op::Tick(&["clk2"]), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Edge("clk2", 1), + Op::Tick(&["clk2"]), + ]); + check(PLAIN, &["p", "q"], false, &ops); +} diff --git a/crates/celox/tests/vcd.rs b/crates/celox/tests/vcd.rs index 0bbd3f71f5e..12b3bb60c99 100644 --- a/crates/celox/tests/vcd.rs +++ b/crates/celox/tests/vcd.rs @@ -195,6 +195,63 @@ mod tests { } out } + + /// A tick whose two level stores nothing observes skips them; a VCD of + /// ticks is the same as one of periods whose levels are stored. + #[test] + fn test_vcd_of_ticks_matches_stored_periods() { + let code = r#" + module Top ( + clk: input clock, + rst: input reset, + cnt: output logic<8>, + ) { + always_ff (clk, rst) { + if_reset { + cnt = 0; + } else { + cnt += 1; + } + } + } + "#; + for four_state in [false, true] { + let ticked_path = format!("test_vcd_ticks_{four_state}.vcd"); + let stored_path = format!("test_vcd_stored_periods_{four_state}.vcd"); + let run = |path: &str, stored: bool| { + let mut sim = SimulatorBuilder::new(code, "Top") + .four_state(four_state) + .vcd(path) + .build() + .unwrap(); + let clk = sim.event("clk"); + assert!( + !sim.event_edges()[celox::EventHandle::id(&clk)].level_read, + "nothing reads the level of clk" + ); + let rst = sim.signal("rst"); + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + for period in 0..6u64 { + if period == 2 { + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + } + if stored { + sim.active_edge(clk).unwrap(); + sim.inactive_edge(clk).unwrap(); + } else { + sim.tick(clk).unwrap(); + } + sim.dump(10 * period); + } + sim.flush_vcd().unwrap(); + }; + run(&ticked_path, false); + run(&stored_path, true); + assert_eq!(without_date(&ticked_path), without_date(&stored_path)); + fs::remove_file(ticked_path).unwrap(); + fs::remove_file(stored_path).unwrap(); + } + } } mod activity {