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