Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/celox-frontend-veryl/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ pub fn schedule_symbolic_rtl(
})
}

/// The period of every `$tb::clock_gen` instance of `module`.
///
/// Veryl 0.22 keeps clock configuration on instance symbols, but only copies it
/// into ClockNext IR. Recover it while the analyzer symbols are still available,
/// using the specialization's overrides rather than a parameter's default.
Expand All @@ -262,11 +264,14 @@ fn configured_clock_periods(
let SymbolKind::Instance(instance) = &symbol.found.kind else {
continue;
};
// A clock variable declared by an instance is a `$tb::clock_gen`;
// without a `period` it has the default period.
let Some((_, target)) = instance
.parameter_connects
.iter()
.find(|(name, _)| name.text.to_string() == "period")
else {
periods.insert(symbol.found.token.text, 2);
continue;
};
let context = context.get_or_insert_with(|| {
Expand Down
18 changes: 17 additions & 1 deletion crates/celox-frontend-veryl/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use celox_testbench::{
AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, ExprBytecode,
ExprOpcode as TbOpcode, LoopBound as GenericLoopBound, SemanticArgument,
SemanticComponentBinding, SemanticSignal, SemanticStatement, SourceLocation, StateLocation,
TestbenchOperator as Op, TestbenchProgram, TestbenchSelection,
TestbenchClock, TestbenchOperator as Op, TestbenchProgram, TestbenchSelection,
TestbenchStatement as GenericTestbenchStatement, TestbenchTarget,
};
use fxhash::{FxHashMap as HashMap, FxHashSet};
Expand Down Expand Up @@ -2568,6 +2568,17 @@ impl<'a> SemanticTestbenchBuilder<'a> {
}
}

/// The `$tb::clock_gen` instances of this source's module.
fn clock_generators(&self) -> impl Iterator<Item = TestbenchClock<StateAddr>> + '_ {
self.testbench_source
.clock_periods
.iter()
.filter_map(|(&name, &period)| {
let (event, _) = self.named_variable(name)?;
Some(TestbenchClock { event, period })
})
}

fn named_variable(&self, name: StrId) -> Option<(StateAddr, &VariableInfo)> {
let instance = self.testbench_source.base_instance(self.lookup);
let module = self.lookup.instance_module.get(&instance)?;
Expand Down Expand Up @@ -3852,19 +3863,24 @@ pub fn compile_semantic_testbench(
.sum();
let mut site_end = runtime_event_site_count.saturating_sub(total_sites);
let mut processes = Vec::new();
let mut clocks = Vec::new();
for source in sources {
let initial_stmts = source.initial_statements.as_ref().unwrap();
validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?;
site_end += count_assert_statements(initial_stmts, &source.functions);
let mut builder = SemanticTestbenchBuilder::new(lookup, source, site_end);
builder.prepared_readmem = super::readmem::prepare_testbench_memories(lookup, source)?;
builder.build_event_map(initial_stmts);
clocks.extend(builder.clock_generators());
processes.extend(builder.convert(initial_stmts));
}
clocks.sort_unstable_by_key(|clock: &TestbenchClock<StateAddr>| clock.event);
clocks.dedup_by_key(|clock| clock.event);
let builder = SemanticTestbenchBuilder::new(lookup, source, runtime_event_site_count);
let component_bindings = builder.convert_component_bindings()?;
Ok(Some(
TestbenchProgram::from_processes(processes)
.with_clocks(clocks)
.with_private_variables(private_variables)
.with_random_seed_option(random_seed)
.with_components(source.components.clone())
Expand Down
38 changes: 27 additions & 11 deletions crates/celox-napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,36 +918,46 @@ enum HandleDerivedTicks {

#[cfg(not(target_arch = "wasm32"))]
impl HandleBackend {
/// Tick an event as `Simulator::tick` does: settle, run its domain,
/// settle, and run the derived clock domains the tick reaches.
/// Tick an event as `Simulator::tick` does: a pulse of its signal to
/// the active level, running every domain sensitive to its edges.
fn tick(
&mut self,
event_id: usize,
derived: &HandleDerivedTicks,
event_edges: &celox::EventEdges,
scratch: &mut celox::DerivedTickScratch,
) -> std::result::Result<(), celox::RuntimeErrorCode> {
fn tick_with<B: celox::SimBackend>(
backend: &mut B,
event_id: usize,
plans: &celox::DerivedTickPlans<B::Event>,
event_edges: &celox::EventEdges,
scratch: &mut celox::DerivedTickScratch,
) -> std::result::Result<(), celox::RuntimeErrorCode> {
let event = backend.id_to_event_slice()[event_id];
match plans.get(event_id) {
Some(Some(plan)) => plan.tick(&mut celox::BackendExecutor(backend), scratch, true),
_ => {
backend.eval_comb()?;
backend.eval_apply_ff_at(event)?;
backend.eval_comb()
}
let plan = plans.get(event_id).and_then(Option::as_ref);
match celox::run_tick(
&mut celox::BackendExecutor(backend),
plan,
event_edges[event_id],
scratch,
event,
true,
celox::set_level,
) {
Ok(()) => Ok(()),
// A bare backend reports no `$finish` or `$stop`; what ran
// settles here.
Err(celox::Halt::Finish | celox::Halt::Stop) => backend.eval_comb(),
Err(celox::Halt::Error(error)) => Err(error),
}
}
match (self, derived) {
(Self::Default(backend), HandleDerivedTicks::Default(plans)) => {
tick_with(backend, event_id, plans, scratch)
tick_with(backend, event_id, plans, event_edges, scratch)
}
(Self::Tiered(backend), HandleDerivedTicks::Tiered(plans)) => {
tick_with(backend.as_mut(), event_id, plans, scratch)
tick_with(backend.as_mut(), event_id, plans, event_edges, scratch)
}
_ => unreachable!("derived tick plans belong to the handle's backend"),
}
Expand Down Expand Up @@ -1544,6 +1554,7 @@ impl NativeSimulatorHandle {
b.tick(
event_id as usize,
&self.derived_ticks,
&self.event_edges,
&mut self.derived_scratch,
)
.map_err(|e| napi_runtime_error(&runtime_errors, e))
Expand Down Expand Up @@ -1620,6 +1631,7 @@ impl NativeSimulatorHandle {
b.tick(
event_id as usize,
&self.derived_ticks,
&self.event_edges,
&mut self.derived_scratch,
)
.map_err(|e| napi_runtime_error(&runtime_errors, e))?;
Expand Down Expand Up @@ -3958,9 +3970,13 @@ mod tests {

#[test]
fn native_handle_dumps_consume_activity_until_memory_is_exposed() {
// A tick writes `clk` as well as `q`. The wide inputs keep those two
// trace groups below half of the design, where a dump scans every
// signal.
let source = "module Top (
clk: input clock, q: output logic<64>,
a: input logic<512>, b: input logic<512>, c: input logic<512>,
d: input logic<512>, e: input logic<512>,
) { always_ff (clk) { q += 1; } }";
let dir = tempfile::tempdir().unwrap();
// Warm the uninstrumented cache first. A traced build must not reuse it.
Expand Down
12 changes: 6 additions & 6 deletions crates/celox-runtime/src/derived_tick.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Derived clock domains of an event-based tick.
//! Derived clock domains of an event-based edge.
//!
//! A tick is one active edge of an event. Clocks derived from the event run
//! with the rules of the timed scheduler:
//! A plan runs the domains one edge of an event reaches. Clocks derived from
//! the event run with the rules of the timed scheduler:
//!
//! - A clock computed combinationally from the event's signal, such as
//! `clk & enable`, changes at the same instant as the event. Its edge is
Expand All @@ -17,9 +17,9 @@
//! commit raises while the clock is high is a further edge. Each domain
//! fires at most once per phase.
//!
//! A tick is the event's active edge only and does not change the event's
//! signal. Domains that react to the signal's opposite edge, such as one
//! clocked by `~clk` or by a falling `clk & en`, do not run on a tick.
//! A plan's [`DerivedTickPlan::tick`] is the event's active edge with its
//! signal left as it is; the edge APIs move the signal around it, and a
//! `Simulator::tick` takes the active edge and then the inactive one.
//!
//! What an event can reach is computed when the simulator is built
//! ([`celox_design::EventTopology::derived_events`] and
Expand Down
52 changes: 52 additions & 0 deletions crates/celox-runtime/src/edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ impl Edge {
Edge::Falling => 0,
}
}

/// The other transition.
pub fn opposite(self) -> Edge {
match self {
Edge::Rising => Edge::Falling,
Edge::Falling => Edge::Rising,
}
}
}

/// What an edge needs to know about one event.
Expand Down Expand Up @@ -346,3 +354,47 @@ where
moved_only(comb_read)
})
}

/// One tick of `event`: a clock period of its signal, defined as the
/// SystemVerilog statements
///
/// ```systemverilog
/// s <= A; #H;
/// s <= I; #L;
/// ```
///
/// where `A` and `I` are the event's active and inactive levels: the active
/// edge, then the inactive edge, each running every domain sensitive to it.
/// Combinational logic is settled afterwards. `dirty` says whether it has
/// pending changes; `write` moves the signal.
#[allow(clippy::too_many_arguments)]
pub fn run_tick<X, E>(
executor: &mut X,
plan: Option<&DerivedTickPlan<E>>,
info: EventEdge,
scratch: &mut DerivedTickScratch,
event: E,
dirty: bool,
mut write: impl FnMut(&mut X::Backend, SignalRef, u8),
) -> Result<(), Halt>
where
X: TickExecutor,
X::Backend: SimBackend<Event = E>,
E: EventHandle,
{
let active = info.active_edge();
let mut dirty = dirty;
for edge in [active, active.opposite()] {
dirty = match run_edge(
executor, plan, info, scratch, event, edge, dirty, &mut write,
)? {
EdgeOutcome::Unchanged | EdgeOutcome::Stored => dirty,
EdgeOutcome::Moved => true,
EdgeOutcome::Settled => false,
};
}
if dirty {
executor.eval_comb()?;
}
Ok(())
}
2 changes: 1 addition & 1 deletion crates/celox-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use derived_tick::{
};
pub use edge::{
Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal,
run_edge, run_edges, set_level,
run_edge, run_edges, run_tick, set_level,
};
pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site};
pub use event_buffer::RuntimeEventBuffer;
Expand Down
10 changes: 10 additions & 0 deletions crates/celox-runtime/src/simulation/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,16 @@ impl<B: SimBackend> SimulationState<B> {
continue;
}
if self.process_state.inactive.is_empty() {
// A domain whose blocking results are observed commits them
// in the active region: the processes they wake run before
// the NBA region publishes its nonblocking results (IEEE
// 1800-2023 4.5).
if self.active_commit_triggered(executor.backend(), round)
&& self.evaluate_before_inactive(executor, current_time, round)?
{
self.observe_driven(executor.backend());
continue;
}
return Ok(());
}
// The active region is empty: the domains it triggered evaluate
Expand Down
19 changes: 19 additions & 0 deletions crates/celox-runtime/src/simulation/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,25 @@ impl<B: SimBackend> SimulationState<B> {
}
}

/// A marked trigger evaluates a domain that commits its blocking
/// results in the active region (the filter of
/// [`Self::evaluate_before_inactive`]).
pub(super) fn active_commit_triggered(&self, backend: &B, round: &Round) -> bool {
if self.model.active_commits.is_empty() {
return false;
}
backend.get_triggered_bits().iter().any(|id| {
let info = self.model.event_info[id];
info.canonical_id != usize::MAX
&& info.eval_only_event.is_some()
&& self.model.active_commits.contains(info.canonical_id)
&& (!info.is_cascaded
|| round.counted_triggered.contains(id)
|| round.edge_approved.contains(id)
|| self.stable_edge_triggered(backend, id))
})
}

/// Evaluate the triggered domains before an inactive region runs. Their
/// nonblocking assignments stay in the working state until the NBA
/// region. A domain that commits its blocking results does so now, in
Expand Down
17 changes: 15 additions & 2 deletions crates/celox-runtime/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use celox_testbench::{
AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, CompiledExpr,
ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound,
ExecutableStatement, ExecutableTestbench, ExprBytecode, LoopBound as GenericLoopBound,
SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchProgram,
TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget,
SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchClock,
TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement,
TestbenchTarget,
};

use crate::{SignalRef, backend::SimBackend};
Expand Down Expand Up @@ -389,6 +390,17 @@ pub fn bind_testbench_program<B: SimBackend>(
}
}
let random_seed = program.configured_random_seed();
// A clock generator without an event drives no domain.
let clocks = program
.clocks()
.iter()
.filter_map(|clock| {
Some(TestbenchClock {
event: backend.resolve_event_opt(&clock.event)?,
period: clock.period,
})
})
.collect();
let components = program.components().to_vec();
let component_libraries = program.component_libraries().to_vec();
let component_file_base = program.component_file_base().map(ToOwned::to_owned);
Expand All @@ -410,6 +422,7 @@ pub fn bind_testbench_program<B: SimBackend>(
.collect();
Some(
ExecutableTestbench::from_processes(processes, random_seed)
.with_clocks(clocks)
.with_private_signals(private_signals)
.with_component_runtime(
components,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,7 @@ four-state expectations; the assertions remain enabled on all Celox variants.
| `sv_verilator_time_in_combinational_logic` | execute | verilator | 1 | Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one. |
| `sv_verilator_intermediate_writes` | execute | verilator | 6 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. |
| `sv_icarus_port_pulses` | execute | icarus | 1 | Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give. The [standalone probe](verification/repros/sv_port_pulses_icarus.json) retains both outputs. |
| `sv_verilator_active_region_waiters` | execute | verilator | 2 | Verilator 5.052 resumes a process woken by a blocking write of an edge-triggered process only after the same edge's nonblocking updates: with `y = ~y; q <= q + 1;` a waiter on `@(y)` reads the updated q, and with `y = 1; y <= 0; y <= 1;` from 0 it does not wait again before the nonblocking updates and counts 1 instead of 3. IEEE 1800-2023 4.5 makes the blocking write an update event of the active region and enters the NBA region only when the active and inactive regions are empty, so the waiter runs first (9.4.2). [Standalone probes](verification/repros/sv_active_region_waiters_verilator.json) print the spec values in Icarus 13.0 and the post-NBA values in Verilator. |

The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json)
retains the failed Icarus runs and minimal sources. Cover comparisons enable
Expand Down
Loading
Loading