From 7972552dfbf76c3eefe8dfe06d8103f4f20aeeb1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 13:29:18 +0900 Subject: [PATCH 1/4] fix(sv): keep the bit ranges a child reads from its input ports Flattening splits combinational paths at the bit boundaries each variable is accessed at, and propagates boundaries across port connections. Input ports only passed the parent's boundaries to the child, so where a child read its input port in parts the connected parent variable stayed one range. A parent that fed other bits of the child's output back into that variable then formed a combinational loop that does not exist; written in one module, the same logic simulates. The boundaries of the child port now propagate to the parent variable when the connection is one range as wide as the port, mapped onto that range, so the parent is split as it is when it reads the bits itself. Closes #1955 Change-Id: I24f244b6bb1f0b940eef0f1fbae08573ca011747 --- .../src/symbolic/assembly.rs | 43 +++++++++++++++ .../src/sv/cases/hierarchy.vtest | 54 +++++++++++++++++++ .../frontends/systemverilog/hierarchy.rs | 9 ++++ 3 files changed, 106 insertions(+) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 8c11b502974..9f14b9f63ac 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2401,6 +2401,29 @@ fn extend_boundaries( target.len() != old_len } +/// Add the boundaries of `source` within its range to `target`, mapping the +/// range of `source` onto the equally wide range of `target`. +fn extend_shifted_boundaries( + boundaries: &mut HashMap>, + (source, source_access): (AbsoluteAddr, BitAccess), + (target, target_access): (AbsoluteAddr, BitAccess), +) -> bool { + let shifted: Vec = boundaries + .get(&source) + .into_iter() + .flatten() + .filter(|&&boundary| source_access.lsb <= boundary && boundary <= source_access.msb + 1) + .map(|&boundary| boundary - source_access.lsb + target_access.lsb) + .collect(); + if shifted.is_empty() || (source == target && source_access == target_access) { + return false; + } + let target = boundaries.entry(target).or_default(); + let old_len = target.len(); + target.extend(shifted); + target.len() != old_len +} + fn propagate_boundaries( bindings: &PackageBindings, expanded: &HashMap, @@ -2453,6 +2476,26 @@ fn propagate_boundaries( child_abs, ); } + + // Child -> Parent: where the child reads the + // port in parts, the connected range of a parent + // variable is read in the same parts, as in + // `a = {x[7:4], ...}` within one module. Only a + // connection of one range as wide as the port maps + // bit for bit. + let mut sources = child_addr.sources.iter(); + if let (Some(source), None) = (sources.next(), sources.next()) + && let GlueAddr::Parent(parent_var) = source.id + && source.access.msb - source.access.lsb + == target.access.msb - target.access.lsb + { + let parent_abs = bindings.locate(*id, parent_var); + changed |= extend_shifted_boundaries( + &mut current_boundaries, + (child_abs, target.access), + (parent_abs, source.access), + ); + } } } diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 6538509dbce..307729ae1be 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1462,3 +1462,57 @@ (top Top) (eval) (assert_eq y (+ (<< 1 128) (+ (<< 2 43) 1))) (assert_eq width 129)) + +; A child's output port depends only on the bits of its input port that +; the child reads, so a parent may feed other bits of that output back into +; the port without a combinational loop (#1955). +(case child_ports_keep_the_bit_ranges_they_read + (source "port_bit_ranges.sv" #" + module Btb(input logic [7:0] ifpc_in, output logic [7:0] tar); + logic [3:0] tgt = 4'h9; + assign tar = {ifpc_in[7:4], tgt}; + endmodule + module Top; + logic clk = 0; + logic [7:0] tar, ifpc_out, fetch; + logic [7:0] ifpc = 8'h50; + assign fetch = tar; + always @(posedge clk) ifpc <= fetch; + assign ifpc_out = {ifpc[7:4], fetch[3:0]}; + Btb b(.ifpc_in(ifpc_out), .tar(tar)); + initial begin + #1 $display("%h", fetch); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "59\n")) + +; The same through a part-select of a wider parent variable connected to the +; input port: the bits the child reads map onto the selected range. +(case child_ports_keep_the_bit_ranges_of_selected_connections + (source "port_select_ranges.sv" #" + module Btb(input logic [7:0] ifpc_in, output logic [7:0] tar); + logic [3:0] tgt = 4'h9; + assign tar = {ifpc_in[7:4], tgt}; + endmodule + module Top; + logic clk = 0; + logic [7:0] tar, fetch; + logic [11:0] ifpc_out; + logic [7:0] ifpc = 8'h50; + assign fetch = tar; + always @(posedge clk) ifpc <= fetch; + assign ifpc_out = {ifpc[7:4], fetch[3:0], 4'h3}; + Btb b(.ifpc_in(ifpc_out[11:4]), .tar(tar)); + initial begin + #1 $display("%h %h", fetch, ifpc_out); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "59 593\n")) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 94f3838738b..ca63ad3c551 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -698,3 +698,12 @@ fn array_parameter_elements_check_unselected_conditional_branch_types() { ); } } + +sv_backends! { + fn child_ports_keep_the_bit_ranges_they_read(sim) { + @case "hierarchy::child_ports_keep_the_bit_ranges_they_read"; + } + fn child_ports_keep_the_bit_ranges_of_selected_connections(sim) { + @case "hierarchy::child_ports_keep_the_bit_ranges_of_selected_connections"; + } +} From 33445331f50fca6f1f20a096c512f77235573fa0 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 14:19:51 +0900 Subject: [PATCH 2/4] feat(runtime): run slots of designs with derived clocks in the compiled scheduler The compiled scheduler rejected every design with gated, inverted or divided clocks ("the design has derived clocks", "RTL logic drives an event signal"), so those designs ran every slot in the reference loop. It now tracks the clocks derived, transitively, from the events its slots change, and runs a slot's domains in the reference loop's waves: after the process phase, combinational logic settles; the domains of the events with an active edge evaluate together with those of the clocks gated by a changed source whose levels moved to their active edge, judged then, whose levels become their baselines; a slot without an active edge runs every tracked event whose level moved to its active edge. After each wave commits and logic settles, the domains not run yet whose clocks moved to their active edge run in another, until none does. Baselines are the levels of the tracked events at the slot's start, in the levels slot, which now covers the derived clocks too, so a run that returns in the middle of a slot leaves their levels as the reference does. RTL logic may drive exactly those derived clocks. A design with derived clocks keeps the reference loop when a waiting kernel stages nonblocking assignments, a tracked domain commits in the active region, or a tracked domain may end the run; and when the host observes a derived clock, which changes in the slots of its sources. Change-Id: Ibb48c1e36a21599607c012f0e6748de35e2616ae --- crates/celox-runtime/src/schedule.rs | 19 +- .../celox-runtime/src/simulation/compiled.rs | 3 + crates/celox/src/scheduler.rs | 599 +++++++++++++----- crates/celox/src/simulation/differential.rs | 76 +++ 4 files changed, 548 insertions(+), 149 deletions(-) diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 85be69ad6e6..064c9049bad 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -83,6 +83,9 @@ pub(crate) struct SchedulerRefs { pub(crate) kernel_events: Vec, /// Per clock slot, the bit of `levels` of its event. pub(crate) clock_events: Vec, + /// The bits of `levels` of clocks derived from the others, which any + /// slot may change. + pub(crate) derived_events: u64, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -324,7 +327,7 @@ impl ResolvedSchedule { time_slots: model.time_slots.iter().map(resolve).collect(), scheduler: model.scheduler.as_ref().and_then(|scheduler| { let slots = &scheduler.slots; - Some(SchedulerRefs { + let mut refs = SchedulerRefs { unit: scheduler.unit?, limit: resolve(&slots.limit), now: resolve(&slots.now), @@ -408,7 +411,19 @@ impl ResolvedSchedule { clock_period: resolve(&slots.clock_period), clock_value: resolve(&slots.clock_value), clock_armed: resolve(&slots.clock_armed), - }) + derived_events: 0, + }; + // What no kernel and no clock writes itself derives from them. + let all = 1u64 + .checked_shl(refs.events.len() as u32) + .map_or(u64::MAX, |bit| bit - 1); + let driven = refs + .kernel_events + .iter() + .chain(&refs.clock_events) + .fold(0, |mask, &bits| mask | bits); + refs.derived_events = all & !driven; + Some(refs) }), kernel_fallback: model .scheduler diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 5fff1ceb3e2..7173050bca6 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -75,6 +75,9 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() + // A derived clock changes with the slots of its sources, which + // the scheduler does not tell apart. + || self.observed_events & scheduler.derived_events != 0 || pending.waiters.iter().any(|(process, _)| { scheduler.waits.get(process).is_none_or(Option::is_none) || self.writes_observed(scheduler, process) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index ad23951dc38..1b8bc883877 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -20,6 +20,11 @@ //! any kernel, and re-arm at its end. A design without kernels gets the //! unit for its host clocks alone. //! +//! Clocks derived from the events the slots change (gated, inverted or +//! divided clocks, which RTL logic drives) run in the same slots: their +//! domains evaluate in the reference loop's waves, which judge each clock +//! against its level at the slot's start (see `Plan::batch`). +//! //! The runtime runs the unit only for slots that touch nothing else (see //! `celox_runtime::SimulationState::run_until_observed`): every other slot, //! and every design or kernel this module does not qualify, runs in the @@ -31,6 +36,7 @@ use celox_design::{ TIME_SLOT_WIDTH, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; +use std::collections::BTreeSet; use crate::{ HashMap, HashSet, @@ -88,7 +94,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { // Without kernels, slots of host clocks alone. let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) .then(|| plan.generate(program, &schema.slots)); - let edged = plan.edged(); + let tracked = plan.tracked(); let kernel_events = plan .kernels .iter() @@ -97,14 +103,14 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .iter() .flat_map(|kernel| &kernel.writes) .map(|event| { - edged + tracked .binary_search(event) - .expect("the scheduler's kernels write edged events") + .expect("the scheduler's kernels write tracked events") }) .collect() }) .collect(); - let events = edged + let events = tracked .into_iter() .map(|event| plan.events[event].signal) .collect(); @@ -195,6 +201,14 @@ struct Plan { /// Where the settles run when they wait until their results are read; /// `None` when every settle runs where the reference loop's does. lazy: Option, + /// The clocks derived from the events the slots change, in event order, + /// as indices into [`Self::events`]: their domains run in the waves of + /// a slot (see `Generator::batch`). + derived: Vec, + /// The events the slots change that gate clocks computed + /// combinationally from them, with those clocks: their edges are judged + /// when the source changes. + gating: Vec<(usize, Vec)>, } /// Deferred settles. The reference loop settles after every pass of the @@ -245,12 +259,6 @@ impl Plan { return Err("the design counts event occurrences".into()); } let topology = &model.events; - if !topology.cascaded_events.is_empty() - || !topology.derived_events.is_empty() - || !topology.combinational_derived.is_empty() - { - return Err("the design has derived clocks".into()); - } if !schema.comb_observers.is_empty() { return Err("the design observes combinational processes".into()); } @@ -343,11 +351,9 @@ impl Plan { .chain(sir.eval_only_ffs.values().flatten()) .chain(sir.apply_ffs.values().flatten()) }; - for unit in rtl_units() { - if !written(unit).is_empty() { - return Err("RTL logic drives an event signal".into()); - } - } + // The events RTL logic drives: clocks derived from the events the + // scheduler's slots change, and only those (checked below). + let rtl_written: BTreeSet = rtl_units().flat_map(written).collect(); // A domain that commits its blocking results in the active region // evaluates before the NBA region when it triggers; a kernel that // may trigger it keeps the reference loop. @@ -704,7 +710,7 @@ impl Plan { latest: u64::MAX - longest, } }); - let plan = Self { + let mut plan = Self { events, kernels, clocks, @@ -712,10 +718,99 @@ impl Plan { finish_sites, settle_reads, lazy, + derived: Vec::new(), + gating: Vec::new(), }; let edged = plan.edged(); - if edged.len() > 1 - && edged.iter().any(|&event| { + // The clocks derived from the events the slots change, transitively: + // their levels change only through those events' domains and + // combinational logic. + let index_of: HashMap = plan + .events + .iter() + .enumerate() + .map(|(index, event)| (event.signal, index)) + .collect(); + let derived_from = |event: usize| -> Vec { + let signal = plan.events[event].signal; + topology + .derived_events + .get(&signal) + .into_iter() + .flatten() + .copied() + .chain( + topology + .combinational_derived + .get(&signal) + .into_iter() + .flatten() + .map(|clock| clock.clock), + ) + .filter_map(|address| index_of.get(&topology.canonical(address)).copied()) + .collect() + }; + let mut derived = BTreeSet::new(); + let mut pending = edged.clone(); + while let Some(event) = pending.pop() { + for next in derived_from(event) { + if !edged.contains(&next) && derived.insert(next) { + pending.push(next); + } + } + } + if !rtl_written.is_subset(&derived) { + return Err("RTL logic drives an event signal".into()); + } + let gating: Vec<(usize, Vec)> = edged + .iter() + .filter_map(|&source| { + let signal = plan.events[source].signal; + let gated: Vec = topology + .combinational_derived + .get(&signal) + .into_iter() + .flatten() + .filter_map(|clock| index_of.get(&topology.canonical(clock.clock)).copied()) + .filter(|gated| derived.contains(gated)) + .collect(); + (!gated.is_empty()).then_some((source, gated)) + }) + .collect(); + plan.derived = derived.into_iter().collect(); + plan.gating = gating; + let tracked = plan.tracked(); + if !plan.derived.is_empty() { + // The domains of a slot evaluate in waves until none triggers + // (see `Generator::batch`), which these the reference loop + // runs otherwise keep out of. + if plan + .kernels + .iter() + .flatten() + .filter_map(|kernel| kernel.wait.as_ref()) + .any(|wait| !wait.sites.is_empty()) + { + return Err("a design with derived clocks stages nonblocking assignments".into()); + } + if tracked.iter().any(|event| active_commits.contains(event)) { + return Err(ACTIVE_COMMIT.into()); + } + let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &plan.finish_sites); + if tracked.iter().any(|&event| { + let event = &plan.events[event]; + event + .eval_apply + .iter() + .chain(event.eval_only.iter().flatten()) + .chain(event.apply.iter().flatten()) + .any(ends) + }) { + return Err("a domain of a design with derived clocks may end the run".into()); + } + } + if tracked.len() > 1 + && tracked.iter().any(|&event| { plan.events[event].eval_only.is_none() || plan.events[event].apply.is_none() }) { @@ -724,6 +819,16 @@ impl Plan { Ok(plan) } + /// The events whose levels the slots record and compare: those that + /// can have edges in them and the clocks derived from those, in event + /// order: the bits of [`SchedulerSlots::levels`]. + fn tracked(&self) -> Vec { + let mut tracked = self.edged(); + tracked.extend(&self.derived); + tracked.sort_unstable(); + tracked + } + /// The events the scheduler's kernels write, in event order: the only /// ones that can have edges in its slots. fn written(&self) -> Vec { @@ -751,6 +856,7 @@ impl Plan { fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { let schema = &program.runtime.runtime_schema; let edged = self.edged(); + let tracked = self.tracked(); let mut b = Builder::new(); let comb = b.new_block(); let mut g = Generator { @@ -922,7 +1028,7 @@ impl Plan { // exit in the middle of the slot; those of the clocks' events below, // when the run has clocks. let mut levels = g.constant(0, MAX_EVENTS); - for (bit, &event) in edged.iter().enumerate() { + for (bit, &event) in tracked.iter().enumerate() { if self.clocks.contains(&event) { continue; } @@ -963,10 +1069,10 @@ impl Plan { let due = g.binary(1, due, BinaryOp::And, on); let value = g.mask_bit(values, bit); let was = g.level(event); - let position = edged + let position = tracked .iter() - .position(|&edged| edged == index) - .expect("clocks are edged"); + .position(|&tracked| tracked == index) + .expect("clocks are tracked"); let level = g.bit(was, position); levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, level); let is = g.b.alloc_bit(1, false); @@ -1214,148 +1320,152 @@ impl Plan { // The domains the edges trigger, then the NBA region. g.b.switch_to_block(domains); - let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); - let mask = g.load(slots.exit_arg, MAX_EVENTS); - let zero = g.constant(0, MAX_EVENTS); - let quiet = g.binary(1, mask, BinaryOp::Eq, zero); - let triggered = g.b.new_block(); - let untriggered = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: quiet, - true_block: (untriggered, Vec::new()), - false_block: (triggered, Vec::new()), - }); - - // Without a domain, published nonblocking values settle once more. - g.b.switch_to_block(untriggered); - if self.lazy.is_some() { - g.publish(&staged); - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); - } else if staged.is_empty() { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + if !self.derived.is_empty() { + self.batch(&mut g, &tracked, slot_end, finish_exit); } else { - let mut any = g.constant(0, 1); - for site in &staged { - let pending = g.load(site.pending, 1); - any = g.binary(1, any, BinaryOp::Or, pending); - } - g.publish(&staged); - let publish_settle = g.b.new_block(); + let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); + let mask = g.load(slots.exit_arg, MAX_EVENTS); + let zero = g.constant(0, MAX_EVENTS); + let quiet = g.binary(1, mask, BinaryOp::Eq, zero); + let triggered = g.b.new_block(); + let untriggered = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: any, - true_block: (publish_settle, Vec::new()), - false_block: (slot_end, Vec::new()), + cond: quiet, + true_block: (untriggered, Vec::new()), + false_block: (triggered, Vec::new()), }); - g.b.switch_to_block(publish_settle); - g.settle_then(slot_end); - } - g.b.switch_to_block(triggered); - let evaluated = g.b.new_block(); - if edged.is_empty() { - // No event can have an edge; the mask stays empty. - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); - } else { - let one = g.constant(1, MAX_EVENTS); - let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); - let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); - let single = g.binary(1, others, BinaryOp::Eq, zero); - let one_domain = g.b.new_block(); - let domains = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: single, - true_block: (one_domain, Vec::new()), - false_block: (domains, Vec::new()), - }); + // Without a domain, published nonblocking values settle once more. + g.b.switch_to_block(untriggered); + if self.lazy.is_some() { + g.publish(&staged); + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } else if staged.is_empty() { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } else { + let mut any = g.constant(0, 1); + for site in &staged { + let pending = g.load(site.pending, 1); + any = g.binary(1, any, BinaryOp::Or, pending); + } + g.publish(&staged); + let publish_settle = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: any, + true_block: (publish_settle, Vec::new()), + false_block: (slot_end, Vec::new()), + }); + g.b.switch_to_block(publish_settle); + g.settle_then(slot_end); + } - // One triggered domain evaluates and applies at once. The events - // kernels write are tested first: a run without clocks reaches - // their domains as soon as without clock events. - g.b.switch_to_block(one_domain); - let written = self.written(); - for &index in written.iter().chain(&self.clocks) { - let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let this = g.binary(1, mask, BinaryOp::Eq, bit); - let unit = g.b.new_block(); - let next = g.b.new_block(); + g.b.switch_to_block(triggered); + let evaluated = g.b.new_block(); + if edged.is_empty() { + // No event can have an edge; the mask stays empty. + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + } else { + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let one_domain = g.b.new_block(); + let domains = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), + cond: single, + true_block: (one_domain, Vec::new()), + false_block: (domains, Vec::new()), }); - g.b.switch_to_block(unit); - let units = match self.lazy.as_ref().map(|lazy| &lazy.domains[index]) { - None | Some(DomainSettle::Pending) => &event.eval_apply, - Some(DomainSettle::Fused(units)) => units, - Some(DomainSettle::Settled) => { + + // One triggered domain evaluates and applies at once. The events + // kernels write are tested first: a run without clocks reaches + // their domains as soon as without clock events. + g.b.switch_to_block(one_domain); + let written = self.written(); + for &index in written.iter().chain(&self.clocks) { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let this = g.binary(1, mask, BinaryOp::Eq, bit); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match self.lazy.as_ref().map(|lazy| &lazy.domains[index]) { + None | Some(DomainSettle::Pending) => &event.eval_apply, + Some(DomainSettle::Fused(units)) => units, + Some(DomainSettle::Settled) => { + let evaluate = g.b.new_block(); + g.settle_then(evaluate); + g.b.switch_to_block(evaluate); + &event.eval_apply + } + }; + for unit in units { + g.inline_writer(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + + // Several evaluate, then apply, each in event order. + g.b.switch_to_block(domains); + if edged.len() < 2 { + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + } else { + let mut mask = mask; + let mut zero = zero; + if self.lazy.as_ref().is_some_and(|lazy| lazy.several) { let evaluate = g.b.new_block(); g.settle_then(evaluate); g.b.switch_to_block(evaluate); - &event.eval_apply + mask = g.load(slots.exit_arg, MAX_EVENTS); + zero = g.constant(0, MAX_EVENTS); } - }; - for unit in units { - g.inline_writer(unit, finish_exit); - } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); - g.b.switch_to_block(next); - } - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - - // Several evaluate, then apply, each in event order. - g.b.switch_to_block(domains); - if edged.len() < 2 { - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - } else { - let mut mask = mask; - let mut zero = zero; - if self.lazy.as_ref().is_some_and(|lazy| lazy.several) { - let evaluate = g.b.new_block(); - g.settle_then(evaluate); - g.b.switch_to_block(evaluate); - mask = g.load(slots.exit_arg, MAX_EVENTS); - zero = g.constant(0, MAX_EVENTS); - } - for phase in [Phase::Evaluate, Phase::Apply] { - for &index in &edged { - let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); - let this = g.binary(1, selected, BinaryOp::Ne, zero); - let unit = g.b.new_block(); - let next = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), - }); - g.b.switch_to_block(unit); - let units = match phase { - Phase::Evaluate => event.eval_only.as_ref(), - Phase::Apply => event.apply.as_ref(), - } - .expect("several edged events have their units (`Plan::new`)"); - for unit in units { - g.inline_writer(unit, finish_exit); + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &edged { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match phase { + Phase::Evaluate => event.eval_only.as_ref(), + Phase::Apply => event.apply.as_ref(), + } + .expect("several edged events have their units (`Plan::new`)"); + for unit in units { + g.inline_writer(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); } - g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); - g.b.switch_to_block(next); } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); } - } - // The domains' results and the nonblocking values publish before - // combinational logic settles. - g.b.switch_to_block(evaluated); - g.publish(&staged); - match &self.lazy { - Some(_) => { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + // The domains' results and the nonblocking values publish before + // combinational logic settles. + g.b.switch_to_block(evaluated); + g.publish(&staged); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } + None => g.settle_then(slot_end), } - None => g.settle_then(slot_end), } // At the end of the slot each clock whose edge applied waits for the @@ -1448,6 +1558,177 @@ impl Plan { } } +impl Plan { + /// The domains of a slot of a design with derived clocks, as the + /// reference loop's waves run them: combinational logic settles; the + /// domains of the events with an active edge evaluate together with + /// those of the clocks computed combinationally from a changed source + /// whose level moved to their active edge, judged now, whose levels + /// become their baseline; without an active edge, every tracked event + /// whose level moved to its active edge since the slot started. After + /// each wave commits and logic settles, the domains not run yet whose + /// clocks moved to their active edge run in another, until none does. + /// The domains run in the slot collect in `exit_arg`. + fn batch( + &self, + g: &mut Generator<'_>, + tracked: &[usize], + slot_end: celox_sir::BlockId, + finish_exit: celox_sir::BlockId, + ) { + let slots = g.slots; + let wave = g.b.new_block(); + let mask = g.b.alloc_bit(MAX_EVENTS, false); + let fire = g.b.new_block_with(vec![mask]); + let judge = g.b.new_block(); + // A pass of the process phase settles before the domains; a + // deferred one runs now. + match &self.lazy { + Some(_) => g.settle_then(judge), + None => { + g.b.seal_block(SIRTerminator::Jump(judge, Vec::new())); + } + } + + g.b.switch_to_block(judge); + let active = g.load(slots.exit_arg, MAX_EVENTS); + let levels = g.load(slots.levels, MAX_EVENTS); + let stable = self.stable_edges(g, tracked, levels); + let mut gated_edges = g.constant(0, MAX_EVENTS); + let mut judged = levels; + for (source, gated) in &self.gating { + let source_bit = position(tracked, *source); + let was = g.mask_bit(levels, source_bit); + let is = g.level(&self.events[*source]); + let changed = g.binary(1, was, BinaryOp::Ne, is); + for &clock in gated { + let clock_bit = position(tracked, clock); + let was = g.mask_bit(levels, clock_bit); + let is = g.level(&self.events[clock]); + let edge = g.edge(&self.events[clock], was, is); + let edge = g.binary(1, edge, BinaryOp::And, changed); + let bit = g.bit(edge, clock); + gated_edges = g.binary(MAX_EVENTS, gated_edges, BinaryOp::Or, bit); + // The judged level is the clock's baseline from now on. + let level = g.b.alloc_bit(1, false); + g.b.emit(SIRInstruction::Mux(level, changed, is, was)); + let keep = g.constant(!(1u64 << clock_bit), MAX_EVENTS); + let kept = g.binary(MAX_EVENTS, judged, BinaryOp::And, keep); + let bit = g.bit(level, clock_bit); + judged = g.binary(MAX_EVENTS, kept, BinaryOp::Or, bit); + } + } + g.store(slots.levels, SCHEDULER_TIME_WIDTH, judged); + let zero = g.constant(0, MAX_EVENTS); + let edged = g.binary(1, active, BinaryOp::Ne, zero); + let sources = g.binary(MAX_EVENTS, active, BinaryOp::Or, gated_edges); + let triggers = g.b.alloc_bit(MAX_EVENTS, false); + g.b.emit(SIRInstruction::Mux(triggers, edged, sources, stable)); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, triggers); + let quiet = g.binary(1, triggers, BinaryOp::Eq, zero); + let first = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (slot_end, Vec::new()), + false_block: (first, Vec::new()), + }); + g.b.switch_to_block(first); + g.b.seal_block(SIRTerminator::Jump(fire, vec![triggers])); + + // A wave after a commit: the domains not run yet whose clocks moved. + g.b.switch_to_block(wave); + let fired = g.load(slots.exit_arg, MAX_EVENTS); + let levels = g.load(slots.levels, MAX_EVENTS); + let stable = self.stable_edges(g, tracked, levels); + let all = g.constant(u64::MAX, MAX_EVENTS); + let unfired = g.binary(MAX_EVENTS, fired, BinaryOp::Xor, all); + let ready = g.binary(MAX_EVENTS, stable, BinaryOp::And, unfired); + let zero = g.constant(0, MAX_EVENTS); + let quiet = g.binary(1, ready, BinaryOp::Eq, zero); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (slot_end, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(next); + let fired = g.binary(MAX_EVENTS, fired, BinaryOp::Or, ready); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, fired); + g.b.seal_block(SIRTerminator::Jump(fire, vec![ready])); + + // A wave: one domain evaluates and commits at once, several + // evaluate, then commit, in event order; then logic settles. + g.b.switch_to_block(fire); + let zero = g.constant(0, MAX_EVENTS); + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let alone = g.b.new_block(); + let together = g.b.new_block(); + let committed = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (alone, Vec::new()), + false_block: (together, Vec::new()), + }); + g.b.switch_to_block(alone); + for &index in tracked { + g.if_bit(mask, index, |g| { + for unit in &self.events[index].eval_apply { + g.inline_writer(unit, finish_exit); + } + }); + } + g.b.seal_block(SIRTerminator::Jump(committed, Vec::new())); + g.b.switch_to_block(together); + if tracked.len() > 1 { + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in tracked { + let event = &self.events[index]; + let units = match phase { + Phase::Evaluate => event.eval_only.as_ref(), + Phase::Apply => event.apply.as_ref(), + } + .expect("tracked events have their units (`Plan::new`)"); + g.if_bit(mask, index, |g| { + for unit in units { + g.inline_writer(unit, finish_exit); + } + }); + } + } + } + g.b.seal_block(SIRTerminator::Jump(committed, Vec::new())); + g.b.switch_to_block(committed); + g.settle_then(wave); + } + + /// The tracked events whose levels moved to their active edge against + /// `levels`, their baselines, as bits by event index. + fn stable_edges( + &self, + g: &mut Generator<'_>, + tracked: &[usize], + levels: RegisterId, + ) -> RegisterId { + let mut edges = g.constant(0, MAX_EVENTS); + for (position, &index) in tracked.iter().enumerate() { + let was = g.mask_bit(levels, position); + let is = g.level(&self.events[index]); + let edge = g.edge(&self.events[index], was, is); + let bit = g.bit(edge, index); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + } + edges + } +} + +/// The place of event `index` among `tracked`, the bit of its level. +fn position(tracked: &[usize], index: usize) -> usize { + tracked.binary_search(&index).expect("the event is tracked") +} + enum Phase { Evaluate, Apply, @@ -1559,6 +1840,30 @@ impl Generator<'_> { self.binary(1, value, BinaryOp::Ne, zero) } + /// Whether a change of `event`'s level from `was` to `is` is its active + /// edge. + fn edge(&mut self, event: &Event, was: RegisterId, is: RegisterId) -> RegisterId { + let changed = self.binary(1, was, BinaryOp::Ne, is); + let active = self.equals(is, u64::from(event.active)); + self.binary(1, changed, BinaryOp::And, active) + } + + /// Run `body` when bit `index` of the 64-bit `mask` is set. + fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { + let set = self.mask_bit(mask, index); + let run = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (run, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(run); + body(self); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + /// A block that ends the run with `exit`, emitted by /// [`Self::emit_exits`]. fn exit_block(&mut self, exit: SchedulerExit) -> celox_sir::BlockId { diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 8a8c3f1ff38..ce77aa31b3e 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -1151,6 +1151,82 @@ mod tests { } } + /// Clocks derived from the clock a kernel drives run in compiled slots: + /// gated by a kernel's enable, gated by an enable the clock's own domain + /// raises, inverted, moved back by the commit after the clock's edge + /// moved it, divided by a register, a divided clock gated by a kernel's + /// enable that changes with the clock's edge (it runs after the commit), + /// and divided twice. + #[test] + fn derived_clocks_run_in_compiled_slots() { + for derived in [ + "assign dclk = clk & en;", + "assign dclk = clk & ren;", + "assign dclk = ~clk;", + "logic tog = 1'b1; always_ff @(posedge clk) tog <= ~tog; assign dclk = clk ^ tog;", + "always_ff @(posedge clk) dclk <= ~dclk;", + "logic div = 1'b0; always_ff @(posedge clk) div <= ~div; assign dclk = div & en;", + "logic half = 1'b0; always_ff @(posedge clk) half <= ~half; \ + always_ff @(posedge half) dclk <= ~dclk;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic en = 1'b0; + logic ren = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + always #5 clk = ~clk; + initial forever begin #17 en = ~en; end + always_ff @(posedge clk) begin a <= a + 8'd1; ren <= a[1]; end + {derived} + always_ff @(posedge dclk) b <= b + a; + assign y = a ^ b; + endmodule" + ); + host_driven_agrees(&source, &[(100, &[]), (333, &[])]); + } + } + + /// A host clock gated by a kernel's enable, or divided, in a design + /// with and without kernels. + #[test] + fn derived_host_clocks_run_in_compiled_slots() { + for (kernel, derived) in [ + ( + "initial forever begin #17 en = ~en; end", + "assign dclk = clk & en;", + ), + ("", "always_ff @(posedge clk) dclk <= ~dclk;"), + ("", "assign dclk = clk & k[0];"), + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic clk, input logic [7:0] k, output logic [7:0] y); + logic en = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + {kernel} + always_ff @(posedge clk) a <= a + k; + {derived} + always_ff @(posedge dclk) b <= b + a; + assign y = a ^ b; + endmodule" + ); + host_driven_agrees( + &source, + &[ + (100, &[Host::Set("k", 3), Host::Clock("clk", 10, 5)]), + (200, &[Host::Set("k", 2)]), + (300, &[]), + ], + ); + } + } + /// A domain whose next state combinational logic computes runs its /// fused units with a settle pending: they compute what it reads. #[test] From 3fb259bef18ef061ef0b8d3328a0cc1bb83e638a Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 14:45:58 +0900 Subject: [PATCH 3/4] fix(runtime): judge derived clocks of slots against every source's level Two cases where the waves of a slot with derived clocks differed from the reference loop's: - A host clock input with no clock armed kept its slot-start level out of the levels slot, which only the clock-apply block filled. The waves compared against zero, so a gate on a clock input the host had set high fired its source's domain at every slot. The levels of every tracked event are now recorded at the slot's start. - A waiting kernel woken by a clock's change runs in a pass after the settle that judges the clocks gated by it; what it writes moves those clocks only for the waves after the commit. The waves judge once, after every pass, so a design with gated clocks whose waiting kernels write what combinational logic reads keeps the reference loop. Change-Id: I42793209eeebcfeffaf0fbc08b91fc586edc58f0 --- crates/celox/src/scheduler.rs | 25 ++++++++- crates/celox/src/simulation/differential.rs | 60 +++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 1b8bc883877..05002091ffb 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -796,6 +796,26 @@ impl Plan { if tracked.iter().any(|event| active_commits.contains(event)) { return Err(ACTIVE_COMMIT.into()); } + // A gated clock is judged at the settle after its source changes, + // before a kernel the change wakes runs in another pass; what that + // kernel writes moves the clock only for the waves after the + // commit. The waves judge once, after every pass. + if !plan.gating.is_empty() { + let comb_reads: HashSet = + sir.eval_comb.iter().flat_map(loads).map(storage).collect(); + let feeds_gates = plan.kernels.iter().enumerate().any(|(index, kernel)| { + kernel.as_ref().is_some_and(|kernel| kernel.wait.is_some()) + && kernel_stores[index] + .iter() + .any(|store| comb_reads.contains(store)) + }); + if feeds_gates { + return Err( + "a waiting kernel writes what combinational logic of a gated clock reads" + .into(), + ); + } + } let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &plan.finish_sites); if tracked.iter().any(|&event| { let event = &plan.events[event]; @@ -1026,10 +1046,11 @@ impl Plan { } // The levels the slot starts from, the baseline of its edges, for an // exit in the middle of the slot; those of the clocks' events below, - // when the run has clocks. + // when the run has clocks, unless the slot's waves compare against + // them: a host clock no clock drives keeps the level the host set. let mut levels = g.constant(0, MAX_EVENTS); for (bit, &event) in tracked.iter().enumerate() { - if self.clocks.contains(&event) { + if self.clocks.contains(&event) && self.derived.is_empty() { continue; } let level = g.level(&self.events[event]); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ce77aa31b3e..44896cfbc7f 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -1227,6 +1227,66 @@ mod tests { } } + /// A host clock input the host set once and no clock drives keeps its + /// level through compiled slots: a gate on it judges from that level, + /// not from an unrecorded one. + #[test] + fn derived_clocks_of_an_unclocked_host_input_keep_its_level() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic clk, output logic [7:0] y); + logic en = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + initial forever #17 en = ~en; + assign dclk = clk & en; + always_ff @(posedge clk) a <= a + 8'd1; + always_ff @(posedge dclk) b <= b + 8'd1; + assign y = a ^ b; + endmodule + "#; + host_driven_agrees(source, &[(100, &[Host::Set("clk", 1)]), (200, &[])]); + } + + /// A gate a waiting kernel writes changes after the pass that judged + /// its clock: the reference judges it again only after the commit, so + /// the design keeps the reference loop. + #[test] + fn gates_written_by_waiting_kernels_keep_the_reference_loop() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic en = 1'b0; + logic gclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + always #5 clk = ~clk; + initial forever @(posedge clk) en = ~en; + assign gclk = clk & en; + always_ff @(posedge clk) a <= a + 8'd1; + always_ff @(posedge gclk) b <= a; + assign y = a ^ b; + endmodule + "#; + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(200).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(200).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?}"); + } + let gate = crate::KernelSchedule::Reference( + "a waiting kernel writes what combinational logic of a gated clock reads".into(), + ); + let kernels = build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!(kernels.iter().all(|kernel| *kernel == gate), "{kernels:?}"); + } + /// A domain whose next state combinational logic computes runs its /// fused units with a settle pending: they compute what it reads. #[test] From 1a5e07966ee8932d1ee8700e4191450f88b7e8df Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 19:51:02 +0900 Subject: [PATCH 4/4] fix(sv)!: defer the actions of deferred assertions in processes `assert #0`, `assume #0`, `assert final` and `assume final` in a process reported at once, like simple immediate assertions. Glitches that a deferred assertion exists to hide were therefore reported. IEEE 1800-2023 16.4 instead has the action wait in the process's deferred assertion report queue: - its arguments are evaluated when the assertion executes; - a flush point of the process discards what waits (16.4.2): a resume from an event control or a wait, but not a resume after a delay; - what is left matures in the Observed region (`#0`) or the Postponed region (`final`) of the time slot. This is the second part of SVA stage 1 (#89). **Flush points as events.** - The SV frontend gives a process that holds a deferred assertion, directly or in a subroutine it calls, a flush-point event site (`DeferredSite::FlushPoint`). A process kernel reports it whenever it wakes from an event control or a wait (`ProcessKernelBuilder::flush_deferred_at`, in `wake_if`). An edge-triggered process reports it at the start of each evaluation, which is a resume from its event control. - The site of a deferred action is `DeferredSite::Action { queue, region }`, where `queue` is the flush-point site of its process. Assembly offsets it like the other sites of the instance. - A deferred `$fatal` does not stop the evaluation; it ends the simulation when it matures. - The SV frontend also finds a deferred assertion in a subroutine that only the default of an omitted argument, or a timing control (`wait`, an event control or a delay), calls. **The queue on the host.** - `PendingRuntimeEvents`, which the simulator's drain and `RuntimeEventDrain` share, holds back the events of action sites in issue order. A flush-point event discards those of its queue. - When the slot is over, `mature` queues what is left: the `#0` actions, then the `final` ones, up to the first fatal one, after which the simulation ends. Events of the slot's active regions, such as `$display` output, come before them. - Nothing is needed for designs without deferred assertions: the site table is empty and `Simulator::deferred_assertions` is false. - Events lost to a full event buffer (`Missed`) may have held a deferred `$fatal`. In a design with a fatal deferred action they end the simulation when the slot matures, with `missed N runtime events, which may have held a deferred $fatal`. **The end of a time slot.** - A step of the runtime ends before its slot when a process waits for zero time, and `try_finish_timed_step` is called at the end of every step. The new `HostBoundary::try_end_time_slot` is called only when no more work is due at that time; the simulator matures the queue there. - A design with deferred assertions runs the runtime's loop (`CompiledSlots::None`), which tells the two apart. - A `Simulator` call is a time slot, so the queue matures after each run of a domain (`fire`), after `tick_events`, and after `edge` and `edges` through derived domains (`note_edge`), which also serve `tick` of a clock with derived domains. **Analyzer.** - The deferral of an immediate assertion is recorded in `AssertionSite::deferral` (previously always `None`). - A deferred action must be one display or severity task call (16.4). User subroutines would run in the Reactive region, which Celox does not model, so they are rejected. Deferred assertions in `always_comb`, `always_latch` and `always` processes lowered as combinational logic still report at once. Module-level ones and deferred cover stay rejected. The next change handles combinational processes. - New `crates/celox/tests/sv_deferred_assertions.rs` on the interpreter, cranelift, native and wasm backends: - a resume from `@(a or b)` flushes the failure of the first execution, while the immediate assertion beside it reports; - the `a3`/`a4` example of 16.4.2: `a3` reports and `a4` is flushed; - `$display` output, then `#0` actions (fail and pass), then `final` ones in one slot; - an edge-triggered process: one edge reports, and a second edge in the slot flushes; - a deferred `$fatal` stops the run at the end of its slot and is drained as a fatal report; - a `Simulator` tick matures the action of an `always_ff`; - a timed `Simulation` built from a reloaded native image flushes the glitch and reports the lasting failure as the in-process build does (`native_simulation_image::deferred_assertions_run_from_the_image`); - `edges` and ticks of a clock with a derived domain mature each call's actions: 9 reports for 2 `edges` periods and 4 ticks. Without `note_edge` maturing none are drained; - a function called only from the default of an omitted argument holds a `#0` assertion: its report follows the `$display` after the call. Without the default scan it comes first; - a deferred `$fatal` followed by 2,000 `$display`s in its slot still ends the run, with a `missed` error; - a `final` action after an `#0` `$fatal` does not mature. Without the change it was drained; - a function called only by a `wait` condition holds an `#0` assertion: its report follows the `$display` after the wait. Without the change it came first; - an action of two statements is rejected. - `cargo nextest run` with CI's features (`celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus`) on celox, celox-frontend-{core,sv,veryl}, celox-sv-analyzer, celox-runtime, celox-design, celox-slt, celox-test-suite, celox-vpi and celox-napi: 15,270 passed, after updating the two analyzer tests that gave deferred assertions assignment actions, which 16.4 does not allow (they now use a `$info` action, and check that the header's deferral makes an assignment action an error). - sv-tests conformance (`conformance/sv-tests/run.py`): unchanged from `expected.tsv`. - `cargo clippy --workspace --all-targets` with CI's features and `-D warnings`, clippy of `celox` without default features, `cargo fmt --check`. - `celox_design::RuntimeEventSite` has the new field `deferred`, of the new type `DeferredSite`. The native image container version is 36. - Deferred assertions in processes report when they mature, at the end of their time slot, and a flush point discards them. Change-Id: I1062591d4b559e6f6fa13de6f7a435b7790c02e5 --- crates/celox-design/src/lib.rs | 21 ++ crates/celox-frontend-core/src/process.rs | 17 + .../src/symbolic/assembly.rs | 6 + crates/celox-frontend-sv/src/lowering/comb.rs | 1 + crates/celox-frontend-sv/src/lowering/ff.rs | 105 +++++- .../celox-frontend-veryl/src/lowering/ff.rs | 1 + .../src/lowering/logic_tree/effect.rs | 1 + crates/celox-frontend-veryl/src/testbench.rs | 1 + crates/celox-runtime/src/simulation/host.rs | 9 + crates/celox-runtime/src/simulation/time.rs | 5 + .../celox-sv-analyzer/src/ast/procedural.rs | 35 +- .../src/ast/procedural/control.rs | 18 +- .../source_tree/tests/immediate_assertions.rs | 29 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 14 +- crates/celox/src/simulator.rs | 140 +++++++- crates/celox/src/simulator/host/file_io.rs | 1 + crates/celox/tests/native_simulation_image.rs | 43 +++ crates/celox/tests/sv_deferred_assertions.rs | 304 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 19 ++ docs/ja/guide/systemverilog-reference.md | 16 + 21 files changed, 768 insertions(+), 20 deletions(-) create mode 100644 crates/celox/tests/sv_deferred_assertions.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index ac20aebb6cb..8e9f73a561d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -157,6 +157,22 @@ pub enum AssertionDeferral { Final, } +/// How the host defers the events of a site (IEEE 1800-2023 16.4). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum DeferredSite { + /// A flush point of a process with deferred assertions (16.4.2): the + /// actions its queue holds are discarded. The events of this site are + /// not shown. + FlushPoint, + /// The action of a deferred assertion: its event waits in the queue of + /// the flush-point site `queue` of the same instance, numbered like the + /// sites of its module, until `region` of the time slot. + Action { + queue: u32, + region: AssertionDeferral, + }, +} + /// Which action block of an assertion issues a report. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum AssertionOutcome { @@ -191,6 +207,10 @@ pub struct RuntimeEventSite { /// The assertion whose action issues this report. #[serde(default)] pub assertion: Option, + /// How the host defers the events of this site, for the processes of + /// deferred assertions. + #[serde(default)] + pub deferred: Option, pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, @@ -1979,6 +1999,7 @@ mod tests { scope: None, location: None, assertion: None, + deferred: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index b141ad8d532..a67dbcf8eb8 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -62,6 +62,9 @@ pub struct ProcessKernelBuilder { resume_blocks: Vec, /// The wait site whose resume point is being lowered. wait_site: Option, + /// The runtime event site the process reports at its flush points + /// (see [`Self::flush_deferred_at`]). + flush_site: Option, } impl ProcessKernelBuilder { @@ -78,9 +81,17 @@ impl ProcessKernelBuilder { }, resume_blocks: vec![start], wait_site: None, + flush_site: None, } } + /// Report runtime event site `site` whenever the process resumes from + /// an event control or a wait: a flush point of its deferred + /// assertions (IEEE 1800-2023 16.4.2). A resume after a delay is not. + pub fn flush_deferred_at(&mut self, site: u32) { + self.flush_site = Some(site); + } + /// The kernel's control slots, with [`ProcessSlots::const_delays`] set /// for the delays lowered so far. pub fn slots(&self) -> ProcessSlots { @@ -225,6 +236,12 @@ impl ProcessKernelBuilder { self.store_delay_constant(u64::from(site)); self.end(ProcessStatus::Pending); self.builder.switch_to_block(woken); + if let Some(site_id) = self.flush_site { + self.builder.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } } /// `wait (condition)` (IEEE 1800-2023 9.4.3) at wait site `site`: diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index aff5ec85d2c..258e3beaf76 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -3257,11 +3257,17 @@ fn relocate_units( } let mut runtime_event_site_map = HashMap::default(); let scope = elaborated_scope_name(root_name, path, expanded, indexed_instances); + let site_base = runtime_event_sites.len() as u32; for (local_site, site) in sim_module.runtime_event_sites.iter().enumerate() { let global_site = runtime_event_sites.len() as u32; runtime_event_site_map.insert(local_site as u32, global_site); let mut site = site.clone(); site.scope = Some(scope.clone()); + // A deferred action names the flush point of its process in the + // same instance. + if let Some(celox_design::DeferredSite::Action { queue, .. }) = &mut site.deferred { + *queue += site_base; + } runtime_event_sites.push(site); } diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index ecaee3626b9..9a4c532d84d 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3605,6 +3605,7 @@ impl<'p, 'a> Comb<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), + deferred: None, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 649d4c6c6a1..6058fabcc4a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -17,7 +17,9 @@ mod strings; use super::procedural::*; use super::*; -use celox_design::{CounterKind, NbaPosition, NbaSite, SPARSE_WORKING_REGION, WaitSite}; +use celox_design::{ + CounterKind, DeferredSite, NbaPosition, NbaSite, SPARSE_WORKING_REGION, WaitSite, +}; use celox_frontend_core::process::{NBA_POSITION_WIDTH, ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; @@ -92,6 +94,9 @@ pub(super) struct Ff<'p, 'a> { /// Whether a combinational process also reruns for occurrences of its /// inputs that left their value unchanged. input_occurrences: bool, + /// The flush-point site of a process with deferred assertions, whose + /// queue their actions wait in. + flush_site: Option, } fn stable(var_id: SourceVarId) -> Addr { @@ -147,9 +152,86 @@ impl<'p, 'a> Ff<'p, 'a> { nba_sites: Vec::new(), host_request_sites: Vec::new(), nba_switches: Vec::new(), + flush_site: None, } } + /// Whether `stmts`, or a subroutine they call, including in timing + /// controls and the defaults of omitted arguments, hold a deferred + /// assertion. + fn has_deferred_assertions( + &self, + stmts: &[sv::ir::Stmt], + visited: &mut HashSet, + ) -> bool { + let mut found = false; + let mut calls = Vec::new(); + for stmt in stmts { + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::SystemTask { + assertion: Some(assertion), + .. + } = stmt + && assertion.deferral != celox_design::AssertionDeferral::None + { + found = true; + } + stmt_calls(stmt, &mut calls); + // Timing controls evaluate their expressions too. + match stmt { + sv::ir::Stmt::Wait(condition) => collect_calls(condition, &mut calls), + sv::ir::Stmt::WaitEvent(items) => { + for item in items { + collect_calls(&item.expr, &mut calls); + } + } + sv::ir::Stmt::Delay { amount, .. } => collect_calls(amount, &mut calls), + _ => {} + } + }); + } + if found { + return true; + } + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = self.m.subroutine(&name).cloned() else { + continue; + }; + default_calls(&subroutine, &args, &mut calls); + if visited.insert(name) && self.has_deferred_assertions(&subroutine.body, visited) { + return true; + } + } + false + } + + /// For a process with deferred assertions, its flush-point site (IEEE + /// 1800-2023 16.4.2), whose queue their actions wait in. + fn deferred_flush_site(&mut self, body: &[sv::ir::Stmt]) -> Option { + if !self.has_deferred_assertions(body, &mut HashSet::default()) { + return None; + } + let site = self.m.event_site(RuntimeEventSite { + kind: RuntimeEventKind::Write, + template: None, + sizing: DisplaySizing::Ieee, + scope: None, + location: None, + assertion: None, + deferred: Some(DeferredSite::FlushPoint), + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + arg_float_precision: Vec::new(), + arg_is_handle: Vec::new(), + }); + self.flush_site = Some(site); + Some(site) + } + /// Lower a combinational process that reruns only when an input value /// changed. Its inputs then need no occurrence counters, so the units /// that write them stay unchanged. @@ -3173,6 +3255,13 @@ impl<'p, 'a> Ff<'p, 'a> { _ => None, }; let event_kind = kind.event_kind(); + // The action of a deferred assertion waits in its process's queue + // until the assertion matures (IEEE 1800-2023 16.4.1). + let deferred = assertion_site + .map(|assertion| assertion.deferral) + .filter(|®ion| region != celox_design::AssertionDeferral::None) + .zip(self.flush_site) + .map(|(region, queue)| DeferredSite::Action { queue, region }); let site_id = self.m.event_site(RuntimeEventSite { kind: event_kind, template: template.clone(), @@ -3180,6 +3269,7 @@ impl<'p, 'a> Ff<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), + deferred, arg_widths, arg_signed, arg_is_string, @@ -3190,7 +3280,8 @@ impl<'p, 'a> Ff<'p, 'a> { site_id, args: regs, }); - if kind.is_fatal() { + // A deferred `$fatal` ends the simulation when it matures. + if kind.is_fatal() && deferred.is_none() { let code = self .m .runtime_error(template.unwrap_or_else(|| sv::ir::SystemTask::Fatal.to_string())); @@ -4272,6 +4363,13 @@ impl<'p, 'a> Ff<'p, 'a> { )); } } + // Each evaluation resumes the process from its event control. + if let Some(site_id) = self.deferred_flush_site(&body) { + self.b.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); } @@ -4710,6 +4808,9 @@ impl Ff<'_, '_> { ) -> Result { self.process = process; let mut kernel = ProcessKernelBuilder::new(slots); + if let Some(site) = self.deferred_flush_site(body) { + kernel.flush_deferred_at(site); + } std::mem::swap(&mut self.b, kernel.builder()); self.kernel = Some(kernel); self.exec_block(body)?; diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 4570dde39a2..474841588f8 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -555,6 +555,7 @@ impl<'a> FfParser<'a> { scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args .iter() .map(|arg| self.get_expression_width(&arg.0)) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index f77095b9bd8..f3c50003647 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -103,6 +103,7 @@ fn register_comb_runtime_event_site<'a>( scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args .iter() .map(|arg| arg.0.comptime().r#type.total_width().unwrap_or(1)) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index e0a5971e020..e94a57e8747 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -111,6 +111,7 @@ fn runtime_event_site_for_assert( scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args.iter().map(assert_arg_width).collect(), arg_signed: value_args .iter() diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 206b2f1cdd0..5e31cbfa1c6 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -134,6 +134,15 @@ pub trait HostBoundary: UnitExecutor { self.finish_timed_step(timestamp); Ok(()) } + + /// Called after [`Self::try_finish_timed_step`] when the time slot + /// `timestamp` is over: no more work is due at that time. A step ends + /// before its slot does when a process waits for zero time. The + /// runtime's loop calls it; a host that has work here returns + /// [`CompiledSlots::None`] from [`Self::compiled_slots`]. + fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } } /// How many time slots a compiled scheduler may run at once (see diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 32c77cebfb0..e25822ae243 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -210,6 +210,11 @@ impl SimulationState { if executor.take_slot_writes() { self.host_pending = true; } + // The slot is over when nothing more is due at its time, host + // writes included. + if !self.host_pending && self.next_work_time() != Some(current_time) { + executor.try_end_time_slot(current_time)?; + } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index adbf305d7f8..17604d9017c 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1623,9 +1623,33 @@ fn assertion_failure(keyword: &str, site: Option) }] } -/// Attribute the severity tasks of an assertion's action block to it. Tasks -/// in subroutines the block calls are not attributed, and the tasks of a -/// nested assertion keep its own attribution. +/// Check the action of a deferred assertion: one subroutine call (IEEE +/// 1800-2023 16.4). Only display and severity tasks are supported, since +/// a user subroutine would run in the Reactive region and could wake +/// processes there. +fn deferred_action(body: &[Stmt]) -> Result<(), AnalyzerError> { + match body { + [] => Ok(()), + [ + Stmt::SystemTask { + task: + SystemTask::Display(_) + | SystemTask::Write(_) + | SystemTask::Severity(_) + | SystemTask::Fatal, + .. + }, + ] => Ok(()), + _ => Err(unsupported( + "deferred assertion action other than one display or severity task call", + )), + } +} + +/// Attribute the severity tasks of an assertion's action block to it, and +/// for a deferred assertion its display tasks, which wait in the same +/// queue. Tasks in subroutines the block calls are not attributed, and the +/// tasks of a nested assertion keep its own attribution. fn attribute_reports( body: &mut [Stmt], assertion: &celox_design::AssertionSite, @@ -1633,11 +1657,14 @@ fn attribute_reports( ) { for stmt in body { stmt.walk_mut(&mut |stmt| { + let deferred = assertion.deferral != celox_design::AssertionDeferral::None; if let Stmt::SystemTask { - task: SystemTask::Severity(_) | SystemTask::Fatal, + task, assertion: attributed @ None, .. } = stmt + && (matches!(task, SystemTask::Severity(_) | SystemTask::Fatal) + || deferred && matches!(task, SystemTask::Display(_) | SystemTask::Write(_))) { *attributed = Some(celox_design::AssertionSite { outcome, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index a2f7748bf8b..a5d8c5c49c5 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -241,6 +241,10 @@ impl BodyBuilder<'_, '_, '_> { failure, } => { let condition = self.native_assertion_condition(keyword, header)?; + let celox_sv_syntax::AssertionHeader::Immediate { deferred, .. } = header + else { + unreachable!("matched an immediate header"); + }; let statement = native.statement(id); jobs.push(Job::AssertionThen { condition, @@ -255,7 +259,15 @@ impl BodyBuilder<'_, '_, '_> { "cover" => celox_design::AssertionDirective::Cover, _ => celox_design::AssertionDirective::Assert, }, - deferral: celox_design::AssertionDeferral::None, + deferral: match deferred { + None => celox_design::AssertionDeferral::None, + Some(celox_sv_syntax::AssertionDeferral::Zero) => { + celox_design::AssertionDeferral::Observed + } + Some(celox_sv_syntax::AssertionDeferral::Final) => { + celox_design::AssertionDeferral::Final + } + }, outcome: celox_design::AssertionOutcome::Fail, }, span: super::source_span(statement.tokens, self.tree), @@ -329,6 +341,10 @@ impl BodyBuilder<'_, '_, '_> { if let Some((keyword, span)) = default_failure { else_body = assertion_failure(&keyword, span); } + if assertion.deferral != celox_design::AssertionDeferral::None { + deferred_action(&then_body)?; + deferred_action(&else_body)?; + } attribute_reports( &mut then_body, &assertion, diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs index d74fb4fa2f9..f7af1518363 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs @@ -37,8 +37,15 @@ fn assigned_literal(statements: &[Stmt]) -> &str { } #[test] fn native_immediate_and_deferred_predicate_operators_drive_real_conditions() { - for keyword in ["assert", "assume", "cover", "assert #0", "assume final"] { - let mut tree = parsed(&format!("{keyword}(a+1) y=1;")); + for (keyword, action) in [ + ("assert", "y=1;"), + ("assume", "y=1;"), + ("cover", "y=1;"), + // A deferred action is one subroutine call (IEEE 1800-2023 16.4). + ("assert #0", "$info(\"p\");"), + ("assume final", "$info(\"p\");"), + ] { + let mut tree = parsed(&format!("{keyword}(a+1) {action}")); subtract(&mut tree); let source = Source::from_syntax(&tree).unwrap(); let Stmt::If { condition, .. } = &source.modules()[0].initial_processes()[0].body()[0] @@ -132,7 +139,7 @@ fn native_assertion_default_failure_cover_and_else_only_actions_keep_contracts() #[test] fn native_assertion_header_and_action_roles_are_authoritative() { for change_deferral in [false, true] { - let mut tree = parsed("assert #0(a) y=1; else y=2;"); + let mut tree = parsed("assert(a) y=1; else y=2;"); for statement in &mut tree.declarations.statements { if let StatementKind::Assertion { header, success, .. @@ -148,6 +155,16 @@ fn native_assertion_header_and_action_roles_are_authoritative() { } } } + // The native header decides the deferral: a deferred action must be + // one subroutine call (IEEE 1800-2023 16.4). + if change_deferral { + let error = Source::from_syntax(&tree).unwrap_err(); + assert!( + error.to_string().contains("deferred assertion action"), + "{error}" + ); + continue; + } let source = Source::from_syntax(&tree).unwrap(); let Stmt::If { then_body, @@ -157,11 +174,7 @@ fn native_assertion_header_and_action_roles_are_authoritative() { else { panic!() }; - if change_deferral { - assert_eq!(assigned_literal(then_body), "1"); - } else { - assert!(then_body.is_empty()); - } + assert!(then_body.is_empty()); assert_eq!(assigned_literal(else_body), "2"); } } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 7278978181c..7adfec4e3b5 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 35; +const CONTAINER_VERSION: u16 = 36; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index d176c7dc1e8..59740d44036 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -271,7 +271,13 @@ impl HostBoundary for Simulator { fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; - if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { + // Deferred assertions mature when a slot is over, which the + // runtime's loop tells apart from the end of a step. + if self.frozen + || !self.components.is_empty() + || self.deferred_assertions + || !self.backend.runs_compiled_scheduler() + { return CompiledSlots::None; } // Waveforms record, the heap collects and a slot observer looks at @@ -294,6 +300,12 @@ impl HostBoundary for Simulator { self.dump_unless_rewound(timestamp); } + /// Deferred assertions mature in the Observed and Postponed regions of + /// the slot (IEEE 1800-2023 16.4). + fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { + self.mature_deferred_assertions().map_err(Halt::Error) + } + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { // The time slot is over: no kernel runs, and its updates are in // state memory. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index dc7af3cc618..d70605ce91b 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -150,6 +150,9 @@ mod host { comb_observer_scratch: Vec, comb_observer_reads: crate::comb_activation::ObserverReads, pub(super) comb_observer_initial_eval: bool, + /// The design has deferred assertions, whose actions mature at the + /// end of each time slot. + pub(crate) deferred_assertions: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -394,6 +397,21 @@ mod host { struct PendingRuntimeEvents { events: std::collections::VecDeque, missed: u64, + deferred: DeferredQueues, + } + + /// The actions of deferred assertions that wait in the queue of their + /// process until they mature (IEEE 1800-2023 16.4.1). + #[derive(Clone, Default)] + struct DeferredQueues { + /// How the events of each site are deferred, and whether the site is + /// fatal, by site id. Empty without deferred assertions. + sites: Vec>, + /// Waiting actions in issue order, with their queue and region. + waiting: Vec<(u32, celox_design::AssertionDeferral, RawRuntimeEvent)>, + /// Events lost to the ring since the last maturity, in a design with + /// fatal deferred actions: they may have held one. + missed: u64, } impl PendingRuntimeEvents { @@ -403,7 +421,65 @@ mod host { } } + /// Queue the event, unless it is the action of a deferred assertion, + /// which waits, or a flush point, which discards the actions waiting + /// in its queue (16.4.2). fn push(&mut self, event: RawRuntimeEvent, capacity: usize) { + if let RawRuntimeEvent::Event { site_id, .. } = &event + && let Some(Some((deferred, _))) = self.deferred.sites.get(*site_id) + { + let site = *site_id as u32; + match *deferred { + celox_design::DeferredSite::FlushPoint => { + self.deferred.waiting.retain(|&(queue, ..)| queue != site); + } + celox_design::DeferredSite::Action { queue, region } => { + self.deferred.waiting.push((queue, region, event)); + } + } + return; + } + if let RawRuntimeEvent::Missed { count } = event + && self + .deferred + .sites + .iter() + .flatten() + .any(|&(_, fatal)| fatal) + { + self.deferred.missed += count; + } + self.push_ready(event, capacity); + } + + /// The time slot ends: queue the waiting actions, those of the + /// Observed region (`#0`) before those of the Postponed region + /// (`final`), up to the first fatal one, which it returns, or + /// [`RawRuntimeEvent::Missed`] when events that may have been one were + /// lost. + fn mature(&mut self, capacity: usize) -> Option { + let waiting = std::mem::take(&mut self.deferred.waiting); + let missed = std::mem::take(&mut self.deferred.missed); + let fatal = (missed > 0).then_some(RawRuntimeEvent::Missed { count: missed }); + for region in [ + celox_design::AssertionDeferral::Observed, + celox_design::AssertionDeferral::Final, + ] { + for (_, _, event) in waiting.iter().filter(|(_, r, _)| *r == region) { + self.push_ready(event.clone(), capacity); + // The simulation ends at a fatal action: the actions + // after it do not run. + if let RawRuntimeEvent::Event { site_id, .. } = event + && let Some(Some((_, true))) = self.deferred.sites.get(*site_id) + { + return fatal.or_else(|| Some(event.clone())); + } + } + } + fatal + } + + fn push_ready(&mut self, event: RawRuntimeEvent, capacity: usize) { if let RawRuntimeEvent::Missed { count } = event { // Ring overwrite means every older pending record also lies // outside the latest `capacity` records of the combined stream. @@ -929,6 +1005,18 @@ mod host { &backend, &program.runtime_schema.comb_observers, ); + let sites = &program.runtime_schema.runtime_event_sites; + let deferred_sites = if sites.iter().any(|site| site.deferred.is_some()) { + sites + .iter() + .map(|site| { + site.deferred + .map(|deferred| (deferred, site.kind.is_fatal())) + }) + .collect() + } else { + Vec::new() + }; let mut sim = Self { backend, program, @@ -941,7 +1029,14 @@ mod host { handle_slots: Default::default(), heap_safepoints_blocked: false, file_io: Default::default(), - pending_host_events: Default::default(), + pending_host_events: Arc::new(std::sync::Mutex::new(PendingRuntimeEvents { + deferred: DeferredQueues { + sites: deferred_sites.clone(), + ..Default::default() + }, + ..Default::default() + })), + deferred_assertions: !deferred_sites.is_empty(), components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1313,6 +1408,39 @@ mod host { self.host_watch.set_log(other.host_watch.log().to_vec()); } + /// The time slot ends: the actions of deferred assertions that their + /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 + /// 16.4). A fatal one ends the simulation with an error. + pub(crate) fn mature_deferred_assertions(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.deferred_assertions { + return Ok(()); + } + self.stash_runtime_events(); + let capacity = self.backend.layout().runtime_event_capacity; + let fatal = self.pending_host_events.lock().unwrap().mature(capacity); + if let Some(RawRuntimeEvent::Missed { count }) = fatal { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "missed {count} runtime events, which may have held a deferred $fatal" + ), + signals: Vec::new(), + }); + } + let Some(RuntimeEvent::Report(report)) = fatal.and_then(|raw| { + render_raw_runtime_event( + raw, + &self.program.runtime_schema.runtime_event_sites, + RuntimeFormatContext::default(), + ) + }) else { + return Ok(()); + }; + Err(RuntimeErrorCode::Runtime { + message: message_diagnostic(&report.message), + signals: Vec::new(), + }) + } + /// Move the events in the backend's buffer to the queue that /// [`Self::drain_runtime_events`] reads. pub(crate) fn stash_runtime_events(&mut self) { @@ -1845,7 +1973,8 @@ mod host { fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { let result = self.fire_unit(event); self.heap_safepoint(); - result.and(self.take_heap_fault()) + result.and(self.take_heap_fault())?; + self.mature_deferred_assertions() } fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2006,6 +2135,9 @@ mod host { self.note_edge(Ok(outcome)) } + /// Settle the outcome of [`celox_runtime::run_edge`] or + /// [`celox_runtime::run_edges`], and mature the deferred assertions + /// they ran. fn note_edge( &mut self, outcome: Result, @@ -2027,7 +2159,8 @@ mod host { Err(celox_runtime::Halt::Finish | celox_runtime::Halt::Stop) => self.dirty = true, Err(celox_runtime::Halt::Error(error)) => return Err(error), } - Ok(()) + // The edges are a time slot, as a tick is. + self.mature_deferred_assertions() } /// A rising edge of `event`'s signal; see [`Self::edge`]. @@ -2231,6 +2364,7 @@ mod host { let result = self.tick_events_unit(&fired); self.heap_safepoint(); result.and(self.take_heap_fault())?; + self.mature_deferred_assertions()?; for &event in events { let info = self.event_edges[event.id()]; self.backend diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 25d04c5ec96..55d2078f84c 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -103,6 +103,7 @@ impl Simulator { scope, location: None, assertion: None, + deferred: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index aab956b1f94..491590fff87 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -241,3 +241,46 @@ endmodule let vcd = std::fs::read_to_string(&path).unwrap(); assert!(vcd.contains("b101"), "{vcd}"); } + +/// Deferred assertions keep their queue through the image: a glitch is +/// flushed, a lasting failure reports at the end of its slot. +#[test] +fn deferred_assertions_run_from_the_image() { + const DEFERRED: &str = r#"`timescale 1ns/1ns +module Top; + bit a, b; + initial forever begin + @(a or b); + d: assert #0 (a == b) else $error("d"); + end + initial begin + #1 a = 1; #0 b = 1; + #1 a = 0; + #1 $display("done"); + end +endmodule +"#; + let run = |sim: &mut Simulation<_>| { + sim.run_until(5).unwrap(); + sim.drain_runtime_events() + .into_iter() + .map(|event| match event { + RuntimeEvent::Report(report) => report.message, + RuntimeEvent::Display { message } => message, + event => panic!("unexpected event {event:?}"), + }) + .collect::>() + }; + let expected = run(&mut builder(DEFERRED).build_native().unwrap()); + assert_eq!(expected, vec![b"d".to_vec(), b"done".to_vec()]); + let image = reloaded( + &builder(DEFERRED) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(run(&mut sim), expected); +} diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs new file mode 100644 index 00000000000..a92d9a44e6f --- /dev/null +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -0,0 +1,304 @@ +#![cfg(feature = "systemverilog")] +//! The actions of deferred immediate assertions in processes wait in the +//! process's deferred assertion report queue: `#0` ones mature in the +//! Observed region, `final` ones in the Postponed region, and a flush point +//! of the process discards those still waiting (IEEE 1800-2023 16.4). +use celox::{AssertionDeferral, Report, RuntimeEvent, Severity}; +use std::path::Path; + +/// The reports and displays of `events`, as (label or message, deferral). +fn summary(events: Vec) -> Vec<(String, Option)> { + events + .into_iter() + .filter_map(|event| match event { + RuntimeEvent::Report(Report { + message, assertion, .. + }) => Some(( + String::from_utf8(message).unwrap(), + assertion.map(|assertion| assertion.deferral), + )), + RuntimeEvent::Display { message } => Some((String::from_utf8(message).unwrap(), None)), + _ => None, + }) + .collect() +} + +macro_rules! deferred { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit a, b, c, x;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("deferred.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn run(body: &str, time: u64) -> Vec<(String, Option)> { + let mut sim = simulation(body); + sim.run_until(time).unwrap(); + summary(sim.drain_runtime_events()) + } + + /// The first execution fails while `b` lags `a`; the process + /// resumes from its event control when `b` follows, which + /// flushes the failure. The immediate assertion reports it. + #[test] + fn an_event_control_resume_flushes_waiting_actions() { + assert_eq!( + run( + " initial forever begin\n \ + @(a or b);\n \ + i: assert (a == b) else $error(\"i\");\n \ + d: assert #0 (a == b) else $error(\"d\");\n \ + end\n \ + initial begin #1 a = 1; #0 b = 1; end", + 1 + ), + vec![("i".to_owned(), Some(AssertionDeferral::None))] + ); + } + + /// IEEE 1800-2023 16.4.2: an Observed region is reached after + /// `a3` and before the next flush point, so `a3` reports; `a4` + /// is flushed when `b` changes after it ran. + #[test] + fn a_delay_resume_is_no_flush_point() { + assert_eq!( + run( + " always @(a or b) begin\n \ + a3: assert #0 (a == b) else $error(\"a3\");\n \ + #1;\n \ + a4: assert #0 (a == b) else $error(\"a4\");\n \ + end\n \ + initial begin #1 a = 1; #1; #0 b = 1; end", + 3 + ), + vec![("a3".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// In one time slot, `$display` output comes first, then the + /// `#0` actions, then the `final` ones. + #[test] + fn observed_actions_mature_before_postponed_ones() { + assert_eq!( + run( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $error(\"f\");\n \ + o: assert #0 (0) else $error(\"o\");\n \ + p: assert #0 (1) $display(\"p\");\n \ + $display(\"d\");\n \ + end", + 1 + ), + vec![ + ("d".to_owned(), None), + ("o".to_owned(), Some(AssertionDeferral::Observed)), + ("p".to_owned(), None), + ("f".to_owned(), Some(AssertionDeferral::Final)), + ] + ); + } + + /// Each evaluation of an edge-triggered process resumes it from + /// its event control: the second edge of a time slot flushes the + /// failure of the first. + #[test] + fn a_second_edge_flushes_a_flip_flop_process() { + let body = " always @(posedge c) o: assert #0 (x) else $error(\"o\");\n "; + assert_eq!( + run(&format!("{body}initial #1 c = 1;"), 1), + vec![("o".to_owned(), Some(AssertionDeferral::Observed))] + ); + assert_eq!( + run(&format!("{body}initial begin #1 c = 1; #0 c = 0; x = 1; #0 c = 1; end"), 1), + vec![] + ); + } + + /// A deferred `$fatal` ends the simulation when it matures, at + /// the end of its time slot. + #[test] + fn a_deferred_fatal_ends_the_simulation_when_it_matures() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $fatal(1, \"boom\");\n \ + $display(\"after\");\n \ + end", + ); + assert!(sim.run_until(5).is_err()); + assert_eq!(sim.time(), 1); + let events = sim.drain_runtime_events(); + assert!(events.iter().any(|event| matches!( + event, + RuntimeEvent::Report(Report { severity: Severity::Fatal, message, .. }) + if message == b"boom" + )), "{events:?}"); + } + + /// A deferred assertion that only a `wait` condition reaches + /// still waits for the end of the slot. + #[test] + fn assertions_in_wait_conditions_are_deferred() { + assert_eq!( + run( + " function automatic bit check();\n \ + d: assert #0 (0) else $error(\"d\");\n \ + return 1;\n \ + endfunction\n \ + initial begin\n \ + #1;\n \ + wait (check());\n \ + $display(\"after\");\n \ + end", + 5 + ), + vec![ + ("after".to_owned(), None), + ("d".to_owned(), Some(AssertionDeferral::Observed)), + ] + ); + } + + /// The simulation ends at a deferred `$fatal`: the actions that + /// would mature after it, here in the Postponed region, do not + /// run. + #[test] + fn actions_after_a_deferred_fatal_do_not_mature() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + assert #0 (0) else $fatal(1, \"boom\");\n \ + assert final (1) $display(\"after fatal\");\n \ + end", + ); + assert!(sim.run_until(5).is_err()); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("boom".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred assertion that only the default of an omitted + /// argument reaches still waits for the end of the slot. + #[test] + fn assertions_in_argument_defaults_are_deferred() { + assert_eq!( + run( + " function automatic bit check();\n \ + d: assert #0 (0) else $error(\"d\");\n \ + return 1;\n \ + endfunction\n \ + function automatic bit f(bit v = check());\n \ + return v;\n \ + endfunction\n \ + initial begin\n \ + #1;\n \ + x = f();\n \ + $display(\"after\");\n \ + end", + 5 + ), + vec![ + ("after".to_owned(), None), + ("d".to_owned(), Some(AssertionDeferral::Observed)), + ] + ); + } + + /// Events lost to a full event buffer may have held a deferred + /// `$fatal`, which then still ends the simulation. + #[test] + fn a_deferred_fatal_lost_to_the_event_buffer_ends_the_simulation() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $fatal(1, \"boom\");\n \ + repeat (2000) $display(\"x\");\n \ + #1 $display(\"after\");\n \ + end", + ); + let error = sim.run_until(5).unwrap_err(); + assert!(error.to_string().contains("missed"), "{error}"); + assert_eq!(sim.time(), 1); + } + } + }; +} + +deferred!(interpreter, build_interpreter); +deferred!(cranelift, build); +#[cfg(target_arch = "x86_64")] +deferred!(native, build_native); +deferred!(wasm, build_wasm); + +/// A `Simulator` call is a time slot: a deferred assertion of a flip-flop +/// domain matures at the end of the tick that ran it. +#[test] +fn deferred_actions_mature_at_the_end_of_a_tick() { + let source = "module Top(input bit clk, input bit x);\n \ + always_ff @(posedge clk) o: assert #0 (x) else $error(\"o\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("o".to_owned(), Some(AssertionDeferral::Observed))] + ); +} + +/// So is a call of the edge APIs that run derived domains, and of +/// `edges`: a later edge does not flush the actions of an earlier one. +#[test] +fn deferred_actions_mature_at_the_end_of_edges_and_derived_ticks() { + let source = "module Top(input bit clk, input bit x);\n \ + bit div;\n \ + always_ff @(posedge clk) div <= !div;\n \ + always_ff @(posedge clk) o: assert #0 (x) else $error(\"o\");\n \ + always_ff @(posedge div) d: assert #0 (x) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + for _ in 0..2 { + sim.edges(&[(clk, celox::Edge::Rising)]).unwrap(); + sim.edges(&[(clk, celox::Edge::Falling)]).unwrap(); + } + for _ in 0..4 { + sim.tick(clk).unwrap(); + } + let labels: Vec<_> = summary(sim.drain_runtime_events()) + .into_iter() + .map(|(label, _)| label) + .collect(); + assert_eq!(labels, ["o", "d", "o", "o", "d", "o", "o", "d", "o"]); +} + +#[test] +fn deferred_actions_are_one_display_or_severity_task_call() { + let source = "module Top; bit a;\n \ + initial assert #0 (a) else begin $error(\"x\"); $error(\"y\"); end\n\ + endmodule"; + let error = celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("deferred assertion action"), + "{error}" + ); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index d3c04e955ab..79e3ef8a4a5 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -623,6 +623,25 @@ host does at each callback, or the time step of the report while and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. +### Deferred assertions + +In an `initial` or `always` process with a timing control, and in an +edge-triggered `always` or `always_ff` process, the action of `assert #0`, +`assume #0`, `assert final` and `assume final` waits in the process's +deferred assertion report queue (IEEE 1800-2023 16.4). Its arguments are +evaluated when the assertion executes. The process flushes the queue each +time it resumes from an event control or a wait, and an edge-triggered +process each time it runs; a resume after a delay is no flush point +(16.4.2). When the time slot is over, the actions still waiting are +executed: those of `#0` ones first, then those of `final` ones. A deferred +`$fatal` ends the simulation then. An action is one display or severity +task call; a user subroutine, or more than one statement, is rejected. + +The same assertions in `always_comb`, `always_latch` or a process lowered as +combinational logic (an `always` whose only timing control is its leading +event control) still report at once, like simple immediate assertions. +Deferred assertions as module items and deferred cover are rejected. + ### Constant functions Constant functions ignore the display and severity tasks they call. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7cd330ff86b..fec9ec48260 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -399,6 +399,22 @@ drain のコンテキストが与える時刻で、VPI ホストはコールバ VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 +### 遅延付きアサーション + +タイミング制御を含む `initial` / `always` プロセスと、エッジで起動する `always` / +`always_ff` プロセスでは、`assert #0`、`assume #0`、`assert final`、`assume final` の +アクションはプロセスの遅延アサーション報告キューで待ちます(IEEE 1800-2023 16.4)。 +引数はアサーションを実行した時点で評価します。プロセスはイベント制御や wait から再開する +たびに、エッジで起動するプロセスは実行するたびにキューをフラッシュします。遅延からの再開は +フラッシュ点ではありません(16.4.2)。タイムスロットが終わると、まだ待っているアクションを +`#0` のもの、`final` のものの順に実行します。遅延付きの `$fatal` はそこでシミュレーションを +終了します。アクションは表示タスクか重大度タスクの呼び出し 1 つで、ユーザーのサブルーチンや +複数の文は拒否します。 + +`always_comb`、`always_latch`、組み合わせ回路として扱うプロセス(タイミング制御が先頭の +イベント制御だけの `always`)の同じアサーションは、まだ単純な即時アサーションと同じく +その場で報告します。モジュール直下の遅延付きアサーションと遅延付きの cover は拒否します。 + ### 定数関数 定数関数は、呼び出す表示タスクと重大度タスクを無視します。