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
9 changes: 9 additions & 0 deletions crates/celox-frontend-sv/src/warning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub enum FrontendWarningKind {
/// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations.
#[error("mixed explicit and default time units or precisions across design elements")]
MixedTimescale,
#[error("`$size` on an interface array is a language extension")]
InterfaceArrayQuery,
/// IEEE 1800-2023 9.2.2.4 restricts writes by other processes.
#[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")]
MultipleAlwaysFfDrivers { module: String, signal: String },
Expand Down Expand Up @@ -96,6 +98,9 @@ pub(crate) fn analyzer_warnings(
found: &[celox_sv_analyzer::ir::AnalyzerWarning],
) -> impl Iterator<Item = PendingWarning> + '_ {
found.iter().map(|warning| match warning {
celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayQuery { site } => {
(FrontendWarningKind::InterfaceArrayQuery, site.clone())
}
celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => {
(FrontendWarningKind::MixedTimescale, None)
}
Expand Down Expand Up @@ -149,6 +154,7 @@ impl miette::Diagnostic for FrontendWarning {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new(match self.kind {
FrontendWarningKind::MixedTimescale => "mixed_timescale",
FrontendWarningKind::InterfaceArrayQuery => "interface_array_query",
FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers",
FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default",
FrontendWarningKind::InferredLatch => "inferred_latch",
Expand All @@ -166,6 +172,9 @@ impl miette::Diagnostic for FrontendWarning {
FrontendWarningKind::InferredLatch => {
"assign every output on every path, or configure diagnostics.inferred_latch as warn or allow"
}
FrontendWarningKind::InterfaceArrayQuery => {
"interface arrays are not data arrays in IEEE 1800-2023 20.7; set interface_array_query=warn or allow for compatibility"
}
FrontendWarningKind::MixedTimescale => {
"declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed"
}
Expand Down
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
Loading
Loading