From 490502bb30f7d49f82042d0bdbd9a04fea87e8b3 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 12:52:43 +0900 Subject: [PATCH] feat(sv)!: support scope enum randomization Support scalar enums in randomize(e) and std::randomize(e), selecting only declared values with unbiased rejection sampling from the process RNG. Preserve enum domains through aliases and local variables, allow mixed enum/integer arguments, and retain short-circuit evaluation and checkpoint replay. Add shared domain and evaluation-order regressions plus Celox checkpoint and forced-rejection tests. Document the observed Icarus 13.0 compile limitation and Verilator 5.052 enum-domain mismatch with narrowly scoped exclusions and reproduction evidence. Validation: analyzer 796 and frontend 4 unit tests; 708 system-function regressions; 4 forced-rejection backend tests; retained-report checks (3); NAPI build and JS tests (432); affected-crate Clippy, cargo fmt and diff checks. Both new shared cases were exercised with Icarus and Verilator; their failures are retained as the tool limitations described above. BREAKING CHANGE: The public celox-sv-analyzer SystemFunction enum gains ScopeRandomizeEnum; downstream exhaustive matches must handle this variant. Change-Id: I2e07aafc25d024b216ce17760324265e3719055d --- crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-frontend-sv/src/lowering/ff.rs | 67 +++++++++++++++++++ crates/celox-sv-analyzer/src/ast.rs | 1 + .../celox-sv-analyzer/src/ast/dimensions.rs | 11 ++- .../src/ast/expression_binding/direct.rs | 59 +++++++++++++--- .../src/ast/packed_structs/selects.rs | 1 + .../src/ast/parameters/skipped.rs | 1 + .../src/ast/patterns/binding.rs | 2 + .../celox-sv-analyzer/src/ast/procedural.rs | 3 +- .../celox-sv-analyzer/src/system_functions.rs | 8 ++- crates/celox-sv-analyzer/src/tests.rs | 9 ++- crates/celox-test-suite/LIMITATIONS.md | 11 +++ .../src/sv/cases/system_functions.vtest | 60 +++++++++++++++++ .../sv_scope_enum_randomize_icarus.json | 33 +++++++++ .../sv_scope_enum_randomize_verilator.json | 33 +++++++++ .../sv/icarus/system_functions.json | 46 +++++++++++++ .../verification/sv/limitations.json | 36 ++++++++++ .../sv/verilator/system_functions.json | 46 +++++++++++++ .../systemverilog/system_functions.rs | 63 +++++++++++++++++ docs/guide/systemverilog-reference.md | 7 +- docs/ja/guide/systemverilog-reference.md | 6 +- 21 files changed, 485 insertions(+), 19 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c44bd3b34c1..ccd2bc7faf5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -6488,6 +6488,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::UrandomRange | SystemFunction::Fopen | SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Fread | SystemFunction::Ftell | SystemFunction::Fseek diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b77cd77394d..ed885a57cd7 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -259,6 +259,7 @@ impl<'p, 'a> Ff<'p, 'a> { use sv::ir::SystemFunction; match function { SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Urandom | SystemFunction::UrandomRange => { self.urandom_state(); @@ -903,6 +904,11 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.fopen(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomizeEnum), + args, + .. + } => self.randomize_enum(args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize), args, @@ -1412,6 +1418,67 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// Randomize one scalar enum from the process stream. Arguments after the + /// writable destination are its declared values, supplied by the analyzer. + fn randomize_enum( + &mut self, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr}; + let Some(Some(Expr::Ident(name))) = args.first() else { + return Err(unsupported("scope enum randomize variable")); + }; + let values = args[1..] + .iter() + .map(Option::as_ref) + .collect::>>() + .filter(|values| !values.is_empty()) + .ok_or_else(|| unsupported("scope enum randomize domain"))?; + let count = u32::try_from(values.len()) + .map_err(|_| unsupported("scope enum randomize domain size"))?; + let threshold = count.wrapping_neg() % count; + let draw_block = self.b.new_block(); + let accepted = self.b.new_block(); + self.jump(draw_block); + self.b.switch_to_block(draw_block); + let draw = self.randomize_word()?; + let rejected = Expr::Binary { + left: Box::new(draw.clone()), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("32'd{threshold}"))), + }; + let cond = self.eval_truth(&rejected)?.0; + self.b.seal_block(SIRTerminator::Branch { + cond, + true_block: (draw_block, Vec::new()), + false_block: (accepted, Vec::new()), + }); + self.b.switch_to_block(accepted); + let index = self.hidden( + "enum_index", + &Expr::Binary { + left: Box::new(draw), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("32'd{count}"))), + }, + false, + )?; + let mut value = (*values.last().unwrap()).clone(); + for (position, member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(index.clone()), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("32'd{position}"))), + }), + then_expr: Box::new((*member).clone()), + else_expr: Box::new(value), + }; + } + self.assign(&sv::ir::LValue::Ident(name.clone()), &value)?; + Ok(Expr::Literal("32'sd1".into())) + } + /// 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. diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index ca7fdc2114e..a33c623e978 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2731,6 +2731,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { randomizable: bool, + enum_values: Option>, real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 7fd131f1d42..a5f17b392a4 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { - randomizable: !port.r#type().is_enum && port.randomizable, + randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + && port.randomizable, + enum_values: port.r#type().enum_values.clone(), real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(port.r#type().kind(), TypeKind::String), class: port.r#type().class().map(str::to_owned), @@ -156,7 +158,10 @@ 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, + randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + && !signal.is_net() + && !signal.is_const, + enum_values: signal.r#type().enum_values.clone(), real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(signal.r#type().kind(), TypeKind::String), class: signal.r#type().class().map(str::to_owned), @@ -365,6 +370,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.enum_values = existing.enum_values.clone(); shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -533,6 +539,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP parameter.name.clone(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, 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 17b50ff3c53..6f80370ce22 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -216,6 +216,7 @@ pub(in crate::ast) fn cast_target_native( } enum Finish { + ScopeRandomize(Vec>>), Unary(String), Binary(String), Mux, @@ -499,6 +500,7 @@ pub(in crate::ast) fn bind_value( } let actuals = args.iter().filter_map(|arg| arg.value).collect::>(); + let mut domains = Vec::with_capacity(actuals.len()); for &actual in &actuals { let ExprKind::Name(name) = &native.expression(actual).kind else { return Err(unsupported( @@ -509,11 +511,17 @@ pub(in crate::ast) fn bind_value( let shape = dimensions .get(&name) .ok_or_else(|| unsupported("scope randomize variable"))?; - if !shape.unpacked.is_empty() || !shape.randomizable { + if !shape.unpacked.is_empty() + || !shape.randomizable + || shape.real + || shape.string + || shape.class.is_some() + { return Err(unsupported( - "scope randomize requires a packed non-enum variable", + "scope randomize requires a packed variable with a supported enum domain", )); } + domains.push(shape.enum_values.clone()); if !expressions::query_actual_is_writable( &Expr::Ident(name), dimensions, @@ -524,12 +532,7 @@ pub(in crate::ast) fn bind_value( } } jobs.push(Job::Finish( - Finish::Call { - name: "std::randomize".into(), - args: actuals.iter().copied().map(Some).collect(), - order: Vec::new(), - system: Some(SystemFunction::ScopeRandomize), - }, + Finish::ScopeRandomize(domains), actuals.len(), scope.clone(), )); @@ -930,6 +933,46 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } + Finish::ScopeRandomize(domains) => { + // Preserve the original call when no enum is present. + // Every scalar operation succeeds and returns signed int 1; + // bitwise AND preserves that type and evaluates all operands. + if domains.iter().all(Option::is_none) { + Expr::Call { + callee: Callee::System(SystemFunction::ScopeRandomize), + args: operands.into_iter().map(Some).collect(), + arg_order: Vec::new(), + } + } else { + let mut calls = + operands.into_iter().zip(domains).map(|(operand, domain)| { + let mut args = vec![Some(operand)]; + let function = if let Some(values) = domain { + args.extend(values.into_iter().map(|value| { + Some(Expr::Literal(format_typed_parameter_literal( + value, + 64, + value < 0, + ))) + })); + SystemFunction::ScopeRandomizeEnum + } else { + SystemFunction::ScopeRandomize + }; + Expr::Call { + callee: Callee::System(function), + args, + arg_order: Vec::new(), + } + }); + let first = calls.next().ok_or_else(disagreement)?; + calls.fold(first, |left, right| Expr::Binary { + left: Box::new(left), + op: BinaryOp::BitAnd, + right: Box::new(right), + }) + } + } Finish::ObjectLoad(property) => { let handle = operands.pop().ok_or_else(disagreement)?; objects::load(&property, handle) 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 26ba51430bd..382384aad5d 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - name.to_string(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 3072f78cc24..1184772f60f 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -502,6 +502,7 @@ fn pattern_items( count as i128 - 1, VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 0253bcdeaec..79d17825612 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -137,6 +137,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, + enum_values: None, real: false, string: false, class: None, @@ -244,6 +245,7 @@ fn select<'a>( .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 47aeab7cdd8..11830353e22 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -73,7 +73,8 @@ 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, + randomizable: !r#type.is_enum || r#type.enum_values.is_some(), + enum_values: r#type.enum_values.clone(), real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), class: r#type.class().map(str::to_owned), diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 3fda772fed5..dfdf49d219d 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -103,6 +103,8 @@ pub enum SystemFunction { Urandom, /// Scope randomization of packed variables, without constraints (18.12). ScopeRandomize, + /// Internal scalar enum randomization: destination followed by legal values. + ScopeRandomizeEnum, /// `$urandom_range` (18.13.2). UrandomRange, /// `$fopen` (21.3.1). @@ -280,6 +282,7 @@ impl SystemFunction { Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", Self::ScopeRandomize => "std::randomize", + Self::ScopeRandomizeEnum => "$__celox_randomize_enum", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", Self::Fread => "$fread", @@ -343,6 +346,7 @@ impl SystemFunction { | Self::Fscanf | Self::UrandomRange | Self::ScopeRandomize + | Self::ScopeRandomizeEnum ) } @@ -357,6 +361,7 @@ impl SystemFunction { /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { self == Self::ScopeRandomize + || (self == Self::ScopeRandomizeEnum && position == 0) || (matches!( self, Self::Random @@ -406,7 +411,8 @@ impl SystemFunction { | Self::Clog2 | Self::Countbits | Self::Countones - | Self::ScopeRandomize => Some((32, true)), + | Self::ScopeRandomize + | Self::ScopeRandomizeEnum => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 81a99a92a65..4314adf6bae 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6303,11 +6303,10 @@ fn scope_randomize_validates_variable_arguments() { ("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)", - ), + ("real value;", "randomize(value)"), + ("string value;", "randomize(value)"), + ("class C; endclass C value;", "randomize(value)"), + ("enum bit [1:0] {A=3, B} value;", "randomize(value)"), ("bit value;", "std::randomize(value) with {value == 1;}"), ] { let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule"); diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 8e44294ee77..97530f68a62 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -709,6 +709,17 @@ IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded; [the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json) retains its unchanged domain assertion. +Scope enum randomization has two narrow tool exclusions for +`system_functions::scope_randomize_enum_values` and +`system_functions::scope_randomize_enum_order`. Icarus 13.0 rejects scope +randomization calls (`sv_icarus_scope_enum_randomize`; +[compile diagnostics](verification/repros/sv_scope_enum_randomize_icarus.json)). +Verilator 5.052 generates `basicStdRandomization` calls using only integer widths, +without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_randomize`; +[mismatch evidence](verification/repros/sv_scope_enum_randomize_verilator.json)). +IEEE 1800-2023 18.3 and 18.12 require the declared enum domain. The shared +assertions remain unchanged, including the direct-enum case without an alias. + ## SystemVerilog packed unions The `unions` shared group covers hard and soft packed untagged unions. With 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 0990ccf7e9f..2463a162fa5 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2892,3 +2892,63 @@ endmodule (top Top) (run_to_finish) (assert_eq status 2)) + +(case scope_randomize_enum_values + (source "scope_enum.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + typedef enum logic [63:0] {ALL='1} wide_t; + alias_t value; + wide_t wide; + int plain; + int seen; + function automatic int local_random(); + alias_t local_value; + if (randomize(local_value) != 1) return 0; + return local_value == NEG || local_value == MID || local_value == HIGH; + endfunction + initial begin + repeat (128) begin + if (std::randomize(value, plain, wide) != 1) errors++; + case (value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (wide != 64'hffffffffffffffff) errors++; + if (local_random() != 1) errors++; + end + if (seen != 7) errors++; + if ($bits(std::randomize(value)) != 32) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + + +(case scope_randomize_enum_order + (source "scope_enum_order.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [7:0] {A=3, B=19, C=97} value_t; + value_t value; + int plain; + int result; + initial begin + value = A; plain = 17; + result = 0 && std::randomize(value, plain); + result = 1 || randomize(value); + if (value != A || plain != 17) errors++; + repeat (64) begin + result = (std::randomize(value, plain) == 1) + && (value == A || value == B || value == C); + if (result != 1) errors++; + if (randomize(value) != 1 || (value != A && value != B && value != C)) errors++; + end + 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_scope_enum_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json new file mode 100644 index 00000000000..b262a613b51 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:13: syntax error\n/source_0.sv:14: error: Malformed statement\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Malformed statement\n/source_0.sv:17: error: Malformed conditional expression.\n/source_0.sv:28: syntax error\n/source_0.sv:28: error: Malformed statement\n/source_0.sv:28: error: Malformed conditional expression.\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json new file mode 100644 index 00000000000..eabf478fa92 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_order at 2887:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_values at 2862:46: assert_eq errors: expected 0x0, got 0x181", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} 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 eacfdc15b69..524ae2cac27 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1619,6 +1619,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index f4839f22972..76dc9455d36 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2247,5 +2247,41 @@ "class::randomization_enum_alias" ] } + }, + { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } + }, + { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index 697545e7c70..93f263f8b17 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -920,6 +920,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 280d9aebc2f..e8d26fe9cd3 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -3226,3 +3226,66 @@ fn time_format_rejects_string_operands() { ); } } + +sv_backends! { + fn scope_randomize_enum_values(sim) { @case "system_functions::scope_randomize_enum_values"; } + fn scope_randomize_enum_order(sim) { @case "system_functions::scope_randomize_enum_order"; } +} + +sv_backends! { + fn scope_randomize_enum_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic [63:0] value); + typedef enum logic signed [63:0] {NEG=-7, POS=2, ALL='1} E; + E e; + always @(posedge clk) begin + void'(std::randomize(e)); + value = e; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("enum_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + let saved = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..16 { + sim.tick(clk).unwrap(); + let (bits, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + expected.push(bits); + } + assert!(expected.windows(2).any(|pair| pair[0] != pair[1])); + sim.restore(&saved).unwrap(); + for bits in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get_four_state(value), (bits, 0u8.into())); + } + } +} + +sv_backends! { + fn scope_randomize_enum_retries_rejected_draw(sim) { + @setup { let source = r#" + module Top(output bit done, output int unsigned next); + typedef enum bit [7:0] {A=3, B=19, C=97} E; + E e; + int ignored; + initial begin + // The process LCG reaches zero on the next draw. Its + // bijective mixer preserves zero, rejected for 3 choices. + ignored = $urandom(32'd4150723358); + ignored = std::randomize(e); + next = $urandom(); + done = 1; + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("enum_rejection.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + // Rejection consumes zero, then 1013904223, leaving the following + // LCG value for the explicit $urandom call. + assert_eq!(sim.get(sim.signal("next")), 1196435762u32.into()); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index c765062dd74..4e45062ed5c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -104,7 +104,12 @@ 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`), enum variables, unpacked arrays, nets, +Scalar enums up to 64 bits are also supported: randomization selects only their +known declared values, including typedef aliases and signed or sparse values. +The process random stream, short-circuit behavior, and checkpoint state apply +to enums as well. Mixed enum and integer argument lists are supported. + +Constraints (`with`), enums with unsupported or unresolved domains, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 46185c6b8c8..29a9a0e11d3 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -93,7 +93,11 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います (IEEE 1800-2023 18.12)。 -`with` 制約、enum 変数、unpacked 配列、net、定数、 +64ビット以下のスカラーenumにも対応し、既知の宣言値だけから抽選します。 +型エイリアス、負数、飛び飛びの値、整数との引数混在を扱えます。enumにもプロセス単位の +乱数列・短絡評価・チェックポイント復元が適用されます。 + +`with` 制約、値域が未対応または未解決のenum、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 ### クラスの乱数化