diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 90b0f717afb..c5056045cb6 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1059,6 +1059,7 @@ impl HiddenObjects<'_> { }, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![width], source: None, module_affiliated: false, @@ -1817,6 +1818,7 @@ pub fn lower_frontend_artifact( type_kind, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![signal.value_type().width()], source: None, module_affiliated: true, diff --git a/crates/celox-frontend-core/src/shared/lookup.rs b/crates/celox-frontend-core/src/shared/lookup.rs index d8faf9d8542..71b1b6cf661 100644 --- a/crates/celox-frontend-core/src/shared/lookup.rs +++ b/crates/celox-frontend-core/src/shared/lookup.rs @@ -66,6 +66,8 @@ pub struct VariableInfo { /// arrays because that is the source-independent storage shape. The /// testbench adapter also needs packed shape for chained selects. pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, } impl std::ops::Deref for VariableInfo { diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 57723894725..d51a615090d 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -22,6 +22,8 @@ pub struct SymbolicVariable { pub signed: bool, pub metadata: VariableMetadata, pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, pub source: Option, pub module_affiliated: bool, } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 487b7e05f77..a52ea6fbb21 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1690,6 +1690,7 @@ fn module_variables( var_kind: variable.kind, signed: variable.signed, packed_dims: variable.packed_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), metadata: variable.metadata.clone(), }, ); diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 3d9b80a809e..ce6ca4bf68e 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -476,6 +476,7 @@ pub fn declare_counter_slots( type_kind: PortTypeKind::Bit, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![EVENT_COUNTER_WIDTH], source: None, module_affiliated: false, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d9bc370afc4..a5a99218b23 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -68,6 +68,7 @@ struct SvVariable { is_4state: bool, packed_ranges: Vec<(i128, i128)>, array_dims: Vec, + unpacked_ranges: Vec<(i128, i128)>, domain_kind: DomainKind, kind: VariableKind, type_kind: PortTypeKind, @@ -91,6 +92,7 @@ impl SvVariable { type_kind: self.type_kind, array_dims: self.array_dims.clone(), }, + unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self .packed_ranges .iter() @@ -1443,6 +1445,7 @@ fn prepare_external_hierarchy_collecting( .map(|&width| ((width - 1) as i128, 0)) .collect(), array_dims: variable.metadata.array_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), domain_kind: variable.metadata.kind, kind: variable.kind, type_kind: variable.metadata.type_kind, @@ -2420,6 +2423,7 @@ fn lower_module_with_overrides( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind, type_kind: type_info.type_kind, @@ -2500,6 +2504,7 @@ fn lower_module_with_overrides( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: type_info.type_kind, @@ -2572,6 +2577,7 @@ fn lower_module_with_overrides( is_4state: true, packed_ranges: vec![(width as i128 - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Parameter, type_kind: PortTypeKind::Logic, @@ -3607,6 +3613,7 @@ fn lower_initial_processes( is_4state: false, packed_ranges: vec![(width as i128 - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: PortTypeKind::Bit, @@ -3956,6 +3963,7 @@ fn ensure_parent_output_signals( is_4state: true, packed_ranges: Vec::new(), array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: PortTypeKind::Logic, @@ -5151,6 +5159,7 @@ struct SvSignalType { is_4state: bool, packed_ranges: Vec<(i128, i128)>, array_dims: Vec, + unpacked_ranges: Vec<(i128, i128)>, type_kind: PortTypeKind, } @@ -5214,6 +5223,11 @@ fn signal_type_from_sv( .ok_or_else(|| { sv::AnalyzerError::Unsupported("unresolved unpacked array dimension".to_string()) })?; + let unpacked_ranges = typ + .unpacked_ranges() + .iter() + .filter_map(|range| unpacked_range_bounds(range, constants, parameter_types)) + .collect(); let element_count = array_dims .iter() .copied() @@ -5253,6 +5267,7 @@ fn signal_type_from_sv( is_4state, packed_ranges, array_dims, + unpacked_ranges, type_kind, }) } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 4ea8560a97d..8960d107d1a 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -565,6 +565,7 @@ impl<'a> ProcModule<'a> { is_4state, packed_ranges: vec![(i128::try_from(width.max(1)).unwrap_or(1) - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: if is_4state { @@ -631,6 +632,7 @@ impl<'a> ProcModule<'a> { is_4state: source.is_4state, packed_ranges: vec![(0, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: kind, kind: VariableKind::Variable, type_kind: source.type_kind, @@ -1033,6 +1035,7 @@ pub(super) fn register_locals( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: type_info.type_kind, diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index b0a0ce5fea2..572c817eb7a 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -446,6 +446,7 @@ pub(crate) fn project_module_with_ids( .collect(), }, packed_dims, + unpacked_ranges: Vec::new(), source: Some(celox_frontend_core::SourceLocation { path: variable.token.beg.source.to_string(), text: source_texts diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 1c008f4e210..097a8059a4a 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -3821,6 +3821,7 @@ mod tests { path: path.clone(), var_kind: VariableKind::Variable, signed: false, + unpacked_ranges: Vec::new(), packed_dims: vec![8], metadata: VariableMetadata { width: 8, diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 20f1aea095c..fa03abdd57a 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -179,7 +179,7 @@ pub trait SimBackend { if let Some(trace) = self.layout().trace.as_ref() { let len = signal.array_layout.map_or_else( || celox_state_layout::get_byte_size(signal.width), - |array| array.plane_size, + |array| array.element_count * array.element_stride, ); let (ptr, _) = self.memory_as_ptr(); // SAFETY: layout homes and metadata fit in the writable state image. diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index 1ea8cfb1cf1..6b16ec8999c 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -44,6 +44,7 @@ pub struct ReflectionSignal { pub signed: bool, pub packed_dims: Vec, pub unpacked_dims: Vec, + pub unpacked_ranges: Vec<(i128, i128)>, pub type_kind: PortTypeKind, } @@ -127,6 +128,20 @@ impl DesignReflection { signal.full_name )); } + if signal.unpacked_dims.len() != signal.unpacked_ranges.len() + || signal + .unpacked_dims + .iter() + .zip(&signal.unpacked_ranges) + .any(|(&size, &(left, right))| { + size == 0 || left.abs_diff(right).checked_add(1) != Some(size as u128) + }) + { + return Err(format!( + "signal `{}` has invalid unpacked bounds", + signal.full_name + )); + } if index > 0 && self.signals[index - 1].full_name >= signal.full_name { return Err("reflection signals are not uniquely name-sorted".into()); } diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index 0088f8a35a7..cf97ddd89e4 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -94,7 +94,7 @@ pub(super) struct VlogStorage { arg_ptrs: Vec<*mut c_char>, } -fn callback_signal(data: &VpiCbData) -> Option { +fn callback_signal(data: &VpiCbData) -> Option { if data.reason != CB_VALUE_CHANGE { return None; } @@ -626,8 +626,16 @@ pub unsafe extern "C" fn vpi_chk_error(_info: *mut VpiErrorInfo) -> i32 { /// # Safety /// /// A non-null `reference` must be a live handle returned by this library. -pub unsafe extern "C" fn vpi_handle_by_index(_reference: VpiHandle, _index: i32) -> VpiHandle { - ptr::null_mut() +pub unsafe extern "C" fn vpi_handle_by_index(reference: VpiHandle, index: i32) -> VpiHandle { + // Safety: forwarded from the caller under the VPI handle contract. + let Some(ObjectRef::Signal(selection)) = (unsafe { object_ref(reference) }) else { + return ptr::null_mut(); + }; + super::with_runtime(|runtime| selection.select(runtime, index)) + .flatten() + .map_or(ptr::null_mut(), |selection| { + super::new_object_handle(ObjectRef::Signal(selection)) + }) } #[unsafe(no_mangle)] diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index b35a0804a69..c2453493604 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -56,6 +56,7 @@ pub const VPI_BINARY_CONST: i32 = 3; pub const VPI_NET: i32 = 36; pub const VPI_PORT: i32 = 44; pub const VPI_REG: i32 = 48; +pub const VPI_REG_ARRAY: i32 = 116; pub const VPI_LEFT_RANGE: i32 = 79; pub const VPI_PARENT: i32 = 81; pub const VPI_RIGHT_RANGE: i32 = 83; @@ -113,10 +114,206 @@ pub struct VpiValue { pub value: VpiValueData, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct VpiSignalIdentity { + storage: NativeSignalIdentity, + slice: Option<(usize, usize)>, +} + +/// A lazy view of an unpacked array. Storage grows with requested handles, +/// rather than with the number of elements in reflected memories. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SignalSelection { + root: ReflectionSignalId, + first: usize, + depth: usize, +} + +impl SignalSelection { + fn root(root: ReflectionSignalId) -> Self { + Self { + root, + first: 0, + depth: 0, + } + } + + fn resolve(self, runtime: &NativeProgramInstance) -> Option { + let mut signal = runtime.reflection().signal(self.root)?.clone(); + if self.depth == 0 { + return Some(signal); + } + let count = signal.unpacked_dims.iter().product::(); + let element_width = signal.signal.width / count; + let remaining = signal + .unpacked_dims + .get(self.depth..)? + .iter() + .product::(); + if self.first.checked_add(remaining)? > count { + return None; + } + let mut stride = count; + for (&size, &(left, right)) in signal + .unpacked_dims + .iter() + .zip(&signal.unpacked_ranges) + .take(self.depth) + { + stride /= size; + let position = (self.first / stride) % size; + let index = if left <= right { + left + position as i128 + } else { + left - position as i128 + }; + let suffix = format!("[{index}]"); + signal.name.push_str(&suffix); + signal.full_name.push_str(&suffix); + } + if let Some(mut array) = signal.signal.array_layout { + signal.signal.offset = signal + .signal + .offset + .checked_add(self.first.checked_mul(array.element_stride)?)?; + signal.signal.width = remaining.checked_mul(element_width)?; + array.element_count = remaining; + signal.signal.array_layout = Some(array); + } + signal.unpacked_dims.drain(..self.depth); + signal.unpacked_ranges.drain(..self.depth); + signal.domain_kind = DomainKind::Other; + Some(signal) + } + + fn select(self, runtime: &NativeProgramInstance, index: i32) -> Option { + let root = runtime.reflection().signal(self.root)?; + let &(left, right) = root.unpacked_ranges.get(self.depth)?; + let index = i128::from(index); + if index < left.min(right) || index > left.max(right) { + return None; + } + let position = usize::try_from(if left <= right { + index - left + } else { + left - index + }) + .ok()?; + let stride = root + .unpacked_dims + .get(self.depth + 1..)? + .iter() + .product::(); + Some(Self { + root: self.root, + first: self.first.checked_add(position.checked_mul(stride)?)?, + depth: self.depth + 1, + }) + } + + // Some arrays use contiguous bits instead of a byte stride (including + // scalar arrays and arrays whose uses cannot be lowered as strided loads). + fn slice(self, runtime: &NativeProgramInstance) -> Option<(usize, usize)> { + let root = runtime.reflection().signal(self.root)?; + if self.depth == 0 || root.signal.array_layout.is_some() { + return None; + } + let element_width = root.signal.width / root.unpacked_dims.iter().product::(); + let remaining = root + .unpacked_dims + .get(self.depth..)? + .iter() + .product::(); + Some((self.first * element_width, remaining * element_width)) + } + + fn width(self, runtime: &NativeProgramInstance) -> Option { + Some( + self.slice(runtime) + .map_or(self.resolve(runtime)?.signal.width, |(_, width)| width), + ) + } + + fn identity(self, runtime: &NativeProgramInstance) -> Option { + let storage = if self.depth == 0 || self.slice(runtime).is_some() { + runtime.signal_identity(self.root)? + } else { + NativeSignalIdentity::State(self.resolve(runtime)?.signal) + }; + Some(VpiSignalIdentity { + storage, + slice: self.slice(runtime), + }) + } + + fn read(self, runtime: &NativeProgramInstance) -> Option<(BigUint, BigUint)> { + let signal = self.resolve(runtime)?.signal; + let Some((offset, width)) = self.slice(runtime) else { + return Some(runtime.backend().get_four_state(signal)); + }; + let (window, shift) = bit_window(signal, offset, width); + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + let bits = (runtime.backend().get_four_state(window).0 >> shift) & &mask; + let unknowns = if signal.is_4state && runtime.four_state() { + let mut mask_window = window; + mask_window.offset += signal.width.div_ceil(8); + (runtime.backend().get_four_state(mask_window).0 >> shift) & mask + } else { + BigUint::default() + }; + Some((bits, unknowns)) + } + + fn write(self, runtime: &mut NativeProgramInstance, bits: BigUint, mask: BigUint) { + let Some(signal) = self.resolve(runtime).map(|signal| signal.signal) else { + return; + }; + let Some((offset, width)) = self.slice(runtime) else { + runtime.backend_mut().set_four_state(signal, bits, mask); + return; + }; + let (window, shift) = bit_window(signal, offset, width); + let selected = ((BigUint::from(1u8) << width) - BigUint::from(1u8)) << shift; + let whole = (BigUint::from(1u8) << window.width) - BigUint::from(1u8); + let retained = &whole ^ &selected; + let old = runtime.backend().get_four_state(window).0; + runtime.backend_mut().set_four_state( + window, + (old & &retained) | ((bits << shift) & &selected), + BigUint::default(), + ); + if signal.is_4state && runtime.four_state() { + let mut mask_window = window; + mask_window.offset += signal.width.div_ceil(8); + let old = runtime.backend().get_four_state(mask_window).0; + runtime.backend_mut().set_four_state( + mask_window, + (old & retained) | ((mask << shift) & selected), + BigUint::default(), + ); + } + } +} + +/// Small byte-aligned window around a logical bit slice. Preserve the boundary +/// bits on writes; even a huge bit-packed RAM needs only the selected bytes. +fn bit_window(signal: celox::SignalRef, offset: usize, width: usize) -> (celox::SignalRef, usize) { + let shift = offset % 8; + ( + celox::SignalRef { + offset: signal.offset + offset / 8, + width: (shift + width).div_ceil(8) * 8, + is_4state: false, + array_layout: None, + }, + shift, + ) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ObjectRef { Scope(ReflectionScopeId), - Signal(ReflectionSignalId), + Signal(SignalSelection), } #[derive(Debug)] @@ -146,7 +343,7 @@ pub type VpiHandle = *mut VpiHandleObject; #[derive(Default)] struct VpiHost { runtime: RefCell>, - forced_values: RefCell>, + forced_values: RefCell>, pending_writes: RefCell, callbacks: RefCell, vlog: RefCell>, @@ -282,21 +479,21 @@ struct ForcedValue { #[derive(Default)] struct PendingWrites { - deposits: HashMap, + deposits: HashMap, edge_batches: Vec, open_edge_batch: Option, settle: bool, } struct PendingEdgeBatch { - active_signals: Vec, - transition_signals: Vec, - deposits: HashMap, + active_signals: Vec, + transition_signals: Vec, + deposits: HashMap, } #[derive(Clone)] struct PendingDeposit { - id: ReflectionSignalId, + id: SignalSelection, value: BigUint, mask: BigUint, } @@ -340,8 +537,8 @@ fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { fn record_pending_write( pending: &mut PendingWrites, - id: ReflectionSignalId, - identity: NativeSignalIdentity, + id: SignalSelection, + identity: VpiSignalIdentity, value: BigUint, mask: BigUint, domain_kind: DomainKind, @@ -389,19 +586,12 @@ fn record_pending_write( fn apply_pending_deposits( runtime: &mut NativeProgramInstance, - deposits: &HashMap, + deposits: &HashMap, ) { - let writes = deposits - .values() - .filter_map(|deposit| { - runtime - .reflection() - .signal(deposit.id) - .map(|signal| (signal.signal, deposit.value.clone(), deposit.mask.clone())) - }) - .collect::>(); - for (signal, value, mask) in writes { - runtime.backend_mut().set_four_state(signal, value, mask); + for deposit in deposits.values() { + deposit + .id + .write(runtime, deposit.value.clone(), deposit.mask.clone()); } } @@ -527,9 +717,8 @@ fn new_object_handle(object: ObjectRef) -> VpiHandle { .reflection() .scope(id) .map(|scope| (scope.name.clone(), scope.full_name.clone())), - ObjectRef::Signal(id) => runtime - .reflection() - .signal(id) + ObjectRef::Signal(id) => id + .resolve(runtime) .map(|signal| (signal.name.clone(), signal.full_name.clone())), }) .flatten() @@ -596,16 +785,28 @@ unsafe fn object_ref(handle: VpiHandle) -> Option { fn object_by_full_name(name: &str) -> Option { with_runtime(|runtime| { - runtime - .reflection() - .scope_by_name(name) - .map(|(id, _)| ObjectRef::Scope(id)) - .or_else(|| { - runtime - .reflection() - .signal_by_name(name) - .map(|(id, _)| ObjectRef::Signal(id)) - }) + let reflection = runtime.reflection(); + if let Some((id, _)) = reflection.scope_by_name(name) { + return Some(ObjectRef::Scope(id)); + } + if let Some((id, _)) = reflection.signal_by_name(name) { + return Some(ObjectRef::Signal(SignalSelection::root(id))); + } + let mut prefix = name; + let mut indices = Vec::new(); + while let Some(end) = prefix.strip_suffix(']') { + let (base, index) = end.rsplit_once('[')?; + indices.push(index.parse::().ok()?); + prefix = base; + if let Some((id, _)) = reflection.signal_by_name(prefix) { + let mut selection = SignalSelection::root(id); + for index in indices.iter().rev() { + selection = selection.select(runtime, *index)?; + } + return Some(ObjectRef::Signal(selection)); + } + } + None }) .flatten() } @@ -658,20 +859,22 @@ pub unsafe extern "C" fn vpi_handle(kind: i32, reference: VpiHandle) -> VpiHandl let Some(ObjectRef::Signal(id)) = (unsafe { object_ref(reference) }) else { return ptr::null_mut(); }; - let width = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| signal.signal.width) + let bounds = with_runtime(|runtime| { + let signal = id.resolve(runtime)?; + Some( + signal + .unpacked_ranges + .first() + .copied() + .unwrap_or((id.width(runtime)?.saturating_sub(1) as i128, 0)), + ) }) .flatten(); - return match (kind, width) { - (VPI_LEFT_RANGE, Some(width)) => { - new_constant_handle(i32::try_from(width.saturating_sub(1)).unwrap_or(i32::MAX)) - } - (VPI_RIGHT_RANGE, Some(_)) => new_constant_handle(0), - _ => ptr::null_mut(), - }; + return bounds + .and_then(|(left, right)| { + i32::try_from(if kind == VPI_LEFT_RANGE { left } else { right }).ok() + }) + .map_or(ptr::null_mut(), new_constant_handle); } // Safety: reference follows the VPI handle contract. let Some(object) = (unsafe { object_ref(reference) }) else { @@ -686,10 +889,15 @@ pub unsafe extern "C" fn vpi_handle(kind: i32, reference: VpiHandle) -> VpiHandl .scope(id) .and_then(|scope| scope.parent) .map(ObjectRef::Scope), - ObjectRef::Signal(id) => runtime - .reflection() - .signal(id) - .map(|signal| ObjectRef::Scope(signal.parent)), + ObjectRef::Signal(id) => { + if kind == VPI_PARENT { + // IEEE 1800-2023 37.17: largest containing unpacked array. + (id.depth != 0).then(|| ObjectRef::Signal(SignalSelection::root(id.root))) + } else { + id.resolve(runtime) + .map(|signal| ObjectRef::Scope(signal.parent)) + } + } }) .flatten(); parent.map_or(ptr::null_mut(), new_object_handle) @@ -727,7 +935,7 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand }) .unwrap_or_default(), ( - VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, + VPI_PORT | VPI_REG | VPI_REG_ARRAY | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, Some(ObjectRef::Scope(id)), ) => reflection .scope(id) @@ -743,13 +951,14 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand } match kind { VPI_PORT => signal.direction != SignalDirection::Internal, - VPI_REG => true, + VPI_REG => signal.unpacked_dims.is_empty(), + VPI_REG_ARRAY => !signal.unpacked_dims.is_empty(), VPI_VARIABLES => signal.direction == SignalDirection::Internal, VPI_NET => false, _ => false, } }) - .map(ObjectRef::Signal) + .map(|id| ObjectRef::Signal(SignalSelection::root(id))) .collect() }) .unwrap_or_default(), @@ -792,17 +1001,18 @@ fn object_type(object: ObjectRef) -> i32 { match object { ObjectRef::Scope(_) => VPI_MODULE, ObjectRef::Signal(id) => with_runtime(|runtime| { - if runtime - .reflection() - .signal(id) - .is_some_and(|signal| signal.is_parameter) - { + let Some(signal) = id.resolve(runtime) else { + return 0; + }; + if !signal.unpacked_dims.is_empty() { + VPI_REG_ARRAY + } else if signal.is_parameter { VPI_PARAMETER } else { VPI_REG } }) - .unwrap_or(VPI_REG), + .unwrap_or(0), } } @@ -841,7 +1051,7 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { let scope = match object { ObjectRef::Scope(id) => reflection.scope(id), ObjectRef::Signal(id) => reflection - .signal(id) + .signal(id.root) .and_then(|signal| reflection.scope(signal.parent)), }; scope.map_or(0, |scope| { @@ -867,13 +1077,28 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { let ObjectRef::Signal(id) = object else { return 0; }; - let Some(signal) = runtime.reflection().signal(id) else { + let Some(signal) = id.resolve(runtime) else { return 0; }; match property { - VPI_SIZE => i32::try_from(signal.signal.width).unwrap_or(i32::MAX), - VPI_SCALAR => i32::from(signal.signal.width == 1), - VPI_VECTOR => i32::from(signal.signal.width != 1), + VPI_SIZE => i32::try_from( + signal + .unpacked_dims + .first() + .copied() + .unwrap_or(id.width(runtime).unwrap_or(0)), + ) + .unwrap_or(i32::MAX), + VPI_SCALAR => i32::from( + id.width(runtime).unwrap_or(0) + / signal.unpacked_dims.iter().product::() + == 1, + ), + VPI_VECTOR => i32::from( + id.width(runtime).unwrap_or(0) + / signal.unpacked_dims.iter().product::() + != 1, + ), VPI_SIGNED => i32::from(signal.signed), VPI_DIRECTION => match signal.direction { SignalDirection::Input => VPI_INPUT, @@ -926,6 +1151,7 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu HandleKind::Object(object) => match object_type(object) { VPI_MODULE => c"vpiModule".as_ptr().cast_mut(), VPI_REG => c"vpiReg".as_ptr().cast_mut(), + VPI_REG_ARRAY => c"vpiRegArray".as_ptr().cast_mut(), _ => ptr::null_mut(), }, HandleKind::Constant(_) => c"vpiConstant".as_ptr().cast_mut(), @@ -936,23 +1162,25 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu } } -fn value_bits(id: ReflectionSignalId) -> Option<(BigUint, BigUint, usize)> { - let (identity, width) = with_runtime(|runtime| { - Some(( - runtime.signal_identity(id)?, - runtime.reflection().signal(id)?.signal.width, - )) +fn value_bits(id: SignalSelection) -> Option<(BigUint, BigUint, usize)> { + if !with_runtime(|runtime| { + id.resolve(runtime) + .is_some_and(|signal| signal.unpacked_dims.is_empty()) }) - .flatten()?; + .unwrap_or(false) + { + return None; + } + let (identity, width) = + with_runtime(|runtime| Some((id.identity(runtime)?, id.width(runtime)?))).flatten()?; if let Some(forced) = with_host(|host| borrow_cell(&host.forced_values, |forced| forced.get(&identity).cloned())) { return Some((forced.value, forced.mask, width)); } with_runtime(|runtime| { - let signal = runtime.reflection().signal(id)?; - let (value, mask) = runtime.backend().get_four_state(signal.signal); - Some((value, mask, signal.signal.width)) + let (value, mask) = id.read(runtime)?; + Some((value, mask, id.width(runtime)?)) }) .flatten() } @@ -1062,10 +1290,8 @@ unsafe fn write_snapshot_value( return; }; let metadata = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| (signal.signal.width, signal.signed)) + id.resolve(runtime) + .and_then(|signal| Some((id.width(runtime)?, signal.signed))) }) .flatten(); let Some((width, signed)) = metadata else { @@ -1104,10 +1330,9 @@ pub unsafe extern "C" fn vpi_get_value(reference: VpiHandle, value: *mut VpiValu let Some((bits, mask, width)) = value_bits(id) else { return; }; - let signed = - with_runtime(|runtime| runtime.reflection().signal(id).map(|signal| signal.signed)) - .flatten() - .unwrap_or(false); + let signed = with_runtime(|runtime| id.resolve(runtime).map(|signal| signal.signed)) + .flatten() + .unwrap_or(false); // Safety: checked non-null above; caller owns the `VpiValue` allocation. encode_signal_value(handle, unsafe { &mut *value }, &bits, &mask, width, signed); } @@ -1246,16 +1471,23 @@ pub unsafe extern "C" fn vpi_put_value( return ptr::null_mut(); }; if with_runtime(|runtime| { - runtime - .reflection() - .signal(id) + id.resolve(runtime) .is_some_and(|signal| signal.is_parameter) }) .unwrap_or(false) { return ptr::null_mut(); } - let identity = with_runtime(|runtime| runtime.signal_identity(id)).flatten(); + if !with_runtime(|runtime| { + id.resolve(runtime) + .is_some_and(|signal| signal.unpacked_dims.is_empty()) + }) + .unwrap_or(false) + || (id.depth != 0 && matches!(flags, VPI_FORCE_FLAG | VPI_RELEASE_FLAG)) + { + return ptr::null_mut(); + } + let identity = with_runtime(|runtime| id.identity(runtime)).flatten(); let Some(identity) = identity else { return ptr::null_mut(); }; @@ -1265,7 +1497,7 @@ pub unsafe extern "C" fn vpi_put_value( }); let succeeded = released.is_none_or(|released| { with_runtime_mut(|runtime| { - let Some(signal) = runtime.reflection().signal(id).cloned() else { + let Some(signal) = id.resolve(runtime) else { return false; }; let (released_value, released_mask) = if matches!( @@ -1279,7 +1511,7 @@ pub unsafe extern "C" fn vpi_put_value( } else { (released.deposited_value, released.deposited_mask) }; - runtime.release_signal(id); + runtime.release_signal(id.root); let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); let old_level = logic_level(&old_value, &old_mask); let new_level = logic_level(&released_value, &released_mask); @@ -1312,11 +1544,11 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - runtime.reflection().signal(id).map(|signal| { - ( - signal.signal.width, + id.resolve(runtime).and_then(|signal| { + Some(( + id.width(runtime)?, signal.signal.is_4state && runtime.four_state(), - ) + )) }) }) .flatten(); @@ -1353,7 +1585,7 @@ pub unsafe extern "C" fn vpi_put_value( }) .or_else(|| { with_runtime(|runtime| { - let signal = runtime.reflection().signal(id)?; + let signal = id.resolve(runtime)?; Some(runtime.backend().get_four_state(signal.signal)) }) .flatten() @@ -1376,20 +1608,20 @@ pub unsafe extern "C" fn vpi_put_value( None }; let succeeded = with_runtime_mut(|runtime| { - let Some(signal) = runtime.reflection().signal(id).cloned() else { + let Some(signal) = id.resolve(runtime) else { + return false; + }; + let Some((old_value, old_mask)) = id.read(runtime) else { return false; }; - let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); let old_level = logic_level(&old_value, &old_mask); let new_level = logic_level(&bits, &mask); if flags == VPI_FORCE_FLAG { - if !runtime.force_signal(id, bits.clone(), mask.clone()) { + if !runtime.force_signal(id.root, bits.clone(), mask.clone()) { return false; } } else { - runtime - .backend_mut() - .set_four_state(signal.signal, bits.clone(), mask.clone()); + id.write(runtime, bits.clone(), mask.clone()); } with_host(|host| { borrow_cell_mut(&host.pending_writes, |pending| { @@ -1439,7 +1671,7 @@ fn flush_pending_writes() -> bool { return true; } let mut final_deposits = pending.deposits; - let mut replay_overrides: HashMap = HashMap::default(); + let mut replay_overrides: HashMap = HashMap::default(); for mut batch in pending.edge_batches { for (id, value) in &replay_overrides { batch.deposits.insert(*id, value.clone()); @@ -1453,7 +1685,7 @@ fn flush_pending_writes() -> bool { .into_iter() .filter_map(|identity| { let deposit = batch.deposits.get(&identity)?; - let signal = runtime.reflection().signal(deposit.id)?; + let signal = deposit.id.resolve(runtime)?; if overridden.contains(&identity) { let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index b0dd703a978..97d8035e9b8 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3154,3 +3154,123 @@ fn two_state_image_converts_unknown_logic_deposits_and_forces() { } clear_runtime(); } + +#[cfg(feature = "systemverilog")] +#[test] +fn unpacked_array_handles_preserve_declared_indices_and_neighbor_values() { + let _serial = lock_vpi(); + let source = r#"module Top( + input logic [7:0] words [3:2][-1:1], + output logic [7:0] first, middle, last + ); + assign first=words[3][-1]; + assign middle=words[2][0]; + assign last=words[2][1]; + endmodule"#; + for (four_state, width) in [false, true] + .into_iter() + .flat_map(|four| [1, 8, 9, 65].map(|width| (four, width))) + { + let source = source.replace("[7:0]", &format!("[{}:0]", width - 1)); + let simulator = Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("arrays.sv"))], + "Top", + ) + .four_state(four_state) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let bytes = simulator + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let runtime = unsafe { NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap(); + let metadata = runtime.signal("Top.words").unwrap(); + assert_eq!(metadata.unpacked_ranges, [(3, 2), (-1, 1)]); + assert_eq!(runtime.reflection().signals().len(), 4); + let _session = install_runtime(runtime).unwrap(); + unsafe { + let array = vpi_handle_by_name(c"Top.words".as_ptr(), ptr::null_mut()); + assert_eq!(vpi_get(VPI_TYPE, array), VPI_REG_ARRAY); + assert_eq!(vpi_get(VPI_SIZE, array), 2); + assert!(vpi_handle_by_index(array, 1).is_null()); + for (kind, expected) in [(VPI_LEFT_RANGE, 3), (VPI_RIGHT_RANGE, 2)] { + let bound = vpi_handle(kind, array); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(bound, &mut value); + assert_eq!(value.value.integer, expected); + vpi_free_object(bound); + } + let row = vpi_handle_by_index(array, 2); + assert_eq!(vpi_get(VPI_SIZE, row), 3); + assert!(vpi_handle_by_index(row, -2).is_null()); + let middle = vpi_handle_by_index(row, 0); + let last = vpi_handle_by_index(row, 1); + let first = vpi_handle_by_name(c"Top.words[3][-1]".as_ptr(), ptr::null_mut()); + assert!(!first.is_null()); + assert_eq!(vpi_get(VPI_TYPE, middle), VPI_REG); + assert_eq!(vpi_get(VPI_SIZE, middle), width as i32); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, middle)), + c"Top.words[2][0]" + ); + let parent = vpi_handle(VPI_PARENT, middle); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, parent)), + c"Top.words" + ); + assert!(vpi_handle(VPI_PARENT, array).is_null()); + let val = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0xa5 }, + }; + assert!(!vpi_put_value(first, &val, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(!vpi_put_value(last, &val, ptr::null(), VPI_NO_DELAY).is_null()); + let xz = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { + str_: if width == 1 { c"x" } else { c"10xz0101" } + .as_ptr() + .cast_mut(), + }, + }; + assert!(!vpi_put_value(middle, &xz, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(vpi_put_value(array, &val, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(vpi_put_value(middle, &val, ptr::null(), VPI_FORCE_FLAG).is_null()); + for (name, expected) in [ + (c"Top.first", if width == 1 { "1" } else { "10100101" }), + (c"Top.last", if width == 1 { "1" } else { "10100101" }), + ( + c"Top.middle", + match (four_state, width) { + (true, 1) => "x", + (false, 1) => "0", + (true, _) => "10xz0101", + (false, _) => "10000101", + }, + ), + ] { + let output = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + let mut value = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(output, &mut value); + assert_eq!( + CStr::from_ptr(value.value.str_).to_str().unwrap(), + format!("{expected:0>width$}"), + "{name:?}, width={width}" + ); + vpi_free_object(output); + } + for handle in [array, row, middle, last, first, parent] { + vpi_free_object(handle); + } + } + clear_runtime(); + } +} diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index 3b4b66860d9..ba7ef9a8ff6 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -143,7 +143,7 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { .arg(&results) .current_dir(&fixture) .env("COCOTB_TESTCASE", "inherited_selector_must_be_cleared") - .env("PYTHONPATH", python_path) + .env("PYTHONPATH", &python_path) .output() .unwrap(); assert!( @@ -530,3 +530,9 @@ fn cocotb_uses_declared_force_targets_in_an_optimized_native_image() { assert!(!xml.contains("> (element * array.element_width)) & &element_mask; let value_bytes = element_value.to_bytes_le(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f0ab19b077a..2aeba1395d7 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 = 20; +const CONTAINER_VERSION: u16 = 21; 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/ir.rs b/crates/celox/src/ir.rs index 00743b70397..718e9675d66 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -54,6 +54,8 @@ pub struct RuntimeVariable { pub var_kind: VariableKind, pub signed: bool, pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, } /// One elaborated runtime instance with direct state-address indices. @@ -153,6 +155,7 @@ impl RuntimeDesign { var_kind: info.var_kind, signed: info.signed, packed_dims: info.packed_dims.clone(), + unpacked_ranges: info.unpacked_ranges.clone(), }, ); } @@ -253,6 +256,7 @@ impl RuntimeDesign { signed: variable.signed, metadata: self.semantic.state_objects.get(address)?.clone(), packed_dims: variable.packed_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), }) } @@ -1049,6 +1053,15 @@ impl RuntimeProgram { }, signed: variable.signed, packed_dims: variable.packed_dims.clone(), + unpacked_ranges: if variable.unpacked_ranges.is_empty() { + metadata + .array_dims + .iter() + .map(|size| (0, *size as i128 - 1)) + .collect() + } else { + variable.unpacked_ranges.clone() + }, unpacked_dims: metadata.array_dims.clone(), type_kind: metadata.type_kind, }); diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 0ea1dda00d7..b8783be3342 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -674,6 +674,25 @@ fn native_program_image_rejects_v16_before_decoding_host_request_schema() { )); } +/// Version 21 retains declared unpacked bounds in runtime and VPI metadata. +#[test] +fn native_program_image_rejects_v20_before_decoding_unpacked_bound_schema() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&20u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(20)) + )); +} + #[test] fn native_program_image_rejects_v3_before_decoding_changed_schema() { let sim = Simulator::builder(ADDER, "Top").build().unwrap();