diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 5dcfc5feaa7..ac966cb01e3 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -60,16 +60,44 @@ impl Ff<'_, '_> { let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?; self.heap_call(ops::OBJECT_STORE, &[object, place, value]) } - ObjectOp::Random | ObjectOp::Check(_) => { + ObjectOp::Random + | ObjectOp::Check(_) + | ObjectOp::ModeGet(..) + | ObjectOp::ModePush + | ObjectOp::ModePop + | ObjectOp::ModeSelected(_) => { let object = self.handle(&args[0])?; self.heap_call( match op { ObjectOp::Check(class) => ops::encode(ops::OBJECT_CHECK, u64::from(*class)), + ObjectOp::ModeGet(offset, random) => ops::encode( + ops::OBJECT_MODE_GET, + u64::from(*offset) | (u64::from(*random) << 32), + ), + ObjectOp::ModePush => ops::OBJECT_MODE_PUSH, + ObjectOp::ModePop => ops::OBJECT_MODE_POP, + ObjectOp::ModeSelected(offset) => { + ops::encode(ops::OBJECT_MODE_SELECTED, u64::from(*offset)) + } _ => ops::OBJECT_RANDOM, }, &[object], ) } + ObjectOp::ModeSet(offset) | ObjectOp::ModeSelect(offset, _) => { + let object = self.handle(&args[0])?; + let enabled = self.integer_of_width(&args[1], 1, false)?; + self.heap_call( + match op { + ObjectOp::ModeSelect(_, random) => ops::encode( + ops::OBJECT_MODE_SELECT, + u64::from(*offset) | (u64::from(*random) << 32), + ), + _ => ops::encode(ops::OBJECT_MODE_SET, u64::from(*offset)), + }, + &[object, enabled], + ) + } ObjectOp::Seed => { let object = self.handle(&args[0])?; let seed = self.integer_of_width(&args[1], 32, false)?; @@ -94,7 +122,13 @@ impl Ff<'_, '_> { | ObjectOp::ClassOf | ObjectOp::Random | ObjectOp::Seed - | ObjectOp::Check(_) => None, + | ObjectOp::Check(_) + | ObjectOp::ModeGet(..) + | ObjectOp::ModePush + | ObjectOp::ModePop + | ObjectOp::ModeSelect(..) + | ObjectOp::ModeSelected(_) + | ObjectOp::ModeSet(_) => None, }; if let Some(kind) = kind { self.m.variables.get_mut(&temp).unwrap().value_kind = kind; diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index b138661edd8..9d708fe87c1 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -293,6 +293,32 @@ mod tests { assert!(!heap.same_contents(&other)); } + #[test] + fn random_modes_restore_nested_scopes_and_participate_in_comparisons() { + let mut heap = Heap::new(); + let object = heap.new_object(1, 16); + assert!(heap.random_mode(object, 0, true)); + assert!(!heap.random_mode(object, 8, false)); + let original = heap.clone(); + heap.set_random_mode(object, 0, false); + assert!(!heap.same_contents(&original)); + let disabled = heap.clone(); + heap.push_random_modes(object); + heap.select_random_mode(object, 0, true, true); + heap.select_random_mode(object, 8, false, true); + assert!(heap.selected_random_mode(object, 8)); + assert!(heap.random_mode(object, 8, false)); + let outer = heap.clone(); + heap.push_random_modes(object); + heap.select_random_mode(object, 8, false, false); + assert!(!heap.selected_random_mode(object, 8)); + assert!(!heap.random_mode(object, 8, false)); + heap.pop_random_modes(object); + assert!(heap.same_contents(&outer)); + heap.pop_random_modes(object); + assert!(heap.same_contents(&disabled)); + } + #[test] fn interning_gives_equal_contents_equal_handles() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 6913e0ccce7..b7d294c8964 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -15,11 +15,20 @@ pub const NULL: Handle = 0; pub(crate) struct Object { class: u32, random_state: u64, + random_modes: RandomModes, + saved_random_modes: Vec, bytes: Box<[u8]>, /// Byte offsets of the handle properties, with what they refer to. pub(crate) handles: Vec<(u32, HandleKind)>, } +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RandomModes { + overrides: fxhash::FxHashMap, + /// Non-rand properties temporarily made random by an argument list. + selected: fxhash::FxHashSet, +} + impl Object { pub(crate) fn size(&self) -> usize { self.bytes.len() @@ -60,6 +69,8 @@ impl Heap { Object { class, random_state: 0, + random_modes: RandomModes::default(), + saved_random_modes: Vec::new(), bytes: vec![0; size].into(), handles: Vec::new(), }, @@ -88,6 +99,56 @@ impl Heap { word ^ (word >> 31) } + /// Random properties start enabled. Modes are shared by aliases of an + /// object and are part of its checkpoint and differential state. + pub fn random_mode(&mut self, handle: Handle, offset: u32, random: bool) -> bool { + self.object_mut(handle).is_some_and(|object| { + object + .random_modes + .overrides + .get(&offset) + .copied() + .unwrap_or(random) + }) + } + + pub fn set_random_mode(&mut self, handle: Handle, offset: u32, enabled: bool) { + if let Some(object) = self.object_mut(handle) { + object.random_modes.overrides.insert(offset, enabled); + } + } + + pub fn push_random_modes(&mut self, handle: Handle) { + if let Some(object) = self.object_mut(handle) { + object.saved_random_modes.push(object.random_modes.clone()); + } + } + + pub fn pop_random_modes(&mut self, handle: Handle) { + if let Some(object) = self.object_mut(handle) { + object.random_modes = object + .saved_random_modes + .pop() + .expect("paired random mode scope"); + } + } + + pub fn select_random_mode(&mut self, handle: Handle, offset: u32, random: bool, enabled: bool) { + if let Some(object) = self.object_mut(handle) { + object.random_modes.overrides.insert(offset, enabled); + if enabled && !random { + object.random_modes.selected.insert(offset); + } else { + object.random_modes.selected.remove(&offset); + } + } + } + + pub fn selected_random_mode(&mut self, handle: Handle, offset: u32) -> bool { + self.object_mut(handle) + .is_some_and(|object| object.random_modes.selected.contains(&offset)) + } + pub(crate) fn check_object(&mut self, handle: Handle, class: u32) -> bool { let Some(object) = self.object_mut(handle) else { return false; diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 705b4e71051..9c38b6a00e0 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -68,6 +68,17 @@ pub const OBJECT_SEED: u64 = 54; /// `check(object)`: record a fault for an invalid receiver or, when the /// parameter is nonzero, a different runtime class. Return 1 on success, 0 on failure. pub const OBJECT_CHECK: u64 = 55; +/// Query the random mode of the property at the parameter's byte offset. +pub const OBJECT_MODE_GET: u64 = 56; +/// Set the random mode at the parameter's byte offset from the low bit of b. +pub const OBJECT_MODE_SET: u64 = 57; +/// Save/restore random modes around an inline member selection. +pub const OBJECT_MODE_PUSH: u64 = 58; +pub const OBJECT_MODE_POP: u64 = 59; +/// Install a selected mode; parameter bit 32 records a declared rand property. +pub const OBJECT_MODE_SELECT: u64 = 60; +/// Whether a non-rand property is temporarily random in the active scope. +pub const OBJECT_MODE_SELECTED: u64 = 61; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -181,6 +192,33 @@ impl Heap { 0 } OBJECT_CHECK => u64::from(self.check_object(a as Handle, parameter as u32)), + OBJECT_MODE_GET => { + u64::from(self.random_mode(a as Handle, parameter as u32, parameter >> 32 != 0)) + } + OBJECT_MODE_SET => { + self.set_random_mode(a as Handle, parameter as u32, b & 1 != 0); + 0 + } + OBJECT_MODE_PUSH => { + self.push_random_modes(a as Handle); + 0 + } + OBJECT_MODE_POP => { + self.pop_random_modes(a as Handle); + 0 + } + OBJECT_MODE_SELECT => { + self.select_random_mode( + a as Handle, + parameter as u32, + parameter >> 32 != 0, + b & 1 != 0, + ); + 0 + } + OBJECT_MODE_SELECTED => { + u64::from(self.selected_random_mode(a as Handle, parameter as u32)) + } other => panic!("unknown heap operation {other}"), } } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index d79431329a3..a44fee5735b 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -22,6 +22,10 @@ pub(super) const THIS: &str = "this"; #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Property { pub name: String, + pub owner: String, + pub constant: bool, + pub local: bool, + pub protected: bool, pub r#type: Type, pub field: ObjectField, pub rand: bool, @@ -93,15 +97,27 @@ pub(super) struct Class { pub has_constraints: bool, } +/// An internal unsigned packed argument of a generated method. +pub(super) fn unsigned_type(width: usize) -> Type { + let mut ty = procedural::int_type(); + ty.is_signed = false; + ty.packed_ranges = vec![PackedRange::new( + ConstExpr::Literal((width - 1).to_string()), + ConstExpr::Literal("0".into()), + )]; + ty +} + impl Class { + pub fn selection_type(&self) -> Type { + unsigned_type(self.properties.len() + 1) + } + /// Validate the supported unconstrained subset before binding a call. pub fn check_randomize(&self, tree: &AnalysisContext<'_>) -> Converted<()> { if self.has_constraints { return Err(unsupported("class randomize with constraints")); } - if self.base.is_some() { - return Err(unsupported("class randomize with inheritance")); - } for property in &self.properties { if property.randc { return Err(unsupported("class randomize with randc properties")); @@ -428,11 +444,16 @@ pub(super) fn class( }); continue; } + let owner = name.to_owned(); let name = property_name; let field = field(&tree.state, &ty, env, size)?; size = field.offset + field.bytes(); properties.push(Property { name, + owner, + constant: property.declaration.constant, + local: property.qualifiers.local, + protected: property.qualifiers.protected, r#type: ty.clone(), field, rand: property.qualifiers.rand, @@ -451,7 +472,7 @@ pub(super) fn class( for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); - if matches!(method_name.as_str(), "randomize" | "srandom") { + if matches!(method_name.as_str(), "randomize" | "srandom" | "rand_mode") { return Err(unsupported( "overriding built-in class randomization methods", )); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 8b8d05203f3..20a1d7b4f05 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -469,7 +469,7 @@ fn class_signatures( context, ); } - for method in ["randomize", "srandom"] { + for method in ["randomize", "srandom", "rand_mode"] { let mut formals = vec![( FunctionArgumentMetadata { name: classes::THIS.into(), @@ -478,16 +478,29 @@ fn class_signatures( }, handle.clone(), )]; - if method == "srandom" { - formals.push(( - FunctionArgumentMetadata { - name: "seed".into(), - direction: ParamDirection::Input, - has_default: false, - }, - procedural::int_type(), - )); - } + let (argument, ty) = match method { + "randomize" => ( + "$selection", + // Signature discovery must not require an otherwise unused class + // to have a supported layout. A call validates the layout before + // using this selection formal; lowering reports layout errors. + classes::class(tree, &class_name, &context.const_env, &context.type_aliases) + .map_or_else( + |_| classes::unsigned_type(1), + |layout| layout.selection_type(), + ), + ), + "srandom" => ("seed", procedural::int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + formals.push(( + FunctionArgumentMetadata { + name: argument.into(), + direction: ParamDirection::Input, + has_default: false, + }, + ty, + )); publish_signature( classes::Class::subroutine_name(&class_name, method), formals, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 0e3c5c64a85..90550ded28a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -17,8 +17,8 @@ pub(super) use lvalues::{net_lvalue, variable_lvalue}; pub(super) use objects::{ Cast as ObjectCast, Receiver as ObjectReceiver, cast as object_cast, check_assignment as check_handle_assignment, constructor as object_constructor, - method as object_method, property as object_property, receiver as object_receiver, - this as object_this, + method as object_method, property as object_property, rand_mode_call as object_rand_mode_call, + receiver as object_receiver, this as object_this, }; pub(super) use strings::{ call as string_call, method as string_method, native_string, to_string as string_operand, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 5927fa59761..9ebd6e1001e 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -240,6 +240,7 @@ enum Finish { name: String, formals: usize, receiver: objects::Receiver, + selection: Option, }, } @@ -265,6 +266,10 @@ pub(in crate::ast) fn bind_value( match job { Job::Enter(id, target, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); + if let Some(call) = objects::rand_mode_call(tree, id, native, dimensions, false)? { + values.push(call); + continue; + } if timescales::is_query(id, native) { values.push(Expr::Literal(parameters::format_typed_parameter_literal( i128::from(timescales::query(id, tree)?), @@ -413,9 +418,16 @@ pub(in crate::ast) fn bind_value( let (name, formals, receiver) = objects::method(tree, *expression, native, dimensions)? .expect("checked by the guard"); - if args.len() > formals - || (name.ends_with("::srandom") && args.len() != 1) - || args.iter().any(|arg| arg.name.is_some()) + let selection = name + .ends_with("::randomize") + .then(|| { + objects::random_selection(tree, dimensions, &name, args, native) + }) + .transpose()?; + if selection.is_none() + && (args.len() > formals + || (name.ends_with("::srandom") && args.len() != 1) + || args.iter().any(|arg| arg.name.is_some())) { return Err(unsupported(format!("arguments of method `{name}`"))); } @@ -423,7 +435,7 @@ pub(in crate::ast) fn bind_value( if let objects::Receiver::Handle(handle) = receiver { children.push((handle, None)); } - for arg in args { + for arg in args.iter().filter(|_| selection.is_none()) { let Some(value) = arg.value else { return Err(unsupported(format!( "omitted argument of method `{name}`" @@ -436,6 +448,7 @@ pub(in crate::ast) fn bind_value( name, formals, receiver, + selection, }, children, ) @@ -924,6 +937,7 @@ pub(in crate::ast) fn bind_value( name, formals, receiver, + selection, } => { let mut args: Vec> = Vec::with_capacity(formals + 1); if receiver == objects::Receiver::This { @@ -931,6 +945,7 @@ pub(in crate::ast) fn bind_value( } let handles = usize::from(receiver != objects::Receiver::Static); args.extend(operands.into_iter().map(Some)); + args.extend(selection.map(Some)); // Omitted trailing arguments take their defaults. args.resize(formals + handles, None); Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 7d46726b339..cfcd38f83ed 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -293,7 +293,7 @@ pub(in crate::ast) fn method( } return Ok(Some(( Class::subroutine_name(&class_name, &method_name), - usize::from(method_name == "srandom"), + 1, receiver, ))); } @@ -516,3 +516,183 @@ pub(in crate::ast) fn constructor( arg_order: Vec::new(), })) } + +/// Inline randomization names are resolved in the receiver's class, not in +/// the caller's scope (18.11). Bit zero distinguishes an explicit empty set. +pub(super) fn random_selection( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + name: &str, + arguments: &[celox_sv_syntax::Argument], + native: &Declarations, +) -> Converted { + let owner = name.strip_suffix("::randomize").expect("randomize method"); + let class = class(tree, dimensions, owner)?; + let mut bits = vec!['0'; class.properties.len() + 1]; + if !arguments.is_empty() { + bits[0] = '1'; + } + for argument in arguments { + let id = argument + .value + .filter(|_| argument.name.is_none()) + .ok_or_else(|| unsupported("randomize arguments must be member names"))?; + match &native.expression(ungroup(id, native)).kind { + ExprKind::Literal(value) if value == "null" && arguments.len() == 1 => {} + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + let index = class + .properties + .iter() + .rposition(|p| p.name == name) + .ok_or_else(|| { + unsupported(format!( + "randomize argument `{name}` is not an instance property" + )) + })?; + let property = &class.properties[index]; + check_random_access(tree, dimensions, property)?; + if property.constant { + return Err(unsupported("randomize argument is a const property")); + } + if property.field.handle.is_some() || property.r#type.is_enum || property.randc { + return Err(unsupported( + "randomize arguments require integral non-enum, non-randc properties", + )); + } + bits[index + 1] = '1'; + } + _ => { + return Err(unsupported( + "randomize arguments must be member names or a single null", + )); + } + } + } + Ok(Expr::Literal(format!( + "{}'b{}", + bits.len(), + bits.into_iter().rev().collect::() + ))) +} + +/// Bind rand_mode's void setter and integer getter separately (18.8). +/// A getter requires one random property; only the setter accepts an object. +pub(in crate::ast) fn rand_mode_call( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + allow_set: bool, +) -> Converted> { + let (callee, args) = match &native.expression(ungroup(id, native)).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (id, &[][..]), + }; + let (property, owner, handle) = match &native.expression(ungroup(callee, native)).kind { + ExprKind::Member { + expression, + separator, + name, + } if separator == "." && name.spelling == "rand_mode" => { + let property_target = property(tree, *expression, native, dimensions)?; + if let Some((property, object)) = property_target.filter(|(property, _)| { + property.rand || property.randc || property.r#type.class().is_none() + }) { + check_random_access(tree, dimensions, &property)?; + if !property.rand && !property.randc { + return Err(unsupported("rand_mode requires a rand or randc property")); + } + ( + Some(property), + None, + receiver(tree, object, native, dimensions)?, + ) + } else if let Some(owner) = native_class(tree, *expression, native, dimensions) { + ( + None, + Some(owner), + bind_value(*expression, native, tree, dimensions, None)?, + ) + } else { + return Err(unsupported( + "rand_mode requires an object or random class property", + )); + } + } + ExprKind::Name(name) + if name.spelling == "rand_mode" && dimensions.get("rand_mode").is_none() => + { + let Some(owner) = scope_class(dimensions) else { + return Ok(None); + }; + if dimensions.get(THIS).is_none() { + return Err(unsupported("rand_mode requires an object receiver")); + } + (None, Some(owner), this()) + } + _ => return Ok(None), + }; + if args.is_empty() { + let property = + property.ok_or_else(|| unsupported("rand_mode getter requires one random property"))?; + return Ok(Some(classes::object_call( + ObjectOp::ModeGet(property.field.offset, true), + vec![handle], + ))); + } + if !allow_set { + return Err(unsupported( + "rand_mode setter is void and cannot be used as a value", + )); + } + if args.len() != 1 || args[0].name.is_some() || args[0].value.is_none() { + return Err(unsupported("rand_mode setter requires one on_off argument")); + } + let enabled = bind_value(args[0].value.unwrap(), native, tree, dimensions, None)?; + Ok(Some(match property { + Some(property) => classes::object_call( + ObjectOp::ModeSet(property.field.offset), + vec![handle, enabled], + ), + None => Expr::Call { + callee: Callee::Subroutine(Class::subroutine_name(&owner.unwrap(), "rand_mode")), + args: vec![Some(handle), Some(enabled)], + arg_order: Vec::new(), + }, + })) +} + +fn check_random_access( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + property: &classes::Property, +) -> Converted<()> { + let scope = scope_class(dimensions); + let accessible = if property.local { + scope.as_deref() == Some(&property.owner) + } else if property.protected { + scope + .and_then(|name| class(tree, dimensions, &name).ok()) + .is_some_and(|class| { + class.derives_from( + tree, + &property.owner, + &dimensions.const_env, + &dimensions.type_aliases, + ) + }) + } else { + true + }; + if !accessible { + return Err(unsupported(format!( + "randomization access to non-public property `{}`", + property.name + ))); + } + Ok(()) +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 986643713f1..2f506a465be 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -704,6 +704,23 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + if let Some(mut call) = + expression_binding::object_rand_mode_call(self.tree, root, native, &self.dims, true)? + { + self.rename_expr(&mut call); + return Ok(Some(match call { + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order, + } => Stmt::Call { + name, + args, + arg_order, + }, + call => Stmt::Eval(call), + })); + } let call = match native.expression(root).kind { celox_sv_syntax::ExprKind::Call { expression, .. } => { if expression_binding::object_method(self.tree, expression, native, &self.dims)? @@ -728,6 +745,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } expression_binding::ObjectReceiver::Static => Vec::new(), }; + if name.ends_with("::randomize") { + args.push(Some(Expr::Literal("1'b0".into()))); + } if name.ends_with("::srandom") { return Err(unsupported("srandom requires a seed argument")); } @@ -1631,14 +1651,23 @@ pub(super) fn subroutine_argument_names( params.into_iter().map(|(name, ..)| name).collect(), ); } - for method in ["randomize", "srandom"] { + for method in ["randomize", "srandom", "rand_mode"] { let qualified = item.name(&classes::Class::subroutine_name(&class, method)); let mut param_names = vec![classes::THIS.to_owned()]; let mut param_shapes = vec![dimensions_from_type(&handle)]; - if method == "srandom" { - param_names.push("seed".into()); - param_shapes.push(dimensions_from_type(&int_type())); - } + let (argument, ty) = match method { + "randomize" => ( + "$selection", + layout.as_ref().map_or_else( + || classes::unsigned_type(1), + |layout| layout.selection_type(), + ), + ), + "srandom" => ("seed", int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + param_names.push(argument.into()); + param_shapes.push(dimensions_from_type(&ty)); directions.insert( qualified.clone(), vec![ParamDirection::Input; param_names.len()], diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 65201af5f5f..2b8d305459e 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -1,10 +1,11 @@ -//! Built-in class randomization methods (IEEE 1800-2023 18.6, 18.13.3). +//! Built-in class randomization methods (IEEE 1800-2023 18.6, 18.8, 18.11). use super::*; use crate::system_functions::ObjectOp; -/// Generate ordinary automatic subroutines so hooks and property updates use -/// the same call machinery as authored class methods. Unsupported randomization -/// is diagnosed at the call site, rather than rejecting an unused class. +/// Generate automatic methods so hooks, dispatch and property updates use +/// ordinary call machinery. The hidden selection argument is zero for the +/// persistent random modes, or has bit 0 set and bit i+1 for selected property i. +/// Inherited properties keep their indices, including hidden base properties. pub(super) fn lower( class: &classes::Class, tree: &AnalysisContext<'_>, @@ -24,7 +25,7 @@ pub(super) fn lower( ) }; let mut result = Vec::new(); - for method in ["randomize", "srandom"] { + for method in ["randomize", "srandom", "rand_mode"] { if method == "randomize" && class.check_randomize(tree).is_err() { continue; } @@ -33,18 +34,33 @@ pub(super) fn lower( builder.automatic = true; let first_local = builder.state.locals.len(); let this = builder.declare(classes::THIS, handle.clone()); - let mut params = vec![SubroutineParam { - name: this.clone(), - source_name: classes::THIS.into(), - direction: ParamDirection::Input, - r#type: convert_type(handle.clone()), - default: None, - }]; - // Heap faults are reported after the kernel completes. Return now so - // a rejected receiver cannot run hooks or mutate the object's state. + let (argument, argument_type) = match method { + "randomize" => ("$selection", class.selection_type()), + "srandom" => ("seed", int_type()), + _ => ("on_off", classes::unsigned_type(1)), + }; + let argument = builder.declare(argument, argument_type.clone()); + let params = vec![ + SubroutineParam { + name: this.clone(), + source_name: classes::THIS.into(), + direction: ParamDirection::Input, + r#type: convert_type(handle.clone()), + default: None, + }, + SubroutineParam { + name: argument.clone(), + source_name: argument.clone(), + direction: ParamDirection::Input, + r#type: convert_type(argument_type), + default: None, + }, + ]; + // Faults are consumed after the kernel completes. Return immediately + // on rejection, before hooks, draws or property/mode updates. let mut body = vec![Stmt::If { condition: classes::object_call( - ObjectOp::Check(if method == "randomize" { class.id } else { 0 }), + ObjectOp::Check(if method == "srandom" { 0 } else { class.id }), vec![Expr::Ident(this.clone())], ), then_body: Vec::new(), @@ -52,47 +68,182 @@ pub(super) fn lower( (method == "randomize").then(|| Expr::Literal("32'sd0".into())), )], }]; - let return_var = if method == "srandom" { - let seed = builder.declare("seed", int_type()); - params.push(SubroutineParam { - name: seed.clone(), - source_name: "seed".into(), - direction: ParamDirection::Input, - r#type: convert_type(int_type()), - default: None, - }); - body.push(Stmt::Eval(classes::object_call( - ObjectOp::Seed, - vec![Expr::Ident(this.clone()), Expr::Ident(seed)], - ))); - None - } else { - let hook = |name| { - class.method(name).map(|method| Stmt::Call { - name: classes::Class::subroutine_name(&method.owner, &method.name), - args: vec![Some(Expr::Ident(this.clone()))], - arg_order: Vec::new(), - }) - }; - body.extend(hook("pre_randomize")); - for property in class.properties.iter().filter(|property| property.rand) { + let return_var = match method { + "srandom" => { body.push(Stmt::Eval(classes::object_call( - ObjectOp::Store(property.field), - vec![ - Expr::Ident(this.clone()), - classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.clone())]), - ], + ObjectOp::Seed, + vec![Expr::Ident(this.clone()), Expr::Ident(argument.clone())], ))); + None + } + "rand_mode" => { + for property in &class.properties { + let update = Stmt::Eval(classes::object_call( + ObjectOp::ModeSet(property.field.offset), + vec![Expr::Ident(this.clone()), Expr::Ident(argument.clone())], + )); + body.push(if property.rand || property.randc { + update + } else { + Stmt::If { + condition: classes::object_call( + ObjectOp::ModeSelected(property.field.offset), + vec![Expr::Ident(this.clone())], + ), + then_body: vec![update], + else_body: Vec::new(), + } + }); + } + None + } + _ => { + let hook = |name| { + class.method(name).map(|method| Stmt::Call { + name: classes::Class::subroutine_name(&method.owner, &method.name), + args: vec![Some(Expr::Ident(this.clone()))], + arg_order: Vec::new(), + }) + }; + let mut select = vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePush, + vec![Expr::Ident(this.clone())], + ))]; + for (index, property) in class.properties.iter().enumerate() { + let selected = Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal((index + 1).to_string())), + }), + op: BinaryOp::BitAnd, + right: Box::new(Expr::Literal("1'b1".into())), + }; + select.push(Stmt::Eval(classes::object_call( + ObjectOp::ModeSelect(property.field.offset, property.rand), + vec![Expr::Ident(this.clone()), selected], + ))); + } + body.push(Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: select, + else_body: Vec::new(), + }); + body.extend(hook("pre_randomize")); + for property in &class.properties { + if property.constant + || property.field.handle.is_some() + || property.r#type.is_enum + { + continue; + } + body.push(Stmt::If { + condition: Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1".into())), + }), + op: BinaryOp::LogicAnd, + right: Box::new(classes::object_call( + ObjectOp::ModeGet(property.field.offset, property.rand), + vec![Expr::Ident(this.clone())], + )), + }, + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![ + Expr::Ident(this.clone()), + classes::object_call( + ObjectOp::Random, + vec![Expr::Ident(this.clone())], + ), + ], + ))], + else_body: Vec::new(), + }); + } + body.extend(hook("post_randomize")); + body.push(Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePop, + vec![Expr::Ident(this.clone())], + ))], + else_body: Vec::new(), + }); + let returned = builder.declare("randomize", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(returned.clone()), + rhs: Expr::Literal("32'sd1".into()), + nonblocking: false, + }); + Some(returned) } - body.extend(hook("post_randomize")); - let returned = builder.declare("randomize", int_type()); - body.push(Stmt::Assign { - lhs: LValue::Ident(returned.clone()), - rhs: Expr::Literal("32'sd1".into()), - nonblocking: false, - }); - Some(returned) }; + if method != "srandom" { + // randomize is virtual, while its pre/post hooks are not (18.6.2). + // Object-wide rand_mode also covers the dynamic object's members. + let mut items = Vec::new(); + let aliases = item.type_aliases(&dimensions.type_aliases); + for declaration in &tree.declarations().classes { + if declaration.interface || declaration.virtual_class { + continue; + } + let name = instances::normalize_identifier(&declaration.name.spelling); + if name == class.name { + continue; + } + let Ok(derived) = classes::class(tree, &name, &item.env, &aliases) else { + continue; + }; + if (method == "randomize" && derived.check_randomize(tree).is_err()) + || !derived.derives_from(tree, &class.name, &item.env, &aliases) + { + continue; + } + let args = vec![ + Some(Expr::Ident(this.clone())), + Some(Expr::Ident(argument.clone())), + ]; + let name = classes::Class::subroutine_name(&name, method); + let call = if method == "randomize" { + vec![Stmt::Return(Some(Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order: Vec::new(), + }))] + } else { + vec![ + Stmt::Call { + name, + args, + arg_order: Vec::new(), + }, + Stmt::Return(None), + ] + }; + items.push(CaseItemBase { + labels: vec![CaseLabel::Value(Expr::Literal(format!( + "32'd{}", + derived.id + )))], + body: call, + }); + } + body.insert( + 0, + Stmt::Case { + kind: CaseKind::Exact, + selector: classes::object_call( + ObjectOp::ClassOf, + vec![Expr::Ident(this.clone())], + ), + items, + default: None, + }, + ); + } for stmt in &mut body { qualify_stmt(item, stmt); } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index d1536006fcc..3fda772fed5 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -793,6 +793,13 @@ pub enum ObjectOp { /// Validate a receiver; a nonzero class also rejects unsupported dynamic /// dispatch through a base handle before randomizing its properties. Check(u32), + /// Query or set the random mode of a property at its byte offset. + ModeGet(u32, bool), + ModeSet(u32), + ModePush, + ModePop, + ModeSelect(u32, bool), + ModeSelected(u32), } impl ObjectOp { @@ -800,7 +807,14 @@ impl ObjectOp { pub fn result_type(&self) -> (usize, bool) { match self { Self::Random => (64, false), - Self::Seed | Self::Check(_) => (32, false), + Self::Seed + | Self::Check(_) + | Self::ModeSet(_) + | Self::ModePush + | Self::ModePop + | Self::ModeSelect(..) + | Self::ModeSelected(_) => (32, false), + Self::ModeGet(..) => (32, true), Self::Load(field) => (field.width as usize, field.signed), Self::New { .. } | Self::ClassOf | Self::Store(_) => (32, false), } @@ -817,6 +831,12 @@ impl fmt::Display for ObjectOp { Self::Random => "object random bits", Self::Seed => "object random seed", Self::Check(_) => "object receiver check", + Self::ModeGet(..) => "random mode query", + Self::ModeSet(_) => "random mode update", + Self::ModePush => "save random modes", + Self::ModePop => "restore random modes", + Self::ModeSelect(..) => "select random property", + Self::ModeSelected(_) => "selected random property query", }) } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 774258ff613..077dddb2f26 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6596,7 +6596,19 @@ fn class_randomize_rejects_unsupported_semantics() { "c.randomize() with { x == 1; }", "unsupported", ), - ("rand int x;", "c.randomize(x)", "arguments"), + ("rand int x;", "c.randomize(x + 1)", "arguments"), + ("rand int x;", "c.randomize(c.x)", "arguments"), + ("rand int x;", "c.randomize(null, x)", "arguments"), + ( + "rand int x;", + "c.randomize(missing)", + "not an instance property", + ), + ("const int x = 1;", "c.randomize(x)", "const"), + ("local int x;", "c.randomize(x)", "non-public"), + ("protected int x;", "c.randomize(x)", "non-public"), + ("rand int x;", "c.rand_mode()", "getter requires"), + ("int x;", "c.x.rand_mode()", "rand or randc"), ( "rand int x; function void pre_randomize(int arg); endfunction", "c.randomize()", @@ -6617,3 +6629,32 @@ fn class_randomize_rejects_unsupported_semantics() { assert!(error.to_lowercase().contains(expected), "{source}: {error}"); } } + +#[test] +fn rand_mode_setter_cannot_be_used_as_a_value() { + let source = "module Top; class C; rand int x; endclass C c; int result; initial begin c = new; result = c.x.rand_mode(1); end endmodule"; + let error = analyze_source(source, Path::new("mode_value.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("setter is void"), "{error}"); +} + +#[test] +fn rand_mode_name_outside_a_class_is_an_ordinary_function() { + let source = "module Top(output int value); function int rand_mode(); return 42; endfunction initial value = rand_mode(); endmodule"; + analyze_source(source, Path::new("ordinary_rand_mode.sv")).unwrap(); +} + +#[test] +fn randomization_signatures_do_not_force_unused_interface_class_layouts() { + for declaration in [ + "interface class I; typedef int T; pure virtual function void f(T x); endclass + interface class J extends I; pure virtual function void g(T x); endclass", + "interface class I #(type T = logic); pure virtual function void f(T x); endclass + interface class J #(type T = logic); pure virtual function void g(T x); endclass + interface class K #(type U = logic) extends I#(U), J#(U); typedef U T; endclass", + ] { + let source = format!("module Top; {declaration} endmodule"); + analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap(); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 05957bd608e..51e04377b4c 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -651,3 +651,21 @@ an unknown display format code. It prints a lowercase `e` for the uppercase `%E` conversion in `real_display_negative_zero`; the negative-zero value is otherwise correct. Its `real_file_display_formats` case passes. The shared assertions remain enabled, and these external differences are not exclusions. + +Randomization control (`sv_icarus_randomization_control`) excludes four new +`class::randomization_*` cases from Icarus 13.0: it rejects `randomize`, `srandom` +and property/object `rand_mode` calls. [Retained diagnostics](verification/repros/sv_randomization_control_icarus.json) +record the failures; they are not passing simulation results. + +Verilator 5.052 has two narrower exclusions, recorded in the +[randomization control evidence](verification/repros/sv_randomization_control_verilator.json): + +- `sv_verilator_inherited_srandom`: `class::randomization_inheritance` fails + compilation with duplicate `srandom` declarations when the same derived + object is seeded through derived and base handles (IEEE 1800-2023 18.6.2, + 18.13.3). Assertions for hidden inherited members and hook dispatch remain. +- `sv_verilator_rand_mode_bit_argument`: `class::randomization_mode_bit_argument` + reports two errors because both forms of `rand_mode(2)` enable the variable. + The setter's formal is `bit` (18.8), so the required conversion truncates 2 to + 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, + inline member selection and pre-hook control cases pass Verilator. diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index a3bb34bf77c..768617f2953 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -790,3 +790,142 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_inheritance + (source "randomization_inheritance.sv" #" +module Top(output bit done, output int errors); + class Base; + rand bit [63:0] x; + int pre, post; + function void pre_randomize(); pre += 1; endfunction + function void post_randomize(); post += 1; endfunction + function bit [63:0] base_x(); return x; endfunction + function int again(); return randomize(); endfunction + endclass + class Child extends Base; + rand bit [63:0] x; + rand bit [63:0] y; + function void pre_randomize(); super.pre_randomize(); pre += 10; endfunction + function void post_randomize(); super.post_randomize(); post += 10; endfunction + endclass + class Grandchild extends Child; endclass + Base b; + Grandchild c; + bit [63:0] bx, cx, cy; + initial begin + c = new; + b = c; + c.srandom(31); + if (!c.randomize()) errors++; + bx = c.base_x(); cx = c.x; cy = c.y; + b.srandom(31); + if (!b.again()) errors++; + if (b.x != bx || c.x != cx || c.y != cy) errors++; + if (b.pre != 22 || b.post != 22) errors++; + b.rand_mode(0); + if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++; + if (!b.randomize() || b.x != bx || c.x != cx || c.y != cy) errors++; + // Inline selection is resolved in the static receiver class. + b.srandom(31); + if (!b.randomize(x) || b.x != bx || c.x != cx || c.y != cy) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_modes_and_selection + (source "randomization_modes.sv" #" +module Top(output bit done, output int errors); + class C; + rand bit [63:0] x, y; + bit [63:0] plain = 19; + int hooks; + function void pre_randomize(); hooks++; endfunction + function void post_randomize(); hooks++; endfunction + function int select_plain(); return randomize(plain); endfunction + function void disable_x(); x.rand_mode(0); endfunction + endclass + C c, alias_c, reference; + int plain = 99; + bit [63:0] x, y, p; + initial begin + c = new; reference = new; alias_c = c; + if (c.x.rand_mode() != 1 || c.y.rand_mode() != 1) errors |= 1; + c.disable_x(); + c.srandom(42); reference.srandom(42); + if (!c.randomize() || !reference.randomize(y)) errors |= 2; + if (c.x != 0 || c.y != reference.y || c.plain != 19) errors |= 4; + c.rand_mode(0); + x = c.x; y = c.y; + if (!c.randomize() || c.x != x || c.y != y) errors |= 8; + alias_c.x.rand_mode(1); + if (c.x.rand_mode() != 1 || c.y.rand_mode() != 0) errors |= 16; + c.x.rand_mode(0); + if (c.x.rand_mode() != 0) errors |= 32; + c.srandom(9); reference.srandom(9); + if (!c.randomize(plain) || !reference.randomize(plain)) errors |= 64; + if (plain != 99 || c.plain != reference.plain || c.x != x || c.y != y) errors |= 128; + if (c.x.rand_mode() || c.y.rand_mode()) errors |= 256; + p = c.plain; + if (!c.randomize(null) || c.x != x || c.y != y || c.plain != p) errors |= 512; + if (c.hooks != 8) errors |= 1024; + c.srandom(7); reference.srandom(7); + if (!c.select_plain() || !reference.randomize(plain)) errors |= 2048; + if (c.plain != reference.plain) errors |= 4096; + c.rand_mode(1); + if (!c.x.rand_mode() || !c.y.rand_mode()) errors |= 8192; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_pre_hook_controls_modes + (source "randomization_hook.sv" #" +module Top(output bit done, output int errors); + class C; + rand bit [63:0] x; + bit disable_randomization; + int seen; + function void pre_randomize(); + seen = x.rand_mode(); + if (disable_randomization) rand_mode(0); + endfunction + endclass + C c, reference; + initial begin + c = new; reference = new; + c.disable_randomization = 1; + if (!c.randomize() || c.x != 0 || c.x.rand_mode()) errors++; + c.srandom(8); reference.srandom(8); + if (!c.randomize(x) || !reference.randomize()) errors++; + if (c.x != 0 || c.x.rand_mode() || c.seen != 1) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + + +(case randomization_mode_bit_argument + (source "mode_bit_argument.sv" #" +module Top(output bit done, output int errors); + class C; rand int x; endclass + C c; + initial begin + c = new; + c.x.rand_mode(2); + if (c.x.rand_mode() != 0) errors++; + c.x.rand_mode(3); + if (c.x.rand_mode() != 1) errors++; + c.rand_mode(2); + if (c.x.rand_mode() != 0) errors++; + c.rand_mode(3); + if (c.x.rand_mode() != 1) errors++; + if (c.x.rand_mode() < -1) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json b/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json new file mode 100644 index 00000000000..28e83c0af99 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randomization_control_icarus.json @@ -0,0 +1,60 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "case_fingerprint": "0790ca7f7a064b5ada217c1bcb303cc08f64d22140af1e703f2687aa00b567f5", + "category": "Types", + "detail": "Icarus build exit status: 22; see /build.log\n/source_0.sv:9: error: No function named `randomize' found in this context (celox_suite_tb.dut.Base.again).\n/source_0.sv:24: error: Can't find task srandom in class Grandchild\n/source_0.sv:24: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:25: Error: randomize is not a method of class Grandchild.\n/source_0.sv:25: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:25: error: Unable to elaborate condition expression.\n/source_0.sv:27: error: Can't find task srandom in class Base\n/source_0.sv:27: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:31: error: Can't find task rand_mode in class Base\n/source_0.sv:31: error: Enable of unknown task ``b.rand_mode''.\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.b has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: y.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:33: Error: randomize is not a method of class Base.\n/source_0.sv:33: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:33: error: Unable to elaborate condition expression.\n/source_0.sv:35: error: Can't find task srandom in class Base\n/source_0.sv:35: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:36: Error: randomize is not a method of class Base.\n/source_0.sv:36: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n22 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "ca2c64e1d788293a78db1e56128c2d271ac015be7f14c463c9829778dc0a114f", + "category": "Types", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:7: error: Can't find task rand_mode in class C\n/source_0.sv:7: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:8: sorry: Method name nesting is not supported yet.\n/source_0.sv:8: : method path: x.rand_mode\n/source_0.sv:8: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:8: error: Unable to elaborate condition expression.\n/source_0.sv:9: error: Can't find task rand_mode in class C\n/source_0.sv:9: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:10: sorry: Method name nesting is not supported yet.\n/source_0.sv:10: : method path: x.rand_mode\n/source_0.sv:10: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:10: error: Unable to elaborate condition expression.\n/source_0.sv:11: error: Can't find task rand_mode in class C\n/source_0.sv:11: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:12: sorry: Method name nesting is not supported yet.\n/source_0.sv:12: : method path: x.rand_mode\n/source_0.sv:12: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:12: error: Unable to elaborate condition expression.\n/source_0.sv:13: error: Can't find task rand_mode in class C\n/source_0.sv:13: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:14: sorry: Method name nesting is not supported yet.\n/source_0.sv:14: : method path: x.rand_mode\n/source_0.sv:14: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:14: error: Unable to elaborate condition expression.\n/source_0.sv:15: sorry: Method name nesting is not supported yet.\n/source_0.sv:15: : method path: x.rand_mode\n/source_0.sv:15: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:15: error: Unable to elaborate condition expression.\n18 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "93d721f6fe140941ddb5068e041dc968ca7e9c60a73e13320da3c8439d0aa8f1", + "category": "Types", + "detail": "Icarus build exit status: 57; see /build.log\n/source_0.sv:10: error: Can't find task rand_mode in class C\n/source_0.sv:10: error: Enable of unknown task ``x.rand_mode''.\n/source_0.sv:10: error: Unable to elaborate statement in function disable_x.\n/source_0.sv:9: error: No function named `randomize' found in this context (celox_suite_tb.dut.C.select_plain).\n/source_0.sv:17: sorry: Method name nesting is not supported yet.\n/source_0.sv:17: : method path: x.rand_mode\n/source_0.sv:17: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:17: sorry: Method name nesting is not supported yet.\n/source_0.sv:17: : method path: y.rand_mode\n/source_0.sv:17: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:17: error: Unable to elaborate condition expression.\n/source_0.sv:19: error: Can't find task srandom in class C\n/source_0.sv:19: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:19: error: Can't find task srandom in class C\n/source_0.sv:19: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:20: Error: randomize is not a method of class C.\n/source_0.sv:20: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:20: Error: randomize is not a method of class C.\n/source_0.sv:20: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:22: error: Can't find task rand_mode in class C\n/source_0.sv:22: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:24: Error: randomize is not a method of class C.\n/source_0.sv:24: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:24: error: Unable to elaborate condition expression.\n/source_0.sv:25: error: Can't find task rand_mode in class C\n/source_0.sv:25: error: Enable of unknown task ``alias_c.x.rand_mode''.\n/source_0.sv:26: sorry: Method name nesting is not supported yet.\n/source_0.sv:26: : method path: x.rand_mode\n/source_0.sv:26: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:26: sorry: Method name nesting is not supported yet.\n/source_0.sv:26: : method path: y.rand_mode\n/source_0.sv:26: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:26: error: Unable to elaborate condition expression.\n/source_0.sv:27: error: Can't find task rand_mode in class C\n/source_0.sv:27: error: Enable of unknown task ``c.x.rand_mode''.\n/source_0.sv:28: sorry: Method name nesting is not supported yet.\n/source_0.sv:28: : method path: x.rand_mode\n/source_0.sv:28: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:28: error: Unable to elaborate condition expression.\n/source_0.sv:29: error: Can't find task srandom in class C\n/source_0.sv:29: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:29: error: Can't find task srandom in class C\n/source_0.sv:29: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:30: Error: randomize is not a method of class C.\n/source_0.sv:30: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:30: Error: randomize is not a method of class C.\n/source_0.sv:30: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:30: error: Unable to elaborate condition expression.\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: x.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:32: sorry: Method name nesting is not supported yet.\n/source_0.sv:32: : method path: y.rand_mode\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:34: Error: randomize is not a method of class C.\n/source_0.sv:34: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:34: error: Unable to elaborate condition expression.\n/source_0.sv:36: error: Can't find task srandom in class C\n/source_0.sv:36: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:36: error: Can't find task srandom in class C\n/source_0.sv:36: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:37: Error: randomize is not a method of class C.\n/source_0.sv:37: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:37: error: Unable to elaborate condition expression.\n/source_0.sv:39: error: Can't find task rand_mode in class C\n/source_0.sv:39: error: Enable of unknown task ``c.rand_mode''.\n/source_0.sv:40: sorry: Method name nesting is not supported yet.\n/source_0.sv:40: : method path: x.rand_mode\n/source_0.sv:40: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:40: sorry: Method name nesting is not supported yet.\n/source_0.sv:40: : method path: y.rand_mode\n/source_0.sv:40: error: Object celox_suite_tb.dut.c has no method \"y.rand_mode(...)\".\n/source_0.sv:40: error: Unable to elaborate condition expression.\n57 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_modes_and_selection", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + }, + { + "case_fingerprint": "e8d29f784ff8a2f5ff9124bc2d57b2406359db7d857778964e2389c86bc7f92b", + "category": "Types", + "detail": "Icarus build exit status: 17; see /build.log\n/source_0.sv:8: sorry: Method name nesting is not supported yet.\n/source_0.sv:8: : method path: x.rand_mode\n/source_0.sv:8: error: Object celox_suite_tb.dut.C.this has no method \"x.rand_mode(...)\".\n/source_0.sv:9: error: Enable of unknown task ``rand_mode''.\n/source_0.sv:16: Error: randomize is not a method of class C.\n/source_0.sv:16: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:16: sorry: Method name nesting is not supported yet.\n/source_0.sv:16: : method path: x.rand_mode\n/source_0.sv:16: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:16: error: Unable to elaborate condition expression.\n/source_0.sv:17: error: Can't find task srandom in class C\n/source_0.sv:17: error: Enable of unknown task ``c.srandom''.\n/source_0.sv:17: error: Can't find task srandom in class C\n/source_0.sv:17: error: Enable of unknown task ``reference.srandom''.\n/source_0.sv:18: Error: randomize is not a method of class C.\n/source_0.sv:18: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:18: Error: randomize is not a method of class C.\n/source_0.sv:18: error: Object celox_suite_tb.dut.reference has no method \"randomize(...)\".\n/source_0.sv:18: error: Unable to elaborate condition expression.\n/source_0.sv:19: sorry: Method name nesting is not supported yet.\n/source_0.sv:19: : method path: x.rand_mode\n/source_0.sv:19: error: Object celox_suite_tb.dut.c has no method \"x.rand_mode(...)\".\n/source_0.sv:19: error: Unable to elaborate condition expression.\n17 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_pre_hook_controls_modes", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717883 + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json b/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json new file mode 100644 index 00000000000..964300cbefb --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randomization_control_verilator.json @@ -0,0 +1,34 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "case_fingerprint": "0790ca7f7a064b5ada217c1bcb303cc08f64d22140af1e703f2687aa00b567f5", + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:25:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 25 | if (!c.randomize()) errors++;\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHTRUNC?v=5.052\n ... Use \"/* verilator lint_off WIDTHTRUNC */\" and lint_on around source to disable this message.\n%Warning-WIDTHTRUNC: /source_0.sv:28:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'again' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 28 | if (!b.again()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:32:29: Logical operator LOGOR expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:32:29: Logical operator LOGOR expects 1 bit on the RHS, but RHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:32:48: Logical operator LOGOR expects 1 bit on the RHS, but RHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 32 | if (b.x.rand_mode() || c.x.rand_mode() || c.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:33:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 33 | if (!b.randomize() || b.x != bx || c.x != cx || c.y != cy) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:36:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 36 | if (!b.randomize(x) || b.x != bx || c.x != cx || c.y != cy) errors++;\n | ^\n%Error: /source_0.sv:3:5: Duplicate declaration of member name: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: /source_0.sv:3:5: Duplicate declaration of function: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n /source_0.sv:3:5: ... Location of original declaration\n 3 | class Base;\n | ^~~~~\n%Error: Exiting due to 2 error(s)\n", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717788 + }, + { + "case_fingerprint": "ca2c64e1d788293a78db1e56128c2d271ac015be7f14c463c9829778dc0a114f", + "category": "Types", + "detail": "class::randomization_mode_bit_argument at 746:46: assert_eq errors: expected 0x0, got 0x2", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792717804 + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 2ffa43e125e..9e91a1b7c19 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_modes_and_selection", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_pre_hook_controls_modes", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "known_issue": { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "detail": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 6688832b0de..b9acfdf7286 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2086,5 +2086,59 @@ "class::unconstrained_randomize" ] } + }, + { + "id": "sv_icarus_randomization_control", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects randomize, srandom and rand_mode calls, including property rand_mode calls (\"Method name nesting is not supported yet\"). IEEE 1800-2023 18.6, 18.8 and 18.11 define these class methods and inline member selection.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_inheritance", + "class::randomization_mode_bit_argument", + "class::randomization_modes_and_selection", + "class::randomization_pre_hook_controls_modes" + ] + } + }, + { + "id": "sv_verilator_inherited_srandom", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_inheritance" + ] + } + }, + { + "id": "sv_verilator_rand_mode_bit_argument", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_mode_bit_argument" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 50899178c71..a255bf9044d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -190,6 +190,52 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "known_issue": { + "id": "sv_verilator_inherited_srandom", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 reports duplicate declarations of the built-in srandom member/function when this inherited randomization case seeds the same object through both derived and base handles. IEEE 1800-2023 18.6.2 and 18.13.3 permit dynamic class randomization and object seeding. Celox preserves the assertions for inherited hidden members and hook dispatch.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_mode_bit_argument", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "known_issue": { + "id": "sv_verilator_rand_mode_bit_argument", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats rand_mode(2) as enabled for both member and object-wide setters. IEEE 1800-2023 18.8 declares a bit on_off formal, so integral 2 truncates to zero. The case records two assertion failures; generated C++ sets the mode to 1 for these calls. Celox retains the required bit conversion.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randomization_control_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index cd7f9ab5212..17b93891c46 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -314,3 +314,67 @@ sv_backends! { } } } + +sv_backends! { + fn class_randomization_mode_bit_argument(sim) { @case "class::randomization_mode_bit_argument"; } + fn class_randomization_inheritance(sim) { @case "class::randomization_inheritance"; } + fn class_randomization_modes_and_selection(sim) { @case "class::randomization_modes_and_selection"; } + fn class_randomization_pre_hook_controls_modes(sim) { @case "class::randomization_pre_hook_controls_modes"; } +} + +sv_backends! { + fn class_random_modes_checkpoint_four_state(sim) { + @setup { let source = r#" + module Top(input bit enable, output int mode, output bit [63:0] value); + timeunit 1ps / 1ps; + class C; rand bit [63:0] x = 17; endclass + C c; + initial begin + c = new; + c.x.rand_mode(0); + #10 if (enable) c.x.rand_mode(1); + #10; + void'(c.randomize()); + value = c.x; + mode = c.x.rand_mode(); + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("mode_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let saved = sim.checkpoint().unwrap(); + let enable = sim.signal("enable"); + sim.modify(|io| io.set(enable, 1u8)).unwrap(); + sim.run_until(25).unwrap(); + assert_eq!(sim.get(sim.signal("mode")), 1u8.into()); + sim.restore(&saved).unwrap(); + sim.run_until(25).unwrap(); + assert_eq!(sim.get(sim.signal("mode")), 0u8.into()); + assert_eq!(sim.get_four_state(sim.signal("value")), (17u8.into(), 0u8.into())); + } + + fn class_random_selection_spans_multiple_words(sim) { + @setup { + let properties = (0..70).map(|i| format!("p{i}")).collect::>().join(", "); + let source = format!(r#" + module Top(output bit done, output int errors); + class C; + bit [63:0] {properties}; + endclass + C c, reference; + initial begin + c = new; reference = new; + c.srandom(71); reference.srandom(71); + if (!c.randomize(p69) || !reference.randomize(p0)) errors++; + if (c.p69 != reference.p0 || c.p0 != 0 || c.p68 != 0) errors++; + done = 1; + end + endmodule + "#); + } + @build celox::Simulation::from_sv_sources(vec![(source.as_str(), Path::new("wide_selection.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + assert_eq!(sim.get(sim.signal("errors")), 0u8.into()); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index fff7ef4fb74..af7fea78edf 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -106,20 +106,37 @@ constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization -`object.randomize()` randomizes the object's `rand` properties and returns -signed `int` value `1`. This first subset supports classes without inheritance -or constraints, with 2-state non-enum integral `rand` properties up to 64 bits. -Other properties keep their values. Zero-argument, non-static, non-virtual -`pre_randomize()` and `post_randomize()` functions run before and after the -updates, including when there are no `rand` properties (IEEE 1800-2023 18.6). -Calls inside a class may use `randomize()` or `this.randomize()`. +`object.randomize()` randomizes enabled `rand` properties and returns signed +`int` value `1`. Supported properties are 2-state, non-enum integral values up +to 64 bits in classes without constraints. Inherited properties are included, +and a call through a base handle uses the dynamic object's class and its +`pre_randomize()` / `post_randomize()` hooks. A derived hook replaces the base +hook; call `super.pre_randomize()` or `super.post_randomize()` explicitly to +include the base hook's work (IEEE 1800-2023 18.6.2). Hooks must be functions +without arguments, non-static and non-virtual. Calls inside a class may use +`randomize()` or `this.randomize()`. + +`object.member.rand_mode(0)` disables a random property; `rand_mode(1)` enables +it, and `object.member.rand_mode()` returns its current mode as signed `int`. +The setter's argument is a `bit`. `object.rand_mode(bit)` sets all random +properties, including inherited ones. All start enabled, and aliases share the +same modes (18.8). + +`object.randomize(x, y)` temporarily selects exactly those instance properties, +including supported properties not declared `rand`. Names are resolved in the +receiver's class, not the caller's scope; expressions and inaccessible members +are rejected. The temporary modes are installed before the pre-hook and restored +after the post-hook; hooks can inspect and change them. `randomize(null)` runs +the hooks without drawing or assigning random values (18.11). Constraints are +not supported even for this checker form. Each object has an independent random stream, seeded from its creating process. -`object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve it -(18.13.3, 18.14.3). Random sequences are implementation-specific. -`randc`, constraints, `with`, argument lists to `randomize`, `rand_mode`, -static random properties, random enum/array/object/string properties and randomization through inheritance -remain unsupported. A call through `null` is a runtime error. +`object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both +RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. +`randc` randomization, constraints, `with`, static random properties, and random +enum/array/object/string properties remain unsupported. A constrained dynamic +subclass is rejected rather than silently randomizing only its base properties. +A call through `null` is a runtime error. ### Time literal delays {#time-literal-delays} diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 358ccd70c5f..c10c355185b 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -97,18 +97,31 @@ select・連結式の引数は未対応として拒否します。 ### クラスの乱数化 -`object.randomize()` は `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 -最初の対応範囲は継承・制約のないクラスと、64ビット以下の2値・非enum整数型の `rand` プロパティです。 -それ以外のプロパティは保持します。引数なし・非static・非virtualの -`pre_randomize()` と `post_randomize()` を更新の前後に呼びます。 -`rand` プロパティがない場合もフックを呼びます(IEEE 1800-2023 18.6)。 +`object.randomize()` は有効な `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 +制約のないクラスで、64ビット以下の2値・非enum整数型に対応します。 +継承したプロパティも対象になり、基底型のハンドルを通した呼び出しでも、実際のオブジェクトの +クラスと `pre_randomize()` / `post_randomize()` を使います。子クラスでフックを定義すると +親のフックを置き換えるため、親の処理も必要なら `super.pre_randomize()` などを明示的に呼びます +(IEEE 1800-2023 18.6.2)。フックは引数なし・非static・非virtualの関数に限ります。 クラス内では `randomize()` や `this.randomize()` と書けます。 +`object.member.rand_mode(0)` で乱数プロパティを無効化し、`rand_mode(1)` で有効化します。 +引数なしの `object.member.rand_mode()` は現在のモードを signed `int` で返します。 +設定側の引数型は `bit` です。`object.rand_mode(bit)` は継承分を含む全乱数プロパティに適用します。 +初期状態はすべて有効で、aliasは同じモードを共有します(18.8)。 + +`object.randomize(x, y)` はその呼び出しに限り対象を指定します。対応型なら `rand` でない +プロパティも指定できます。名前は呼び出し元ではなくreceiverのクラスで解決し、式やアクセス権のない +メンバーは拒否します。一時モードはpreフックの前に設定し、postフックの後に復元します。 +フックから一時モードを参照・変更できます。`randomize(null)` は乱数生成や代入を行わずフックを +呼びます(18.11)。この形式でも制約付きクラスは未対応です。 + オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 -`object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態も保持します +`object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc`、制約、`with`、`randomize` の引数指定、`rand_mode`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の -乱数化、継承を使った乱数化は未対応です。`null` を通した呼び出しは実行時エラーです。 +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 +`null` を通した呼び出しは実行時エラーです。 ### 時間リテラルによる遅延 {#time-literal-delays}