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-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index af000d0e460..2f439a631e1 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -1780,6 +1780,140 @@ impl NativeSimulatorHandle { } } +/// A runtime event of a simulation: `$display`, `$write`, a report of a +/// severity task, `$finish`, `$stop`, or events the design's event buffer +/// overwrote before they were drained. +#[cfg(not(target_arch = "wasm32"))] +#[napi(object)] +pub struct NapiRuntimeEvent { + /// `"display"`, `"write"`, `"report"`, `"finish"`, `"stop"` or + /// `"missed"`. + pub kind: String, + pub message: Option, + /// `"info"`, `"warning"`, `"error"` or `"fatal"` for a report. + pub severity: Option, + pub time: Option, + pub scope: Option, + pub file: Option, + pub line: Option, + pub assertion: Option, + /// The number of missed events. + pub count: Option, +} + +/// The assertion whose action block issued a report. +#[cfg(not(target_arch = "wasm32"))] +#[napi(object)] +pub struct NapiAssertionSite { + pub label: Option, + /// `"assert"`, `"assume"` or `"cover"`. + pub directive: String, + /// `"none"`, `"observed"` (`#0`) or `"final"`. + pub deferral: String, + /// `"pass"` or `"fail"`. + pub outcome: String, +} + +#[cfg(not(target_arch = "wasm32"))] +fn severity_name(severity: celox::Severity) -> &'static str { + match severity { + celox::Severity::Info => "info", + celox::Severity::Warning => "warning", + celox::Severity::Error => "error", + celox::Severity::Fatal => "fatal", + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn parse_severity(name: &str) -> Result { + Ok(match name { + "info" => celox::Severity::Info, + "warning" => celox::Severity::Warning, + "error" => celox::Severity::Error, + "fatal" => celox::Severity::Fatal, + _ => { + return Err(Error::from_reason(format!( + "unknown severity `{name}`: expected info, warning, error or fatal" + ))); + } + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn napi_runtime_event(event: celox::RuntimeEvent) -> NapiRuntimeEvent { + let mut out = NapiRuntimeEvent { + kind: String::new(), + message: None, + severity: None, + time: None, + scope: None, + file: None, + line: None, + assertion: None, + count: None, + }; + match event { + celox::RuntimeEvent::Display { message } => { + out.kind = "display".into(); + out.message = Some(message.into()); + } + celox::RuntimeEvent::Write { message } => { + out.kind = "write".into(); + out.message = Some(message.into()); + } + celox::RuntimeEvent::Report(report) => { + out.kind = "report".into(); + out.severity = Some(severity_name(report.severity).into()); + out.message = Some(report.message.into()); + out.time = report.time.map(|time| time as f64); + out.scope = report.scope; + if let Some(location) = report.location { + out.file = Some(location.file); + out.line = Some(location.line as u32); + } + out.assertion = report.assertion.map(|assertion| NapiAssertionSite { + label: assertion.label, + directive: match assertion.directive { + celox::AssertionDirective::Assert => "assert", + celox::AssertionDirective::Assume => "assume", + celox::AssertionDirective::Cover => "cover", + } + .into(), + deferral: match assertion.deferral { + celox::AssertionDeferral::None => "none", + celox::AssertionDeferral::Observed => "observed", + celox::AssertionDeferral::Final => "final", + } + .into(), + outcome: match assertion.outcome { + celox::AssertionOutcome::Pass => "pass", + celox::AssertionOutcome::Fail => "fail", + } + .into(), + }); + } + celox::RuntimeEvent::Finish => out.kind = "finish".into(), + celox::RuntimeEvent::Stop => out.kind = "stop".into(), + celox::RuntimeEvent::Missed { count } => { + out.kind = "missed".into(); + out.count = Some(count as f64); + } + } + out +} + +/// The error of a run that stopped at a report of the `failOn` severity. +#[cfg(not(target_arch = "wasm32"))] +fn check_failure(sim: &celox::Simulation) -> Result<()> { + match sim.failure() { + Some(report) => Err(Error::from_reason(format!( + "failOn: {}", + String::from_utf8_lossy(&report.render()) + ))), + None => Ok(()), + } +} + /// Low-level handle wrapping a `celox::Simulation`. #[cfg(not(target_arch = "wasm32"))] #[napi] @@ -2082,7 +2216,8 @@ impl NativeSimulationHandle { .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; sim.run_until(end_time as u64) - .map_err(|e| Error::from_reason(format!("{}", e))) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim) } /// Advance until `end_time` taking at most `max_steps` steps. Returns @@ -2093,8 +2228,40 @@ impl NativeSimulationHandle { .sim .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; - sim.run_until_bounded(end_time as u64, max_steps as u64) - .map_err(|e| Error::from_reason(format!("{}", e))) + let reached = sim + .run_until_bounded(end_time as u64, max_steps as u64) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim)?; + Ok(reached) + } + + /// Take the runtime events the design emitted since the last call, in + /// emission order. + #[napi] + pub fn drain_runtime_events(&mut self) -> Result> { + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + Ok(sim + .drain_runtime_events() + .into_iter() + .map(napi_runtime_event) + .collect()) + } + + /// Make runs and steps fail after the time step of a report of at least + /// `severity` (`"info"`, `"warning"`, `"error"` or `"fatal"`); `null` + /// fails only at `$fatal`. + #[napi] + pub fn set_fail_on(&mut self, severity: Option) -> Result<()> { + let severity = severity.as_deref().map(parse_severity).transpose()?; + let sim = self + .sim + .as_mut() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + sim.set_fail_on(severity); + Ok(()) } /// Report that the host wrote the state through the shared memory: the @@ -2117,9 +2284,12 @@ impl NativeSimulationHandle { .sim .as_mut() .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; - sim.step() + let time = sim + .step() .map(|opt| opt.map(|t| t as f64)) - .map_err(|e| Error::from_reason(format!("{}", e))) + .map_err(|e| Error::from_reason(format!("{}", e)))?; + check_failure(sim)?; + Ok(time) } /// Returns the current simulation time. diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 4bbd67c6922..32c77cebfb0 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -288,8 +288,9 @@ impl SimulationState { Ok(()) } - /// The next time with scheduled events or processes to run. - pub(super) fn next_work_time(&self) -> Option { + /// The next time with scheduled events or processes to run, apart + /// from host writes to settle. + pub fn next_work_time(&self) -> Option { if self.finished { return None; } 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 19cb12d383a..bc57d47a063 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 e9f97a5cddb..3f5e9c99ed6 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2387,5 +2387,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/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index bcd32cd682b..f471d653da4 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -59,7 +59,17 @@ impl NativeProgramInstance { /// /// The image's machine code must come from a trusted source. Image /// validation is structural and does not authenticate executable code. + /// + /// An image with process kernels, which only a timed + /// [`crate::Simulation`] runs, fails to attach. pub unsafe fn from_image(image: NativeProgramImage) -> Result { + let schema = image.runtime_schema(); + if !schema.processes.is_empty() { + let origin = schema.process_origins.first().cloned().unwrap_or_default(); + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4023e326033..d176c7dc1e8 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -99,6 +99,19 @@ pub struct Simulation { checked_steps: u64, /// Why [`crate::SchedulerMode::Differential`] has no shadow. unchecked: Option<&'static str>, + /// Boxed: only runs with `fail_on` use it. + reports: Box, +} + +/// Reports a simulation stops at, set by [`Simulation::set_fail_on`]. +#[derive(Debug, Default)] +struct ReportWatch { + fail_on: Option, + /// Events taken after each step while `fail_on` is set, with the time of + /// that step, for the next [`Simulation::drain_runtime_events`]. + events: Vec, + /// The first report of the last run at or above `fail_on`. + failure: Option, } impl std::fmt::Debug for Simulation { @@ -416,6 +429,7 @@ impl Simulation { shadow: None, checked_steps: 0, unchecked: None, + reports: Box::default(), }) } @@ -653,9 +667,40 @@ impl Simulation { /// Returns the new simulation time, the current time when only host /// writes were settled, or None if nothing was to do. pub fn step(&mut self) -> Result, RuntimeErrorCode> { + self.reports.failure = None; + if self.reports.fail_on.is_some() { + return self.watched_step(); + } self.step_until(u64::MAX) } + /// [`Self::step`] while [`Self::set_fail_on`] is set: a slot that only + /// settles host writes is watched before the step goes on to the next + /// time. + #[cold] + #[inline(never)] + fn watched_step(&mut self) -> Result, RuntimeErrorCode> { + let mut settled = None; + while let Some(next_time) = self.state.next_event_time() { + if next_time > self.state.time() { + self.watch_settle()?; + if self.reports.failure.is_some() { + return Ok(Some(self.state.time())); + } + } + let host_only = + self.state.host_pending() && self.state.next_work_time() != Some(next_time); + let time = self.step_until(next_time)?; + self.watch_reports(); + if !host_only || self.state.is_stopped() || self.reports.failure.is_some() { + return Ok(time); + } + settled = time; + } + self.watch_settle()?; + Ok(settled) + } + /// [`Self::step`] that, after settling host writes at the current time, /// does not advance past `end_time`. fn step_until(&mut self, end_time: u64) -> Result, RuntimeErrorCode> { @@ -671,12 +716,112 @@ impl Simulation { result } + /// The steps of a run while [`Self::set_fail_on`] is set, apart from + /// the run loop that has no reports to watch. Returns `false` when a + /// step stopped at `$stop` or at a failure, or `max_steps` ran out. + #[cold] + #[inline(never)] + fn watched_steps(&mut self, end_time: u64, max_steps: u64) -> Result { + let mut steps = 0; + while let Some(next_time) = self.state.next_event_time() { + if next_time > end_time { + break; + } + if steps >= max_steps { + return Ok(false); + } + if next_time > self.state.time() { + self.watch_settle()?; + if self.reports.failure.is_some() { + return Ok(false); + } + } + // One slot per step, so that a slot that only settles host + // writes is watched before the next runs. + self.step_until(next_time)?; + self.watch_reports(); + steps += 1; + if self.state.is_stopped() || self.reports.failure.is_some() { + return Ok(false); + } + } + self.watch_settle()?; + Ok(self.reports.failure.is_none()) + } + + /// Settle combinational logic that no step settled, as after host writes + /// that wake no process, at the current time, and watch its reports. A + /// watched run does this before it moves to a later time. + fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.simulator.dirty { + return Ok(()); + } + if let Err(error) = self.simulator.eval_comb_checked() { + self.flush_error_output(); + return Err(error); + } + self.simulator.dirty = false; + self.watch_reports(); + Ok(()) + } + + /// Stop [`Self::run_until`] and [`Self::run_until_bounded`] after the + /// time step of the first report of at least `severity`, which + /// [`Self::failure`] then returns. While it is set, the events of each + /// step are taken from the design's event buffer after the step and keep + /// the time of that step, so none are missed and their reports have an + /// exact time. They wait for [`Self::drain_runtime_events`]. `None` + /// stops only at `$fatal`, as before. + pub fn set_fail_on(&mut self, severity: Option) { + self.reports.fail_on = severity; + } + + /// The report the last run stopped at (see [`Self::set_fail_on`]). + /// The next run clears it. + pub fn failure(&self) -> Option<&crate::Report> { + self.reports.failure.as_ref() + } + + fn watch_reports(&mut self) { + let Some(fail_on) = self.reports.fail_on else { + return; + }; + // A step leaves combinational logic settled. + let events = + self.simulator + .drain_settled_runtime_events_with_context(crate::RuntimeFormatContext { + tb_time: Some(self.state.time()), + scope: None, + }); + if self.reports.failure.is_none() { + self.reports.failure = events.iter().find_map(|event| match event { + crate::RuntimeEvent::Report(report) if report.severity >= fail_on => { + Some(report.clone()) + } + // A lost event may have been a failure. + crate::RuntimeEvent::Missed { count } => Some(crate::Report::new( + fail_on, + format!("missed {count} runtime events").into_bytes(), + )), + _ => None, + }); + } + self.reports.events.extend(events); + } + /// Advance time and run until `end_time` (inclusive). /// Targets earlier than the current time leave time and state unchanged. /// A process that executes `$stop` returns control early, after the time /// slot of the stop, with [`Self::is_stopped`] set; calling this again - /// continues. + /// continues. A report of the severity of [`Self::set_fail_on`] returns + /// early in the same way, with [`Self::failure`] set. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + self.reports.failure = None; + // With reports to watch, step one slot at a time; the run below + // then only advances the time. + if self.reports.fail_on.is_some() && !self.watched_steps(end_time, u64::MAX)? { + return Ok(()); + } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, Some(mut shadow) => { @@ -701,10 +846,32 @@ impl Simulation { Ok(()) } + /// Run every time slot before `time`, then move to `time` without + /// running its slot: the next [`Self::step`] or [`Self::run_until`] + /// runs it, together with the host writes made in between. A target not + /// after the current time changes nothing. Like [`Self::run_until`], it + /// returns early, before `time`, at a `$stop` or `$finish`. + pub fn advance_to(&mut self, time: u64) -> Result<(), RuntimeErrorCode> { + let Some(last) = time.checked_sub(1).filter(|&last| last >= self.time()) else { + return Ok(()); + }; + self.run_until(last)?; + if self.time() != last || self.is_finished() || self.is_stopped() { + return Ok(()); + } + self.state.advance_time(&mut self.simulator.backend, time); + if let Some(shadow) = &mut self.shadow { + shadow + .state + .advance_time(&mut shadow.simulator.backend, time); + } + Ok(()) + } + /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, /// when another step would be needed to reach `end_time`, including when - /// a step stopped at `$stop`. + /// a step stopped at `$stop` or at a [`Self::failure`]. pub fn run_until_bounded( &mut self, end_time: u64, @@ -713,6 +880,14 @@ impl Simulation { if end_time < self.state.time() { return Ok(true); } + self.reports.failure = None; + if self.reports.fail_on.is_some() { + if !self.watched_steps(end_time, max_steps)? { + return Ok(false); + } + self.run_until(end_time)?; + return Ok(!self.state.is_stopped()); + } let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { @@ -761,7 +936,9 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { - self.simulator.drain_runtime_events() + let mut events = std::mem::take(&mut self.reports.events); + events.extend(self.simulator.drain_runtime_events()); + events } /// Returns the time of the next scheduled event, if any. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0df0be8c0d4..dc7af3cc618 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1188,6 +1188,19 @@ mod host { self.collect_formatted_runtime_events(ctx) } + /// Drain runtime events while combinational logic is settled, as + /// after a step of a timed simulation. + pub(crate) fn drain_settled_runtime_events_with_context( + &mut self, + ctx: RuntimeFormatContext<'_>, + ) -> Vec { + assert!( + !self.runtime_event_drain_active.load(Ordering::Acquire), + "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", + ); + self.collect_formatted_runtime_events(ctx) + } + fn eval_comb_for_runtime_event_drain(&mut self) -> Result<(), RuntimeErrorCode> { let (result, _) = self.eval_comb_capturing_events(); self.check_comb_backend_result(result)?; diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 7f8b600c462..c732c12f32f 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1710,20 +1710,24 @@ mod host { /// /// Keeping compilation separate from initialization lets compiler-only /// clients stop after native code generation without applying initial - /// values or executing the first combinational settle. + /// values or executing the first combinational settle. `Target` is what + /// [`Self::initialize`] builds: a [`Simulator`], or a timed + /// [`crate::Simulation`] whose image carries the process kernels and the + /// compiled scheduler. #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", target_arch = "aarch64" ))] #[must_use] - pub struct NativeCompilation { + pub struct NativeCompilation { image: crate::backend::native::NativeProgramImage, program: LaidOutProgram, warnings: Vec, options: SimulatorOptions, vcd_path: Option, injected_components: crate::InjectedComponents, + _target: std::marker::PhantomData, } /// `Simulator` runs no process kernel, so a design with one would @@ -1741,6 +1745,37 @@ mod host { )) } + /// A native image records waveforms only if its arrays are packed, + /// which an image compiled with VCD enabled has: a VCD file of the host + /// (`vcd_path`) or of the design (`$dumpvars`) needs one. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + fn validate_native_vcd_layout( + layout: &crate::MemoryLayout, + program: &crate::ir::RuntimeProgram, + vcd_path: &Option, + ) -> Result<(), SimulatorError> { + let source_vcd = program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if (vcd_path.is_some() || source_vcd) + && layout.unpacked_arrays.values().any(|array| { + !array.element_width.is_multiple_of(8) + || array.element_stride != array.element_width / 8 + }) + { + return Err(SimulatorError::from(crate::CodegenError::message( + "VCD requires packed array storage; compile this native image with VCD enabled", + ))); + } + Ok(()) + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1759,22 +1794,8 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - let source_vcd = sim - .program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Vcd); - if vcd_path.is_some() || source_vcd { - if sim.layout().unpacked_arrays.values().any(|array| { - !array.element_width.is_multiple_of(8) - || array.element_stride != array.element_width / 8 - }) { - return Err(SimulatorError::from(crate::CodegenError::message( - "VCD requires packed array storage; compile this native image with VCD enabled", - )) - .with_warnings(std::mem::take(&mut sim.warnings))); - } + if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { + return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); } if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -1851,7 +1872,7 @@ mod host { feature = "arm64-codegen", target_arch = "aarch64" ))] - impl NativeCompilation { + impl NativeCompilation { /// Warnings emitted while compiling this artifact. pub fn warnings(&self) -> &[CompilationWarning] { &self.warnings @@ -1885,7 +1906,14 @@ mod host { ) -> Result<(), crate::backend::native::NativeImageContainerError> { self.image.write_container(output_path) } + } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { /// Load the image into executable memory and initialize runtime state. pub fn initialize( self, @@ -1897,6 +1925,7 @@ mod host { options, vcd_path, injected_components, + _target, } = self; initialize_native_image( image, @@ -1909,6 +1938,38 @@ mod host { } } + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + impl NativeCompilation { + /// Load the image into executable memory and start a timed + /// simulation of it. + pub fn initialize( + self, + ) -> Result, SimulatorError> + { + let Self { + image, + program, + warnings, + options, + vcd_path, + injected_components, + _target, + } = self; + SimulatorBuilder::::start_native_image( + image, + program.into_runtime(), + warnings, + options, + vcd_path, + injected_components, + ) + } + } + impl Default for SimulatorOptions { fn default() -> Self { let opt = crate::optimizer::OptimizeOptions::default(); @@ -3175,6 +3236,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }) } @@ -3230,6 +3292,7 @@ mod host { options, vcd_path, injected_components, + _target: std::marker::PhantomData, }, trace, )) @@ -3716,6 +3779,68 @@ mod host { ) } + /// Compiles a timed simulation into a native image without loading + /// it. The image carries the process kernels and the compiled + /// scheduler; [`NativeCompilation::initialize`] or + /// [`Self::build_native_from_image`] starts a simulation of it. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn compile_native( + mut self, + ) -> Result, SimulatorError> { + self.options.emit_triggers = true; + let (laid_out, mut warnings, options, vcd_path, injected_components) = self + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + )?; + let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; + Ok(NativeCompilation { + image, + program: laid_out, + warnings, + options, + vcd_path, + injected_components, + _target: std::marker::PhantomData, + }) + } + + /// Starts a timed simulation of a native image from + /// [`Self::compile_native`], without code generation. The design's + /// runtime metadata comes from `image`; the sources of this builder + /// are not used, its runtime options (scheduler, DPI symbols, + /// plusargs, VCD output) are. + /// + /// An image from [`Simulator::builder`] has no compiled scheduler, + /// so every time slot runs in the reference loop. + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + pub fn build_native_from_image( + self, + image: crate::backend::native::NativeProgramImage, + ) -> Result, SimulatorError> + { + let mut options = self.options; + options.four_state = image.four_state(); + options.emit_triggers = true; + let program = image.runtime_program(); + Self::start_native_image( + image, + program, + Vec::new(), + options, + self.vcd_path, + self.injected_components, + ) + } + /// Compiles a timed simulation using the Wasmtime WASM backend. pub fn build_wasm( self, @@ -3758,36 +3883,111 @@ mod host { self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - let shadow = if !matches!( + let shadow = Self::start_shadow( + |shadow_options| compile(&laid_out, shadow_options), + &laid_out.runtime, + &options, + &injected_components, + )?; + let mut simulation = Self::start_simulation( + backend, + laid_out.into_runtime(), + warnings, + &options, + vcd_path, + injected_components, + )?; + if let Some(shadow) = shadow { + simulation.set_shadow(shadow); + } + Ok(simulation) + } + + /// The reference-loop shadow of a differential simulation of + /// `program`, with `backend` providing its own copy of the code, or + /// why it has none. Other scheduler modes have no shadow. + #[allow(clippy::type_complexity)] + fn start_shadow( + backend: impl FnOnce(&SimulatorOptions) -> Result, + program: &crate::ir::RuntimeProgram, + options: &SimulatorOptions, + injected_components: &crate::InjectedComponents, + ) -> Result>, &'static str>>, SimulatorError> + { + if !matches!( options.scheduler, crate::SchedulerMode::Differential | crate::SchedulerMode::DifferentialRuns ) { - None - } else if !injected_components.definitions.is_empty() { - Some(Err("the design has external components")) - } else { - let mut shadow_options = options.clone(); - shadow_options.trace = Default::default(); - shadow_options.scheduler = crate::SchedulerMode::Reference; - let backend = compile(&laid_out, &shadow_options)?; - let shadow = Self::start_simulation( - backend, - laid_out.runtime.clone(), - Vec::new(), - &shadow_options, - None, - Default::default(), - )?; - // Host state outside the memory image, such as open files, - // cannot be shared with a shadow. - Some(match shadow.simulator.check_host_checkpoint_support() { + return Ok(None); + } + if !injected_components.definitions.is_empty() { + return Ok(Some(Err("the design has external components"))); + } + let mut shadow_options = options.clone(); + shadow_options.trace = Default::default(); + shadow_options.scheduler = crate::SchedulerMode::Reference; + let backend = backend(&shadow_options)?; + let shadow = Self::start_simulation( + backend, + program.clone(), + Vec::new(), + &shadow_options, + None, + Default::default(), + )?; + // Host state outside the memory image, such as open files, + // cannot be shared with a shadow. + Ok(Some( + match shadow.simulator.check_host_checkpoint_support() { Ok(()) => Ok(Box::new(shadow)), Err(_) => Err("the design keeps host state outside its memory image"), - }) + }, + )) + } + + /// Load `image` into executable memory and start a timed simulation + /// of `program`, its runtime metadata. A differential simulation + /// loads a second copy of the image for its shadow. + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + fn start_native_image( + image: crate::backend::native::NativeProgramImage, + program: crate::ir::RuntimeProgram, + warnings: Vec, + options: SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> + { + if let Err(error) = validate_native_vcd_layout(image.layout(), &program, &vcd_path) { + return Err(error.with_warnings(warnings)); + } + let load = |image, options: &SimulatorOptions| { + // Safety: callers either produced the image in this process + // or loaded it from an explicitly trusted native-image + // artifact, and `from_image` validates its structure first. + unsafe { + crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi) + } + }; + let shadow = match Self::start_shadow( + |shadow_options| load(image.clone(), shadow_options), + &program, + &options, + &injected_components, + ) { + Ok(shadow) => shadow, + Err(error) => return Err(error.with_warnings(warnings)), + }; + let backend = match load(image, &options) { + Ok(backend) => backend, + Err(error) => return Err(error.with_warnings(warnings)), }; let mut simulation = Self::start_simulation( backend, - laid_out.into_runtime(), + program, warnings, &options, vcd_path, @@ -3799,6 +3999,25 @@ mod host { Ok(simulation) } + /// A cross-compiling build cannot execute the code of a native image. + #[cfg(any( + all(feature = "arm64-codegen", not(target_arch = "aarch64")), + all(feature = "x86_64-codegen", not(target_arch = "x86_64")) + ))] + fn start_native_image( + image: crate::backend::native::NativeProgramImage, + program: crate::ir::RuntimeProgram, + warnings: Vec, + options: SimulatorOptions, + vcd_path: Option, + injected_components: crate::InjectedComponents, + ) -> Result, SimulatorError> + { + let _ = (image, program, options, vcd_path, injected_components); + Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(warnings)) + } + /// Initialize a timed simulation of `program` compiled into /// `backend`. fn start_simulation( 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/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index dacbd92e6f5..6ad262ad875 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -300,6 +300,18 @@ fn build(design: &Design, backend: &str) -> Result> { ); return Ok(match backend { "native" => Box::new(TimedBackend::new(builder.build_native()?)), + // The image goes through its container bytes, as an attached + // image does, and the simulation takes its metadata from it. + "native-image" => { + let image = builder.compile_native()?.into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes()?)?; + Box::new(TimedBackend::new( + Simulation::from_sv_sources(Vec::new(), &design.top) + .scheduler_mode(scheduler_mode()) + .build_native_from_image(image)?, + )) + } "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), "native-parallel" => Box::new(TimedBackend::new( builder @@ -340,6 +352,19 @@ fn build(design: &Design, backend: &str) -> Result> { }; Ok(match backend { "native" => Box::new(CeloxBackend(builder.build_native().map_err(rejected)?)), + "native-image" => { + let image = builder + .compile_native() + .map_err(rejected)? + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes()?)?; + Box::new(CeloxBackend( + Simulator::from_sv_sources(Vec::new(), &design.top) + .build_native_from_image(image) + .map_err(rejected)?, + )) + } "cranelift" => Box::new(CeloxBackend(builder.build_cranelift().map_err(rejected)?)), "native-parallel" => Box::new(CeloxBackend( builder diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index c5c05ec7d41..9df87b6b032 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -2,7 +2,8 @@ //! processes, driven through the timed `Simulation`. //! //! Every exclusion names what Celox lacks for the case, so the change that -//! adds it removes the exclusion. Supported cases run on every backend. +//! adds it removes the exclusion. Supported cases run on every backend, +//! and natively also from a serialized native image. macro_rules! timed_cases { () => {}; @@ -25,6 +26,13 @@ macro_rules! timed_cases { crate::suite::run_case($case, "cranelift"); } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + $(#[$attr])* + fn native_image() { + crate::suite::run_case($case, "native-image"); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] #[test] $(#[$attr])* diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs new file mode 100644 index 00000000000..aab956b1f94 --- /dev/null +++ b/crates/celox/tests/native_simulation_image.rs @@ -0,0 +1,243 @@ +//! A timed `Simulation` built from a native image: the image carries the +//! process kernels and the compiled scheduler, so a serialized image runs as +//! the in-process build does (#1730). +#![cfg(all( + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) +))] + +use std::path::Path; + +use celox::{ + NativeProgramImage, NativeProgramInstance, RuntimeEvent, SchedulerMode, Simulation, + SimulatorErrorKind, +}; + +const PROCESSES: &str = r#"`timescale 1ns/1ns +module Top(output logic [7:0] count, output logic [7:0] seen); + logic clk = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 1; + initial begin + count = 0; + seen = 0; + #12 $display("at %0t count=%0d", $time, count); + @(posedge clk) seen = count; + #20 $display("at %0t seen=%0d count=%0d", $time, seen, count); + end +endmodule +"#; + +fn builder(source: &str) -> celox::SimulatorBuilder<'_, Simulation> { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") +} + +/// The image, through its container bytes. +fn reloaded(image: &NativeProgramImage) -> NativeProgramImage { + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap() +} + +/// What a simulation shows up to `end`: its events and outputs. +fn transcript( + sim: &mut Simulation, + end: u64, +) -> (Vec, u64, u64) { + sim.run_until(end).unwrap(); + let count = sim.get(sim.signal("count")).try_into().unwrap(); + let seen = sim.get(sim.signal("seen")).try_into().unwrap(); + (sim.drain_runtime_events(), count, seen) +} + +#[test] +fn a_serialized_native_image_runs_its_processes() { + let expected = transcript(&mut builder(PROCESSES).build_native().unwrap(), 60); + assert_eq!( + expected.0, + vec![ + RuntimeEvent::Display { + message: b"at 12 count=1".to_vec() + }, + RuntimeEvent::Display { + message: b"at 35 seen=1 count=3".to_vec() + }, + ] + ); + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); + assert!(sim.scheduler_stats().compiled_slots > 0); + let mut sim = builder(PROCESSES) + .compile_native() + .unwrap() + .initialize() + .unwrap(); + assert_eq!(transcript(&mut sim, 60), expected); +} + +#[test] +fn a_differential_simulation_loads_its_shadow_from_the_image() { + let image = reloaded( + &builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native_from_image(image) + .unwrap(); + let (events, count, _) = transcript(&mut sim, 60); + assert_eq!(events.len(), 2); + assert_eq!(count, 6); + assert!(sim.scheduler_stats().checked_steps > 0); +} + +/// An image from `Simulator` has no compiled scheduler: every slot runs in +/// the reference loop, to the same state as a fresh `Simulation` build. +#[test] +fn an_untimed_image_runs_as_a_simulation_in_the_reference_loop() { + let source = "module Top(input logic clk, input logic [7:0] step, output logic [7:0] count, + output logic [7:0] sum); + always_ff @(posedge clk) count <= count + 1; + always_ff @(negedge clk) sum <= sum + count + step; + endmodule"; + let run = |sim: &mut Simulation| { + let step = sim.signal("step"); + sim.modify(|io| io.set(step, 3u8)).unwrap(); + sim.add_clock("clk", 10, 5); + sim.run_until(97).unwrap(); + sim.save_state().unwrap() + }; + let mut fresh = builder(source).build_native().unwrap(); + let expected = run(&mut fresh); + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(reloaded(&image)) + .unwrap(); + assert_eq!(run(&mut sim), expected); + assert_eq!(sim.get(sim.signal("count")), 10u8.into()); + assert_eq!(sim.scheduler_stats().compiled_slots, 0); +} + +#[test] +fn process_images_do_not_load_as_untimed_programs() { + let image = builder(PROCESSES) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = + celox::Simulator::from_sv_sources(Vec::new(), "Top").build_native_from_image(image.clone()) + else { + panic!("a Simulator runs no process"); + }; + assert!(matches!( + error.kind(), + SimulatorErrorKind::ProcessRequiresSimulation(_) + )); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance runs no process"); + }; + assert!(error.to_string().contains("is a process"), "{error}"); +} + +#[test] +fn advance_to_stops_before_the_slot_and_its_host_writes_join_it() { + let source = r#"`timescale 1ns/1ns +module Top(input logic [7:0] value, output logic [7:0] seen); + initial begin + seen = 0; + #5 seen = value; + $display("at %0t value=%0d", $time, value); + end +endmodule +"#; + let image = reloaded( + &builder(source) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // The write is the host's at time 5, before the process resumes there. + let value = sim.signal("value"); + sim.modify(|io| io.set(value, 7u8)).unwrap(); + sim.advance_to(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 0u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("seen")), 7u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"at 5 value=7".to_vec() + }] + ); + sim.advance_to(3).unwrap(); + assert_eq!(sim.time(), 5); +} + +/// Element-strided unpacked arrays cannot be dumped: an image compiled +/// without VCD is rejected for a VCD run, as `Simulator` rejects it, and one +/// compiled with VCD records the elements. +#[test] +fn a_vcd_run_needs_an_image_compiled_with_vcd() { + let source = r#"`timescale 1ns/1ns +module Top; + logic [2:0] values [4]; + initial begin + values[2] = 3'd0; + #1 values[2] = 3'd5; + end +endmodule +"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("top.vcd"); + let strided = builder(source) + .compile_native() + .unwrap() + .into_program_image(); + let Err(error) = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&strided)) + else { + panic!("a strided image cannot record VCD"); + }; + assert!( + error + .to_string() + .contains("compile this native image with VCD enabled"), + "{error}" + ); + let packed = builder(source) + .vcd(&path) + .compile_native() + .unwrap() + .into_program_image(); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(reloaded(&packed)) + .unwrap(); + sim.run_until(2).unwrap(); + drop(sim); + let vcd = std::fs::read_to_string(&path).unwrap(); + assert!(vcd.contains("b101"), "{vcd}"); +} diff --git a/crates/celox/tests/sv_reports.rs b/crates/celox/tests/sv_reports.rs index d03a96c5735..cceecc58a08 100644 --- a/crates/celox/tests/sv_reports.rs +++ b/crates/celox/tests/sv_reports.rs @@ -148,6 +148,142 @@ macro_rules! reports { ); } + /// With `failOn`, a run stops after the time step of the first + /// report of at least that severity, the next run continues, + /// and every report keeps the time it was issued at. + #[test] + fn fail_on_stops_runs_at_the_time_of_a_report() { + let source = "`timescale 1ns/1ns\nmodule Top;\n initial begin\n \ + #1 $warning(\"w\");\n \ + #1 $error(\"e\");\n \ + #1 $display(\"after\");\n \ + end\nendmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 2); + let failure = sim.failure().unwrap(); + assert_eq!(failure.message, b"e"); + assert_eq!(failure.time, Some(2)); + let times: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Report(report) => (report.severity, report.time), + event => panic!("unexpected event {event:?}"), + }) + .collect(); + assert_eq!( + times, + vec![(Severity::Warning, Some(1)), (Severity::Error, Some(2))] + ); + sim.run_until(10).unwrap(); + assert!(sim.failure().is_none()); + assert_eq!(sim.time(), 10); + assert!(matches!( + sim.drain_runtime_events().as_slice(), + [celox::RuntimeEvent::Display { message }] if message == b"after" + )); + } + + /// A report caused by a host write stops the run in the slot + /// that settles the write, before later slots run. + #[test] + fn fail_on_stops_at_reports_of_host_writes() { + let source = "`timescale 1ns/1ns\nmodule Top(input logic a);\n \ + always @(posedge a) $error(\"e\");\n \ + initial #5 $display(\"later\");\nendmodule"; + for step in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(2).unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + if step { + assert_eq!(sim.step().unwrap(), Some(2)); + } else { + sim.run_until(10).unwrap(); + } + assert_eq!(sim.time(), 2); + assert_eq!(sim.failure().unwrap().time, Some(2)); + let events = sim.drain_runtime_events(); + assert!( + matches!( + events.as_slice(), + [celox::RuntimeEvent::Report(report)] if report.message == b"e" + ), + "{events:?}" + ); + } + } + + /// A report of combinational logic that a host write leaves to + /// settle, with no step at the current time, stops the run there, + /// by `run_until` or by `step`, also before later work. + #[test] + fn fail_on_stops_at_reports_of_settles_without_steps() { + for later in ["", "\n initial #5 $display(\"later\");"] { + let source = format!("`timescale 1ns/1ns\nmodule Top(input logic a);\n \ + always_comb if (a) $error(\"e\");{later}\nendmodule"); + for step in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(2).unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + if step { + sim.step().unwrap(); + } else { + sim.run_until(10).unwrap(); + } + assert_eq!(sim.time(), 2, "step: {step}"); + let failure = sim.failure().expect("a failure"); + assert_eq!(failure.message, b"e"); + assert_eq!(failure.time, Some(2)); + sim.run_until(10).unwrap(); + assert!(sim.failure().is_none()); + assert_eq!(sim.time(), 10); + } + } + } + + /// Events lost to a full event buffer may have been failures. + #[test] + fn fail_on_stops_at_missed_events() { + let source = "`timescale 1ns/1ns\nmodule Top;\n initial begin\n \ + #1;\n \ + for (int i = 0; i < 2000; i++) $display(\"x\");\n \ + #1 $display(\"after\");\n \ + end\nendmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 1); + let failure = sim.failure().unwrap(); + assert_eq!(failure.severity, Severity::Error); + assert!(failure.message.starts_with(b"missed "), "{failure:?}"); + } + #[test] fn line_directives_set_the_reported_location() { let reports = reports("`line 40 \"other.sv\" 0\n initial $info(\"moved\");"); diff --git a/crates/celox/tests/tick_semantics.rs b/crates/celox/tests/tick_semantics.rs index e25afb59e0f..e42cd2555d0 100644 --- a/crates/celox/tests/tick_semantics.rs +++ b/crates/celox/tests/tick_semantics.rs @@ -246,20 +246,17 @@ const COINCIDENT: [Op; 5] = [ Op::Tick(&["clk"]), ]; -/// Coincident ticks sample each other's values from before the edge. The -/// commit-raised gate's domain (`e`) is checked against Icarus below until -/// the timed reference sees its edge in a coincident batch (#1860). +/// Coincident ticks sample each other's values from before the edge. #[test] fn ticks_of_several_events_are_coincident() { - check_except(&COINCIDENT, &["e"]); + check(&COINCIDENT); } /// At the second coincident tick `clk` rises while `ren` is already high, so /// `rclk` rises in the active region and `e` counts: Icarus 13.0 gives -/// `e` = 0 0 1 2 3 after the operations. The timed reference gives 0 0 1 1 2 -/// (#1860); both `Simulator` paths agree with Icarus. +/// `e` = 0 0 1 2 3 after the operations, and so do the timed reference +/// (#1860) and both `Simulator` paths. #[test] -#[ignore = "#1860"] fn coincident_ticks_run_the_domain_of_a_gate_the_commit_raised() { let e = OUTPUTS.iter().position(|name| *name == "e").unwrap(); let values = |rows: Vec>| rows.iter().map(|row| row[e]).collect::>(); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 737f2d4a129..d3c04e955ab 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -146,7 +146,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. @@ -612,7 +618,8 @@ action block of an immediate assertion also names that assertion: its statement label, `assert`, `assume` or `cover`, and whether the pass or the fail action issued it. Severity tasks in subroutines the action block calls are not attributed. `time` is the time the drain's context gives, as the VPI -host does at each callback. `Report::render` formats a report as the VPI host +host does at each callback, or the time step of the report while +`Simulation::set_fail_on` is set. `Report::render` formats a report as the VPI host and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index 141bb6de910..95b96532fd1 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -197,6 +197,34 @@ sim.runUntil(10000); sim.runUntil(10000, { maxSteps: 500 }); ``` +### Runtime Events and Reports + +`drainRuntimeEvents()` returns what the design emitted since the last call, in +emission order: `$display` and `$write` output, `report` events of severity +tasks and failed assertions, `$finish` and `$stop`. A report has its +`severity` (`"info"`, `"warning"`, `"error"` or `"fatal"`), its `message` bytes, +and the `scope`, `file` and `line` that issued it. + +`setFailOn(severity)` makes `runUntil()`, `step()` and the waits throw after the +time step of the first report of at least that severity. While it is set, each +report keeps the `time` it was issued at. Events lost to a full event buffer +(a `missed` event) count as a failure, since they may have held one. A later +call continues the simulation. + +```typescript +sim.setFailOn("error"); +try { + sim.runUntil(10000); +} catch (error) { + // "failOn: Error: ..." at the time of the first $error +} +for (const event of sim.drainRuntimeEvents()) { + if (event.kind === "report") { + console.log(event.severity, event.time, new TextDecoder().decode(event.message)); + } +} +``` + ## Simulator Options Both `Simulator` and `Simulation` accept the following options: diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 22c756c2ce5..7cd330ff86b 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` を通した呼び出しは実行時エラーです。 @@ -389,7 +394,8 @@ static な output 引数も、代入しない経路では以前の値を保持 スコープを持ちます。即時アサーションのアクションブロックからの報告は、そのアサーションも示します。 文ラベル、`assert` / `assume` / `cover` の別、pass と fail のどちらのアクションから出たかです。 アクションブロックが呼ぶサブルーチン内の重大度タスクは、アサーションに結び付けません。`time` は -drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Report::render` は、 +drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Simulation::set_fail_on` +の設定中は、報告が出たタイムステップの時刻です。`Report::render` は、 VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 42b3607e8e1..f68ad81fe86 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -159,6 +159,32 @@ sim.runUntil(10000); sim.runUntil(10000, { maxSteps: 500 }); ``` +### 実行時イベントと報告 + +`drainRuntimeEvents()` は、前回の呼び出し以降に設計が出したものを出した順に返します。 +`$display` と `$write` の出力、重大度タスクと失敗したアサーションの `report` イベント、 +`$finish`、`$stop` です。報告は `severity`(`"info"`、`"warning"`、`"error"`、`"fatal"`)、 +`message` のバイト列、報告した `scope`、`file`、`line` を持ちます。 + +`setFailOn(severity)` を設定すると、その重大度以上の報告が最初に出たタイムステップの後で、 +`runUntil()`、`step()`、各種の待ちが例外を投げます。設定中は、各報告が出た時刻を `time` に +保持します。イベントバッファがあふれて失われたイベント(`missed` イベント)は、失敗を +含んでいた可能性があるため失敗として扱います。次の呼び出しはシミュレーションを続けます。 + +```typescript +sim.setFailOn("error"); +try { + sim.runUntil(10000); +} catch (error) { + // 最初の $error の時刻で "failOn: Error: ..." +} +for (const event of sim.drainRuntimeEvents()) { + if (event.kind === "report") { + console.log(event.severity, event.time, new TextDecoder().decode(event.message)); + } +} +``` + ## シミュレータオプション `Simulator` と `Simulation` の両方で以下のオプションが使えます: diff --git a/packages/celox/src/index.ts b/packages/celox/src/index.ts index 3130ff6815b..bf0892490af 100644 --- a/packages/celox/src/index.ts +++ b/packages/celox/src/index.ts @@ -59,9 +59,11 @@ export { runTestFromProject, runTestWithFrontendArtifact, } from "./testbench.js"; +// Runtime events // Core types /** @internal */ export type { + AssertionSite, ClockEdge, CreateResult, EventHandle, @@ -79,6 +81,9 @@ export type { OptimizeOptions, ParamOverride, PortInfo, + Report, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 3ad0f006c11..5730a231ffc 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -13,6 +13,7 @@ import { withOwnedHandle } from "./handle-ownership.js"; import type { NativeCreateSimulationFn } from "./simulation.js"; import type { NativeCreateFn } from "./simulator.js"; import type { + AssertionSite, CreateResult, FrontendSimulatorHandle, LoopBreak, @@ -21,6 +22,9 @@ import type { NativeSimulationHandle, NativeSimulatorHandle, PortInfo, + Report, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, @@ -63,9 +67,66 @@ export interface RawNapiSimulationHandle { loadState?(bytes: Uint8Array): void; clockPeriods?(): { eventId: number; period: number }[]; switchVcd?(path: string): void; + drainRuntimeEvents?(): RawRuntimeEvent[]; + setFailOn?(severity: string | null): void; dispose(): void; } +/** A runtime event as the addon returns it: absent fields are null. */ +export interface RawRuntimeEvent { + kind: string; + message?: Uint8Array | null; + severity?: string | null; + time?: number | null; + scope?: string | null; + file?: string | null; + line?: number | null; + assertion?: { + label?: string | null; + directive: string; + deferral: string; + outcome: string; + } | null; + count?: number | null; +} + +/** Convert an addon event to a `RuntimeEvent`, dropping absent fields. */ +export function runtimeEvent(raw: RawRuntimeEvent): RuntimeEvent { + switch (raw.kind) { + case "display": + case "write": + return { kind: raw.kind, message: raw.message ?? new Uint8Array() }; + case "finish": + case "stop": + return { kind: raw.kind }; + case "missed": + return { kind: "missed", count: raw.count ?? 0 }; + case "report": { + const report: Report = { + kind: "report", + severity: raw.severity as Severity, + message: raw.message ?? new Uint8Array(), + }; + if (raw.time != null) report.time = raw.time; + if (raw.scope != null) report.scope = raw.scope; + if (raw.file != null) report.file = raw.file; + if (raw.line != null) report.line = raw.line; + if (raw.assertion != null) { + const assertion: AssertionSite = { + directive: raw.assertion.directive as AssertionSite["directive"], + deferral: raw.assertion.deferral as AssertionSite["deferral"], + outcome: raw.assertion.outcome as AssertionSite["outcome"], + }; + if (raw.assertion.label != null) assertion.label = raw.assertion.label; + report.assertion = assertion; + } + return report; + } + default: + throw new Error(`unknown runtime event kind \`${raw.kind}\``); + } +} + export interface NapiFalseLoop { from: NapiSignalPath; to: NapiSignalPath; @@ -925,6 +986,14 @@ export function wrapDirectSimulationHandle( ...(raw.clockPeriods ? { clockPeriods: () => raw.clockPeriods!() } : {}), ...(raw.isFinished ? { isFinished: () => raw.isFinished!() } : {}), ...(raw.isStopped ? { isStopped: () => raw.isStopped!() } : {}), + ...(raw.drainRuntimeEvents + ? { + drainRuntimeEvents: () => raw.drainRuntimeEvents!().map(runtimeEvent), + } + : {}), + ...(raw.setFailOn + ? { setFailOn: (severity: Severity | null) => raw.setFailOn!(severity) } + : {}), }; } diff --git a/packages/celox/src/runtime-events-addon.test.ts b/packages/celox/src/runtime-events-addon.test.ts new file mode 100644 index 00000000000..05081f5807e --- /dev/null +++ b/packages/celox/src/runtime-events-addon.test.ts @@ -0,0 +1,87 @@ +/** Runtime events and `failOn` through the native addon. */ +import { afterEach, describe, expect, test } from "vitest"; +import { createSimulationBridge, loadNativeAddon } from "./napi-helpers.js"; +import { Simulation } from "./simulation.js"; +import type { ModuleDefinition, Report } from "./types.js"; + +const VERYL = ` +module Top ( + clk: input clock, + cnt: output logic<8>, +) { + var r: logic<8>; + always_ff (clk) { + $display("tick %0d", r); + $assert_continue(r != 8'd2, "r=%0d", r); + r = r + 1; + } + assign cnt = r; +} +`; + +type Ports = { readonly cnt: bigint }; + +const Top: ModuleDefinition = { + __celox_module: true, + name: "Top", + sources: [{ path: "Top.veryl", content: VERYL }], + ports: { + clk: { direction: "input", type: "clock", width: 1 }, + cnt: { direction: "output", type: "logic", width: 8 }, + }, + events: ["clk"], +}; + +let live: Simulation[] = []; + +function simulation(): Simulation { + const sim = Simulation.create(Top, { + __nativeCreate: createSimulationBridge(loadNativeAddon()), + }); + sim.addClock("clk", { period: 10 }); + live.push(sim); + return sim; +} + +afterEach(() => { + for (const sim of live) sim.dispose(); + live = []; +}); + +const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes); + +describe("runtime events through the addon", () => { + test("drainRuntimeEvents returns displays and reports in order", () => { + const sim = simulation(); + sim.runUntil(100); + const events = sim.drainRuntimeEvents(); + const reports = events.filter((event) => event.kind === "report"); + expect(reports).toHaveLength(1); + expect(reports[0]).toMatchObject({ severity: "error" }); + expect(text((reports[0] as Report).message)).toBe("r=2"); + const before = events.slice(0, events.indexOf(reports[0]!)); + expect( + before.map((event) => event.kind === "display" && text(event.message)), + ).toContain("tick 2"); + expect(sim.drainRuntimeEvents()).toEqual([]); + }); + + test("failOn stops the run after the time step of the report", () => { + const sim = simulation(); + sim.setFailOn("error"); + expect(() => sim.runUntil(1000)).toThrow(/failOn: Error/); + const stopped = sim.time(); + expect(stopped).toBeLessThan(1000); + const report = sim + .drainRuntimeEvents() + .find((event): event is Report => event.kind === "report"); + expect(report?.time).toBe(stopped); + sim.runUntil(1000); + expect(sim.time()).toBe(1000); + }); + + test("failOn rejects an unknown severity", () => { + const sim = simulation(); + expect(() => sim.setFailOn("loud" as never)).toThrow(/unknown severity/); + }); +}); diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index 49fbeb41a32..7feb23e896a 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -22,6 +22,8 @@ import type { FourStateValue, ModuleDefinition, NativeSimulationHandle, + RuntimeEvent, + Severity, SignalLayout, SimulatorOptions, SourceFile, @@ -495,6 +497,35 @@ export class Simulation

