From 39e3a635f388c63cae3aa2cf6973bcacd22cdb95 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:25:35 +0000 Subject: [PATCH 1/4] chore(deps): update rust toolchain to b0829a2 --- flake.lock | 8 ++++---- flake.nix | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/flake.lock b/flake.lock index bc239f01aa4..d7f1e5b8c23 100644 --- a/flake.lock +++ b/flake.lock @@ -50,17 +50,17 @@ ] }, "locked": { - "lastModified": 1792653800, - "narHash": "sha256-E8zFJilWlORqzIUJizyhZ/0WKBOizuM6s1nRSgPRomo=", + "lastModified": 1792739799, + "narHash": "sha256-M2rr/yPbTHvgAzCyZ+zHJHflFM0XU7t42Sw2skA3TQM=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2", + "rev": "b0829a2cc9f7b596583331d78a942c1e5170d8a0", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2", + "rev": "b0829a2cc9f7b596583331d78a942c1e5170d8a0", "type": "github" } } diff --git a/flake.nix b/flake.nix index aa84fea5b01..f4bdf4dbf28 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/5f267b7f323a4d6df0b9c0e3eaa043cbe85386f2"; + url = "github:oxalica/rust-overlay/b0829a2cc9f7b596583331d78a942c1e5170d8a0"; inputs.nixpkgs.follows = "nixpkgs"; }; }; From 436b10a32a54ee580bb8535700c614c7d07e6f80 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 01:38:20 +0900 Subject: [PATCH 2/4] feat(sv): run nonblocking assignments in processes to array elements and run-time positions A nonblocking assignment in a process can now target an unpacked array element, a reversed array slice, and a bit or part select at a run-time position. The position is evaluated when the assignment executes; the update goes through the same staged or queued NBA path as a constant one. A run-time site stages a bit offset and the number of bits written, so bits outside the target, or in the array element a select stays within, are not written, and a position with an X or Z bit writes nothing (IEEE 1800-2023 7.4.6, 11.5.1). A constant position outside the target writes nothing, and one partly outside writes the bits inside. Verilator 5.052 drops overlapping run-time part-select updates and writes an out-of-range update into bit 0; the two affected cases are excluded with an adapter-free reproduction. Icarus passes all four new cases. Fixes #1709 Change-Id: If5c77a6b7c4bdf593210070c988a351dd69138f2 --- crates/celox-design/src/lib.rs | 28 +- crates/celox-frontend-core/src/process.rs | 25 +- crates/celox-frontend-core/src/sdk.rs | 2 +- .../src/symbolic/artifact.rs | 13 +- .../src/symbolic/assembly.rs | 10 +- crates/celox-frontend-sv/src/lowering/ff.rs | 439 +++++++++++++++--- crates/celox-runtime/src/schedule.rs | 4 +- crates/celox-runtime/src/simulation/nba.rs | 52 ++- crates/celox-runtime/src/timing.rs | 4 +- crates/celox-test-suite/LIMITATIONS.md | 13 + .../src/sv/cases/timing.vtest | 181 ++++++++ .../repros/process_nba_positions.sv | 16 + .../process_nba_positions_verilator.json | 40 ++ .../verification/sv/icarus/timing.json | 242 ++++++++++ .../verification/sv/limitations.json | 19 + .../verification/sv/verilator/timing.json | 246 ++++++++++ .../systemverilog/review_regressions.rs | 20 - .../tests/frontends/systemverilog/timing.rs | 109 ++++- 18 files changed, 1316 insertions(+), 147 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/process_nba_positions.sv create mode 100644 crates/celox-test-suite/verification/repros/process_nba_positions_verilator.json diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7cb1572d8e2..05ccbf062d8 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -641,9 +641,9 @@ pub struct NbaSite { /// Staging object of `width` bits holding the assigned value, with the /// target's state representation. pub value: A, - /// Two-state staging object holding a bit offset added to `lsb`, for an - /// assignment whose position is computed at run time. - pub offset: Option, + /// For an assignment whose position is computed at run time, the + /// staging objects of the position. + pub position: Option>, /// One-bit flag of a site whose destination has no other writer in the /// design (no other nonblocking site, no store of any unit, not a /// top-level port) and whose update order nothing observes (no wait, @@ -667,12 +667,32 @@ impl NbaSite { lsb: self.lsb, width: self.width, value: map(self.value), - offset: self.offset.map(&mut map), + position: self.position.map(|position| position.map(&mut map)), pending: self.pending.map(&mut map), } } } +/// The run-time position of a nonblocking assignment: two-state staging +/// objects holding a bit offset added to the site's `lsb` and the number of +/// bits written there, the low bits of the value and at most the site's +/// `width`. Zero bits write nothing, as for a position outside the target +/// or one with an unknown bit (IEEE 1800-2023 7.4.6, 11.5.1). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct NbaPosition { + pub offset: A, + pub width: A, +} + +impl NbaPosition { + pub fn map(&self, mut map: impl FnMut(A) -> B) -> NbaPosition { + NbaPosition { + offset: map(self.offset), + width: map(self.width), + } + } +} + /// Controls which combinational stores dead store elimination preserves. /// /// The policy is part of the runtime contract: host-side handles resolve diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 8f8c1373831..1931a26203b 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -21,7 +21,7 @@ //! [`WaitSite`]: celox_design::WaitSite use celox_design::{ - HostRequestKind, NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, + HostRequestKind, NbaPosition, NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ @@ -50,9 +50,9 @@ pub enum ProcessKernelError { TooManySuspensions, } -/// Width of the bit offset staged by a nonblocking assignment whose position -/// is computed at run time ([`NbaSite::offset`]). -pub const NBA_OFFSET_WIDTH: usize = 64; +/// Width of the bit offset and of the bit count staged by a nonblocking +/// assignment whose position is computed at run time ([`NbaPosition`]). +pub const NBA_POSITION_WIDTH: usize = 64; /// Builder of one process kernel. pub struct ProcessKernelBuilder { @@ -259,9 +259,9 @@ impl ProcessKernelBuilder { /// process, described by `site`: schedule a value for the NBA region of /// the current time (IEEE 1800-2023 10.4.2). `lower` lowers the /// right-hand side at the open block and returns the value, a register - /// of `site.width` bits, and for a site with a run-time position the - /// bit offset, an unsigned two-state register of [`NBA_OFFSET_WIDTH`] - /// bits. + /// of `site.width` bits, and for a site with a run-time position the bit + /// offset and the number of bits written, unsigned two-state registers + /// of [`NBA_POSITION_WIDTH`] bits. /// /// A site with a `pending` flag stages the value without returning. If /// the flag is still set from an earlier execution in the same time @@ -274,7 +274,7 @@ impl ProcessKernelBuilder { site: &NbaSite, lower: impl FnOnce( &mut SIRBuilder, - ) -> Result<(RegisterId, Option), E>, + ) -> Result<(RegisterId, Option>), E>, ) -> Result<(), E> { if let Some(pending) = site.pending { let flag = self.builder.alloc_bit(1, false); @@ -298,10 +298,11 @@ impl ProcessKernelBuilder { .seal_block(SIRTerminator::Jump(stage, Vec::new())); self.builder.switch_to_block(stage); } - let (value, offset) = lower(&mut self.builder)?; + let (value, position) = lower(&mut self.builder)?; self.store(site.value, site.width, value); - if let (Some(slot), Some(offset)) = (site.offset, offset) { - self.store(slot, NBA_OFFSET_WIDTH, offset); + if let (Some(slots), Some(position)) = (site.position, position) { + self.store(slots.offset, NBA_POSITION_WIDTH, position.offset); + self.store(slots.width, NBA_POSITION_WIDTH, position.width); } if let Some(pending) = site.pending { self.store_constant(pending, 1, 1); @@ -327,7 +328,7 @@ impl ProcessKernelBuilder { switch: SourceVarId, lower: impl FnOnce( &mut SIRBuilder, - ) -> Result<(RegisterId, Option), E>, + ) -> Result<(RegisterId, Option>), E>, ) -> Result<(), E> { assert!( site.pending.is_some(), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 88633549f9f..f74172ab2a4 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1425,7 +1425,7 @@ fn lower_statements( lsb: target.lsb(), width: target.width(), value: staged, - offset: None, + position: None, pending, }; kernel.nonblocking(index, &site, |builder| { diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index cf8d54a5bba..ec42afd1a4a 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeSet, fmt}; use celox_design::{ - CounterSlots, ExternFunction, InitialStateValue, ModuleId, NbaSite, ProcessSlots, + CounterSlots, ExternFunction, InitialStateValue, ModuleId, NbaPosition, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet, VarAtomBase, VariableMetadata, WaitSite, }; @@ -162,7 +162,8 @@ pub struct SimModule { /// queued path leaves the value in `queued` and returns to the runtime. /// Assembly keeps one path: the staged one only if nothing else writes the /// site's target and nothing can observe when the target is updated. For the -/// queued path it makes `queued` the site's value and drops the flag. +/// queued path it makes `queued` the site's value and `queued_position` its +/// position, and drops the flag. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NbaSwitch { /// The site's `value` object, which identifies the site. @@ -172,14 +173,20 @@ pub struct NbaSwitch { pub switch: A, /// The value object of the queued path. pub queued: A, + /// The position objects of the queued path, for a site with a run-time + /// position. + pub queued_position: Option>, } -impl NbaSwitch { +impl NbaSwitch { pub fn map(&self, mut map: impl FnMut(&A) -> B) -> NbaSwitch { NbaSwitch { value: map(&self.value), switch: map(&self.switch), queued: map(&self.queued), + queued_position: self + .queued_position + .map(|position| position.map(|var| map(&var))), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 6a8f45347bb..cf4b9590f6f 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2006,7 +2006,14 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain( nba_sites .iter() - .flat_map(|site| [Some(site.value), site.offset, site.pending]) + .flat_map(|site| { + [ + Some(site.value), + site.position.map(|position| position.offset), + site.position.map(|position| position.width), + site.pending, + ] + }) .flatten(), ) .chain(host_request_sites.iter().flat_map(|site| site.slots())) @@ -3542,6 +3549,7 @@ fn select_nba_paths( }; if !staged.contains(&switch.switch) { site.value = switch.queued; + site.position = switch.queued_position; site.pending = None; } } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 9e44351660d..2784a824630 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -17,8 +17,8 @@ mod strings; use super::procedural::*; use super::*; -use celox_design::{CounterKind, NbaSite, SPARSE_WORKING_REGION, WaitSite}; -use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; +use celox_design::{CounterKind, 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; use num_traits::{ToPrimitive, Zero}; @@ -4101,6 +4101,36 @@ pub(super) struct FfProcessUnits { pub staged: Vec<(SourceVarId, SourceVarId, SourceVarId)>, } +/// A part of a nonblocking assignment in a process: it takes `width` bits +/// of the right-hand side and writes them into `id` as `place` says. +struct NbaTarget { + id: SourceVarId, + width: usize, + /// For a slice of an unpacked array whose range runs against the + /// array's, the element width: the part's elements are written in + /// reverse order. + reversed: Option, + place: NbaPlace, +} + +enum NbaPlace { + /// A constant position: the part's bits from `drop` up, `width` of them, + /// are written at bit `lsb`. A position outside the target writes none. + Static { + lsb: usize, + width: usize, + drop: usize, + }, + /// A position evaluated at run time into the variables of `position`, + /// an offset from bit `lsb`. The part is shifted down first by the + /// value of the variable `drop`, the bits that fall below the target. + Dynamic { + lsb: usize, + position: NbaPosition, + drop: Option, + }, +} + /// The staging of a variable a process writes both by blocking and by /// nonblocking assignments: the nonblocking value and a mask of the bits /// the nonblocking assignments wrote. @@ -4329,8 +4359,9 @@ impl Ff<'_, '_> { } /// A nonblocking assignment in a process (IEEE 1800-2023 10.4.2): the - /// right-hand side is evaluated now, once, and each target part becomes - /// an update the runtime queues for the NBA region. + /// positions of the targets and the right-hand side are evaluated now, + /// once, and each target part becomes an update the runtime queues for + /// the NBA region. fn nonblocking( &mut self, parts: &[sv::ir::LValue], @@ -4338,61 +4369,120 @@ impl Ff<'_, '_> { ) -> Result<(), sv::AnalyzerError> { let mut targets = Vec::with_capacity(parts.len()); for part in parts { - targets.push(self.nba_target(part)?); + let part = self.propagate_lvalue(part); + let part = self.hoist_lvalue(&part)?; + targets.push(self.nba_target(&part)?); } - let total: usize = targets.iter().map(|(_, _, width)| width).sum(); - let four_state = targets.iter().any(|(id, _, _)| self.m.var(*id).is_4state); + let total: usize = targets.iter().map(|target| target.width).sum(); + let four_state = targets.iter().any(|target| self.m.var(target.id).is_4state); let (_, value_name) = self.m.temp("nba", total, false, four_state); self.assign(&sv::ir::LValue::Ident(value_name.clone()), rhs)?; // The parts, most significant first, take consecutive bits of the // value. let mut high = total; - for (id, lsb, width) in targets { - let low = high - width; + for target in targets { + let low = high - target.width; + high = low; + let id = target.id; + let select = |name: &str, msb: usize, lsb: usize| sv::ir::Expr::Select { + expr: Box::new(sv::ir::Expr::Ident(name.to_string())), + msb: sv::ir::ConstExpr::Literal(msb.to_string()), + lsb: sv::ir::ConstExpr::Literal(lsb.to_string()), + signed: false, + }; + let (source, low) = match target.reversed { + Some(element_width) => { + let (_, name) = self.m.temp("nba_order", target.width, false, four_state); + let elements = (0..target.width / element_width) + .map(|element| { + let bottom = low + element * element_width; + select(&value_name, bottom + element_width - 1, bottom) + }) + .collect(); + self.assign( + &sv::ir::LValue::Ident(name.clone()), + &sv::ir::Expr::Concat(elements), + )?; + (name, 0) + } + None => (value_name.clone(), low), + }; + let part = |msb: usize, lsb: usize| select(&source, msb, lsb); + let (lsb, width, value, position) = match target.place { + NbaPlace::Static { lsb, width, drop } => { + if width == 0 { + continue; + } + let from = low + drop; + (lsb, width, part(from + width - 1, from), None) + } + NbaPlace::Dynamic { + lsb, + position, + drop, + } => { + let value = part(low + target.width - 1, low); + let value = match drop { + Some(drop) => sv::ir::Expr::Binary { + left: Box::new(value), + op: sv::ir::BinaryOp::Shr, + right: Box::new(sv::ir::Expr::Ident(drop)), + }, + None => value, + }; + (lsb, target.width, value, Some(position)) + } + }; let (staged, staged_name) = self.m .temp("nba_part", width, false, self.m.var(id).is_4state); - self.assign( - &sv::ir::LValue::Ident(staged_name), - &sv::ir::Expr::Select { - expr: Box::new(sv::ir::Expr::Ident(value_name.clone())), - msb: sv::ir::ConstExpr::Literal((high - 1).to_string()), - lsb: sv::ir::ConstExpr::Literal(low.to_string()), - signed: false, - }, - )?; - high = low; - // The staged value has an object of its own: a value still - // staged from earlier in the time slot is queued before it is - // replaced. Assembly keeps the staged or the queued path. + self.assign(&sv::ir::LValue::Ident(staged_name), &value)?; + // The staged value and position have objects of their own: a + // value still staged from earlier in the time slot is queued + // before they are replaced. Assembly keeps the staged or the + // queued path. let staged_four_state = self.m.var(staged).is_4state; let (value, _) = self.m.temp("nba_value", width, false, staged_four_state); let (pending, _) = self.m.temp("nba_pending", 1, false, false); let (switch, _) = self.m.temp("nba_staged", 1, false, false); + let slots = position.map(|_| NbaPosition { + offset: self + .m + .temp("nba_offset", NBA_POSITION_WIDTH, false, false) + .0, + width: self.m.temp("nba_width", NBA_POSITION_WIDTH, false, false).0, + }); let site = NbaSite { process: self.process, target: id, lsb, width, value, - offset: None, + position: slots, pending: Some(pending), }; let index = self.nba_sites.len() as u32; self.with_kernel(|kernel| { kernel.nonblocking_switched(index, &site, switch, |builder| { - let value = if staged_four_state { - builder.alloc_logic(width) - } else { - builder.alloc_bit(width, false) + let load = |builder: &mut SIRBuilder<_>, var, width, four_state| { + let register = if four_state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Load( + register, + stable(var), + SIROffset::Static(0), + width, + )); + register }; - builder.emit(SIRInstruction::Load( - value, - stable(staged), - SIROffset::Static(0), - width, - )); - Ok::<_, ProcessKernelError>((value, None)) + let value = load(builder, staged, width, staged_four_state); + let position = position.map(|position: NbaPosition| { + position.map(|var| load(builder, var, NBA_POSITION_WIDTH, false)) + }); + Ok::<_, ProcessKernelError>((value, position)) }) }) .map_err(kernel_error)?; @@ -4400,57 +4490,268 @@ impl Ff<'_, '_> { value, switch, queued: staged, + queued_position: position, }); self.nba_sites.push(site); } Ok(()) } - /// The variable and the constant bit range a nonblocking assignment in - /// a process writes. - fn nba_target( - &self, - lvalue: &sv::ir::LValue, - ) -> Result<(SourceVarId, usize, usize), sv::AnalyzerError> { + /// The variable a part of a nonblocking assignment in a process writes + /// and where. A position is evaluated now; bits outside the target, and + /// a position with an unknown bit, write nothing (IEEE 1800-2023 7.4.6, + /// 11.5.1). + fn nba_target(&mut self, lvalue: &sv::ir::LValue) -> Result { let id = self .m .id(lvalue.name()) .ok_or_else(|| unsupported(format!("assignment target `{}`", lvalue.name())))?; let variable = self.m.var(id); - if !variable.array_dims.is_empty() { + let var_width = variable.width; + let (msb, lsb) = match lvalue { + sv::ir::LValue::Ident(_) => { + return Ok(NbaTarget { + id, + width: var_width, + reversed: None, + place: NbaPlace::Static { + lsb: 0, + width: var_width, + drop: 0, + }, + }); + } + sv::ir::LValue::Select { msb, lsb, .. } => (msb, lsb), + }; + let constants = self.m.constants; + let parameter_types = self.m.parameter_types; + let constant = + |expr| sv::typecheck::eval_const_expr_with_types(expr, constants, parameter_types); + // A slice of an unpacked array whose range runs against the array's + // takes the elements of the value in reverse order. + let reversed = match lvalue { + sv::ir::LValue::Select { + array_slice_width: Some(element_width), + array_slice_reversed: true, + .. + } => Some( + constant(element_width) + .and_then(|width| usize::try_from(width).ok()) + .filter(|width| *width != 0) + .ok_or_else(|| unsupported("assignment lvalue order"))?, + ), + _ => None, + }; + if let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) { + let (Some(msb), Some(lsb)) = ( + packed_index_position(variable, msb), + packed_index_position(variable, lsb), + ) else { + return Err(unsupported("nonblocking assignment position")); + }; + if msb < lsb { + return Err(unsupported( + "nonblocking assignment to a reversed part select in a process", + )); + } + let width = usize::try_from(msb - lsb + 1) + .map_err(|_| unsupported("nonblocking assignment position"))?; + let top = i128::try_from(var_width).unwrap_or(i128::MAX); + let start = lsb.clamp(0, top); + let end = (msb + 1).clamp(0, top); + let (start, written) = if start < end { + (start, end - start) + } else { + (0, 0) + }; + if reversed.is_some_and(|element_width| !width.is_multiple_of(element_width)) { + return Err(unsupported("assignment lvalue order")); + } + return Ok(NbaTarget { + id, + width, + reversed, + place: NbaPlace::Static { + lsb: start as usize, + width: written as usize, + drop: if written == 0 { + 0 + } else { + (start - lsb) as usize + }, + }, + }); + } + if reversed.is_some() { return Err(unsupported( - "nonblocking assignment to an unpacked array in a process", + "nonblocking assignment to a reversed array slice at a run-time position", )); } - match lvalue { - sv::ir::LValue::Ident(_) => Ok((id, 0, variable.width)), - sv::ir::LValue::Select { msb, lsb, .. } => { - let constant = |expr| { - sv::typecheck::eval_const_expr_with_types( - expr, - self.m.constants, - self.m.parameter_types, - ) - }; - let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) else { - return Err(unsupported( - "nonblocking assignment with a run-time position in a process", - )); - }; - let (Some(msb), Some(lsb)) = ( - packed_index_offset(variable, msb), - packed_index_offset(variable, lsb), - ) else { - return Err(unsupported("nonblocking assignment outside its target")); - }; - if msb < lsb { - return Err(unsupported( - "nonblocking assignment to a reversed part select in a process", - )); - } - Ok((id, lsb, msb - lsb + 1)) + let mut arena = SLTNodeArena::new(); + if let Some((_, element_width, offset, access)) = dynamic_array_element_lvalue( + lvalue, + self.m.variables, + self.m.name_to_id, + constants, + parameter_types, + ) { + // A run-time element: its whole selected part or nothing. + let width = access.msb - access.lsb + 1; + let offset = expr_from_const_expr(&offset) + .ok_or_else(|| unsupported("dynamic assignment index"))?; + let offset = self.propagate(&offset); + let (bit_offset, _) = lower_expr_with_context( + &offset, + self.m.variables, + self.m.name_to_id, + constants, + parameter_types, + &mut arena, + None, + None, + ) + .ok_or_else(|| unsupported("dynamic assignment index"))?; + let bit_offset = + coerce_node_width(&mut arena, bit_offset, Some(NBA_POSITION_WIDTH), false) + .map_err(slt_error)?; + let stride = slt_constant(&mut arena, BigUint::from(element_width), 64, false)?; + let index = arena + .alloc(SLTNode::Binary(bit_offset, BinaryOp::DivU, stride)) + .map_err(slt_error)?; + let (index, valid) = + dynamic_array_index_guard_slt(&mut arena, index, var_width / element_width.max(1)) + .ok_or_else(|| unsupported("dynamic assignment index"))?; + let offset = arena + .alloc(SLTNode::Binary(index, BinaryOp::Mul, stride)) + .map_err(slt_error)?; + let full = slt_constant(&mut arena, BigUint::from(width), 64, false)?; + let zero = slt_constant(&mut arena, BigUint::zero(), 64, false)?; + let written = arena + .alloc(SLTNode::Mux { + cond: valid, + then_expr: full, + else_expr: zero, + }) + .map_err(slt_error)?; + let position = NbaPosition { + offset: self.nba_position_temp("nba_at", &arena, offset)?, + width: self.nba_position_temp("nba_bits", &arena, written)?, + }; + return Ok(NbaTarget { + id, + width, + reversed: None, + place: NbaPlace::Dynamic { + lsb: access.lsb, + position, + drop: None, + }, + }); + } + let write = dynamic_packed_write( + lvalue, + self.m.variables, + self.m.name_to_id, + constants, + parameter_types, + ) + .ok_or_else(|| unsupported(format!("assignment target `{}`", lvalue.name())))?; + // A run-time part select: the bits of it inside the target, or + // inside the array element it stays within. + let shift = |expr: &sv::ir::Expr, arena: &mut SLTNodeArena| { + let (node, _) = lower_expr_with_context( + &self.propagate(expr), + self.m.variables, + self.m.name_to_id, + constants, + parameter_types, + arena, + None, + Some(false), + ) + .ok_or_else(|| unsupported("dynamic assignment position"))?; + coerce_node_width(arena, node, Some(NBA_POSITION_WIDTH), false).map_err(slt_error) + }; + let up = shift(&write.up, &mut arena)?; + let down = shift(&write.down, &mut arena)?; + let window = write + .window + .unwrap_or_else(|| BitAccess::new(0, var_width - 1)); + let binary = |arena: &mut SLTNodeArena, left, op, right| { + arena + .alloc(SLTNode::Binary(left, op, right)) + .map_err(slt_error) + }; + let mux = |arena: &mut SLTNodeArena, cond, then_expr, else_expr| { + arena + .alloc(SLTNode::Mux { + cond, + then_expr, + else_expr, + }) + .map_err(slt_error) + }; + let constant = |arena: &mut SLTNodeArena, value: usize| { + slt_constant(arena, BigUint::from(value), NBA_POSITION_WIDTH, false) + }; + // The select's bit 0 sits at `up - down`, which may be below the + // bottom of the window; the comparisons are signed. + let at = binary(&mut arena, up, BinaryOp::Sub, down)?; + let bottom = constant(&mut arena, window.lsb)?; + let top = constant(&mut arena, window.msb + 1)?; + let select_width = constant(&mut arena, write.select_width)?; + let below = binary(&mut arena, at, BinaryOp::LtS, bottom)?; + let start = mux(&mut arena, below, bottom, at)?; + let reach = binary(&mut arena, at, BinaryOp::Add, select_width)?; + let above = binary(&mut arena, reach, BinaryOp::GtS, top)?; + let end = mux(&mut arena, above, top, reach)?; + let mut valid = binary(&mut arena, start, BinaryOp::LtS, end)?; + if self.m.four_state { + for position in [up, down] { + let two_state = arena + .alloc(SLTNode::Unary(UnaryOp::ToTwoState, position)) + .map_err(slt_error)?; + let known = binary(&mut arena, position, BinaryOp::EqCase, two_state)?; + valid = slt_and(&mut arena, &mut ConstCache::default(), valid, known)?; } } + let zero = constant(&mut arena, 0)?; + let span = binary(&mut arena, end, BinaryOp::Sub, start)?; + let written = mux(&mut arena, valid, span, zero)?; + let offset = mux(&mut arena, valid, start, zero)?; + let skipped = binary(&mut arena, start, BinaryOp::Sub, at)?; + let skipped = mux(&mut arena, valid, skipped, zero)?; + let position = NbaPosition { + offset: self.nba_position_temp("nba_at", &arena, offset)?, + width: self.nba_position_temp("nba_bits", &arena, written)?, + }; + let (drop, drop_name) = self.m.temp("nba_drop", NBA_POSITION_WIDTH, false, false); + let skipped = self.lower_slt(&arena, skipped)?; + self.store(drop, SIROffset::Static(0), NBA_POSITION_WIDTH, skipped); + Ok(NbaTarget { + id, + width: write.select_width, + reversed: None, + place: NbaPlace::Dynamic { + lsb: 0, + position, + drop: Some(drop_name), + }, + }) + } + + /// A new two-state variable of [`NBA_POSITION_WIDTH`] bits holding the + /// value of `node`, evaluated now. + fn nba_position_temp( + &mut self, + purpose: &str, + arena: &SLTNodeArena, + node: NodeId, + ) -> Result { + let (temp, _) = self.m.temp(purpose, NBA_POSITION_WIDTH, false, false); + let value = self.lower_slt(arena, node)?; + self.store(temp, SIROffset::Static(0), NBA_POSITION_WIDTH, value); + Ok(temp) } /// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index e555082d04d..0a7ee5d0524 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -183,7 +183,9 @@ impl ResolvedSchedule { lsb: site.lsb, width: site.width, value: resolve(&site.value), - offset: site.offset.as_ref().map(resolve), + position: site + .position + .map(|position| position.map(|id| resolve(&id))), pending: site.pending.as_ref().map(resolve), }) .collect(), diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index 7110263524e..f2395e208c7 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -8,7 +8,7 @@ use super::round::Round; use crate::{ SignalRef, backend::SimBackend, - timing::{Halt, Value, read}, + timing::{Halt, NbaSiteRefs, Value, read}, }; impl SimulationState { @@ -20,7 +20,7 @@ impl SimulationState { process: usize, site: usize, ) -> Result<(), Halt> { - let refs = *self.model.processes[process] + let refs = self.model.processes[process] .nba_sites .get(site) .ok_or_else(|| Self::site_error(process, site))?; @@ -29,13 +29,13 @@ impl SimulationState { // NBA region and returned before staging over the earlier value. backend.set(pending, 0u8); } - let offset = refs - .offset - .map_or(0, |offset| backend.get_as::(offset) as usize); + let Some((lsb, width)) = refs.range(backend) else { + return Ok(()); + }; self.process_state.nba_queue.push(NbaUpdate { target: refs.target, - lsb: refs.lsb + offset, - width: refs.width, + lsb, + width, value: read(backend, refs.value), }); Ok(()) @@ -76,37 +76,40 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); round.transitions.clear(); } - for update in queued.drain(..) { + for update in &queued { let new = NbaValue::Queued(&update.value); - self.publish_update(executor.backend_mut(), &update, new); + self.publish_update(executor.backend_mut(), update, new); if several { self.record_transitions(executor.backend(), round); } } // Keep the queue's storage for the next time slot. + queued.clear(); self.process_state.nba_queue = queued; if flagged > 0 { for process in 0..self.model.processes.len() { for site in 0..self.model.processes[process].nba_sites.len() { - let site = self.model.processes[process].nba_sites[site]; let backend = executor.backend_mut(); - let Some(pending) = site.pending else { + let Some(pending) = self.model.processes[process].nba_sites[site].pending + else { continue; }; if backend.get_as::(pending) == 0 { continue; } backend.set(pending, 0u8); - let offset = site - .offset - .map_or(0, |offset| backend.get_as::(offset) as usize); + let site = &self.model.processes[process].nba_sites[site]; + let Some((lsb, width)) = site.range(backend) else { + continue; + }; + let (target, value) = (site.target, site.value); let update = NbaUpdate { - target: site.target, - lsb: site.lsb + offset, - width: site.width, + target, + lsb, + width, value: Value::default(), }; - self.publish_update(backend, &update, NbaValue::Staged(site.value)); + self.publish_update(backend, &update, NbaValue::Staged(value)); if several { self.record_transitions(executor.backend(), round); } @@ -161,6 +164,19 @@ impl SimulationState { } } +impl NbaSiteRefs { + /// The bit position and the number of bits the site writes now, or + /// `None` when it writes nothing. + fn range(&self, backend: &B) -> Option<(usize, usize)> { + let Some(position) = self.position else { + return Some((self.lsb, self.width)); + }; + let width = backend.get_as::(position.width) as usize; + let offset = backend.get_as::(position.offset) as usize; + (width != 0).then(|| (self.lsb + offset, width.min(self.width))) + } +} + /// The value of a nonblocking update: queued, or staged in a site's value /// object. enum NbaValue<'a> { diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 87b98bb827f..e84008b4979 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -9,7 +9,7 @@ //! that writes it counts each occurrence, and a wait on it compares //! counters instead. -use celox_design::CounterKind; +use celox_design::{CounterKind, NbaPosition}; use num_bigint::BigUint; pub use crate::simulation::{Baseline, HostWatch, NbaUpdate, Waiter, Waiters}; @@ -123,7 +123,7 @@ pub struct NbaSiteRefs { pub lsb: usize, pub width: usize, pub value: SignalRef, - pub offset: Option, + pub position: Option>, pub pending: Option, } diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 62c13e0dfb4..99270bee0a2 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -394,6 +394,19 @@ fails its startup assertion in Verilator and passes in Icarus 13.0, which also passes the unchanged shared assertions. The [retained observation](verification/repros/event_list_declaration_startup_verilator.json) records both failures; `--include-ignored` retains their assertions. +Verilator 5.052 keeps only the last of the nonblocking updates that an inner +loop issues to overlapping part-selects at run-time positions when an outer loop +delays between iterations, in +`timing::process_nonblocking_assignments_at_run_time_positions`, and writes a +nonblocking update of `q[8]` of `logic [7:0] q` into bit 0, in +`timing::process_nonblocking_assignments_outside_their_target`. Each +nonblocking assignment is its own update in issue order (IEEE 1800-2023 10.4.2), +and bits outside the target are not written (11.5.1, 7.4.6). The +[adapter-free reproduction](verification/repros/process_nba_positions.sv) fails +both checks in Verilator and passes in Icarus 13.0, which also passes the +unchanged shared assertions. The [retained observation](verification/repros/process_nba_positions_verilator.json) +records both failures; `--include-ignored` retains their assertions. + Verilator 5.052 repeats activation of the self-reading latch in `latch::guarded_activation`, producing 3 where one `seed`/`en` change should produce 1. The [adapter-free reproduction](verification/repros/latch_activation.sv) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 1b446580399..6700235ed25 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2159,3 +2159,184 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (assert_eq count 2) (run_until 4) (assert_eq count 3)) + +; A nonblocking assignment in a process to an element of an unpacked array +; or at a run-time position evaluates the position when it executes and +; updates those bits in the NBA region (IEEE 1800-2023 10.4.2). +(case process_nonblocking_assignments_to_array_elements + (source "process_nba_elements.sv" #" + module Top(output logic [7:0] m0, m1, m2, m3, e, d1, d2, output logic [3:0] lo, hi, + output logic [7:0] early); + logic [7:0] m [0:3]; + logic [7:0] grid [4][2]; + logic [3:0] mem [3:0]; + int i, j; + initial begin + for (i = 0; i < 4; i++) begin + m[i] = 8'd0; + mem[i] = 4'd0; + for (j = 0; j < 2; j++) grid[i][j] = 8'd0; + end + #1; + m[1] <= 8'h11; + i = 2; + m[i] <= 8'h22; + i = 3; + #0 early = m[2]; + #1; + for (i = 0; i < 4; i++) m[i] <= m[i] + 8'h40; + i = 1; + m[i][3:0] <= 4'h9; + m[i][7:4] <= 4'hc; + i = 2; + j = 1; + grid[i][j] <= 8'hab; + grid[3][0] <= 8'hcd; + mem[i] <= 4'h5; + mem[0] <= 4'h7; + #1; + i = 0; + m[i] <= 8'h01; + m[i] <= 8'h02; + {m[3], mem[i]} <= 12'hfe3; + end + assign m0 = m[0]; + assign m1 = m[1]; + assign m2 = m[2]; + assign m3 = m[3]; + assign e = grid[2][1]; + assign d1 = grid[3][0]; + assign d2 = grid[2][0]; + assign lo = mem[0]; + assign hi = mem[2]; + endmodule"#) + (top Top) + (run_until 1) + (assert_eq early 0 "the update lands after the inactive region") + (assert_eq m1 0x11) + (assert_eq m2 0x22 "the index is read when the assignment executes") + (assert_eq m3 0) + (run_until 2) + (assert_eq m0 0x40) + (assert_eq m1 0xc9 "a part of a run-time element keeps its other bits") + (assert_eq m2 0x62) + (assert_eq m3 0x40) + (assert_eq e 0xab) + (assert_eq d1 0xcd) + (assert_eq d2 0) + (assert_eq hi 5) + (assert_eq lo 7) + (run_until 3) + (assert_eq m0 0x02 "the last update of a time slot wins") + (assert_eq m3 0xfe) + (assert_eq lo 3)) + +(case process_nonblocking_assignments_at_run_time_positions + (source "process_nba_positions.sv" #" + module Top(output logic [7:0] q, a, output logic [15:0] staged, output logic [14:0] packed_bits); + logic [0:7] up; + logic [7:0] r [0:3]; + int i, n; + initial begin + q = 8'd0; + up = 8'd0; + #1; + i = 2; + q[i] <= 1'b1; + up[i] <= 1'b1; + i = 4; + q[i +: 3] <= 3'b101; + up[i -: 2] <= 2'b11; + i = 7; + end + // The only writer of `r` and `p`: their updates are staged. + logic [13:0] p = 14'd0; + int j; + initial begin + for (n = 0; n < 2; n++) begin + for (j = n; j < n + 6; j++) begin + r[j % 4] <= 8'h10 * n + j; + p[2 * j +: 3] <= j; + end + #1; + end + end + assign a = up; + assign staged = {r[3], r[0]}; + // Extended, so that `p` does not become a port. + assign packed_bits = {1'b0, p}; + endmodule"#) + (top Top) + (run_until 0) + (assert_eq staged 0x0304 "one site several times in a time slot: the last update wins") + (assert_eq packed_bits 0x14e4 "bits past the top are not written") + (run_until 1) + (assert_eq q 0x54) + (assert_eq a 0x38 "an ascending vector counts its bits from the left") + (assert_eq staged 0x1314) + (assert_eq packed_bits 0x24e4)) + +; Bits outside the target are not written: a nonblocking assignment wholly +; outside has no effect, and one partly outside writes the bits inside +; (IEEE 1800-2023 7.4.6, 11.5.1). +(case process_nonblocking_assignments_outside_their_target + (source "process_nba_outside.sv" #" + module Top(output logic [7:0] q, p, m0, m1, m2, m3); + logic [7:0] m [0:3]; + int i, k; + initial begin + q = 8'd0; + p = 8'd0; + for (i = 0; i < 4; i++) m[i] = 8'd0; + #1; + q[8] <= 1'b1; + q[9:6] <= 4'b1111; + i = 4; + m[i] <= 8'hff; + i = -1; + m[i] <= 8'hee; + k = 6; + p[k +: 4] <= 4'b0101; + k = -2; + p[k +: 4] <= 4'b1010; + end + assign m0 = m[0]; + assign m1 = m[1]; + assign m2 = m[2]; + assign m3 = m[3]; + endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 0xc0) + (assert_eq p 0x42) + (assert_eq m0 0) + (assert_eq m1 0) + (assert_eq m2 0) + (assert_eq m3 0)) + +; A position with an unknown bit writes nothing (IEEE 1800-2023 7.4.6, +; 11.5.1). +(case process_nonblocking_assignments_at_unknown_positions + (source "process_nba_unknown.sv" #" + module Top(output logic [7:0] q, m0, m1); + logic [7:0] m [0:1]; + logic [2:0] i = 3'bx; + initial begin + q = 8'd0; + m[0] = 8'd0; + m[1] = 8'd0; + #1; + m[i] <= 8'hff; + q[i] <= 1'b1; + q[i +: 2] <= 2'b11; + i = 3'd1; + end + assign m0 = m[0]; + assign m1 = m[1]; + endmodule"#) + (top Top) + (four_state) + (run_until 1) + (assert_eq q 0) + (assert_eq m0 0) + (assert_eq m1 0)) diff --git a/crates/celox-test-suite/verification/repros/process_nba_positions.sv b/crates/celox-test-suite/verification/repros/process_nba_positions.sv new file mode 100644 index 00000000000..3f9ddbb8761 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/process_nba_positions.sv @@ -0,0 +1,16 @@ +module Top; + logic [7:0] q = 8'd0; + logic [13:0] p = 14'd0; + int n, j; + initial begin + for (n = 0; n < 2; n++) begin + for (j = n; j < n + 6; j++) p[2 * j +: 3] <= j; + #1 $display("p=%h", p); + end + if (p !== 14'h24e4) $fatal(1, "nonblocking updates in issue order give 24e4, not %h", p); + q[8] <= 1'b1; + #1 $display("q=%h", q); + if (q !== 8'h00) $fatal(1, "an update outside the target changed q to %h", q); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/process_nba_positions_verilator.json b/crates/celox-test-suite/verification/repros/process_nba_positions_verilator.json new file mode 100644 index 00000000000..b71214ec7c7 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/process_nba_positions_verilator.json @@ -0,0 +1,40 @@ +{ + "schema_version": 3, + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "category": "Sequential", + "detail": "timing::process_nonblocking_assignments_at_run_time_positions at 1816:3: assert_eq packed_bits: expected 0x14e4, got 0x1400 (bits past the top are not written)", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_at_run_time_positions", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "timing::process_nonblocking_assignments_outside_their_target at 1854:3: assert_eq q: expected 0xc0, got 0xc1", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_outside_their_target", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "standard": "IEEE 1800-2023 10.4.2 schedules each nonblocking assignment as its own update event in the NBA region, in the order the assignments execute, so every update of a part-select at a run-time position lands. 11.5.1 and 7.4.6 make a write outside the target, wholly or in part, have no effect on the bits outside: q[8] of logic [7:0] q writes nothing.", + "adapter_free": { + "source": "verification/repros/process_nba_positions.sv", + "verilator_command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir process_nba_positions.sv", + "verilator_output": "p=1400\np=2400\n[2] %Fatal: process_nba_positions.sv:10: Assertion failed in Top: nonblocking updates in issue order give 24e4, not 2400", + "verilator_output_without_the_p_check": "p=1400\np=2400\nq=01\n[3] %Fatal: process_nba_positions.sv:13: Assertion failed in Top: an update outside the target changed q to 01", + "icarus_command": "iverilog -g2012 -s Top -o process_nba_positions.sv; vvp ", + "icarus_version": "Icarus Verilog version 13.0", + "icarus_output": "p=14e4\np=24e4\nq=00\nprocess_nba_positions.sv:14: $finish called at 3 (1s)" + } +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index b6998ae9588..ebe8418ed61 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::asynchronous_reset_driven_by_a_delay_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -232,6 +243,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delay_process_nonblocking_updates_reach_later_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -265,6 +287,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_count_generated_clock_edges_in_any_declaration_order", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_on_script_inputs_next_to_a_generated_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -332,6 +376,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::explicit_list_of_every_read_waits_for_a_change", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -354,6 +409,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_from_a_delay_process_between_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -409,6 +475,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::four_state_nonblocking_updates_keep_unknown_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::generated_clocks_with_a_common_edge_sample_each_other", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -552,6 +640,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_in_a_loop_through_always_comb_converges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_missing_a_read_does_not_wake_on_it", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_of_every_read_with_a_nonblocking_body_runs", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_outside_a_loop_keeps_its_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_with_an_extra_signal_wakes_on_it", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -585,6 +728,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::narrow_nonblocking_updates_keep_the_other_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -717,6 +871,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_at_run_time_positions", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_at_unknown_positions", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_outside_their_target", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_to_array_elements", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -816,6 +1014,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::script_writes_between_runs_reach_generated_clock_domains", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -849,6 +1058,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::staged_nonblocking_updates_keep_their_order", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -1048,6 +1268,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_delay_clock_changes_its_period", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -1081,6 +1312,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::zero_delay_process_ends_a_pulse_after_its_edge_triggers", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 97556438bd9..70b36e60f7c 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2049,5 +2049,24 @@ "timing::blocking_write_waiters_rearm_before_nonblocking_updates" ] } + }, + { + "id": "sv_verilator_process_nba_positions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "reason": "Verilator keeps only the last of the nonblocking updates that an inner loop issues to overlapping part-selects at run-time positions when an outer loop delays between iterations (p is 1400 instead of 14e4), and writes a nonblocking update of q[8] of logic [7:0] q into bit 0. IEEE 1800-2023 10.4.2 schedules every nonblocking assignment as its own update in issue order; 11.5.1 and 7.4.6 make bits outside the target unwritten. Icarus passes the unchanged shared assertions; the adapter-free source reproduces both Verilator failures.", + "upstream": [], + "evidence": [ + "verification/repros/process_nba_positions_verilator.json", + "verification/repros/process_nba_positions.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::process_nonblocking_assignments_at_run_time_positions", + "timing::process_nonblocking_assignments_outside_their_target" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 7a14137d3b9..35f824e434c 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::asynchronous_reset_driven_by_a_delay_process", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -220,6 +231,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::delay_process_nonblocking_updates_reach_later_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -253,6 +275,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_count_generated_clock_edges_in_any_declaration_order", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_on_script_inputs_next_to_a_generated_clock", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -354,6 +398,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::finish_from_a_delay_process_between_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -409,6 +464,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::four_state_nonblocking_updates_keep_unknown_bits", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::generated_clocks_with_a_common_edge_sample_each_other", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -624,6 +701,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_in_a_loop_through_always_comb_converges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_missing_a_read_does_not_wake_on_it", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_of_every_read_with_a_nonblocking_body_runs", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::list_outside_a_loop_keeps_its_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator executes an always procedure whose event control lists variables without edges at time zero, before any listed variable changes: y loses the value its initial procedure wrote, and a $display body prints once more. IEEE 1800-2023 6.8 initializes static declarations before initial/always processes start, and 9.4.2 makes the event control wait for a value change. Icarus passes the unchanged shared assertions; the adapter-free source reproduces the Verilator failure.", @@ -681,6 +802,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::narrow_nonblocking_updates_keep_the_other_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -825,6 +957,76 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator keeps only the last of the nonblocking updates that an inner loop issues to overlapping part-selects at run-time positions when an outer loop delays between iterations (p is 1400 instead of 14e4), and writes a nonblocking update of q[8] of logic [7:0] q into bit 0. IEEE 1800-2023 10.4.2 schedules every nonblocking assignment as its own update in issue order; 11.5.1 and 7.4.6 make bits outside the target unwritten. Icarus passes the unchanged shared assertions; the adapter-free source reproduces both Verilator failures.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/process_nba_positions_verilator.json", + "verification/repros/process_nba_positions.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_process_nba_positions", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator keeps only the last of the nonblocking updates that an inner loop issues to overlapping part-selects at run-time positions when an outer loop delays between iterations (p is 1400 instead of 14e4), and writes a nonblocking update of q[8] of logic [7:0] q into bit 0. IEEE 1800-2023 10.4.2 schedules every nonblocking assignment as its own update in issue order; 11.5.1 and 7.4.6 make bits outside the target unwritten. Icarus passes the unchanged shared assertions; the adapter-free source reproduces both Verilator failures.", + "upstream": [] + }, + "name": "timing::process_nonblocking_assignments_at_run_time_positions", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_at_unknown_positions", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator keeps only the last of the nonblocking updates that an inner loop issues to overlapping part-selects at run-time positions when an outer loop delays between iterations (p is 1400 instead of 14e4), and writes a nonblocking update of q[8] of logic [7:0] q into bit 0. IEEE 1800-2023 10.4.2 schedules every nonblocking assignment as its own update in issue order; 11.5.1 and 7.4.6 make bits outside the target unwritten. Icarus passes the unchanged shared assertions; the adapter-free source reproduces both Verilator failures.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/process_nba_positions_verilator.json", + "verification/repros/process_nba_positions.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_process_nba_positions", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator keeps only the last of the nonblocking updates that an inner loop issues to overlapping part-selects at run-time positions when an outer loop delays between iterations (p is 1400 instead of 14e4), and writes a nonblocking update of q[8] of logic [7:0] q into bit 0. IEEE 1800-2023 10.4.2 schedules every nonblocking assignment as its own update in issue order; 11.5.1 and 7.4.6 make bits outside the target unwritten. Icarus passes the unchanged shared assertions; the adapter-free source reproduces both Verilator failures.", + "upstream": [] + }, + "name": "timing::process_nonblocking_assignments_outside_their_target", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::process_nonblocking_assignments_to_array_elements", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -924,6 +1126,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::script_writes_between_runs_reach_generated_clock_domains", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -1003,6 +1216,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::staged_nonblocking_updates_keep_their_order", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -1180,6 +1404,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_delay_clock_changes_its_period", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -1213,6 +1448,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::zero_delay_process_ends_a_pulse_after_its_edge_triggers", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 9684113cba3..286bcb3b487 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -899,26 +899,6 @@ fn applies_unsigned_coercion_to_typed_parameter_comparisons() { assert_eq!(sim.get(sim.signal("all_ones")), 1u8.into()); } -/// Nonblocking assignments in processes whose target bits are not known at -/// compile time are not lowered yet; they are rejected by name. -#[test] -fn rejects_process_nonblocking_assignments_without_a_constant_target() { - for (body, construct) in [ - ( - "logic [7:0] q; logic [2:0] i; initial #1 q[i] <= 1'b1;", - "nonblocking assignment with a run-time position in a process", - ), - ( - "logic [7:0] mem [4]; initial #1 mem[1] <= 8'd1;", - "nonblocking assignment to an unpacked array in a process", - ), - ] { - let source = format!("module Top; {body} endmodule"); - let error = cranelift_build_error(&source); - assert!(error.contains(construct), "`{body}`: {error}"); - } -} - #[test] fn compile_sv_to_sir_forwards_parameter_overrides() { let source = r#" diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 95b9a964de4..62909a73fa8 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -94,6 +94,10 @@ timed_cases! { fn blocking_ff_clock_edges_trigger_their_domains_before_inactive_work = "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work"; fn nonblocking_assignments_in_processes_update_in_the_nba_region = "timing::nonblocking_assignments_in_processes_update_in_the_nba_region"; fn staged_nonblocking_updates_keep_their_order = "timing::staged_nonblocking_updates_keep_their_order"; + fn process_nonblocking_assignments_to_array_elements = "timing::process_nonblocking_assignments_to_array_elements"; + fn process_nonblocking_assignments_at_run_time_positions = "timing::process_nonblocking_assignments_at_run_time_positions"; + fn process_nonblocking_assignments_outside_their_target = "timing::process_nonblocking_assignments_outside_their_target"; + fn process_nonblocking_assignments_at_unknown_positions = "timing::process_nonblocking_assignments_at_unknown_positions"; fn narrow_nonblocking_updates_keep_the_other_bits = "timing::narrow_nonblocking_updates_keep_the_other_bits"; fn four_state_nonblocking_updates_keep_unknown_bits = "timing::four_state_nonblocking_updates_keep_unknown_bits"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; @@ -493,22 +497,6 @@ fn unimplemented_timing_features_are_rejected() { "always_ff event control", 88, ), - // #1709 - ( - "bit [7:0] m[4]; initial #1 m[1] <= 5;", - "nonblocking assignment to an unpacked array in a process", - 88, - ), - ( - "bit [3:0] q; int i = 2; initial #1 q[i] <= 1;", - "nonblocking assignment with a run-time position in a process", - 88, - ), - ( - "bit [3:0] q; initial #1 q[5] <= 1;", - "nonblocking assignment outside its target", - 88, - ), // #1710 ( "bit q; task t(); #1 q = 1; endtask always @* t();", @@ -869,3 +857,92 @@ fn counted_wait_baselines_survive_a_state_file() { assert_eq!(counts(&mut loaded), expected, "four_state={four_state}"); } } + +/// The run-time position cases cover staged and queued sites alike. +#[test] +fn run_time_nonblocking_positions_cover_staged_and_queued_sites() { + for (case, staged, queued) in [ + ( + "timing::process_nonblocking_assignments_at_run_time_positions", + &["r", "p"][..], + &["q"][..], + ), + ( + "timing::process_nonblocking_assignments_to_array_elements", + &[][..], + &["m", "grid", "mem"][..], + ), + ] { + let design = celox_test_suite::sv::cases() + .find(|candidate| candidate.name == case) + .unwrap() + .design(); + let sources = design + .sources + .iter() + .map(|source| (source.text.as_str(), source.path.as_path())) + .collect::>(); + let simulation = celox::Simulation::from_sv_sources(sources, &design.top) + .build() + .unwrap(); + let program = simulation.program(); + let sites = |name: &str| { + let target = program.get_addr(&[], &[name]).unwrap(); + let sites = program + .runtime_schema + .nba_sites + .iter() + .filter(|site| site.target == target) + .collect::>(); + assert!( + sites.iter().any(|site| site.position.is_some()), + "{name} has a run-time position" + ); + sites + }; + for name in staged { + assert!( + sites(name).iter().all(|site| site.pending.is_some()), + "{name} stages its updates" + ); + } + for name in queued { + assert!( + sites(name).iter().all(|site| site.pending.is_none()), + "{name} queues its updates" + ); + } + } +} + +/// A nonblocking assignment to a slice of an unpacked array whose range +/// runs against the array's takes the elements in reverse order, as a +/// blocking one does (IEEE 1800-2023 7.6). Neither Icarus nor Verilator +/// compiles the slice. +#[test] +fn nonblocking_assignments_to_reversed_array_slices_reverse_the_elements() { + let source = r#" + module Top(output logic [31:0] elements); + timeunit 1ps / 1ps; + logic [7:0] m [4]; + logic [7:0] w [2]; + assign elements = {m[3], m[2], m[1], m[0]}; + initial begin + m[0] = 8'd1; m[1] = 8'd2; m[2] = 8'd3; m[3] = 8'd4; + w[0] = 8'haa; w[1] = 8'hbb; + #1; + m[1:0] <= w; + m[3:2] = w; + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("reversed_slice.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(2).unwrap(); + // m[1:0] <= w writes w[0] to m[1], as m[3:2] = w writes w[0] to m[3]. + assert_eq!(sim.get(sim.signal("elements")), 0xaabb_aabbu32.into()); +} From 605514fdb2064e101fa3ea28e45fb67f778874c5 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 01:38:21 +0900 Subject: [PATCH 3/4] docs(sv): describe nonblocking assignments in processes to any target Change-Id: I6eb95ebed371843c56421db2b5be708f5f491d14 --- docs/guide/systemverilog-reference.md | 7 ++----- docs/ja/guide/systemverilog-reference.md | 6 ++---- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6cf5838e16b..2722e799c75 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -53,7 +53,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: | `#delay` | integral and real delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero | | `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads | | `wait (condition)` | any condition; an X or Z condition counts as false | -| Assignments | blocking and nonblocking; nonblocking updates take effect in the NBA region of the time slot | +| Assignments | blocking and nonblocking, to any target a blocking assignment takes, including unpacked array elements and run-time positions; nonblocking updates take effect in the NBA region of the time slot, at the position evaluated when the assignment executes, and bits outside the target or at a position with an X or Z bit are not written | An `always` whose sensitivity list names exactly the variables its statement reads, as `@*` would (IEEE 1800-2023 9.4.2.2), simulates like `always @*` in @@ -141,10 +141,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), package-scoped delay values ([#1710](https://github.com/celox-sim/celox/issues/1710)), impure function calls in event expressions, and - `wait` or event expressions reading a static task argument. Nonblocking - assignments in a process cannot yet target an unpacked array element, a - run-time position or a constant position outside the target - ([#1709](https://github.com/celox-sim/celox/issues/1709)). + `wait` or event expressions reading a static task argument. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. - Ports and instances: non-ANSI port declarations ([#426](https://github.com/celox-sim/celox/issues/426)), `ref` ports diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 4d357524ae6..2662f0b5f7b 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -52,7 +52,7 @@ outline: [2, 3] | `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | | `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` | | `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | -| 代入 | ブロッキング代入とノンブロッキング代入。ノンブロッキング代入はそのタイムスロットの NBA 領域で反映 | +| 代入 | ブロッキング代入とノンブロッキング代入。代入先はブロッキング代入と同じで、unpacked 配列の要素や実行時に決まる位置も使えます。ノンブロッキング代入は代入を実行した時点で評価した位置に、そのタイムスロットの NBA 領域で反映します。代入先の範囲外のビットと、X や Z のビットを含む位置には書き込みません | 文が読む変数をちょうど並べたセンシティビティリスト(`@*` が求めるもの、IEEE 1800-2023 9.4.2.2)を持つ `always` は、`always @(a or b) y = a + b;` や `always @(b, a) y = a + b;` のように、 @@ -131,9 +131,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、 package スコープの遅延値 ([#1710](https://github.com/celox-sim/celox/issues/1710))、イベント式内の impure な関数呼び出し、 - static task 引数を読む `wait` 条件とイベント式。プロセス内のノンブロッキング代入は、 - unpacked 配列の要素、実行時に決まる位置、代入先の範囲外の定数位置をまだ代入先にできません - ([#1709](https://github.com/celox-sim/celox/issues/1709))。 + static task 引数を読む `wait` 条件とイベント式。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 From fe58ec1071d7039fad4ddf180e00f80deb55a210 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 13:46:31 +0900 Subject: [PATCH 4/4] feat(runtime)!: fuse clock-waiting kernels into compiled slots The compiled scheduler now also runs kernels whose every wait is the same single edge of a one-bit signal that one compiled delay-only kernel alone drives, whose statuses are Wait, Nba, Done or Finish, and whose nonblocking sites stage their values into targets nothing else writes. Such a kernel wakes at most once a slot, so a site is never staged again before the NBA region. A slot runs the ready kernels lowest first, tests the waits after each run while kernels remain ready or the kernel resumes at once, and again after each pass's settle, as the reference's process phase does; a wait compares against a baseline that follows every tested change. The ready set is a mask over the compiled kernels in kernel order. Staged values publish after the domains, or with a settle of their own without one. Waiting kernels move between Waiters and the scheduler's slots at each run, and a run that ends in the middle of a slot hands back the ready set and the baselines as the reference leaves them. Kernels that drive or wait for a clock whose domain commits blocking results in the active region keep the reference loop. BREAKING CHANGE: SchedulerSlots has new fields, `ready` and `baseline`. Native images use container format 30; images written by earlier versions must be rebuilt. Change-Id: Ib033a13b9ad213155c0ffca86c4e891fe61876b2 --- crates/celox-design/src/lib.rs | 19 +- .../src/symbolic/assembly.rs | 4 + crates/celox-runtime/src/schedule.rs | 59 +- .../celox-runtime/src/simulation/compiled.rs | 96 ++- crates/celox-runtime/src/simulation/mod.rs | 12 +- crates/celox-runtime/src/simulation/wait.rs | 9 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 797 ++++++++++++++---- crates/celox/src/simulation/differential.rs | 179 ++++ 9 files changed, 960 insertions(+), 217 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7cb1572d8e2..4c4d6077810 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -850,10 +850,12 @@ pub struct RuntimeSchema { /// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], /// [`SchedulerSlots::exit_arg`], [`SchedulerSlots::count`], -/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`] and every [`SchedulerSlots::wake`] object. +/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`], +/// [`SchedulerSlots::ready`] and every [`SchedulerSlots::wake`] object. pub const SCHEDULER_TIME_WIDTH: usize = 64; /// Width of [`SchedulerSlots::exit`], [`SchedulerSlots::finish`], -/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] object. +/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] and +/// [`SchedulerSlots::baseline`] object. pub const SCHEDULER_FLAG_WIDTH: usize = 8; /// Hidden state objects through which a compiled scheduler and the runtime @@ -881,11 +883,16 @@ pub struct SchedulerSlots { /// The levels of the event signals at the start of the last slot, one /// bit per event in event order. pub levels: A, + /// The kernels ready to run in the current slot, one bit per kernel in + /// kernel order. + pub ready: A, /// The time each process kernel resumes at, in kernel order, valid /// where [`Self::waiting`] is set. pub wake: Vec, - /// Whether each process kernel waits for its wake time. + /// Whether each process kernel waits for its wake time or event. pub waiting: Vec, + /// The level a kernel waiting for an event last saw its signal at. + pub baseline: Vec, } impl SchedulerSlots { @@ -900,8 +907,10 @@ impl SchedulerSlots { count: map(self.count), current: map(self.current), levels: map(self.levels), + ready: map(self.ready), wake: self.wake.into_iter().map(&mut map).collect(), - waiting: self.waiting.into_iter().map(map).collect(), + waiting: self.waiting.into_iter().map(&mut map).collect(), + baseline: self.baseline.into_iter().map(map).collect(), } } @@ -917,10 +926,12 @@ impl SchedulerSlots { &self.count, &self.current, &self.levels, + &self.ready, ] .into_iter() .chain(&self.wake) .chain(&self.waiting) + .chain(&self.baseline) } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 6a8f45347bb..60da2d2ba27 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2156,12 +2156,16 @@ fn declare_scheduler_slots( count: declare("count".into(), TIME), current: declare("current".into(), TIME), levels: declare("levels".into(), TIME), + ready: declare("ready".into(), TIME), wake: (0..process_count) .map(|index| declare(format!("wake[{index}]"), TIME)) .collect(), waiting: (0..process_count) .map(|index| declare(format!("waiting[{index}]"), FLAG)) .collect(), + baseline: (0..process_count) + .map(|index| declare(format!("baseline[{index}]"), FLAG)) + .collect(), }) } diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index e555082d04d..31214b821c6 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -54,9 +54,18 @@ pub(crate) struct SchedulerRefs { pub(crate) count: SignalRef, pub(crate) current: SignalRef, pub(crate) levels: SignalRef, - /// The wake and waiting slots of each kernel the scheduler runs, by - /// process index. + pub(crate) ready: SignalRef, + /// The wake and waiting slots of each kernel the scheduler runs that + /// only delays, by process index. pub(crate) wake: Vec>, + /// The waiting and baseline slots of each kernel the scheduler runs that + /// waits for an edge, by process index. + pub(crate) waits: Vec>, + /// The number of such kernels. + pub(crate) wait_kernels: usize, + /// The bit of each kernel the scheduler runs in its ready mask: its + /// place among them in kernel order. + pub(crate) ordinals: Vec>, /// The event ids of the bits of `levels`. pub(crate) events: Vec, } @@ -246,17 +255,45 @@ impl ResolvedSchedule { count: resolve(&slots.count), current: resolve(&slots.current), levels: resolve(&slots.levels), - wake: slots - .wake - .iter() - .zip(&slots.waiting) - .zip(&scheduler.fallback) - .map(|((wake, waiting), fallback)| { - fallback - .is_none() - .then(|| (resolve(wake), resolve(waiting))) + ready: resolve(&slots.ready), + wake: (0..scheduler.fallback.len()) + .map(|index| { + (scheduler.fallback[index].is_none() + && model.processes[index].waits.is_empty()) + .then(|| (resolve(&slots.wake[index]), resolve(&slots.waiting[index]))) + }) + .collect(), + waits: (0..scheduler.fallback.len()) + .map(|index| { + (scheduler.fallback[index].is_none() + && !model.processes[index].waits.is_empty()) + .then(|| { + ( + resolve(&slots.waiting[index]), + resolve(&slots.baseline[index]), + ) + }) }) .collect(), + ordinals: { + let mut next = 0; + scheduler + .fallback + .iter() + .map(|fallback| { + fallback.is_none().then(|| { + next += 1; + next - 1 + }) + }) + .collect() + }, + wait_kernels: (0..scheduler.fallback.len()) + .filter(|&index| { + scheduler.fallback[index].is_none() + && !model.processes[index].waits.is_empty() + }) + .count(), events: scheduler .events .iter() diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index fb98dba1379..973e0dcdaac 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -5,8 +5,12 @@ use std::cmp::Reverse; use celox_design::SchedulerExit; -use super::{CompiledSlots, SchedulerMode, SimulationExecutor, SimulationState}; -use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; +use super::{Baseline, CompiledSlots, SchedulerMode, SimulationExecutor, SimulationState}; +use crate::{ + SimulatorErrorCode, + backend::SimBackend, + timing::{Halt, copy_planes}, +}; impl SimulationState { /// Whether a compiled scheduler may run slots of this simulation. @@ -37,7 +41,10 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() - || !pending.waiters.is_empty() + || pending + .waiters + .iter() + .any(|(process, _)| scheduler.waits.get(process).is_none_or(Option::is_none)) { return None; } @@ -111,6 +118,28 @@ impl SimulationState { for &(_, waiting) in scheduler.wake.iter().flatten() { backend.set(waiting, 0u8); } + backend.set(scheduler.ready, 0u64); + // The scheduler's waiting kernels wait in its slots during the run, + // with the level each wait last saw. + for (process, slots) in scheduler.waits.iter().enumerate() { + let Some((waiting, baseline)) = *slots else { + continue; + }; + let level = match self.process_state.waiters.get(process) { + Some(waiter) => match waiter.baselines.first() { + Some(Baseline::Raw(raw)) => raw.first().is_some_and(|byte| byte & 1 != 0), + Some(Baseline::Value((value, _))) => value.bit(0), + _ => return Err(SimulatorErrorCode::InternalError.into()), + }, + None => { + backend.set(waiting, 0u8); + continue; + } + }; + backend.set(waiting, 1u8); + backend.set(baseline, u8::from(level)); + self.process_state.waiters.remove(process); + } // The scheduler's kernels wait in its wake slots during the run. let mut kept = Vec::with_capacity(self.process_wakeups.len()); for wakeup @ Reverse((time, process)) in self.process_wakeups.drain() { @@ -136,26 +165,69 @@ impl SimulationState { let now: u64 = backend.get_as(scheduler.now); let exit = SchedulerExit::from_code(backend.get_as(scheduler.exit)); let current: u64 = backend.get_as(scheduler.current); + let ready: u64 = backend.get_as(scheduler.ready); let complete = result.is_ok() && exit == Some(SchedulerExit::Limit); + // A run that returned in the middle of slot `now` leaves the kernel + // that ended it filed nowhere, as the reference loop leaves it, and + // the kernels still ready in the slot ready. + let ordinals = &scheduler.ordinals; + let is_ready = |process: usize| { + ordinals + .get(process) + .copied() + .flatten() + .is_some_and(|ordinal| ready >> ordinal & 1 != 0) + }; + let pending = + |process: usize| !complete && (process as u64 == current || is_ready(process)); for (process, wake) in scheduler.wake.iter().enumerate() { let Some((wake, waiting)) = *wake else { continue; }; - if backend.get_as::(waiting) == 0 { + if pending(process) || backend.get_as::(waiting) == 0 { continue; } let time: u64 = backend.get_as(wake); - if !complete && time == now { - // The run returned in the middle of slot `now`: the kernel - // that ended it is filed nowhere, as the reference loop - // leaves it, and kernels due then that did not run yet are - // still ready. - if process as u64 != current { + self.process_wakeups.push(Reverse((time, process))); + } + for (process, slots) in scheduler.waits.iter().enumerate() { + let Some((waiting, baseline)) = *slots else { + continue; + }; + if pending(process) || backend.get_as::(waiting) == 0 { + continue; + } + let site = backend.get_as::(self.model.processes[process].delay) as usize; + let terms = self.model.processes[process] + .wait_sites + .get(site) + .ok_or_else(|| Self::site_error(process, site))?; + let level = [backend.get_as::(baseline)]; + // The slot keeps its storage, as `register_waiter` reuses it. + self.process_state.waiters.register( + process, + terms.iter().any(|term| term.driven), + |waiter| { + waiter.site = site; + waiter.baselines.truncate(1); + match waiter.baselines.first_mut() { + Some(Baseline::Raw(raw)) => copy_planes(raw, &level, 1), + _ => { + let mut raw = Vec::with_capacity(1); + copy_planes(&mut raw, &level, 1); + waiter.baselines.clear(); + waiter.baselines.push(Baseline::Raw(raw)); + } + } + }, + ); + } + if !complete { + for process in 0..ordinals.len() { + if is_ready(process) && process as u64 != current { self.process_state.ready.insert(process); } - continue; } - self.process_wakeups.push(Reverse((time, process))); } self.stats.compiled_slots += count; if count > 0 { diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index f5f950ad24b..7523e231da0 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -295,13 +295,19 @@ impl SimulationState { return Ok(false); } let compiles = self.compiles_slots(); + let waiting_kernels = self + .model + .scheduler + .as_ref() + .map_or(0, |scheduler| scheduler.wait_kernels); while let Some(next_time) = self.next_event_time() { if next_time > end { break; } - // A waiting process keeps the slot in the reference loop; test - // that first, as fallback designs fail it at every step. - let compiled = if compiles && self.process_state.waiters.is_empty() { + // A process the scheduler does not run waits: the slot stays in + // the reference loop. Test that first, as designs with such + // processes fail it at every step. + let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels { self.compiled_limit(executor, end, observer.one_slot()) } else { None diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 1bb95a744e9..e9eb1e13904 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -323,6 +323,15 @@ impl Waiters { self.register(process, driven, |slot| *slot = waiter); } + /// The wait of process `process`, if it waits. + pub fn get(&self, process: usize) -> Option<&Waiter> { + self.waiting + .get(process) + .copied() + .unwrap_or(false) + .then(|| &self.slots[process]) + } + /// Process `process` no longer waits. pub fn remove(&mut self, process: usize) { if self.waiting.get(process).copied().unwrap_or(false) { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a36af8f6961..4c53415d477 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 = 29; +const CONTAINER_VERSION: u16 = 30; 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/scheduler.rs b/crates/celox/src/scheduler.rs index 2186b9e3589..347abdd54c3 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -17,8 +17,9 @@ //! reference loop. use celox_design::{ - DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, - STABLE_REGION, SchedulerExit, SchedulerSlots, TIME_SLOT_WIDTH, schedule::ScheduleModel, + CounterKind, DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_FLAG_WIDTH, + SCHEDULER_TIME_WIDTH, STABLE_REGION, SchedulerExit, SchedulerSlots, TIME_SLOT_WIDTH, + schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; @@ -36,6 +37,28 @@ type Builder = SIRBuilder; /// The most events whose edges one slot can record. const MAX_EVENTS: usize = 64; +/// The most kernels the ready mask of a slot holds. +const MAX_KERNELS: usize = 64; + +/// The widest selector of a nonblocking site index. +const SITE_BITS: usize = 8; + +const ACTIVE_COMMIT: &str = "the process drives or waits for a clock whose domain commits blocking results in the active region"; + +const DELAY_STATUSES: [ProcessStatus; 4] = [ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Done, + ProcessStatus::Finish, +]; + +const WAIT_STATUSES: [ProcessStatus; 4] = [ + ProcessStatus::Wait, + ProcessStatus::Nba, + ProcessStatus::Done, + ProcessStatus::Finish, +]; + /// Generate the compiled scheduler of `program`, if it qualifies, and record /// for every process kernel whether the scheduler runs it. pub(crate) fn attach(program: &mut LaidOutProgram) { @@ -91,6 +114,26 @@ struct Kernel { /// The events whose signal the kernel writes, as indices into /// [`Plan::events`]. writes: Vec, + /// For a kernel that waits for one edge, the edge and its staged + /// nonblocking assignments; `None` for a kernel that only delays. + wait: Option, +} + +/// The single edge a kernel waits for at every wait site. +struct Wait { + signal: AbsoluteAddr, + kind: CounterKind, + /// Its nonblocking sites, by local index. + sites: Vec, +} + +/// A nonblocking site that stages its value and sets a pending flag. +struct Staged { + pending: AbsoluteAddr, + value: AbsoluteAddr, + target: AbsoluteAddr, + lsb: usize, + width: usize, } struct Plan { @@ -200,13 +243,14 @@ impl Plan { written.dedup(); written }; - let rtl_units = sir - .eval_comb - .iter() - .chain(sir.eval_apply_ffs.values().flatten()) - .chain(sir.eval_only_ffs.values().flatten()) - .chain(sir.apply_ffs.values().flatten()); - for unit in rtl_units { + let rtl_units = || { + sir.eval_comb + .iter() + .chain(sir.eval_apply_ffs.values().flatten()) + .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()); } @@ -220,9 +264,36 @@ impl Plan { .filter(|(_, event)| model.active_commits.contains(&event.signal)) .map(|(index, _)| index) .collect(); + // The storage each unit writes. + let stores = |unit: &Unit| -> HashSet { + instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Store(target, ..) | SIRInstruction::Commit(_, target, ..) => { + Some(storage(target.absolute_addr())) + } + _ => None, + }) + .collect() + }; + let rtl_stores: HashSet = rtl_units().flat_map(stores).collect(); + let kernel_stores: Vec> = sir + .processes + .iter() + .take(schema.processes.len()) + .map(stores) + .collect(); + let waited: HashSet = model.waited.iter().map(|s| storage(*s)).collect(); + let mut nba_targets: HashMap = HashMap::default(); + for process in &model.processes { + for site in &process.nbas { + *nba_targets.entry(storage(site.target)).or_default() += 1; + } + } - let mut kernels = Vec::with_capacity(schema.processes.len()); + let mut kernels: Vec> = Vec::with_capacity(schema.processes.len()); let mut fallback = Vec::with_capacity(schema.processes.len()); + // Kernels that only delay first: the signals they write are those a + // waiting kernel's edge may be on. for (index, slots) in schema.processes.iter().enumerate() { let process = &model.processes[index]; let unit = &sir.processes[index]; @@ -230,23 +301,16 @@ impl Plan { Some("a declaration initializer") } else if slots.requires_timed_simulation { Some("an edge procedure") + } else if !process.host_requests.is_empty() { + Some("the process makes host requests") + } else if !process.waits.is_empty() { + None } else if !slots.const_delays { Some("a delay is not a constant of at least one time unit") - } else if !process.waits.is_empty() { - Some("the process waits for events") } else if !process.nbas.is_empty() { Some("the process has nonblocking assignments") - } else if !process.host_requests.is_empty() { - Some("the process makes host requests") - } else if !delay_statuses_only(unit, slots.status) { + } else if !statuses_only(unit, slots.status, &DELAY_STATUSES) { Some("the process suspends other than for a delay") - } else if written(unit) - .iter() - .any(|event| active_commits.contains(event)) - { - Some( - "the process drives a clock whose domain commits blocking results in the active region", - ) } else { None }; @@ -255,14 +319,130 @@ impl Plan { kernels.push(None); fallback.push(Some(reason.to_string())); } + None if process.waits.is_empty() => { + let writes = written(unit); + if writes.iter().any(|event| active_commits.contains(event)) { + kernels.push(None); + fallback.push(Some(ACTIVE_COMMIT.to_string())); + } else { + kernels.push(Some(Kernel { writes, wait: None })); + fallback.push(None); + } + } None => { - kernels.push(Some(Kernel { - writes: written(unit), - })); + kernels.push(None); fallback.push(None); } } } + // How many kernels that only delay write each storage. A waiting + // kernel's signal has one such writer, which runs once a slot, so + // the waiting kernel wakes at most once a slot. + let mut delay_writers: HashMap = HashMap::default(); + for (_, stores) in kernels + .iter() + .zip(&kernel_stores) + .filter(|(kernel, _)| kernel.is_some()) + { + for store in stores { + *delay_writers.entry(*store).or_default() += 1; + } + } + // Storage the other kernels write, waiting ones included. + let other_stores: HashSet = kernels + .iter() + .zip(&kernel_stores) + .filter(|(kernel, _)| kernel.is_none()) + .flat_map(|(_, stores)| stores.iter().copied()) + .collect(); + for index in 0..schema.processes.len() { + let process = &model.processes[index]; + if process.waits.is_empty() || fallback[index].is_some() { + continue; + } + let slots = &schema.processes[index]; + let unit = &sir.processes[index]; + let term = &process.waits[0].first(); + let wait = (|| -> Result { + let term = term.ok_or("the process waits for a level")?; + if process + .waits + .iter() + .any(|terms| terms.len() != 1 || terms[0] != *term) + { + return Err("the process waits for more than one edge"); + } + let signal = storage(term.signal); + if program.layout().widths.get(&term.signal) != Some(&1) + || delay_writers.get(&signal) != Some(&1) + || rtl_stores.contains(&signal) + || other_stores.contains(&signal) + { + return Err( + "the process waits for a signal that one kernel that only delays does not drive alone", + ); + } + if event_storage + .get(&signal) + .is_some_and(|event| active_commits.contains(event)) + { + return Err(ACTIVE_COMMIT); + } + if !statuses_only(unit, slots.status, &WAIT_STATUSES) { + return Err("the process suspends other than for one edge"); + } + let writes = &kernel_stores[index]; + if !written(unit).is_empty() || writes.iter().any(|store| waited.contains(store)) { + return Err("the process drives an event or a waited signal"); + } + let sites = process + .nbas + .iter() + .map(|site| { + let target = storage(site.target); + let pending = site.pending.ok_or("a nonblocking site queues its values")?; + if site.offset.is_some() + || nba_targets.get(&target) != Some(&1) + || rtl_stores.contains(&target) + || kernel_stores.iter().any(|stores| stores.contains(&target)) + || waited.contains(&target) + || event_storage.contains_key(&target) + { + return Err("a nonblocking target has other writers or observers"); + } + Ok(Staged { + pending, + value: site.value, + target: site.target, + lsb: site.lsb, + width: site.width, + }) + }) + .collect::, _>>()?; + if sites.len() > 1 << SITE_BITS { + return Err("the process has too many nonblocking sites"); + } + Ok(Wait { + signal: term.signal, + kind: term.kind, + sites, + }) + })(); + match wait { + Ok(wait) => { + kernels[index] = Some(Kernel { + writes: Vec::new(), + wait: Some(wait), + }) + } + Err(reason) => fallback[index] = Some(reason.to_string()), + } + } + if kernels.iter().flatten().count() > MAX_KERNELS { + return Err(format!( + "the design has more than {MAX_KERNELS} kernels to compile" + )); + } let finish_sites = schema .runtime_event_sites .iter() @@ -301,24 +481,38 @@ impl Plan { finish_sites: &self.finish_sites, exits: Vec::new(), }; + let waits: Vec<(usize, &Wait)> = self + .kernels + .iter() + .enumerate() + .filter_map(|(index, kernel)| Some((index, kernel.as_ref()?.wait.as_ref()?))) + .collect(); + let delays: Vec = self + .kernels + .iter() + .enumerate() + .filter(|(_, kernel)| kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none())) + .map(|(index, _)| index) + .collect(); + // The bit of each kernel in the ready mask: its place among the + // kernels the scheduler runs, in kernel order. + let ordinals = ordinals(&self.kernels); let header = g.b.new_block(); g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - // The next slot: the earliest wake time of a waiting kernel. + // The next slot: the earliest wake time of a kernel waiting for one. g.b.switch_to_block(header); let mut time = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); let mut any = g.constant(0, 1); - for (index, kernel) in self.kernels.iter().enumerate() { - if kernel.is_some() { - let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); - let waiting = g.waiting(index); - let earlier = g.binary(1, wake, BinaryOp::LtU, time); - let earlier = g.binary(1, earlier, BinaryOp::And, waiting); - let next = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); - g.b.emit(SIRInstruction::Mux(next, earlier, wake, time)); - time = next; - any = g.binary(1, any, BinaryOp::Or, waiting); - } + for &index in &delays { + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let earlier = g.binary(1, wake, BinaryOp::LtU, time); + let earlier = g.binary(1, earlier, BinaryOp::And, waiting); + let next = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); + g.b.emit(SIRInstruction::Mux(next, earlier, wake, time)); + time = next; + any = g.binary(1, any, BinaryOp::Or, waiting); } let limit = g.load(slots.limit, SCHEDULER_TIME_WIDTH); let after = g.binary(1, time, BinaryOp::GtU, limit); @@ -326,7 +520,7 @@ impl Plan { let none = g.binary(1, any, BinaryOp::Xor, one); let stop = g.binary(1, after, BinaryOp::Or, none); let run = g.b.new_block(); - let limit_exit = g.exit_block(SchedulerExit::Limit, None); + let limit_exit = g.exit_block(SchedulerExit::Limit); g.b.seal_block(SIRTerminator::Branch { cond: stop, true_block: (limit_exit, Vec::new()), @@ -354,31 +548,68 @@ impl Plan { levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, value); } g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); - let finish_exit = g.exit_block(SchedulerExit::Finish, None); - let internal_exit = g.exit_block(SchedulerExit::Internal, None); - - // The kernels due now, in kernel order, and the active edges they - // give, as a mask over the events. - let mut mask = g.constant(0, MAX_EVENTS); - for (index, kernel) in self.kernels.iter().enumerate() { - let Some(kernel) = kernel else { - continue; - }; - let process = &schema.processes[index]; + // The kernels due now are ready; the edges of the slot collect in + // `exit_arg`. + let mut ready = g.constant(0, MAX_KERNELS); + for &index in &delays { let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); let waiting = g.waiting(index); let due = g.binary(1, wake, BinaryOp::Eq, time); let due = g.binary(1, due, BinaryOp::And, waiting); + let bit = g.bit(due, ordinals[index]); + ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); + } + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); + let zero = g.constant(0, MAX_EVENTS); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, zero); + let finish_exit = g.exit_block(SchedulerExit::Finish); + let internal_exit = g.exit_block(SchedulerExit::Internal); + let pick = g.b.new_block(); + g.b.seal_block(SIRTerminator::Jump(pick, Vec::new())); + + // A pass of the process phase: the lowest ready kernel runs, and + // the waits see its writes before the next one while kernels remain + // ready (`run_ready`); then combinational logic settles. + g.b.switch_to_block(pick); + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let idle = g.binary(1, ready, BinaryOp::Eq, zero); + let pass_end = g.b.new_block(); + let chosen = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: idle, + true_block: (pass_end, Vec::new()), + false_block: (chosen, Vec::new()), + }); + g.b.switch_to_block(chosen); + let mut runs = Vec::new(); + for (index, kernel) in self.kernels.iter().enumerate() { + if kernel.is_none() { + continue; + } + let bit = g.constant(1 << ordinals[index], MAX_KERNELS); + let selected = g.binary(MAX_KERNELS, ready, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); let run = g.b.new_block(); - let joined = g.b.alloc_bit(MAX_EVENTS, false); - let join = g.b.new_block_with(vec![joined]); + let next = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: due, + cond: this, true_block: (run, Vec::new()), - false_block: (join, vec![mask]), + false_block: (next, Vec::new()), }); + runs.push((index, run)); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + for (index, run) in runs { + let kernel = self.kernels[index].as_ref().expect("selected above"); + let process = &schema.processes[index]; g.b.switch_to_block(run); + let ready = g.load(slots.ready, MAX_KERNELS); + let keep = g.constant(!(1u64 << ordinals[index]), MAX_KERNELS); + let ready = g.binary(MAX_KERNELS, ready, BinaryOp::And, keep); + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); let current = g.constant(index as u64, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, current); let before: Vec<_> = kernel @@ -386,6 +617,9 @@ impl Plan { .iter() .map(|&event| g.level(&self.events[event])) .collect(); + let enter = g.b.new_block(); + g.b.seal_block(SIRTerminator::Jump(enter, Vec::new())); + g.b.switch_to_block(enter); g.inline(&program.sir.processes[index], finish_exit); let status = g.load(process.status, celox_design::PROCESS_STATUS_WIDTH); let code = |status: ProcessStatus| u64::from(status.code()); @@ -397,68 +631,112 @@ impl Plan { false_block: (not_finished, Vec::new()), }); g.b.switch_to_block(not_finished); - let done = g.equals(status, code(ProcessStatus::Done)); - let ended = g.b.new_block(); - let suspended = g.b.new_block(); let resumed = g.b.new_block(); + match &kernel.wait { + None => { + let done = g.equals(status, code(ProcessStatus::Done)); + let ended = g.b.new_block(); + let suspended = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: done, + true_block: (ended, Vec::new()), + false_block: (suspended, Vec::new()), + }); + g.b.switch_to_block(ended); + let idle = g.constant(0, SCHEDULER_FLAG_WIDTH); + g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, idle); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + g.b.switch_to_block(suspended); + let delay = g.equals(status, code(ProcessStatus::Delay)); + let inactive = g.equals(status, code(ProcessStatus::InactiveDelay)); + let delayed = g.binary(1, delay, BinaryOp::Or, inactive); + let wait = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: delayed, + true_block: (wait, Vec::new()), + false_block: (internal_exit, Vec::new()), + }); + g.b.switch_to_block(wait); + let amount = g.load(process.delay, celox_design::PROCESS_DELAY_WIDTH); + let wake = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, amount); + let overflow = g.binary(1, wake, BinaryOp::LtU, time); + let overflow_exit = g.exit_block(SchedulerExit::DelayOverflow); + let in_range = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: overflow, + true_block: (overflow_exit, Vec::new()), + false_block: (in_range, Vec::new()), + }); + g.b.switch_to_block(in_range); + g.store(slots.wake[index], SCHEDULER_TIME_WIDTH, wake); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + // The edges of this run, against the levels before it. + g.b.switch_to_block(resumed); + let mut edges = g.load(slots.exit_arg, MAX_EVENTS); + for (&event, &was) in kernel.writes.iter().zip(&before) { + let is = g.level(&self.events[event]); + let changed = g.binary(1, was, BinaryOp::Ne, is); + let active = g.equals(is, u64::from(self.events[event].active)); + let edge = g.binary(1, changed, BinaryOp::And, active); + let bit = g.bit(edge, event); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + } + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + } + Some(wait) => { + // A kernel runs at most once a slot (see `Plan::new`), so + // a staged site is never staged again before the NBA + // region and the kernel never returns `Nba`. + let done = g.equals(status, code(ProcessStatus::Done)); + let suspends = g.equals(status, code(ProcessStatus::Wait)); + let other = g.b.new_block(); + let suspended = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: done, + true_block: (resumed, Vec::new()), + false_block: (other, Vec::new()), + }); + g.b.switch_to_block(other); + g.b.seal_block(SIRTerminator::Branch { + cond: suspends, + true_block: (suspended, Vec::new()), + false_block: (internal_exit, Vec::new()), + }); + + // It waits again: the edge is judged against the level + // now (`register_waiter`). + g.b.switch_to_block(suspended); + let flag = g.constant(1, SCHEDULER_FLAG_WIDTH); + g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, flag); + let level = g.signal_level(wait.signal); + let level = g.widen(level, SCHEDULER_FLAG_WIDTH); + g.store(slots.baseline[index], SCHEDULER_FLAG_WIDTH, level); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + g.b.switch_to_block(resumed); + } + } + // Before the next run, the waits see this one's writes. + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let more = g.binary(1, ready, BinaryOp::Ne, zero); + let check = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: done, - true_block: (ended, Vec::new()), - false_block: (suspended, Vec::new()), - }); - g.b.switch_to_block(ended); - let idle = g.constant(0, SCHEDULER_FLAG_WIDTH); - g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, idle); - g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); - - g.b.switch_to_block(suspended); - let delay = g.equals(status, code(ProcessStatus::Delay)); - let inactive = g.equals(status, code(ProcessStatus::InactiveDelay)); - let delayed = g.binary(1, delay, BinaryOp::Or, inactive); - let wait = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: delayed, - true_block: (wait, Vec::new()), - false_block: (internal_exit, Vec::new()), - }); - g.b.switch_to_block(wait); - let amount = g.load(process.delay, celox_design::PROCESS_DELAY_WIDTH); - let wake = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, amount); - let overflow = g.binary(1, wake, BinaryOp::LtU, time); - let overflow_exit = g.exit_block(SchedulerExit::DelayOverflow, None); - let in_range = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: overflow, - true_block: (overflow_exit, Vec::new()), - false_block: (in_range, Vec::new()), + cond: more, + true_block: (check, Vec::new()), + false_block: (pick, Vec::new()), }); - g.b.switch_to_block(in_range); - g.store(slots.wake[index], SCHEDULER_TIME_WIDTH, wake); - g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); - - g.b.switch_to_block(resumed); - let mut edges = mask; - for (&event, &was) in kernel.writes.iter().zip(&before) { - let is = g.level(&self.events[event]); - let changed = g.binary(1, was, BinaryOp::Ne, is); - let active = g.equals(is, u64::from(self.events[event].active)); - let edge = g.binary(1, changed, BinaryOp::And, active); - let set = g.constant(1 << event, MAX_EVENTS); - let unset = g.constant(0, MAX_EVENTS); - let bit = g.b.alloc_bit(MAX_EVENTS, false); - g.b.emit(SIRInstruction::Mux(bit, edge, set, unset)); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); - } - g.b.seal_block(SIRTerminator::Jump(join, vec![edges])); - g.b.switch_to_block(join); - mask = joined; + g.b.switch_to_block(check); + g.check_waits(&waits_of(&waits, &ordinals)); + g.b.seal_block(SIRTerminator::Jump(pick, Vec::new())); } - // The settle after the kernels, shared with the one after the - // domains: the mask waits in `exit_arg` meanwhile. + // The settles after a pass and after the domains share one copy of + // combinational logic. + g.b.switch_to_block(pass_end); let none = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, none); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, mask); let comb = g.b.new_block(); g.call_comb(comb, 1); @@ -484,75 +762,79 @@ impl Plan { default: internal_exit, }); - // The domains the edges trigger. + // After the settle of a pass the waits see its writes; woken + // kernels run in another pass. g.b.switch_to_block(settled); - if written.is_empty() { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); - g.b.switch_to_block(slot_end); - g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - return g.finish(); - } + g.check_waits(&waits_of(&waits, &ordinals)); + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let more = g.binary(1, ready, BinaryOp::Ne, zero); + let domains = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (pick, Vec::new()), + false_block: (domains, Vec::new()), + }); + + // 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: (slot_end, Vec::new()), + true_block: (untriggered, Vec::new()), false_block: (triggered, Vec::new()), }); - g.b.switch_to_block(triggered); - 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(); - let evaluated = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: single, - true_block: (one_domain, Vec::new()), - false_block: (domains, Vec::new()), - }); - // One triggered domain evaluates and applies at once. - g.b.switch_to_block(one_domain); - for &index in &written { - 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(); + // Without a domain, published nonblocking values settle once more. + g.b.switch_to_block(untriggered); + 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: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), + cond: any, + true_block: (publish_settle, Vec::new()), + false_block: (slot_end, Vec::new()), }); - g.b.switch_to_block(unit); - for unit in &event.eval_apply { - g.inline(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 written.len() < 2 { - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - g.b.switch_to_block(evaluated); + g.b.switch_to_block(publish_settle); g.call_comb(comb, 2); - g.b.switch_to_block(slot_end); - g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - return g.finish(); } - for phase in [Phase::Evaluate, Phase::Apply] { + + g.b.switch_to_block(triggered); + let evaluated = g.b.new_block(); + if written.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()), + }); + + // One triggered domain evaluates and applies at once. + g.b.switch_to_block(one_domain); for &index in &written { 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 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 { @@ -561,20 +843,52 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(unit); - let units = match phase { - Phase::Evaluate => &event.eval_only, - Phase::Apply => &event.apply, - }; - for unit in units { + for unit in &event.eval_apply { g.inline(unit, finish_exit); } - g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + 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 written.len() < 2 { + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + } else { + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &written { + 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, + Phase::Apply => &event.apply, + }; + for unit in units { + g.inline(unit, finish_exit); + } + 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); g.call_comb(comb, 2); g.b.switch_to_block(slot_end); @@ -593,7 +907,7 @@ struct Generator<'a> { slots: &'a SchedulerSlots, finish_sites: &'a HashSet, /// Exit blocks not yet emitted. - exits: Vec<(celox_sir::BlockId, SchedulerExit, Option)>, + exits: Vec<(celox_sir::BlockId, SchedulerExit)>, } impl Generator<'_> { @@ -660,14 +974,106 @@ impl Generator<'_> { self.binary(1, value, BinaryOp::Ne, zero) } - /// A block that ends the run with `exit` and its argument, emitted by + /// A block that ends the run with `exit`, emitted by /// [`Self::emit_exits`]. - fn exit_block(&mut self, exit: SchedulerExit, argument: Option) -> celox_sir::BlockId { + fn exit_block(&mut self, exit: SchedulerExit) -> celox_sir::BlockId { let block = self.b.new_block(); - self.exits.push((block, exit, argument)); + self.exits.push((block, exit)); block } + /// Bit `index` of a 64-bit mask, set when `condition` holds. + fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { + let set = self.constant(1 << index, MAX_KERNELS); + let unset = self.constant(0, MAX_KERNELS); + let bit = self.b.alloc_bit(MAX_KERNELS, false); + self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); + bit + } + + /// The value of the one-bit signal `address`. + fn signal_level(&mut self, address: AbsoluteAddr) -> RegisterId { + self.load(address, 1) + } + + /// The one-bit `value` as a `width`-bit number. + fn widen(&mut self, value: RegisterId, width: usize) -> RegisterId { + let set = self.constant(1, width); + let unset = self.constant(0, width); + let wide = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Mux(wide, value, set, unset)); + wide + } + + /// Test the waits of `waits`, (kernel, ready bit, signal, edge), against their + /// signals now (`check_waits`): a wait whose edge occurred since its + /// baseline wakes its kernel; every changed signal becomes the + /// baseline. + fn check_waits(&mut self, waits: &[(usize, usize, AbsoluteAddr, CounterKind)]) { + if waits.is_empty() { + return; + } + let mut woken = self.constant(0, MAX_KERNELS); + for &(index, ordinal, signal, kind) in waits { + let waiting = self.waiting(index); + let baseline = self.load(self.slots.baseline[index], SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let was = self.binary(1, baseline, BinaryOp::Ne, zero); + let is = self.signal_level(signal); + let changed = self.binary(1, was, BinaryOp::Ne, is); + let occurred = match kind { + CounterKind::Changes => changed, + CounterKind::Rises => self.binary(1, changed, BinaryOp::And, is), + CounterKind::Falls => self.binary(1, changed, BinaryOp::And, was), + }; + let wake = self.binary(1, occurred, BinaryOp::And, waiting); + let level = self.widen(is, SCHEDULER_FLAG_WIDTH); + let next = self.b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); + self.b + .emit(SIRInstruction::Mux(next, waiting, level, baseline)); + self.store(self.slots.baseline[index], SCHEDULER_FLAG_WIDTH, next); + let one = self.constant(1, 1); + let stays = self.binary(1, wake, BinaryOp::Xor, one); + let still = self.binary(1, waiting, BinaryOp::And, stays); + let flag = self.widen(still, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.waiting[index], SCHEDULER_FLAG_WIDTH, flag); + let bit = self.bit(wake, ordinal); + woken = self.binary(MAX_KERNELS, woken, BinaryOp::Or, bit); + } + let ready = self.load(self.slots.ready, MAX_KERNELS); + let ready = self.binary(MAX_KERNELS, ready, BinaryOp::Or, woken); + self.store(self.slots.ready, SCHEDULER_TIME_WIDTH, ready); + } + + /// Publish the staged values of `sites` whose pending flag is set into + /// their targets, clearing the flags (`publish_nba`). + fn publish(&mut self, sites: &[&Staged]) { + for site in sites { + let pending = self.load(site.pending, 1); + let publish = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: pending, + true_block: (publish, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(publish); + let clear = self.constant(0, 1); + self.store(site.pending, 1, clear); + let value = self.load(site.value, site.width); + self.b.emit(SIRInstruction::Store( + stable(site.target), + SIROffset::Static(site.lsb), + site.width, + value, + Vec::new(), + Vec::new(), + )); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + } + /// The unit, once every block is sealed. fn finish(mut self) -> Unit { self.emit_exits(); @@ -680,14 +1086,10 @@ impl Generator<'_> { } fn emit_exits(&mut self) { - for (block, exit, argument) in std::mem::take(&mut self.exits) { + for (block, exit) in std::mem::take(&mut self.exits) { self.b.switch_to_block(block); let code = self.constant(exit as u64, SCHEDULER_FLAG_WIDTH); self.store(self.slots.exit, SCHEDULER_FLAG_WIDTH, code); - if let Some(argument) = argument { - let argument = self.constant(argument, SCHEDULER_TIME_WIDTH); - self.store(self.slots.exit_arg, SCHEDULER_TIME_WIDTH, argument); - } self.b.seal_block(SIRTerminator::Return); } } @@ -775,6 +1177,32 @@ impl Generator<'_> { } } +/// The waits of `waits` as (kernel, its bit in the ready mask, signal, +/// edge). +fn waits_of( + waits: &[(usize, &Wait)], + ordinals: &[usize], +) -> Vec<(usize, usize, AbsoluteAddr, CounterKind)> { + waits + .iter() + .map(|(index, wait)| (*index, ordinals[*index], wait.signal, wait.kind)) + .collect() +} + +/// The place of each kernel among those the scheduler runs, in kernel +/// order; unused for the others. +fn ordinals(kernels: &[Option]) -> Vec { + let mut next = 0; + kernels + .iter() + .map(|kernel| { + let ordinal = next; + next += usize::from(kernel.is_some()); + ordinal + }) + .collect() +} + fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) } @@ -783,9 +1211,9 @@ fn instructions(unit: &Unit) -> impl Iterator bool { +/// Whether every status `unit` stores into `status` is a constant among +/// `allowed`. +fn statuses_only(unit: &Unit, status: AbsoluteAddr, allowed: &[ProcessStatus]) -> bool { let constants: HashMap = instructions(unit) .filter_map(|inst| match inst { SIRInstruction::Imm(register, value) => u64::try_from(&value.payload) @@ -794,13 +1222,10 @@ fn delay_statuses_only(unit: &Unit, status: AbsoluteAddr) -> bool { _ => None, }) .collect(); - let allowed = [ - ProcessStatus::Delay, - ProcessStatus::InactiveDelay, - ProcessStatus::Done, - ProcessStatus::Finish, - ] - .map(|status| u64::from(status.code())); + let allowed: Vec = allowed + .iter() + .map(|status| u64::from(status.code())) + .collect(); let status = stable(status); instructions(unit).all(|inst| match inst { SIRInstruction::Store(target, _, _, value, ..) if *target == status => constants diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 5cbcd773323..9abca864a23 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -503,6 +503,185 @@ mod tests { } } + /// Run `source` to `end` in every mode and compare the state files with + /// the reference's; at least one slot must run compiled. + fn agrees_with_the_reference(source: &str, end: u64) { + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(end).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(end).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?}"); + let stats = sim.scheduler_stats(); + assert!(stats.compiled_slots > 0, "{mode:?}: {stats:?}"); + } + } + + /// A kernel waiting for a clock edge writes what the domain of that edge + /// samples, blocking and nonblocking. + #[test] + fn clock_kernels_run_in_compiled_slots() { + for assign in ["=", "<="] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] sum); + logic clk = 1'b0; + logic [7:0] stim = 8'd0; + logic [7:0] r = 8'd0; + always #5 clk = ~clk; + initial forever @(posedge clk) stim {assign} stim + 8'd3; + always_ff @(posedge clk) r <= r + stim; + assign sum = r; + endmodule" + ); + agrees_with_the_reference(&source, 1000); + } + } + + /// Kernels woken in the middle of a pass, declared before and after the + /// clock kernels, and waits for falling and any edges. + #[test] + fn clock_kernels_wake_in_the_reference_order() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] seen); + logic a = 1'b0; + logic b = 1'b0; + logic [7:0] log = 8'd0; + logic [7:0] acc = 8'd0; + initial forever @(posedge a) log = log * 8'd3 + 8'd1; + always #5 a = ~a; + initial forever @(negedge a) log = log * 8'd5 + 8'd2; + always #5 b = ~b; + initial forever @(b) log = log * 8'd7 + 8'd3; + initial forever @(posedge b) acc <= acc + log; + assign seen = log + acc; + endmodule + "#; + agrees_with_the_reference(source, 200); + } + + /// A clock kernel's `$finish` ends a compiled slot as the reference's. + #[test] + fn clock_kernels_finish_compiled_slots() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] n); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin + n = 8'd0; + forever @(posedge clk) begin + n = n + 8'd1; + if (n == 8'd7) $finish; + end + end + endmodule + "#; + agrees_with_the_reference(source, 1000); + } + + /// Compiled kernels declared after more than 64 others keep their own + /// bits in the ready mask. + #[test] + fn compiled_kernels_after_many_processes() { + let mut source = String::from( + "`timescale 1ns/1ns\nmodule Top(output logic [7:0] n);\nlogic clk = 1'b0;\n", + ); + for index in 0..66 { + source.push_str(&format!( + "logic d{index} = 1'b0;\ninitial #0 d{index} = 1'b1;\n" + )); + } + source.push_str( + "always #5 clk = ~clk;\n\ + initial begin n = 8'd0; forever @(posedge clk) n = n + 8'd1; end\n\ + endmodule\n", + ); + agrees_with_the_reference(&source, 200); + } + + /// A kernel that waits and then loops without suspending yields now and + /// then, and keeps the reference loop. + #[test] + fn waiting_kernels_that_yield_fall_back() { + let reasons = |source: &str| -> Vec { + build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels + .into_iter() + .filter_map(|kernel| match kernel { + crate::KernelSchedule::Reference(reason) => Some(reason), + crate::KernelSchedule::Compiled => None, + }) + .collect() + }; + // A loop that does not suspend yields now and then. + let spinning = r#" + `timescale 1ns/1ns + module Top(output logic q); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin q = 1'b0; @(posedge clk); forever q <= ~q; end + endmodule + "#; + assert_eq!( + reasons(spinning), + ["the process suspends other than for one edge"] + ); + } + + /// A nonblocking site in a loop runs several times in one run of its + /// kernel. A loop the frontend keeps yields now and then, and the + /// copies of one it unrolls queue their values: either way the kernel + /// keeps the reference loop, and every mode leaves its state. + #[test] + fn nonblocking_sites_in_loops_keep_the_reference_loop() { + for (bound, reason) in [ + ("n", "the process suspends other than for one edge"), + ("2", "a nonblocking site queues its values"), + ] { + for tail in ["", "$finish;"] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] q); + logic clk = 1'b0; + int n = 2; + always #5 clk = ~clk; + initial begin + q = 8'd0; + forever begin + @(posedge clk); + for (int i = 0; i < {bound}; i++) q <= q + 8'(i) + 8'd1; + {tail} + end + end + endmodule" + ); + let kernels = build_in(&source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!( + kernels.contains(&crate::KernelSchedule::Reference(reason.into())), + "{bound} {tail}: {kernels:?}" + ); + let mut reference = build_in(&source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(&source, mode); + sim.run_until(100).unwrap(); + assert_eq!( + sim.save_state().unwrap(), + expected, + "{bound} {tail} {mode:?}" + ); + } + } + } + } + #[test] fn differential_mode_reports_a_diverging_step() { let mut sim = build(SchedulerMode::Differential);