diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index ac966cb01e3..9f2026bb1c5 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -60,6 +60,14 @@ 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::RandomCyclic { offset, count } => { + let object = self.handle(&args[0])?; + let count = self.constant64(u64::from(*count)); + self.heap_call( + ops::encode(ops::OBJECT_RANDOM_CYCLIC, u64::from(*offset)), + &[object, count], + ) + } ObjectOp::Random | ObjectOp::Check(_) | ObjectOp::ModeGet(..) @@ -121,6 +129,7 @@ impl Ff<'_, '_> { ObjectOp::Store(_) | ObjectOp::ClassOf | ObjectOp::Random + | ObjectOp::RandomCyclic { .. } | ObjectOp::Seed | ObjectOp::Check(_) | ObjectOp::ModeGet(..) diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index b7d294c8964..bace65434d6 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -17,6 +17,8 @@ pub(crate) struct Object { random_state: u64, random_modes: RandomModes, saved_random_modes: Vec, + /// Remaining domain indices for each randc property, keyed by byte offset. + random_cycles: fxhash::FxHashMap>, bytes: Box<[u8]>, /// Byte offsets of the handle properties, with what they refer to. pub(crate) handles: Vec<(u32, HandleKind)>, @@ -30,6 +32,14 @@ struct RandomModes { } impl Object { + fn random(&mut self) -> u64 { + self.random_state = self.random_state.wrapping_add(0x9e3779b97f4a7c15); + let mut word = self.random_state; + word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); + word ^ (word >> 31) + } + pub(crate) fn size(&self) -> usize { self.bytes.len() } @@ -71,6 +81,7 @@ impl Heap { random_state: 0, random_modes: RandomModes::default(), saved_random_modes: Vec::new(), + random_cycles: Default::default(), bytes: vec![0; size].into(), handles: Vec::new(), }, @@ -92,11 +103,36 @@ impl Heap { let Some(object) = self.object_mut(handle) else { return 0; }; - object.random_state = object.random_state.wrapping_add(0x9e3779b97f4a7c15); - let mut word = object.random_state; - word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); - word ^ (word >> 31) + object.random() + } + + /// Draw without replacement from an immutable domain (IEEE 1800-2023 + /// 18.4.2). Lazy Fisher-Yates uses bounded storage and uniform draws. + /// Seeding changes the RNG, but does not discard an unfinished cycle. + pub(crate) fn random_cyclic_object(&mut self, handle: Handle, offset: u32, count: u64) -> u64 { + assert!((1..=256).contains(&count), "invalid randc domain size"); + let Some(object) = self.object_mut(handle) else { + return 0; + }; + let remaining = object.random_cycles.entry(offset).or_default(); + if remaining.is_empty() { + remaining.extend(0..count as u16); + } + let count = remaining.len() as u64; + let threshold = count.wrapping_neg() % count; + let index = loop { + let draw = object.random(); + if draw >= threshold { + break (draw % count) as usize; + } + }; + u64::from( + object + .random_cycles + .get_mut(&offset) + .unwrap() + .swap_remove(index), + ) } /// Random properties start enabled. Modes are shared by aliases of an @@ -287,6 +323,40 @@ mod tests { mod random_tests { use super::*; + #[test] + fn cyclic_domains_survive_reseeding_and_checkpoint_restore() { + for count in [1, 3, 256] { + let mut heap = Heap::new(); + let object = heap.new_object(1, 2); + let other = heap.new_object(1, 2); + heap.seed_object(object, 12); + heap.seed_object(other, 12); + let first = heap.random_cyclic_object(object, 0, count); + assert_eq!(first, heap.random_cyclic_object(other, 0, count)); + let mut saved = heap.clone(); + let mut seen = crate::HashSet::from_iter([first]); + for _ in 1..count { + // Seeding does not make consumed values eligible again. + heap.seed_object(object, 19); + saved.seed_object(object, 19); + let value = heap.random_cyclic_object(object, 0, count); + assert_eq!(value, saved.random_cyclic_object(object, 0, count)); + assert!(seen.insert(value)); + } + for offset in [0, 1, 0] { + let seen: crate::HashSet<_> = (0..count) + .map(|_| heap.random_cyclic_object(object, offset, count)) + .collect(); + assert_eq!(seen.len(), count as usize); + assert!(seen.iter().all(|&value| value < count)); + } + assert_eq!(heap.take_fault(), None); + } + let mut heap = Heap::new(); + assert_eq!(heap.random_cyclic_object(NULL, 0, 3), 0); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + } + #[test] fn random_streams_are_independent_and_checkpointed() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 9c38b6a00e0..d0485579576 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -79,6 +79,8 @@ pub const OBJECT_MODE_POP: u64 = 59; 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; +/// Draw a randc domain index; parameter is the property offset, b its domain size. +pub const OBJECT_RANDOM_CYCLIC: u64 = 62; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -187,6 +189,7 @@ impl Heap { } OBJECT_CLASS => self.class_of(a as Handle).into(), OBJECT_RANDOM => self.random_object(a as Handle), + OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b), OBJECT_SEED => { self.seed_object(a as Handle, b as u32); 0 diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 4b92fe3940d..467292a8c8e 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -34,6 +34,25 @@ pub(super) struct Property { pub initializer: Option, } +impl Property { + pub fn cyclic_domain_size(&self) -> Option { + if self.field.handle.is_some() { + return None; + } + if self.r#type.is_enum { + self.r#type.enum_values.as_ref().and_then(|values| { + (1..=256) + .contains(&values.len()) + .then_some(values.len() as u16) + }) + } else { + (1..=8) + .contains(&self.field.width) + .then(|| 1u16 << self.field.width) + } + } +} + /// A static property of a class: one variable of the module that declares /// the class, shared by all of its objects (IEEE 1800-2023 8.9). #[derive(Debug, Clone, PartialEq, Eq)] @@ -119,10 +138,12 @@ impl Class { return Err(unsupported("class randomize with constraints")); } for property in &self.properties { - if property.randc { - return Err(unsupported("class randomize with randc properties")); + if property.randc && property.cyclic_domain_size().is_none() { + return Err(unsupported( + "randc requires a 1-8 bit integer or an enum with at most 256 declared values", + )); } - if property.rand + if (property.rand || property.randc) && (property.field.handle.is_some() || (property.r#type.is_enum && property.r#type.enum_values.is_none())) { 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 26d4e676a93..1c91118b142 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -557,10 +557,10 @@ pub(super) fn random_selection( } if property.field.handle.is_some() || (property.r#type.is_enum && property.r#type.enum_values.is_none()) - || property.randc + || (property.randc && property.cyclic_domain_size().is_none()) { return Err(unsupported( - "randomize arguments require integral, non-randc properties with a supported enum domain", + "randomize arguments require integral properties with a supported enum domain", )); } bits[index + 1] = '1'; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 597458d6c73..f92f50ec209 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -120,7 +120,10 @@ pub(super) fn lower( right: Box::new(Expr::Literal("1'b1".into())), }; select.push(Stmt::Eval(classes::object_call( - ObjectOp::ModeSelect(property.field.offset, property.rand), + ObjectOp::ModeSelect( + property.field.offset, + property.rand || property.randc, + ), vec![Expr::Ident(this.clone()), selected], ))); } @@ -146,7 +149,10 @@ pub(super) fn lower( }), op: BinaryOp::LogicAnd, right: Box::new(classes::object_call( - ObjectOp::ModeGet(property.field.offset, property.rand), + ObjectOp::ModeGet( + property.field.offset, + property.rand || property.randc, + ), vec![Expr::Ident(this.clone())], )), }, @@ -264,36 +270,56 @@ fn random_property( property: &classes::Property, this: &str, ) -> Vec { - let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]); + let random = || { + let op = if property.randc { + ObjectOp::RandomCyclic { + offset: property.field.offset, + count: property + .cyclic_domain_size() + .expect("validated randc domain"), + } + } else { + ObjectOp::Random + }; + classes::object_call(op, vec![Expr::Ident(this.into())]) + }; let mut body = Vec::new(); let value = if let Some(values) = &property.r#type.enum_values { let count = values.len() as u64; let threshold = count.wrapping_neg() % count; let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); - body.push(Stmt::Loop { - kind: LoopKind::DoWhile, - init: Vec::new(), - condition: Some(Expr::Binary { - left: Box::new(Expr::Ident(draw.clone())), - op: BinaryOp::Lt, - right: Box::new(Expr::Literal(format!("64'd{threshold}"))), - }), - step: Vec::new(), - body: vec![Stmt::Assign { + if property.randc { + body.push(Stmt::Assign { lhs: LValue::Ident(draw.clone()), rhs: random(), nonblocking: false, - }], - }); - body.push(Stmt::Assign { - lhs: LValue::Ident(draw.clone()), - rhs: Expr::Binary { - left: Box::new(Expr::Ident(draw.clone())), - op: BinaryOp::Mod, - right: Box::new(Expr::Literal(format!("64'd{count}"))), - }, - nonblocking: false, - }); + }); + } else { + body.push(Stmt::Loop { + kind: LoopKind::DoWhile, + init: Vec::new(), + condition: Some(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("64'd{threshold}"))), + }), + step: Vec::new(), + body: vec![Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: random(), + nonblocking: false, + }], + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("64'd{count}"))), + }, + nonblocking: false, + }); + } let literal = |value| { Expr::Literal(format_typed_parameter_literal( value, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f8f63e9284b..e496c9871eb 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -793,6 +793,11 @@ pub enum ObjectOp { ClassOf, /// Advance the object's independent RNG, returning 64 random bits. Random, + /// Draw a domain index without replacement for the property at `offset`. + RandomCyclic { + offset: u32, + count: u16, + }, /// Seed the object's RNG from the second argument. Seed, /// Validate a receiver; a nonzero class also rejects unsupported dynamic @@ -811,7 +816,7 @@ impl ObjectOp { /// The width and signedness of the result. pub fn result_type(&self) -> (usize, bool) { match self { - Self::Random => (64, false), + Self::Random | Self::RandomCyclic { .. } => (64, false), Self::Seed | Self::Check(_) | Self::ModeSet(_) @@ -834,6 +839,7 @@ impl fmt::Display for ObjectOp { Self::Store(_) => "property write", Self::ClassOf => "class query", Self::Random => "object random bits", + Self::RandomCyclic { .. } => "object random cyclic index", Self::Seed => "object random seed", Self::Check(_) => "object receiver check", Self::ModeGet(..) => "random mode query", diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index bc7669ccad1..c3c271322e4 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6592,7 +6592,7 @@ fn class_randomize_rejects_unsupported_semantics() { "c.randomize()", "constraints", ), - ("randc bit [1:0] x;", "c.randomize()", "randc"), + ("randc bit [8:0] x;", "c.randomize()", "randc"), ("rand int x;", "c.srandom()", "argument"), ("rand int x;", "c.srandom(1, 2)", "arguments"), ( @@ -6799,3 +6799,26 @@ endmodule assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), None); } } + +#[test] +fn class_randc_checks_domain_limits() { + let values = (0..257) + .map(|i| format!("V{i}={i}")) + .collect::>() + .join(","); + for (declarations, members) in [ + (String::new(), "randc bit [8:0] x;"), + ( + format!("typedef enum bit [15:0] {{{values}}} E;"), + "randc E x;", + ), + ] { + for call in ["c.randomize()", "c.randomize(x)"] { + let source = format!( + "module Top; {declarations} class C; {members} endclass C c; initial begin c=new; void'({call}); end endmodule" + ); + let error = analyze_source(&source, Path::new("randc_limits.sv")).unwrap_err(); + assert!(error.to_string().contains("randc"), "{error}"); + } + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 94290b6f9ef..574be054d9b 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -725,6 +725,14 @@ without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_r 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. +Cyclic randomization (IEEE 1800-2023 18.4.2) retains narrow external +exclusions: Icarus 13.0 cannot elaborate the three `randomization_cyclic_*` +cases ([diagnostics](verification/repros/sv_randc_icarus.json)). Verilator +5.052 passes the integer and direct-enum domain case, but emits duplicate +`srandom` declarations for the inheritance/control case and draws undeclared +values for an enum typedef alias ([evidence](verification/repros/sv_randc_verilator.json)). +The original cycle, mode and domain assertions remain unchanged. + ## 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/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 06c4057355b..15ee5508f33 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1067,3 +1067,147 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_domains + (source "randc_domains.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [63:0] {NEG=-7, MID=2, HIGH=91} E; + typedef enum bit [63:0] {ONLY='1} Single; + class C; + randc bit [7:0] byte_value; + randc bit signed [1:0] signed_value; + randc E value; + randc Single single_value; + rand bit [7:0] ordinary; + endclass + C c; + bit [255:0] seen; + bit [3:0] signed_seen; + bit [2:0] enum_seen; + int index; + initial begin + c = new; + repeat (3) begin + seen = 0; + repeat (256) begin + if (!c.randomize(byte_value, single_value, ordinary)) errors++; + if (seen[c.byte_value]) errors++; + seen[c.byte_value] = 1; + if (c.single_value != 64'hffffffffffffffff) errors++; + end + if (seen != '1) errors++; + end + repeat (8) begin + signed_seen = 0; + repeat (4) begin + if (!c.randomize(signed_value)) errors++; + if (c.signed_value < -2 || c.signed_value > 1) errors++; + index = c.signed_value + 2; + if (signed_seen[index]) errors++; + signed_seen[index] = 1; + end + if (signed_seen != 15) errors++; + enum_seen = 0; + repeat (3) begin + if (!c.randomize(value)) errors++; + case (c.value) + NEG: index=0; + MID: index=1; + HIGH: index=2; + default: begin errors++; index=0; end + endcase + if (enum_seen[index]) errors++; + enum_seen[index] = 1; + end + if (enum_seen != 7) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_controls + (source "randc_controls.sv" #" +module Top(output bit done, output int errors); + class Base; + randc bit [2:0] x; + int calls; + function void post_randomize(); calls++; endfunction + endclass + class Derived extends Base; + randc bit [1:0] y; + endclass + Derived a, alias_a, b; + Base base_a; + bit [7:0] seen; + bit [3:0] seen_y; + bit [2:0] saved_x; + bit [1:0] saved_y; + initial begin + a = new; b = new; alias_a = a; base_a = a; + a.srandom(27); b.srandom(27); + if (!a.x.rand_mode() || !a.y.rand_mode()) errors++; + repeat (8) begin + if (!base_a.randomize() || !b.randomize()) errors++; + if (a.x != b.x || a.y != b.y) errors++; + if (seen[a.x]) errors++; + seen[a.x] = 1; + end + if (seen != 255) errors++; + seen = 0; seen_y = 0; + repeat (8) begin + if (!a.randomize(x)) errors++; + if (seen[a.x]) errors++; + seen[a.x] = 1; + saved_x = a.x; saved_y = a.y; + alias_a.rand_mode(0); + repeat (2) if (!a.randomize()) errors++; + if (!a.randomize(null)) errors++; + if (a.x != saved_x || a.y != saved_y) errors++; + if (!a.randomize(y)) errors++; + if (seen_y[a.y]) errors++; + seen_y[a.y] = 1; + if (a.x.rand_mode() || a.y.rand_mode()) errors++; + if (seen_y == 15) seen_y = 0; + alias_a.rand_mode(1); + end + if (seen != 255 || seen_y != 0) errors++; + if (a.calls != 48) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_enum_alias + (source "randc_enum_alias.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [63:0] {NEG=-7, MID=2, HIGH=91} E; + typedef E Alias; + class C; randc Alias value; endclass + C c; + bit [2:0] seen; + int index; + initial begin + c = new; + repeat (8) begin + seen = 0; + repeat (3) begin + if (!c.randomize()) errors++; + case (c.value) + NEG: index=0; + MID: index=1; + HIGH: index=2; + default: begin errors++; index=0; end + endcase + if (seen[index]) errors++; + seen[index] = 1; + end + if (seen != 7) 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_randc_icarus.json b/crates/celox-test-suite/verification/repros/sv_randc_icarus.json new file mode 100644 index 00000000000..2a1d280dd49 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randc_icarus.json @@ -0,0 +1,44 @@ +{ + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "exclude_stronger_than_sv": false, + "include_ignored": false, + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 31; see /build.log\n/source_0.sv:19: error: Can't find task srandom in class Derived\n/source_0.sv:19: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:19: error: Can't find task srandom in class Derived\n/source_0.sv:19: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:20: sorry: Method name nesting is not supported yet.\n/source_0.sv:20: : method path: x.rand_mode\n/source_0.sv:20: error: Object celox_suite_tb.dut.a has no method \"x.rand_mode(...)\".\n/source_0.sv:20: sorry: Method name nesting is not supported yet.\n/source_0.sv:20: : method path: y.rand_mode\n/source_0.sv:20: error: Object celox_suite_tb.dut.a has no method \"y.rand_mode(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:22: Error: randomize is not a method of class Base.\n/source_0.sv:22: error: Object celox_suite_tb.dut.base_a has no method \"randomize(...)\".\n/source_0.sv:22: Error: randomize is not a method of class Derived.\n/source_0.sv:22: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:22: error: Unable to elaborate condition expression.\n/source_0.sv:30: Error: randomize is not a method of class Derived.\n/source_0.sv:30: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:30: error: Unable to elaborate condition expression.\n/source_0.sv:34: error: Can't find task rand_mode in class Derived\n/source_0.sv:34: error: Enable of unknown task ``alias_a.rand_mode''.\n/source_0.sv:35: Error: randomize is not a method of class Derived.\n/source_0.sv:35: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:35: error: Unable to elaborate condition expression.\n/source_0.sv:36: Error: randomize is not a method of class Derived.\n/source_0.sv:36: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n/source_0.sv:38: Error: randomize is not a method of class Derived.\n/source_0.sv:38: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:38: error: Unable to elaborate condition expression.\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: x.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"x.rand_mode(...)\".\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: y.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"y.rand_mode(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n/source_0.sv:43: error: Can't find task rand_mode in class Derived\n/source_0.sv:43: error: Enable of unknown task ``alias_a.rand_mode''.\n31 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:22: Error: randomize is not a method of class C.\n/source_0.sv:22: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:22: error: Unable to elaborate condition expression.\n/source_0.sv:32: Error: randomize is not a method of class C.\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:41: Error: randomize is not a method of class C.\n/source_0.sv:41: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n9 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_domains", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:14: Error: randomize is not a method of class C.\n/source_0.sv:14: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:14: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_randc_verilator.json b/crates/celox-test-suite/verification/repros/sv_randc_verilator.json new file mode 100644 index 00000000000..797443f1b7a --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randc_verilator.json @@ -0,0 +1,33 @@ +{ + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "exclude_stronger_than_sv": false, + "include_ignored": false, + "cases": [ + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:20:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 20 | if (!a.x.rand_mode() || !a.y.rand_mode()) 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:20:33: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 20 | if (!a.x.rand_mode() || !a.y.rand_mode()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:22:17: 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 22 | if (!base_a.randomize() || !b.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:22:40: 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 22 | if (!base_a.randomize() || !b.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:30:17: 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 30 | if (!a.randomize(x)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:35:28: 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 35 | repeat (2) if (!a.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:36:17: 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 (!a.randomize(null)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:38:17: 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 38 | if (!a.randomize(y)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:41:33: 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 41 | if (a.x.rand_mode() || a.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:41:33: 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 41 | if (a.x.rand_mode() || a.y.rand_mode()) 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_cyclic_controls", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::randomization_cyclic_enum_alias at 1213:46: assert_eq errors: expected 0x0, got 0x20", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 96bafddf611..1cde7a83605 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -608,6 +608,75 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_domains", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index fe1ffd7e92f..e90cd817cd0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2386,5 +2386,58 @@ "program::programs_reject_instances" ] } + }, + { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_cyclic_controls", + "class::randomization_cyclic_domains", + "class::randomization_cyclic_enum_alias" + ] + } + }, + { + "id": "sv_verilator_randc_inheritance", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_cyclic_controls" + ] + } + }, + { + "id": "sv_verilator_randc_enum_alias", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_cyclic_enum_alias" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 67802610550..0afd033620e 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -303,6 +303,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_verilator_randc_inheritance", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_verilator_randc_enum_alias", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index b2c81061d78..de50527500c 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -388,3 +388,37 @@ sv_backends! { sv_backends! { fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } } + +sv_backends! { + fn class_randomization_cyclic_enum_alias(sim) { @case "class::randomization_cyclic_enum_alias"; } + fn class_randomization_cyclic_domains(sim) { @case "class::randomization_cyclic_domains"; } + fn class_randomization_cyclic_controls(sim) { @case "class::randomization_cyclic_controls"; } + fn class_randomization_cyclic_checkpoint(sim) { + @setup { let source = r#" + module Top(output bit [63:0] value); + timeunit 1ps / 1ps; + class C; randc bit [2:0] x; endclass + C c; + initial begin + c = new; + c.srandom(41); + void'(c.randomize()); + #10; + repeat (16) begin + void'(c.randomize()); + value = (value << 3) | c.x; + end + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("cyclic_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let saved = sim.checkpoint().unwrap(); + let value = sim.signal("value"); + sim.run_until(15).unwrap(); + let expected = sim.get_four_state(value); + sim.restore(&saved).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index aa944c98e4d..cee9451f494 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -145,7 +145,13 @@ 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 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 +`randc` supports 1–8-bit two-state integers and scalar enums with up to 256 +members. Each property visits every value once before starting another cycle +(18.4.2), including inherited properties and explicit member selection. +Disabled properties retain their cycle; checkpoints restore it. `srandom` +reseeds the RNG without making already consumed values eligible again. + +Constraints, `with`, larger `randc` domains, static random properties, and random 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. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 22c756c2ce5..2ac2f662659 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -127,7 +127,12 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の +`randc` は1〜8ビットの2値整数と、宣言値が256個以下のスカラーenumに対応します。 +各プロパティは全値を重複なく一巡してから次の循環に進みます(18.4.2)。継承、 +`rand_mode`、引数による対象選択とチェックポイント復元にも対応します。無効化中は +循環を進めず、`srandom` は消費済みの値を保持したまま乱数生成器を再シードします。 + +制約、`with`、上記の上限を超える `randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。