> { return t; } + /** + * Take the runtime events the design emitted since the last call, in + * emission order: `$display` and `$write` output, reports of severity + * tasks, `$finish` and `$stop`. + */ + drainRuntimeEvents(): RuntimeEvent[] { + this.ensureAlive(); + if (!this._handle.drainRuntimeEvents) { + throw new Error( + "This simulation does not support draining runtime events", + ); + } + return this._handle.drainRuntimeEvents(); + } + + /** + * Make `runUntil()`, `step()` and the waits throw after the time step of + * the first report of at least `severity`, such as `"error"` for + * `$error` and failed assertions. While it is set, each report keeps the + * exact time it was issued at. `null` throws only at `$fatal`. + */ + setFailOn(severity: Severity | null): void { + this.ensureAlive(); + if (!this._handle.setFailOn) { + throw new Error("This simulation does not support failOn"); + } + this._handle.setFailOn(severity); + } + /** Current simulation time. */ time(): number { this.ensureAlive(); diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 7dfee70b78f..b358062dc33 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -227,6 +227,47 @@ export interface NativeSimulatorHandle { * Opaque handle returned by NAPI for time-based simulation. * @internal */ +/** The severity of a report (IEEE 1800-2023 20.10). */ +export type Severity = "info" | "warning" | "error" | "fatal"; + +/** The assertion whose action block issued a report. */ +export interface AssertionSite { + /** The statement label, which names the assertion within its scope. */ + label?: string; + directive: "assert" | "assume" | "cover"; + /** `"observed"` is `#0`. */ + deferral: "none" | "observed" | "final"; + /** Which action block issued the report. */ + outcome: "pass" | "fail"; +} + +/** + * What a severity task (`$info`, `$warning`, `$error`, `$fatal`) reports. + * `message` holds the formatted bytes; decode them explicitly when the + * design emits text. + */ +export interface Report { + kind: "report"; + severity: Severity; + message: Uint8Array; + /** The simulation time, when it is known (see `Simulation.setFailOn`). */ + time?: number; + /** The hierarchical name of the scope that issued the report. */ + scope?: string; + /** The file and line of the task call. */ + file?: string; + line?: number; + assertion?: AssertionSite; +} + +/** A runtime event a simulation drains with `drainRuntimeEvents()`. */ +export type RuntimeEvent = + | { kind: "display" | "write"; message: Uint8Array } + | Report + | { kind: "finish" | "stop" } + /** Events the design's event buffer overwrote before they were drained. */ + | { kind: "missed"; count: number }; + export interface NativeSimulationHandle { addClock(eventId: number, period: number, initialDelay: number): void; schedule(eventId: number, time: number, value: number): void; @@ -264,6 +305,10 @@ export interface NativeSimulationHandle { clockPeriods?(): { eventId: number; period: number }[]; /** Continue the waveform in a new VCD file. */ switchVcd?(path: string): void; + /** Take the runtime events emitted since the last call. */ + drainRuntimeEvents?(): RuntimeEvent[]; + /** Fail runs and steps at a report of at least `severity`. */ + setFailOn?(severity: Severity | null): void; } /**