From a7cebae47250349883480e632860d885596c1205 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:36:04 +0900 Subject: [PATCH] feat(sv)!: add Annex N integer distribution functions Support `$dist_normal`, `$dist_exponential`, `$dist_poisson`, `$dist_chi_square`, `$dist_t` and `$dist_erlang` in timed `Simulation`. Use the Annex N algorithms with signed 32-bit formals and results, evaluate seed selectors once, and preserve deterministic checkpoint replay. Invalid positive parameters report an error without updating the seed. Validate native image serialization with both formatted-input and distribution host requests; container version 23 distinguishes the extended host schema. Validation: runtime reference vectors (3 tests), API tests across four backends and both state modes (21 tests), shared backend variants (10 tests), native image roundtrip, and host-request encoding tests. Two cases each passed Icarus and Verilator. Integrated Clippy, formatting and NAPI/JS boundary tests passed. sv-tests: reviewed the full official CI report (2,054 mode runs) and updated twelve distribution expectation rows that now pass in both state modes. The file-input improvements are retained by the lower PR; no regressions or other verdict changes were observed. BREAKING CHANGE: Adds variants to the public SystemFunction and HostRequestKind enums. Native images must be regenerated for container version 23. Change-Id: I5e156a7970741d8649b8ef33497ca1d1b54b3280 --- conformance/sv-tests/README.md | 6 + conformance/sv-tests/expected.tsv | 24 +-- crates/celox-design/src/lib.rs | 6 +- crates/celox-frontend-sv/src/lowering.rs | 6 + crates/celox-frontend-sv/src/lowering/ff.rs | 86 ++++++++ crates/celox-runtime/src/distribution.rs | 199 ++++++++++++++++++ crates/celox-runtime/src/lib.rs | 1 + .../src/ast/expression_binding/direct.rs | 6 + .../celox-sv-analyzer/src/system_functions.rs | 48 ++++- .../src/sv/cases/distributions.vtest | 67 ++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 3 + crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/builder.rs | 54 +++++ .../celox/src/simulator/host/distribution.rs | 40 ++++ .../systemverilog/system_functions.rs | 9 + crates/celox/tests/sv_distributions.rs | 170 +++++++++++++++ docs/guide/systemverilog-reference.md | 11 + docs/ja/guide/systemverilog-reference.md | 9 + 20 files changed, 737 insertions(+), 15 deletions(-) create mode 100644 crates/celox-runtime/src/distribution.rs create mode 100644 crates/celox-test-suite/src/sv/cases/distributions.vtest create mode 100644 crates/celox/src/simulator/host/distribution.rs create mode 100644 crates/celox/tests/sv_distributions.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 9c7ea0eefc7..2964661cb26 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -117,6 +117,12 @@ The integral file-input extension updates six expectation rows: `21.3--feof`, remaining file-input probes retain their measured verdicts; several still use unsupported `final` constructs. +The six Annex N distribution probes (`20.15--dist_normal`, `dist_exponential`, +`dist_poisson`, `dist_chi_square`, `dist_t` and `dist_erlang`) now pass simulation +in both state modes, updating twelve more expectation rows. The scanner probes +retain failures caused by unsupported `final` constructs or internal data types; +no scanner expectation is changed. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 80bf4ffdc7a..01dce0b551b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -681,18 +681,18 @@ chapter-20/20.10--warning.sv 2state pass chapter-20/20.10--warning.sv 4state pass chapter-20/20.14--coverage.sv 2state fail chapter-20/20.14--coverage.sv 4state fail -chapter-20/20.15--dist_chi_square.sv 2state fail -chapter-20/20.15--dist_chi_square.sv 4state fail -chapter-20/20.15--dist_erlang.sv 2state fail -chapter-20/20.15--dist_erlang.sv 4state fail -chapter-20/20.15--dist_exponential.sv 2state fail -chapter-20/20.15--dist_exponential.sv 4state fail -chapter-20/20.15--dist_normal.sv 2state fail -chapter-20/20.15--dist_normal.sv 4state fail -chapter-20/20.15--dist_poisson.sv 2state fail -chapter-20/20.15--dist_poisson.sv 4state fail -chapter-20/20.15--dist_t.sv 2state fail -chapter-20/20.15--dist_t.sv 4state fail +chapter-20/20.15--dist_chi_square.sv 2state pass +chapter-20/20.15--dist_chi_square.sv 4state pass +chapter-20/20.15--dist_erlang.sv 2state pass +chapter-20/20.15--dist_erlang.sv 4state pass +chapter-20/20.15--dist_exponential.sv 2state pass +chapter-20/20.15--dist_exponential.sv 4state pass +chapter-20/20.15--dist_normal.sv 2state pass +chapter-20/20.15--dist_normal.sv 4state pass +chapter-20/20.15--dist_poisson.sv 2state pass +chapter-20/20.15--dist_poisson.sv 4state pass +chapter-20/20.15--dist_t.sv 2state pass +chapter-20/20.15--dist_t.sv 4state pass chapter-20/20.15--dist_uniform.sv 2state pass chapter-20/20.15--dist_uniform.sv 4state pass chapter-20/20.15--random.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index d27a3367137..513374414a3 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -303,6 +303,7 @@ pub enum HostRequestKind { FileIo, Vcd, Scan, + Distribution, } impl HostRequestKind { @@ -313,6 +314,7 @@ impl HostRequestKind { Self::FileIo => 2, Self::Vcd => 3, Self::Scan => 4, + Self::Distribution => 5, }; (family << 32) | site as u64 } @@ -324,6 +326,7 @@ impl HostRequestKind { 2 => Self::FileIo, 3 => Self::Vcd, 4 => Self::Scan, + 5 => Self::Distribution, _ => return None, }; Some((family, request as u32)) @@ -1456,6 +1459,7 @@ mod tests { HostRequestKind::FileIo, HostRequestKind::Vcd, HostRequestKind::Scan, + HostRequestKind::Distribution, ] { for site in [0, 1, u32::MAX] { assert_eq!( @@ -1464,7 +1468,7 @@ mod tests { ); } } - for invalid in [0, u32::MAX as u64, 5u64 << 32, 1u64 << 63] { + for invalid in [0, u32::MAX as u64, 6u64 << 32, 1u64 << 63] { assert_eq!(HostRequestKind::decode(invalid), None); } assert_eq!( diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 612d4cd26c3..45e824749e0 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5975,6 +5975,12 @@ fn lower_bit_vector_function_slt( | SystemFunction::Stime | SystemFunction::Random | SystemFunction::DistUniform + | SystemFunction::DistNormal + | SystemFunction::DistExponential + | SystemFunction::DistPoisson + | SystemFunction::DistChiSquare + | SystemFunction::DistT + | SystemFunction::DistErlang | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs | SystemFunction::Urandom diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b58c9900e4f..bf950285f04 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -918,6 +918,19 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.plusargs(*function, args)?, + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::DistNormal + | sv::ir::SystemFunction::DistExponential + | sv::ir::SystemFunction::DistPoisson + | sv::ir::SystemFunction::DistChiSquare + | sv::ir::SystemFunction::DistT + | sv::ir::SystemFunction::DistErlang), + ), + args, + .. + } => self.distribution(*function, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::DistUniform), args, @@ -1822,6 +1835,79 @@ impl<'p, 'a> Ff<'p, 'a> { Ok((id, sv::ir::Expr::Ident(name))) } + fn distribution( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + use sv::ir::{Expr, SystemFunction as F}; + if self.kernel.is_none() { + return Err(unsupported(format!( + "{} outside a timed process", + function.name() + ))); + } + let operation = match function { + F::DistNormal => 0, + F::DistExponential => 1, + F::DistPoisson => 2, + F::DistChiSquare => 3, + F::DistT => 4, + F::DistErlang => 5, + _ => unreachable!(), + }; + let seed = args + .first() + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("distribution seed"))?; + // Capture selectors once before evaluating the other actuals, and + // suspend with an int formal rather than writing the caller's storage. + let (lvalues, captured) = self.capture_system_actual(seed)?; + let formal = self.int_formal(captured); + let (seed_id, seed_result) = + self.host_hidden("distribution_seed", &formal, 32, true, true)?; + let value = |id| HostRequestValue { + float_precision: None, + id, + width: 32, + signed: true, + is_string: false, + }; + let mut operands = vec![value(seed_id)]; + for arg in args.iter().skip(1) { + let arg = self.hoist( + arg.as_ref() + .ok_or_else(|| unsupported("distribution argument"))?, + )?; + let formal = self.int_formal(arg); + let (id, _) = self.host_hidden("distribution_arg", &formal, 32, true, true)?; + operands.push(value(id)); + } + let (ret_id, ret_name) = self.m.temp("distribution_result", 32, true, false); + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Distribution) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: 0, + kind: HostRequestKind::Distribution, + requires_timed_simulation: false, + operation, + args: operands, + results: vec![value(ret_id), value(seed_id)], + strings: Vec::new(), + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Distribution, site)) + .map_err(kernel_error)?; + match lvalues.as_slice() { + [lvalue] => self.assign(lvalue, &seed_result)?, + parts => self.assign_concat(parts, &seed_result)?, + } + Ok(Expr::Ident(ret_name)) + } + fn plusargs( &mut self, function: sv::ir::SystemFunction, diff --git a/crates/celox-runtime/src/distribution.rs b/crates/celox-runtime/src/distribution.rs new file mode 100644 index 00000000000..aa4e4db54ba --- /dev/null +++ b/crates/celox-runtime/src/distribution.rs @@ -0,0 +1,199 @@ +//! Integer probabilistic distributions (IEEE 1800-2023 20.14.2, Annex N). +//! +//! The seed transition wraps at 32 bits. Floating point is only an internal +//! implementation detail; all SystemVerilog formals and results are signed int. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Distribution { + Normal, + Exponential, + Poisson, + ChiSquare, + T, + Erlang, +} + +impl Distribution { + pub fn from_code(code: u32) -> Option { + Some(match code { + 0 => Self::Normal, + 1 => Self::Exponential, + 2 => Self::Poisson, + 3 => Self::ChiSquare, + 4 => Self::T, + 5 => Self::Erlang, + _ => return None, + }) + } + + pub fn name(self) -> &'static str { + match self { + Self::Normal => "$dist_normal", + Self::Exponential => "$dist_exponential", + Self::Poisson => "$dist_poisson", + Self::ChiSquare => "$dist_chi_square", + Self::T => "$dist_t", + Self::Erlang => "$dist_erlang", + } + } + + /// Draw one value, updating `seed` only after validating the int formals. + pub fn sample(self, seed: &mut i32, args: &[i32]) -> Result { + let arity = if matches!(self, Self::Normal | Self::Erlang) { + 2 + } else { + 1 + }; + if args.len() != arity { + return Err(format!( + "{} requires {arity} distribution parameters", + self.name() + )); + } + if self != Self::Normal && args.iter().any(|value| *value <= 0) { + return Err(format!( + "{} requires positive distribution parameters", + self.name() + )); + } + let sample = match self { + Self::Normal => normal(seed) * f64::from(args[1]) + f64::from(args[0]), + Self::Exponential => exponential(seed) * f64::from(args[0]), + Self::Poisson => return Ok(poisson(seed, args[0])), + Self::ChiSquare => chi_square(seed, args[0]), + Self::T => { + let chi = chi_square(seed, args[0]); + normal(seed) / (chi / f64::from(args[0])).sqrt() + } + Self::Erlang => { + let mut product = 1.0; + for _ in 0..args[0] { + product *= uniform(seed, 0.0, 1.0); + } + -f64::from(args[1]) * product.ln() / f64::from(args[0]) + } + }; + // Annex N rounds symmetrically, halfway away from zero. Its 32-bit + // C conversion produces INT_MIN on an out-of-range result on the + // reference targets; make that behavior explicit instead of relying + // on Rust's saturating float-to-int conversion. + let rounded = sample.round(); + Ok( + if !rounded.is_finite() + || rounded < f64::from(i32::MIN) + || rounded > f64::from(i32::MAX) + { + i32::MIN + } else { + rounded as i32 + }, + ) + } +} + +fn uniform(seed: &mut i32, start: f64, end: f64) -> f64 { + if *seed == 0 { + *seed = 259_341_593; + } + *seed = seed.wrapping_mul(69_069).wrapping_add(1); + let base = f64::from(f32::from_bits(((*seed as u32) >> 9) | 0x3f80_0000)); + let adjusted = base + base * (1.0 / 8_388_608.0); + (end - start) * (adjusted - 1.0) + start +} + +fn normal(seed: &mut i32) -> f64 { + loop { + let first = uniform(seed, -1.0, 1.0); + let second = uniform(seed, -1.0, 1.0); + let radius = first * first + second * second; + if radius < 1.0 && radius != 0.0 { + return first * (-2.0 * radius.ln() / radius).sqrt(); + } + } +} + +fn exponential(seed: &mut i32) -> f64 { + let value = uniform(seed, 0.0, 1.0); + if value == 0.0 { 0.0 } else { -value.ln() } +} + +fn poisson(seed: &mut i32, mean: i32) -> i32 { + let threshold = (-f64::from(mean)).exp(); + let mut product = uniform(seed, 0.0, 1.0); + let mut count = 0; + while threshold < product { + count += 1; + product *= uniform(seed, 0.0, 1.0); + } + count +} + +fn chi_square(seed: &mut i32, degrees: i32) -> f64 { + let mut result = if degrees % 2 != 0 { + normal(seed).powi(2) + } else { + 0.0 + }; + for _ in 0..degrees / 2 { + result += 2.0 * exponential(seed); + } + result +} + +#[cfg(test)] +mod tests { + use super::Distribution::*; + + #[test] + fn annex_n_fixed_seed_vectors() { + for (distribution, args, expected, next) in [ + (Normal, vec![0, 10], -4, -642_763_923), + (Exponential, vec![10], 82, 1_174_174), + (Poisson, vec![10], 3, -642_763_923), + (ChiSquare, vec![5], 2, -1_369_077_693), + (T, vec![5], 0, -434_453_879), + (Erlang, vec![3, 10], 33, 861_173_020), + ] { + let mut seed = 17; + assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected); + assert_eq!(seed, next); + } + } + + #[test] + fn zero_negative_seeds_and_small_shape_parameters() { + for (distribution, initial, args, expected, next) in [ + (Normal, 0, vec![-3, 5], -1, 1_082_744_015), + (Exponential, -1, vec![10], 0, -69_068), + (Poisson, -1, vec![1], 3, 1_486_841_147), + (ChiSquare, 1, vec![2], 22, 69_070), + (T, 1, vec![1], -4, 2_044_158_073), + (Erlang, 0, vec![1, 3], 2, -1_844_104_698), + ] { + let mut seed = initial; + assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected); + assert_eq!(seed, next); + } + } + + #[test] + fn invalid_parameters_do_not_advance_seed() { + for (distribution, args) in [ + (Exponential, vec![0]), + (Poisson, vec![-1]), + (ChiSquare, vec![0]), + (T, vec![-2]), + (Erlang, vec![0, 10]), + (Erlang, vec![2, 0]), + ] { + let mut seed = 17; + assert!( + distribution + .sample(&mut seed, &args) + .unwrap_err() + .contains("positive") + ); + assert_eq!(seed, 17); + } + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index dfa181a6ef4..2d2b872cc15 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -2,6 +2,7 @@ pub mod backend; mod derived_tick; +pub mod distribution; mod edge; mod error; mod event_buffer; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 3ffb6629f9b..22a1180b48f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -853,6 +853,12 @@ pub(in crate::ast) fn bind_value( SystemFunction::Urandom | SystemFunction::Random | SystemFunction::DistUniform + | SystemFunction::DistNormal + | SystemFunction::DistExponential + | SystemFunction::DistPoisson + | SystemFunction::DistChiSquare + | SystemFunction::DistT + | SystemFunction::DistErlang | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs | SystemFunction::Fopen diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 6c4bed0ad19..80f13c40ff6 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -64,6 +64,12 @@ pub enum SystemFunction { Random, /// `$dist_uniform` (20.14.2). DistUniform, + DistNormal, + DistExponential, + DistPoisson, + DistChiSquare, + DistT, + DistErlang, /// Command-line prefix query (21.6). TestPlusargs, @@ -118,6 +124,12 @@ impl SystemFunction { | Self::Fscanf | Self::TestPlusargs | Self::ValuePlusargs + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang ) } @@ -154,6 +166,12 @@ impl SystemFunction { Self::Isunknown => "$isunknown", Self::Random => "$random", Self::DistUniform => "$dist_uniform", + Self::DistNormal => "$dist_normal", + Self::DistExponential => "$dist_exponential", + Self::DistPoisson => "$dist_poisson", + Self::DistChiSquare => "$dist_chi_square", + Self::DistT => "$dist_t", + Self::DistErlang => "$dist_erlang", Self::TestPlusargs => "$test$plusargs", Self::ValuePlusargs => "$value$plusargs", @@ -201,6 +219,12 @@ impl SystemFunction { self, Self::Random | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang | Self::TestPlusargs | Self::ValuePlusargs | Self::Urandom @@ -230,7 +254,17 @@ impl SystemFunction { /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { self == Self::ScopeRandomize - || (matches!(self, Self::Random | Self::DistUniform) && position == 0) + || (matches!( + self, + Self::Random + | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang + ) && position == 0) || (self == Self::ValuePlusargs && position == 1) || (self == Self::Fread && position == 0) || (matches!(self, Self::Sscanf | Self::Fscanf) && position >= 2) @@ -251,6 +285,12 @@ impl SystemFunction { Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang | Self::TestPlusargs | Self::ValuePlusargs | Self::Fread @@ -749,6 +789,12 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ // 20.14 Probabilistic distribution functions function(SystemFunction::Random, 0, Some(1)), function(SystemFunction::DistUniform, 3, Some(3)), + function(SystemFunction::DistNormal, 3, Some(3)), + function(SystemFunction::DistExponential, 2, Some(2)), + function(SystemFunction::DistPoisson, 2, Some(2)), + function(SystemFunction::DistChiSquare, 2, Some(2)), + function(SystemFunction::DistT, 2, Some(2)), + function(SystemFunction::DistErlang, 3, Some(3)), // 20.15 Stochastic analysis tasks and functions unsupported("$q_initialize", Task), unsupported("$q_add", Task), diff --git a/crates/celox-test-suite/src/sv/cases/distributions.vtest b/crates/celox-test-suite/src/sv/cases/distributions.vtest new file mode 100644 index 00000000000..1a2769cb1f9 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/distributions.vtest @@ -0,0 +1,67 @@ +(group distributions (category sequential)) + +; IEEE 1800-2023 20.14.2 and normative Annex N: signed int values and +; exact explicit-seed transitions, independently corroborated with Icarus. +(case annex_n_reference_values + (source "distributions.sv" #" + module Top(output logic ok); + int seed, value; + initial begin + ok = 1; + seed = 17; value = $dist_normal(seed, 0, 10); + ok &= value == -4 && seed == -642763923; + seed = 17; value = $dist_exponential(seed, 10); + ok &= value == 82 && seed == 1174174; + seed = 17; value = $dist_poisson(seed, 10); + ok &= value == 3 && seed == -642763923; + seed = 17; value = $dist_chi_square(seed, 5); + ok &= value == 2 && seed == -1369077693; + seed = 17; value = $dist_t(seed, 5); + ok &= value == 0 && seed == -434453879; + seed = 17; value = $dist_erlang(seed, 3, 10); + ok &= value == 33 && seed == 861173020; + seed = 0; value = $dist_normal(seed, -3, 5); + ok &= value == -1 && seed == 1082744015; + seed = -1; value = $dist_exponential(seed, 10); + ok &= value == 0 && seed == -69068; + seed = -1; value = $dist_poisson(seed, 1); + ok &= value == 3 && seed == 1486841147; + seed = 1; value = $dist_chi_square(seed, 2); + ok &= value == 22 && seed == 69070; + seed = 1; value = $dist_t(seed, 1); + ok &= value == -4 && seed == 2044158073; + seed = 0; value = $dist_erlang(seed, 1, 3); + ok &= value == 2 && seed == -1844104698; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +(case replay_and_normal_parameters + (source "distribution_replay.sv" #" + module Top(output logic ok); + int a, b, seed, replay; + initial begin + seed = 0; replay = 0; ok = 1; + for (int i = 0; i < 4; i++) begin + a = $dist_normal(seed, -17, 0); b = $dist_normal(replay, -17, 0); + ok &= a == -17 && a == b && seed == replay; + a = $dist_exponential(seed, 7); b = $dist_exponential(replay, 7); + ok &= a == b && seed == replay; + a = $dist_poisson(seed, 8); b = $dist_poisson(replay, 8); + ok &= a == b && seed == replay; + a = $dist_chi_square(seed, 2); b = $dist_chi_square(replay, 2); + ok &= a == b && seed == replay; + a = $dist_t(seed, 1); b = $dist_t(replay, 1); + ok &= a == b && seed == replay; + a = $dist_erlang(seed, 2, 9); b = $dist_erlang(replay, 2, 9); + ok &= a == b && seed == replay; + end + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index a5b92a1328e..6e73b02bedf 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -23,6 +23,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/scan.vtest", text: include_str!("scan.vtest"), }, + Group { + file: "src/sv/cases/distributions.vtest", + text: include_str!("distributions.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a10353520a4..d06e3ac5f3c 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 25; +const CONTAINER_VERSION: u16 = 26; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8783baa50fa..4d0022f33ef 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -138,6 +138,9 @@ impl UnitExecutor for Simulator { celox_design::HostRequestKind::Plusargs => { self.run_plusargs_request(request, timestamp) } + celox_design::HostRequestKind::Distribution => { + self.run_distribution_request(request, timestamp) + } celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), celox_design::HostRequestKind::Vcd => self.run_vcd_request(request, timestamp), celox_design::HostRequestKind::Scan => self.run_scan_request(request, timestamp), diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 2cecf40b355..efb2aef7073 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -36,6 +36,7 @@ pub use state_file::{StateError, StateMismatch, StateSchema}; #[cfg(feature = "host-runtime")] mod host { mod declaration; + mod distribution; mod file_io; mod fread; mod scan; diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index e191f3ae49f..804edbd5c5a 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1723,6 +1723,17 @@ mod host { fn validate_untimed_host_requests( program: &crate::ir::RuntimeProgram, ) -> Result<(), SimulatorError> { + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Distribution) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message: "probabilistic distributions require Simulation; Simulator does not execute scheduled process kernels".into(), + signals: Vec::new(), + })); + } if program .runtime_schema .host_request_sites @@ -3801,6 +3812,49 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) + ))] + #[test] + fn extended_host_requests_survive_native_image_roundtrip() { + let source = r#"module Top(output bit ok); + int seed, value, parsed, count; + initial begin + seed = 17; + value = $dist_normal(seed, 0, 10); + count = $sscanf("42", "%d", parsed); + ok = value == -4 && parsed == 42 && count == 1; + end + endmodule"#; + let (program, warnings, options, _, _) = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("host_image.sv"))], + "Top", + ) + .emit_triggers() + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .unwrap(); + let image = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let image = + crate::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let runtime = image.runtime_program(); + // SAFETY: this image was compiled from the trusted source above. + let backend = unsafe { crate::backend::native::NativeBackend::from_image(image) }.unwrap(); + let mut simulator = + crate::Simulator::with_backend_and_program_for_simulation(backend, runtime, warnings); + simulator.apply_initial_values(); + simulator.modify(|_| {}).unwrap(); + let mut sim = crate::Simulation::new(simulator); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("ok")), num_bigint::BigUint::from(1u8)); + } + #[cfg(all( test, feature = "systemverilog", diff --git a/crates/celox/src/simulator/host/distribution.rs b/crates/celox/src/simulator/host/distribution.rs new file mode 100644 index 00000000000..ef17534251b --- /dev/null +++ b/crates/celox/src/simulator/host/distribution.rs @@ -0,0 +1,40 @@ +use super::*; +use celox_design::HostRequestSite; +use celox_runtime::{Halt, SimulatorErrorCode, distribution::Distribution}; + +impl Simulator { + pub(crate) fn run_distribution_request( + &mut self, + site: &HostRequestSite, + _timestamp: u64, + ) -> Result<(), Halt> { + let error = |message| { + Halt::Error(SimulatorErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }; + let distribution = Distribution::from_code(site.operation) + .ok_or_else(|| error("invalid distribution operation".into()))?; + let values: Vec = site + .args + .iter() + .map(|arg| { + let (value, mask) = self.backend.get_four_state(arg.id); + // The reference integer arithmetic has no X/Z representation; + // coerce each unknown bit to zero, as for integral random seeds. + let known = value & (BigUint::from(u32::MAX) ^ mask); + known.to_u32_digits().first().copied().unwrap_or(0) as i32 + }) + .collect(); + let mut seed = values[0]; + let value = distribution + .sample(&mut seed, &values[1..]) + .map_err(error)?; + self.backend + .set_wide(site.results[0].id, BigUint::from(value as u32)); + self.backend + .set_wide(site.results[1].id, BigUint::from(seed as u32)); + Ok(()) + } +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index ea78f60de55..5e75bdb4124 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -472,6 +472,15 @@ sv_backends! { fn dist_uniform_bounds_seed_and_replay(sim) { @case "random_plusargs::dist_uniform_bounds_seed_and_replay"; } +} + +sv_backends! { + fn distribution_annex_n_reference_values(sim) { + @case "distributions::annex_n_reference_values"; + } + fn distribution_replay_and_normal_parameters(sim) { + @case "distributions::replay_and_normal_parameters"; + } fn dist_uniform_reference_sequence(sim) { @case "random_plusargs::dist_uniform_reference_sequence"; } diff --git a/crates/celox/tests/sv_distributions.rs b/crates/celox/tests/sv_distributions.rs new file mode 100644 index 00000000000..d9c00c69507 --- /dev/null +++ b/crates/celox/tests/sv_distributions.rs @@ -0,0 +1,170 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +const DISTRIBUTIONS: [(&str, &str, i32, i32); 6] = [ + ("$dist_normal", "0, 10", -4, -642_763_923), + ("$dist_exponential", "10", 82, 1_174_174), + ("$dist_poisson", "10", 3, -642_763_923), + ("$dist_chi_square", "5", 2, -1_369_077_693), + ("$dist_t", "5", 0, -434_453_879), + ("$dist_erlang", "3, 10", 33, 861_173_020), +]; + +fn actuals_source() -> String { + let mut body = String::new(); + for (name, parameters, expected, next) in DISTRIBUTIONS { + body.push_str(&format!( + r#" + seeds[0] = 17; seeds[1] = 91; calls = 0; + value = {name}(seeds[index()], {parameters}); + ok &= value == {expected} && calls == 1 && seeds[0] == {next} && seeds[1] == 91; + narrow = -1; reference = -1; + value = {name}(narrow, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && narrow == reference[7:0]; + unsigned_seed = 255; reference = 255; + value = {name}(unsigned_seed, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && unsigned_seed == reference[7:0]; + wide = 64'h1234567800000011; reference = 17; + value = {name}(wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && wide == extended; + wide = 64'hxxxxxxxx00000011; reference = 17; + value = {name}(wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && wide === extended; + unsigned_wide = 17; reference = 17; + value = {name}(unsigned_wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && unsigned_wide == extended; + masked = 32'hxxxxxxxx; reference = 0; + value = {name}(masked, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && masked === reference && !$isunknown(masked); + masked = 32'h0000x011; reference = 17; + value = {name}(masked, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && masked === reference && !$isunknown(masked); + "# + )); + } + format!( + r#"module Top(output bit ok); + int seeds[0:1], calls, value, other, reference; + logic signed [7:0] narrow; + logic [7:0] unsigned_seed; + logic [63:0] unsigned_wide; + logic [31:0] masked; + longint wide, extended; + function automatic int index(); calls = calls + 1; return calls - 1; endfunction + initial begin ok = 1; {body} end + endmodule"# + ) +} + +macro_rules! distribution_backends { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + #[test] + fn distribution_int_formals_capture_and_masks() { + let source = actuals_source(); + for four_state in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_actuals.sv"))], "Top", + ).four_state(four_state).$backend().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("ok")), 1u8.into(), "four_state={four_state}"); + } + } + + #[test] + fn distribution_rejects_invalid_positive_formals_without_copyout() { + for (function, parameters) in [ + ("$dist_exponential", "0"), ("$dist_poisson", "-1"), + ("$dist_chi_square", "0"), ("$dist_t", "-1"), + ("$dist_erlang", "0, 10"), ("$dist_erlang", "2, 0"), + ] { + let source = format!(r#"module Top(output longint seed, output int value); + initial begin seed = 64'h1234567800000011; + value = {function}(seed, {parameters}); end + endmodule"#); + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_invalid.sv"))], "Top", + ).$backend().unwrap(); + let error = sim.run_until(0).unwrap_err(); + assert!(error.to_string().contains("requires positive distribution parameters"), "{error}"); + assert_eq!(sim.get(sim.signal("seed")), 0x1234567800000011u64.into()); + } + } + + #[test] + fn distribution_checkpoint_replays_seed_and_return_slots() { + let source = r#"module Top(output int value, seed); + timeunit 1ps; timeprecision 1ps; + initial seed = 17; + always begin #1; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("distribution_checkpoint.sv"))], "Top", + ).$backend().unwrap(); + sim.run_until(0).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(2).unwrap(); + let expected_seed = sim.get(sim.signal("seed")); + let expected_value = sim.get(sim.signal("value")); + sim.restore(&checkpoint).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("seed")), expected_seed); + assert_eq!(sim.get(sim.signal("value")), expected_value); + } + + #[test] + fn distribution_initial_requires_timed_simulation() { + let source = r#"module Top(output int value); + int seed; + initial begin seed = 17; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let error = celox::Simulator::from_sv_sources( + vec![(source, Path::new("distribution_initial.sv"))], "Top", + ).$backend().err().expect("untimed initial distribution accepted"); + assert!(error.to_string().contains("distributions require Simulation")); + } + + #[test] + fn distribution_edge_requires_timed_simulation() { + let source = r#"module Top(input bit clk, output int value); + int seed; + always_ff @(posedge clk) begin seed = 17; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let error = celox::Simulator::from_sv_sources( + vec![(source, Path::new("distribution_edge.sv"))], "Top", + ).$backend().err().expect("untimed distribution accepted"); + assert!(error.to_string().contains("require Simulation")); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("distribution_edge.sv"))], "Top", + ).$backend().unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("value")), (u32::MAX - 3).into()); + } + } + }; +} +distribution_backends!(interpreter, build_interpreter); +distribution_backends!(cranelift, build); +#[cfg(target_arch = "x86_64")] +distribution_backends!(native, build_native); +distribution_backends!(wasm, build_wasm); + +#[test] +fn distribution_seed_is_an_integral_inout_variable() { + for (name, parameters, _, _) in DISTRIBUTIONS { + let source = + format!("module Top; int value; initial value = {name}(17, {parameters}); endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_seed.sv"))], + "Top", + ) + .build_interpreter() + .expect_err("literal inout seed accepted"); + assert!(error.to_string().contains("output/inout"), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 5540ed2fde1..4f2bcd15a00 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -530,6 +530,17 @@ the whole design. its integral seed variable and includes both bounds. Equal or reversed bounds return `start` without advancing the seed. +`$dist_normal`, `$dist_exponential`, `$dist_poisson`, `$dist_chi_square`, +`$dist_t` and `$dist_erlang` use the Annex N distributions in timed +`Simulation` processes and their subroutines. Arguments and results are signed +32-bit integers; the integral inout seed is converted to an int and copied +back once, including when its actual is an indexed element. Exponential and +Poisson means, chi-square and t degrees of freedom, and both Erlang parameters +must be positive; invalid parameters report a runtime error without updating +the seed. Normal accepts any integer mean and standard deviation. These +functions do not require an SV `real` type. Their seed is design state, so +checkpoints replay their sequence. + ## Mixing Veryl and SystemVerilog {#mixed-language} `Simulator::from_mixed_sources`combines both source lists in one simulation. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 3a1f32d52dc..b7e4c3e542e 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -349,6 +349,15 @@ checkpoint と状態ファイルの保存・復元はエラーになります。 `$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 両端を含み、境界が同じ値か逆順なら seed を進めず `start` を返します。 +`$dist_normal`、`$dist_exponential`、`$dist_poisson`、`$dist_chi_square`、 +`$dist_t`、`$dist_erlang` は時間付き `Simulation` のプロセスとそのサブルーチンで +Annex N の分布を使います。引数と戻り値は符号付き32ビット整数です。 +整数の inout seed は int に変換し、添字付き要素の場合も一度だけ書き戻します。 +指数・Poisson分布の mean、カイ二乗・t分布の自由度、Erlang分布の両引数は正値が必要です。 +不正な値は seed を更新せず実行時エラーとして診断します。正規分布の mean と標準偏差は +任意の整数を受け付けます。SV の `real` 型は必要ありません。seed はデザインの状態なので、 +checkpoint の復元で乱数列を再現できます。 + ## 時刻と精度 {#time-and-precision} `$timeunit` と `$timeprecision` は秒を基準とする指数を32ビットの符号付き整数で