diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 7b440f50b12..bee7b6587b4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5497,6 +5497,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::Urandom | SystemFunction::UrandomRange | SystemFunction::Fopen + | SystemFunction::ScopeRandomize | SystemFunction::Timeunit | SystemFunction::Timeprecision | SystemFunction::Isunbounded diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 64b54726a4a..6784552d67b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -239,7 +239,9 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::Callee::System(function) => { use sv::ir::SystemFunction; match function { - SystemFunction::Urandom | SystemFunction::UrandomRange => { + SystemFunction::ScopeRandomize + | SystemFunction::Urandom + | SystemFunction::UrandomRange => { self.urandom_state(); } SystemFunction::Random if args.is_empty() => { @@ -823,6 +825,30 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.fopen(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize), + args, + .. + } => { + for arg in args.iter().flatten() { + let Expr::Ident(name) = arg else { + return Err(unsupported("scope randomize variable")); + }; + let target = sv::ir::LValue::Ident(name.clone()); + let width = self.lvalue_width(&target)?; + let mut words = Vec::with_capacity(width.div_ceil(32)); + for offset in (0..width).step_by(32) { + words.push(Expr::Resize { + expr: Box::new(self.randomize_word()?), + width: (width - offset).min(32), + signed: false, + }); + } + words.reverse(); + self.assign(&target, &Expr::Concat(words))?; + } + Expr::Literal("32'sd1".into()) + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom), args, @@ -1283,6 +1309,44 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// A bijective 32-bit output permutation of the process RNG. Mixing + /// high bits into low bits prevents the LCG's short low-bit periods from + /// freezing bits when a wide variable consumes an even number of words. + fn randomize_word(&mut self) -> Result { + use sv::ir::{BinaryOp, Expr}; + let mut word = self.urandom(None)?; + for (shift, multiplier) in [(16, 0x7feb352du32), (15, 0x846ca68bu32)] { + let mixed = Expr::Binary { + left: Box::new(word.clone()), + op: BinaryOp::BitXor, + right: Box::new(Expr::Binary { + left: Box::new(word), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal(shift.to_string())), + }), + }; + word = self.hidden( + "randomize_mix", + &Expr::Binary { + left: Box::new(mixed), + op: BinaryOp::Mul, + right: Box::new(Expr::Literal(format!("32'd{multiplier}"))), + }, + false, + )?; + } + let mixed = Expr::Binary { + left: Box::new(word.clone()), + op: BinaryOp::BitXor, + right: Box::new(Expr::Binary { + left: Box::new(word), + op: BinaryOp::Shr, + right: Box::new(Expr::Literal("16".into())), + }), + }; + self.hidden("randomize_word", &mixed, false) + } + /// IEEE 1800-2023 18.13.2: a number of the `$urandom` stream between the /// two bounds, in either order, inclusive. fn urandom_range( diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 220496f725f..da42fe0cd09 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1609,6 +1609,7 @@ impl Parameter { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Port { + randomizable: bool, name: String, direction: PortDirection, r#type: Type, @@ -1618,6 +1619,7 @@ pub struct Port { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Signal { + is_const: bool, name: String, r#type: Type, is_net: bool, @@ -1631,6 +1633,7 @@ impl Signal { name, r#type, is_net: false, + is_const: false, package_variable: None, } } @@ -1640,6 +1643,7 @@ impl Signal { name, r#type, is_net: true, + is_const: false, package_variable: None, } } @@ -1671,6 +1675,7 @@ impl Port { name, direction, r#type, + randomizable: !is_net, is_net, default: None, } @@ -1863,6 +1868,7 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { + is_enum: bool, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -1877,6 +1883,7 @@ pub struct Type { impl Type { fn implicit() -> Self { Self { + is_enum: false, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -1889,6 +1896,7 @@ impl Type { fn new(kind: TypeKind) -> Self { Self { kind, + is_enum: false, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), @@ -2567,6 +2575,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { + randomizable: bool, packed: Vec, unpacked: Vec, signed: bool, diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index b6d9aebd366..e983092529e 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -11,6 +11,7 @@ pub(super) fn ports_from_scope( let mut ports = Vec::new(); let mut inherited_direction = PortDirection::Unspecified; let mut inherited_type = Type::implicit(); + let mut inherited_variable = false; for native in port_owners::scope(selected, syntax_tree)? { let direction = native .direction @@ -69,15 +70,27 @@ pub(super) fn ports_from_scope( .ok_or_else(|| unsupported("nonconstant input port default")) }) .transpose()?; - ports.push( - Port::new( - native_port_name(native)?, - direction, - ty, - !explicit && !native.variable, - ) - .with_default(default), - ); + let variable = native.variable + || (direction == PortDirection::Output + && native.net_type.is_none() + && (native.data_type.is_some_and(|id| { + !matches!( + syntax_tree.declarations().data_type(id).kind, + celox_sv_syntax::DataTypeKind::Implicit + ) + }) || (native.direction.is_none() + && native.data_type.is_none() + && inherited_variable))); + inherited_variable = variable; + let mut port = Port::new( + native_port_name(native)?, + direction, + ty, + !explicit && !native.variable, + ) + .with_default(default); + port.randomizable = variable && direction != PortDirection::Input; + ports.push(port); } Ok(ports) } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index f62510932aa..e9ac9ddfb74 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -131,6 +131,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { + randomizable: !port.r#type().is_enum && port.randomizable, packed: signal_packed_dimension_widths(port.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()), signed: port.r#type().is_signed(), @@ -144,6 +145,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( signal.name().to_string(), VariableDimensions { + randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()), signed: signal.r#type().is_signed(), @@ -326,6 +328,7 @@ fn extend_variable_dimensions_from_const_env( } let packed_ranges = ranges.split_off(unpacked); let ty = Type { + is_enum: false, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, @@ -338,6 +341,7 @@ fn extend_variable_dimensions_from_const_env( }; let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { + shape.randomizable = existing.randomizable; shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -505,6 +509,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP ( parameter.name.clone(), VariableDimensions { + randomizable: true, packed: function_packed_dimension_widths(¶meter.packed_ranges), unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), 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 65c00b72f49..f3c11aabc6c 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -367,6 +367,62 @@ pub(in crate::ast) fn bind_value( expression, arguments: args, } => { + if matches!( + call_name(&tree.state, *expression, native).as_deref(), + Some("randomize" | "std::randomize") + ) { + if args + .iter() + .any(|arg| arg.name.is_some() || arg.value.is_none()) + { + return Err(unsupported( + "scope randomize requires positional variable identifiers", + )); + } + let actuals = + args.iter().filter_map(|arg| arg.value).collect::>(); + for &actual in &actuals { + let ExprKind::Name(name) = &native.expression(actual).kind else { + return Err(unsupported( + "scope randomize requires whole packed variable identifiers", + )); + }; + let name = instances::normalize_identifier(&name.spelling); + let shape = dimensions + .get(&name) + .ok_or_else(|| unsupported("scope randomize variable"))?; + if !shape.unpacked.is_empty() || !shape.randomizable { + return Err(unsupported( + "scope randomize requires a packed non-enum variable", + )); + } + if !expressions::query_actual_is_writable( + &Expr::Ident(name), + dimensions, + ) { + return Err(unsupported( + "scope randomize argument is not writable", + )); + } + } + jobs.push(Job::Finish( + Finish::Call { + name: "std::randomize".into(), + args: actuals.iter().copied().map(Some).collect(), + order: Vec::new(), + system: Some(SystemFunction::ScopeRandomize), + }, + actuals.len(), + scope.clone(), + )); + jobs.extend( + actuals + .into_iter() + .rev() + .map(|id| Job::Enter(id, None, scope.clone())), + ); + continue; + } let name = bound_callable_name(tree, *expression, native, dimensions)? .ok_or_else(|| unsupported("method or randomize call"))?; if name.starts_with('$') && !name.contains("::") { @@ -727,6 +783,7 @@ pub(in crate::ast) fn bind_value( | SystemFunction::ValuePlusargs | SystemFunction::Fopen | SystemFunction::UrandomRange + | SystemFunction::ScopeRandomize ) { for (position, arg) in operands.iter().enumerate() { if expr_static_width(&tree.state, arg, dimensions).is_none() diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 3e80db98927..8b6b6f83e0c 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -116,6 +116,11 @@ impl ScopeImports { && let celox_sv_syntax::ExprKind::Name(package) = &native.expression(*base).kind { let package = normalize_identifier(&package.spelling); + // std::randomize is a built-in scope function, not a + // user-declared package dependency (IEEE 1800-2023 18.12). + if package == "std" && normalize_identifier(&name.spelling) == "randomize" { + continue; + } if !nested.iter().any(|(start, end, names)| { (*start..*end).contains(&expression.tokens.start) && names.contains(&package) }) { diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 29a0ebcec0a..7aa9069c412 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -448,6 +448,7 @@ pub(super) fn analyze_module( name: port.name.clone(), r#type: port.r#type.clone(), is_net: port.is_net, + is_const: false, package_variable: None, }; module.symbols.as_mut().unwrap().signals.push(signal); diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 643d48c5e50..f778f37a118 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -56,6 +56,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - result.insert( name.to_string(), VariableDimensions { + randomizable: true, packed: function_packed_dimension_widths(&r#type.packed_ranges), unpacked: Vec::new(), signed: r#type.is_signed, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 8270742c94e..a5097bab957 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -490,6 +490,7 @@ fn pattern_items( 0, count as i128 - 1, VariableDimensions { + randomizable: true, packed: Vec::new(), unpacked: Vec::new(), members: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index fd82c4f5bac..4348cc7ed20 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -203,6 +203,7 @@ fn select<'a>( { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + randomizable: true, packed: rest.to_vec(), unpacked: Vec::new(), signed: shape.signed_element_depth == Some(1), @@ -236,6 +237,7 @@ fn select<'a>( let width = shape_width(state, &shape, dims) .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { + randomizable: true, packed: Vec::new(), unpacked: Vec::new(), signed: false, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 3d5af5962cc..ba171258fd8 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -68,6 +68,7 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { + randomizable: !r#type.is_enum, packed: dimensions::signal_packed_dimension_widths(r#type.packed_ranges()), unpacked: unpacked_dimension_widths(r#type.unpacked_ranges()), signed: r#type.is_signed(), @@ -98,6 +99,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - /// The `int` type of a loop variable declared by `foreach`. fn int_type() -> Type { Type { + is_enum: false, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( @@ -651,6 +653,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None => None, }; let name = self.declare(signal.name(), signal.r#type().clone()); + if signal.is_const { + let mut shape = self.dims.get(signal.name()).unwrap().clone(); + shape.randomizable = false; + self.dims.insert(signal.name().to_string(), shape); + } let automatic = match native.lifetime.as_deref() { Some("automatic") => true, Some("static") => false, @@ -746,6 +753,22 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if let celox_sv_syntax::ExprKind::Call { expression, .. } = + self.tree.declarations().expression(query_root).kind + && matches!( + expression_binding::native_name( + &self.tree.state, + expression, + self.tree.declarations() + ) + .as_deref(), + Some("randomize" | "std::randomize") + ) + { + let mut call = self.native_value(query_root)?; + self.rename_expr(&mut call); + return Ok(vec![Stmt::Eval(call)]); + } if timescales::is_query(query_root, self.tree.declarations()) { let value = timescales::query(query_root, self.tree)?; return Ok(vec![Stmt::Eval(Expr::Literal( diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 1cf876d378f..7d58a46ff99 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -82,7 +82,9 @@ pub(super) fn local_signals( base.clone(), constant_binding::bind_unpacked_ranges(&variable.dimensions, tree, &context)?, ); - signals.push(Signal::new(name, ty)); + let mut signal = Signal::new(name, ty); + signal.is_const = declaration.constant; + signals.push(signal); } Ok(signals) } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 7c239591da1..e1bde36666e 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -77,6 +77,7 @@ pub(in crate::ast) fn bind_in( jobs.push(Job::Enter(*base)); } else { let mut ty = builtin_type("int", None).unwrap(); + ty.is_enum = true; ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -147,6 +148,7 @@ pub(in crate::ast) fn bind_in( let mut outer = ranges; outer.extend(ty.packed_ranges); ty.packed_ranges = outer; + ty.is_enum = true; values.push(ty); } Job::Aggregate { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 5ded0654667..684f08aad24 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -64,6 +64,8 @@ pub enum SystemFunction { ValuePlusargs, /// `$urandom` (18.13.1). Urandom, + /// Scope randomization of packed variables, without constraints (18.12). + ScopeRandomize, /// `$urandom_range` (18.13.2). UrandomRange, /// `$fopen` (21.3.1). @@ -86,7 +88,7 @@ impl SystemFunction { matches!(self, Self::Fopen | Self::TestPlusargs | Self::ValuePlusargs) } - /// The name, with its leading `$`. + /// The built-in name (`$` functions or `std::randomize`). pub const fn name(self) -> &'static str { match self { Self::Time => "$time", @@ -116,6 +118,7 @@ impl SystemFunction { Self::TestPlusargs => "$test$plusargs", Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", + Self::ScopeRandomize => "std::randomize", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", } @@ -154,6 +157,7 @@ impl SystemFunction { | Self::Urandom | Self::Fopen | Self::UrandomRange + | Self::ScopeRandomize ) } @@ -167,7 +171,8 @@ impl SystemFunction { /// Whether the call writes argument `position` back, as `$random(seed)` /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { - (matches!(self, Self::Random | Self::DistUniform) && position == 0) + self == Self::ScopeRandomize + || (matches!(self, Self::Random | Self::DistUniform) && position == 0) || (self == Self::ValuePlusargs && position == 1) } @@ -181,7 +186,8 @@ impl SystemFunction { | Self::Timeprecision | Self::Clog2 | Self::Countbits - | Self::Countones => Some((32, true)), + | Self::Countones + | Self::ScopeRandomize => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform | Self::TestPlusargs | Self::ValuePlusargs => { Some((32, true)) diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 306854de72f..30ec684be69 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6202,6 +6202,42 @@ fn unpacked_constant_function_bounds_survive_analysis_without_losing_the_contrac assert!(typecheck::eval_const_expr(range.right(), &HashMap::default()).is_none()); } +#[test] +fn scope_randomize_validates_variable_arguments() { + for call in [ + "randomize(value)", + "std::randomize(value)", + "std::randomize()", + ] { + let source = + format!("module Top; logic [2048:0] value; bit ok; initial ok = {call}; endmodule"); + analyze_source(&source, Path::new("randomize.sv")).unwrap(); + } + for (declaration, call) in [ + ("bit value;", "randomize(1)"), + ("bit value;", "randomize(value[0])"), + ("bit value;", "randomize({value})"), + ("bit value;", "randomize(.value(value))"), + ("bit value;", "randomize(value,)"), + ("localparam value = 1;", "randomize(value)"), + ("bit value[2];", "randomize(value)"), + ("wire value;", "randomize(value)"), + ("const bit value = 1;", "randomize(value)"), + ("enum bit [1:0] {A=0, B=3} value;", "randomize(value)"), + ( + "typedef enum bit [1:0] {A=0, B=3} E; E value;", + "std::randomize(value)", + ), + ("bit value;", "std::randomize(value) with {value == 1;}"), + ] { + let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule"); + assert!( + analyze_source(&source, Path::new("invalid_randomize.sv")).is_err(), + "accepted {source}" + ); + } +} + #[test] fn time_literal_delays_reject_scheduler_overflow() { let error = analyze_source( @@ -6226,3 +6262,22 @@ fn time_literal_delays_accept_numeric_separators() { assert_eq!(*ticks_per_unit, 1); assert!(matches!(amount, ir::Expr::Literal(value) if value == "64'd1000")); } + +#[test] +fn scope_randomize_respects_port_variable_kinds() { + for source in [ + "module Top(output logic [8:0] a, b); initial void'(std::randomize(a,b)); endmodule", + "module Top(output var bit a); initial void'(randomize(a)); endmodule", + ] { + analyze_source(source, Path::new("randomized_output.sv")).unwrap(); + } + for source in [ + "module Top(input var bit a); initial void'(randomize(a)); endmodule", + "module Top(output wire logic a); initial void'(randomize(a)); endmodule", + ] { + assert!( + analyze_source(source, Path::new("randomized_net.sv")).is_err(), + "accepted {source}" + ); + } +} diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index dff1230348c..961efccc184 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2743,3 +2743,85 @@ endmodule (assert_eq ok 1) (assert_eq covered 1) (assert_eq width 32)) + +(case scope_randomize_fills_arbitrary_packed_widths + (source "scope_randomize.sv" #" + module Top(input bit clk, output bit passed, output bit [7:0] coverage); + int count = 0; + bit success; + logic [0:0] v1, ones1 = '0, zeros1 = '1; + logic [4:0] v5, ones5 = '0, zeros5 = '1; + logic [15:0] v16, ones16 = '0, zeros16 = '1; + logic [31:0] v32, ones32 = '0, zeros32 = '1; + logic [63:0] v64, ones64 = '0, zeros64 = '1; + logic [980:0] v981, ones981 = '0, zeros981 = '1; + logic [1023:0] v1024, ones1024 = '0, zeros1024 = '1; + logic [2050:0] v2051, ones2051 = '0, zeros2051 = '1; + always @(posedge clk) begin + success = std::randomize(v1, v5, v16, v32, v64, v981, v1024, v2051); + if (!success) $fatal(1, "scope randomization failed"); + if ($isunknown(v1)) $fatal(1, "unknown randomized bits"); + ones1 |= v1; zeros1 &= v1; + if ($isunknown(v5)) $fatal(1, "unknown randomized bits"); + ones5 |= v5; zeros5 &= v5; + if ($isunknown(v16)) $fatal(1, "unknown randomized bits"); + ones16 |= v16; zeros16 &= v16; + if ($isunknown(v32)) $fatal(1, "unknown randomized bits"); + ones32 |= v32; zeros32 &= v32; + if ($isunknown(v64)) $fatal(1, "unknown randomized bits"); + ones64 |= v64; zeros64 &= v64; + if ($isunknown(v981)) $fatal(1, "unknown randomized bits"); + ones981 |= v981; zeros981 &= v981; + if ($isunknown(v1024)) $fatal(1, "unknown randomized bits"); + ones1024 |= v1024; zeros1024 &= v1024; + if ($isunknown(v2051)) $fatal(1, "unknown randomized bits"); + ones2051 |= v2051; zeros2051 &= v2051; + count++; + if (count == 64) begin + coverage[0] = (&ones1) && !(|zeros1); + coverage[1] = (&ones5) && !(|zeros5); + coverage[2] = (&ones16) && !(|zeros16); + coverage[3] = (&ones32) && !(|zeros32); + coverage[4] = (&ones64) && !(|zeros64); + coverage[5] = (&ones981) && !(|zeros981); + coverage[6] = (&ones1024) && !(|zeros1024); + coverage[7] = (&ones2051) && !(|zeros2051); + passed = &coverage; + end + end + endmodule + "#) + (top Top) + (for draw (range 0 64) (tick clk)) + (assert_eq coverage 255 "coverage by width: 1,5,16,32,64,981,1024,2051") + (assert_eq passed 1 "every bit, including high bits and partial words, varied")) + +(case scope_randomize_obeys_control_flow_and_statement_order + (source "scope_randomize_order.sv" #" + module Top(output int status); + bit a = 0, b = 1; + bit ok; + function automatic bit draw; + bit local_value; + return std::randomize(local_value); + endfunction + initial begin + if (0 && randomize(a)) $fatal(1, "short circuit"); + if (1 || randomize(b)) status = 1; + if (a !== 0 || b !== 1) $fatal(1, "short circuited randomize wrote its argument"); + if ($bits(std::randomize(a)) != 32) $fatal(1, "randomize return width"); + ok = randomize(); + if (!ok || !draw()) $fatal(1, "empty or function call failed"); + void'(std::randomize(a, b)); + std::randomize(a); + randomize(b); + if ($isunknown({a, b})) $fatal(1, "unknown results"); + status = 2; + #1; + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (assert_eq status 2)) diff --git a/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json new file mode 100644 index 00000000000..a533600b07c --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_randomize_icarus.json @@ -0,0 +1,31 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "name": "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "category": "Functions", + "expectation": "Simulation", + "status": "compile_error", + "phase": "compile", + "detail": "source_0.sv:14: syntax error\nsource_0.sv:14: error: Malformed statement", + "stronger_than_sv": false, + "tags": [], + "tag_reasons": {} + }, + { + "name": "system_functions::scope_randomize_obeys_control_flow_and_statement_order", + "category": "Functions", + "expectation": "Simulation", + "status": "compile_error", + "phase": "compile", + "detail": "source_0.sv:7: syntax error\nsource_0.sv:7: error: Malformed statement\nsource_0.sv:13: syntax error\nsource_0.sv:13: error: Malformed statement\nsource_0.sv:13: error: Malformed conditional expression.\nsource_0.sv:16: syntax error\nsource_0.sv:16: error: Malformed statement\nsource_0.sv:17: syntax error\nsource_0.sv:17: error: Malformed statement", + "stronger_than_sv": false, + "tags": [], + "tag_reasons": {} + } + ], + "note": "Focused unexcluded compile failures of the two new scope randomize cases; native, Cranelift, Wasm and Verilator execute these cases." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index a37381f1e66..341ab3ef479 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1529,6 +1529,52 @@ "observed_version": "Icarus 13.0", "reason": "Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks." } + }, + { + "category": "Functions", + "detail": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "system_functions::scope_randomize_obeys_control_flow_and_statement_order", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 40f8787d4b0..73ed891d85f 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1485,5 +1485,23 @@ "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals" ] } + }, + { + "id": "sv_icarus_scope_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects std::randomize calls with syntax errors before executing the testbench. IEEE 1800-2023 18.12 defines scope randomization of variables without requiring a class. Verilator executes both the arbitrary-width and control-flow regressions successfully.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "system_functions::scope_randomize_fills_arbitrary_packed_widths", + "system_functions::scope_randomize_obeys_control_flow_and_statement_order" + ] + } } ] diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 4a0960a7a7c..ea78f60de55 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -160,6 +160,38 @@ sv_backends! { assert!(sim.drain_runtime_events().is_empty()); } + fn scope_randomize_fills_arbitrary_packed_widths(sim) { + @case "system_functions::scope_randomize_fills_arbitrary_packed_widths"; + } + + fn scope_randomize_obeys_control_flow_and_statement_order(sim) { + @case "system_functions::scope_randomize_obeys_control_flow_and_statement_order"; + } + + fn scope_randomize_preserves_four_state_storage_and_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic signed [2048:0] value); + always @(posedge clk) void'(std::randomize(value)); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("randomize_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + let saved = sim.checkpoint().unwrap(); + sim.tick(clk).unwrap(); + let (first, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + assert!(first.bits() > 2000, "upper words must receive random bits"); + sim.tick(clk).unwrap(); + let second = sim.get(value); + assert_ne!(first, second); + sim.restore(&saved).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), first); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), second); + } + fn urandom_extends_signed_seed_values(sim) { @case "system_functions::urandom_extends_signed_seed_values"; } @@ -3050,3 +3082,40 @@ sv_backends! { assert_eq!(warnings[0].1, source_line(&source, "$readmemh")); } } + +#[test] +fn scope_randomize_survives_all_optimization_levels() { + let source = r#" + module Top(input bit clk, output logic [980:0] value); + always @(posedge clk) void'(std::randomize(value)); + endmodule + "#; + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + for four_state in [false, true] { + let mut sim = Simulator::from_sv_sources( + vec![(source, Path::new("randomize_optimization.sv"))], + "Top", + ) + .opt_level(level) + .four_state(four_state) + .build_native() + .unwrap(); + let value = sim.signal("value"); + let clk = sim.event("clk"); + let checkpoint = sim.checkpoint().unwrap(); + sim.tick(clk).unwrap(); + let first = sim.get(value); + assert!(first.bits() > 64, "{level:?} four_state={four_state}"); + if four_state { + assert_eq!(sim.get_four_state(value).1, 0u8.into()); + } + sim.restore(&checkpoint).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), first, "{level:?} four_state={four_state}"); + } + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index a60253953f4..0d578221e67 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -61,6 +61,19 @@ until shared argument storage and its change notifications are supported. Event expressions have the same restrictions as waits written directly in a process. +### Scope randomization + +`randomize(a, b)` and `std::randomize(a, b)` support unconstrained whole packed +variables, including signed vectors and packed structures, at any supported +width. Each call fills every word with random zero/one bits and returns the +signed `int` success value `1`. An empty argument list succeeds without writing a +variable or advancing the random stream. Calls follow procedural statement order +and short-circuit evaluation, and use the calling process's persistent random +stream (IEEE 1800-2023 18.12). + +Constraints (`with`), class methods, enum variables, unpacked arrays, nets, +constants, selects and concatenation arguments are unsupported and rejected. + ### Time literal delays Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 131ffb7deb5..1423954aed7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -56,6 +56,17 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task 共有ストレージと変更通知に対応するまで拒否します。 イベント式の制約は、プロセスに直接記述するイベント待ちと同じです。 +### スコープ変数の乱数化 + +`randomize(a, b)` と `std::randomize(a, b)` は、制約なしで packed 変数全体を乱数化します。 +符号付きベクタと packed struct を含め、Celox が扱える幅で各ワードに0/1の乱数を設定し、 +成功値の1(signed `int`)を返します。引数なしの場合は変数や乱数列を変更せず成功します。 +プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います +(IEEE 1800-2023 18.12)。 + +`with` 制約、class メソッド、enum 変数、unpacked 配列、net、定数、 +select・連結式の引数は未対応として拒否します。 + ### 時間リテラルによる遅延 遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に