From 96e0a9efe34ce43ece4b95b02cd82750197d6668 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 05:29:27 +0900 Subject: [PATCH] feat(cli): configure SV parameter literals and simulation state modes Allow CLI and project parameter overrides to preserve signed values, packed strings, explicit widths, unbased fills and X/Z bits. Add the corresponding SimulatorBuilder::param_literal API; numeric overrides keep their existing API and last-value-wins behavior. Reject SV literals for Veryl inputs. Add --two-state/--four-state and four_state in project and target settings, with project < target < CLI precedence. Use two-state simulation as the default. Serialize the selected mode into native executables and normalize VPI X/Z deposits and forces using the effective runtime mode. This lets Taxi's APB-to-AXI-Lite and AXI-to-AXI-Lite adapter tests use the same two-state condition as their upstream Verilator runs. The original 8-bit configurations pass all 12 cocotb tests each at O1; the AXI adapter run takes about 419 seconds. Other remaining Taxi failures are not hidden by this setting. Validation: O2 literal-parameter API regressions across backends; all project CLI tests, including merge precedence, native image round trips and Veryl input rejection; VPI deposits/forces and package tests; affected-crate Clippy and formatting. Also check celox without default features to preserve builds without SystemVerilog support. Change-Id: I349bbcdce9d4747dcac4c19b985b5a29622022b3 --- crates/celox-vpi/src/bin/celox.rs | 7 +- crates/celox-vpi/src/bin/celox/project.rs | 104 +++++++- crates/celox-vpi/src/bin/celox/runner.rs | 4 +- crates/celox-vpi/src/driver.rs | 46 +++- crates/celox-vpi/src/lib.rs | 10 +- crates/celox-vpi/tests/basic_vpi.rs | 66 +++++ crates/celox-vpi/tests/project_cli.rs | 233 +++++++++++++++++- .../celox/src/backend/native/runtime_image.rs | 5 + crates/celox/src/parser.rs | 4 +- crates/celox/src/simulator/builder.rs | 146 +++++++---- .../frontends/systemverilog/hierarchy.rs | 25 ++ docs/guide/cocotb.md | 5 +- docs/ja/guide/cocotb.md | 3 +- 13 files changed, 574 insertions(+), 84 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 040afeae2ab..99295fba55a 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -156,7 +156,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) - .four_state(arguments.execution.four_state) + .four_state(arguments.design.four_state.unwrap_or(false)) .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) @@ -403,7 +403,7 @@ fn compile_native_design(design: &Design) -> Result .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulator::from_sv_sources(refs, &design.top) - .four_state(true) + .four_state(design.four_state.unwrap_or(false)) .diagnostic_policy(design.diagnostics.clone()) .signal_access(design.signal_access.clone()) .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); @@ -427,13 +427,14 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let (image, warnings) = celox_vpi::driver::compile_native_image_with_parameters( + let (image, warnings) = celox_vpi::driver::compile_native_image_with_state( &design.sources[0], &design.top, design.diagnostics.clone(), design.opt_level.unwrap_or(celox::OptLevel::O1), design.signal_access.clone(), &design.parameters, + design.four_state.unwrap_or(false), )?; report_warnings(&warnings)?; Ok(image) diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 4a46c0528be..f3082b12cb5 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -18,6 +18,12 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Use two-state simulation, resolving X/Z to zero. + #[arg(long, conflicts_with = "four_state")] + two_state: bool, + /// Use four-state simulation, overriding the project (default: two-state). + #[arg(long)] + four_state: bool, /// Optimization level: O0, O1, O2 (default: project setting or O2 for run, O1 for vpi build). #[arg(short = 'O', long, value_parser = super::parse_opt_level)] opt_level: Option, @@ -56,7 +62,7 @@ pub(super) struct DesignArgs { /// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins). #[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")] defines: Vec, - /// Override a numeric top parameter (repeatable; last value wins). + /// Override a top parameter with an integer or SV literal (repeatable; last value wins). #[arg( short = 'G', long = "parameter", @@ -95,6 +101,7 @@ struct Manifest { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -127,6 +134,7 @@ struct Target { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -140,8 +148,10 @@ pub(super) struct Design { pub include_dirs: Vec, pub defines: BTreeMap, pub parameters: BTreeMap, + sv_parameters: BTreeMap, pub top: String, pub opt_level: Option, + pub four_state: Option, pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -275,6 +285,7 @@ impl DesignArgs { design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; + design.four_state = config.four_state; if let Some(target) = selected { design.extend_parameters(&target.parameters)?; design.diagnostics.0.extend(target.diagnostics.0.clone()); @@ -296,6 +307,7 @@ impl DesignArgs { design.signal_access.force_signals.clone_from(paths); } design.max_steps = target.max_steps.or(design.max_steps); + design.four_state = target.four_state.or(design.four_state); } design.opt_level = opt_level .map(|value| { @@ -322,6 +334,12 @@ impl DesignArgs { } })); design.opt_level = self.opt_level.or(design.opt_level); + if self.two_state { + design.four_state = Some(false); + } + if self.four_state { + design.four_state = Some(true); + } if self.no_live_signals { design.signal_access.live_signals.clear(); } else if !self.live_signals.is_empty() { @@ -359,7 +377,7 @@ impl DesignArgs { let (name, value) = parameter .split_once('=') .ok_or_else(|| format!("invalid parameter `{parameter}`: expected NAME=VALUE"))?; - design.set_parameter(name, parse_parameter_value(value)?)?; + design.set_parameter_text(name, value, false)?; } if let Some(top) = self.top { design.top = top; @@ -372,6 +390,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && !design.sv_parameters.is_empty() { + return Err("SV parameter literals require .sv/.v sources".to_string()); + } if !design.is_sv() && (!design.include_dirs.is_empty() || !design.defines.is_empty()) { return Err( "include directories and defines require SystemVerilog sources".to_string(), @@ -381,12 +402,13 @@ impl DesignArgs { } } -/// TOML integers cover ordinary values; strings also permit radix prefixes -/// and the full unsigned 64-bit range supported by SimulatorBuilder::param. +/// Preserve ordinary integer settings while admitting signed SV literals and +/// textual parameters without losing their width or signedness. #[derive(Deserialize)] #[serde(untagged)] enum ParameterValue { Integer(u64), + Signed(i64), String(String), } @@ -424,6 +446,9 @@ impl Design { for (name, value) in &self.parameters { builder = builder.param(name, *value); } + for (name, literal) in &self.sv_parameters { + builder = builder.param_literal(name, literal); + } builder } @@ -432,16 +457,25 @@ impl Design { parameters: &BTreeMap, ) -> Result<(), String> { for (name, value) in parameters { - let value = match value { - ParameterValue::Integer(value) => *value, - ParameterValue::String(value) => parse_parameter_value(value)?, - }; - self.set_parameter(name, value)?; + match value { + ParameterValue::Integer(value) => self.set_parameter(name, *value)?, + ParameterValue::Signed(value) => { + self.set_parameter_text(name, &value.to_string(), false)? + } + ParameterValue::String(value) => self.set_parameter_text(name, value, true)?, + } } Ok(()) } fn set_parameter(&mut self, name: &str, value: u64) -> Result<(), String> { + Self::validate_parameter_name(name)?; + self.sv_parameters.remove(name); + self.parameters.insert(name.to_string(), value); + Ok(()) + } + + fn validate_parameter_name(name: &str) -> Result<(), String> { if name.is_empty() || !name.bytes().enumerate().all(|(index, byte)| { byte == b'_' @@ -451,10 +485,60 @@ impl Design { { return Err(format!("invalid top parameter name `{name}`")); } - self.parameters.insert(name.to_string(), value); Ok(()) } + fn set_parameter_text( + &mut self, + name: &str, + text: &str, + bare_string: bool, + ) -> Result<(), String> { + if let Ok(value) = parse_parameter_value(text) { + return self.set_parameter(name, value); + } + #[cfg(feature = "systemverilog")] + { + let literal = if celox_sv_analyzer::typecheck::parse_parameter_literal(text).is_some() { + text.to_string() + } else if bare_string { + // TOML strings are ordinary string values unless they spell a + // numeric literal. Encode bytes using SV's escape rules. + let mut quoted = String::from("\""); + for byte in text.bytes() { + match byte { + b'"' => quoted.push_str("\\\""), + b'\\' => quoted.push_str("\\\\"), + b'\n' => quoted.push_str("\\n"), + b'\t' => quoted.push_str("\\t"), + 32..=126 => quoted.push(char::from(byte)), + 0..=127 => quoted.push_str(&format!("\\{byte:03o}")), + _ => return Err(format!("non-ASCII string parameter `{name}`")), + } + } + quoted.push('"'); + quoted + } else { + return Err(format!( + "invalid parameter value `{text}`: expected an unsigned 64-bit integer or SV literal" + )); + }; + // Reuse the name validation and remove whichever representation a + // lower-precedence project or target setting used. + Self::validate_parameter_name(name)?; + self.parameters.remove(name); + self.sv_parameters.insert(name.to_string(), literal); + Ok(()) + } + #[cfg(not(feature = "systemverilog"))] + { + let _ = (name, bare_string); + Err(format!( + "invalid parameter value `{text}`: SV literals require the systemverilog feature" + )) + } + } + pub fn is_sv(&self) -> bool { !self.sources.is_empty() && self.sources.iter().all(|path| { diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index b3bc75ac7ae..802e60033c9 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -33,8 +33,6 @@ pub(super) struct ExecutionArgs { #[arg(long, value_enum, default_value = "native")] pub backend: Backend, #[arg(long)] - pub four_state: bool, - #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. #[arg(long, value_name = "PATH")] @@ -197,7 +195,7 @@ pub(super) fn run( test: design.top.clone(), opt_level: design.opt_level.unwrap_or(OptLevel::O2), backend: cli.backend, - four_state: cli.four_state, + four_state: design.four_state.unwrap_or(false), compile_only: cli.compile_only, native_image_output: cli.native_image_output, native_image_input: cli.native_image_input, diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 350ecd6912f..c7bd819169c 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -60,7 +60,10 @@ pub fn compile_native_image_with_diagnostics( policy, celox::OptLevel::O0, celox::SignalAccessOptions::default(), - true, + CompileMode { + legacy_force: true, + four_state: true, + }, &BTreeMap::new(), ) } @@ -85,16 +88,45 @@ pub fn compile_native_image_with_parameters( access: celox::SignalAccessOptions, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { - compile_native_image_configured(source, top, policy, level, access, false, parameters) + compile_native_image_with_state(source, top, policy, level, access, parameters, true) } -fn compile_native_image_configured( +/// Compile numeric parameters with an explicit four-state simulation mode. +pub fn compile_native_image_with_state( source: &Path, top: &str, policy: DiagnosticPolicy, level: celox::OptLevel, access: celox::SignalAccessOptions, + parameters: &BTreeMap, + four_state: bool, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured( + source, + top, + policy, + level, + access, + CompileMode { + legacy_force: false, + four_state, + }, + parameters, + ) +} + +struct CompileMode { legacy_force: bool, + four_state: bool, +} + +fn compile_native_image_configured( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + mode: CompileMode, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { let compiled = if let Ok(metadata_path) = Metadata::search_from(source) { @@ -118,8 +150,8 @@ fn compile_native_image_configured( let builder = Simulator::from_sources(source_refs, top) .with_metadata(metadata) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters @@ -133,8 +165,8 @@ fn compile_native_image_configured( .map_err(|error| format!("failed to read {}: {error}", source.display()))?; let builder = Simulator::from_sources(vec![(contents.as_str(), source)], top) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 7b72d33a241..b35a0804a69 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1312,10 +1312,12 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| (signal.signal.width, signal.signal.is_4state)) + runtime.reflection().signal(id).map(|signal| { + ( + signal.signal.width, + signal.signal.is_4state && runtime.four_state(), + ) + }) }) .flatten(); let Some((width, is_4state)) = signal_info else { diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index fe2ef1926b0..b0dd703a978 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3088,3 +3088,69 @@ fn interface_members_are_navigable_after_native_image_round_trip() { } } } + +#[cfg(feature = "systemverilog")] +#[test] +fn two_state_image_converts_unknown_logic_deposits_and_forces() { + let _serial = lock_vpi(); + let source = "module Top(input logic[3:0] a,output logic[3:0] y); assign y=a; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("two_state.sv"))], "Top") + .four_state(false) + .native_force_support(true) + .build() + .unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + unsafe { + let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); + let y = vpi_handle_by_name(c"Top.y".as_ptr(), ptr::null_mut()); + let mut word = VpiVecVal { aval: 15, bval: 10 }; + let input = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { vector: &mut word }, + }; + let mut output = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { integer: 0 }, + }; + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_NO_DELAY), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 5); + assert_eq!((*output.value.vector).bval, 0); + let mut force_word = VpiVecVal { aval: 15, bval: 5 }; + let force_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut force_word, + }, + }; + assert_eq!( + vpi_put_value(a, &force_value, ptr::null(), VPI_FORCE_FLAG), + a + ); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 10); + assert_eq!((*output.value.vector).bval, 0); + let mut deposited_word = VpiVecVal { aval: 15, bval: 12 }; + let deposited_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut deposited_word, + }, + }; + assert_eq!( + vpi_put_value(a, &deposited_value, ptr::null(), VPI_NO_DELAY), + a + ); + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_RELEASE_FLAG), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 3); + assert_eq!((*output.value.vector).bval, 0); + vpi_free_object(a); + vpi_free_object(y); + } + clear_runtime(); +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index bf043129c4f..06be274810f 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -583,18 +583,231 @@ fn top_parameters_reach_veryl_run_and_native_build() { fn invalid_parameter_assignments_are_rejected() { let root = tempfile::tempdir().unwrap(); for value in [ - "V", - "=1", - "x.y=1", - "V=", - "V=-1", - "V=1+2", - "V=18446744073709551616", - "V=0x", - "V=0b2", - "V=_1", + "V", "=1", "x.y=1", "V=", "V=--1", "V=1+2", "V=8'hG", "V=0x", "V=0b2", "V=_1", ] { let output = invoke(root.path(), &["run", "dut.sv", "--top", "Top", "-G", value]); rejected(&output, "parameter"); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { + let root = tempfile::tempdir().unwrap(); + let source = r#" + module Top #(parameter VENDOR="GENERIC", parameter NEG=3, + parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [3:0] UNKNOWN=0)(output logic matched); + assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) + && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) + && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (UNKNOWN === 4'b10xz); + initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); + $display("ok"); $finish; end + endmodule + "#; + fs::write(root.path().join("top.sv"), source).unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources=["top.sv"] + top="Top" + [parameters] + VENDOR="GENERIC" + NEG=3 + FILL=0 + [targets.literals.parameters] + VENDOR="XILINX" + NEG=-8 + WIDE="65'h10000000000000001" + FILL="'1" + UNKNOWN="4'b10xz" + "#, + ) + .unwrap(); + let output = invoke(root.path(), &["run", "--target", "literals"]); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + let args = [ + "--target", + "literals", + "-GVENDOR=0", + "-GVENDOR=\"XILINX\"", + "-GNEG=8", + "-GNEG=-8", + "-GFILL=0", + "-GFILL='1", + ]; + let output = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let matched = instance.signal_ref("Top.matched").unwrap(); + assert_eq!( + celox::SimBackend::get_as::(instance.backend(), matched), + 1 + ); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#" + module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b",y); $finish; end + endmodule + "#, + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\nfour_state=true\n[targets.two]\nfour_state=false\n", + ) + .unwrap(); + for (args, expected, is_four) in [ + (vec![], "value=xxxx\n", true), + (vec!["--two-state"], "value=0000\n", false), + (vec!["--target", "two"], "value=0000\n", false), + ( + vec!["--target", "two", "--four-state"], + "value=xxxx\n", + true, + ), + ] { + let run = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&run); + assert_eq!(String::from_utf8(run.stdout).unwrap(), expected); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), is_four); + let (value, mask) = celox::SimBackend::get_four_state( + instance.backend(), + instance.signal_ref("Top.y").unwrap(), + ); + assert_eq!( + mask.to_u64_digits(), + if is_four { vec![15] } else { vec![] } + ); + if !is_four { + assert_eq!(value.to_u64_digits(), Vec::::new()); + } + } +} + +#[test] +fn sv_literal_parameters_are_rejected_for_veryl_in_both_commands() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top #(param W:u32=8) (y:output logic) { assign y=0; }", + ) + .unwrap(); + for prefix in [&["run"][..], &["vpi", "build"][..]] { + let output = invoke( + root.path(), + &[prefix, &["top.veryl", "--top", "Top", "-GW=-8"]].concat(), + ); + rejected(&output, "SV parameter literals require"); + } +} + +#[test] +fn veryl_native_images_preserve_the_selected_state_mode() { + for with_metadata in [false, true] { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top (y:output logic<4>) { assign y=3; }", + ) + .unwrap(); + if with_metadata { + fs::write( + root.path().join("Veryl.toml"), + "[project]\nname='state_mode'\nversion='0.1.0'\n", + ) + .unwrap(); + } + for (flag, four_state) in [("--two-state", false), ("--four-state", true)] { + let output = invoke( + root.path(), + &[ + "vpi", + "build", + "top.veryl", + "--top", + "Top", + flag, + "-o", + "sim", + ], + ); + success(&output); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), four_state); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_cli_defaults_to_two_state_for_run_and_native_images() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#"module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b", y); $finish; end + endmodule"#, + ) + .unwrap(); + let run = invoke(root.path(), &["run", "top.sv", "--top", "Top"]); + success(&run); + assert_eq!(run.stdout, b"value=0000\n"); + success(&invoke( + root.path(), + &["vpi", "build", "top.sv", "--top", "Top", "-o", "sim"], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: this test compiled the source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert!(!instance.four_state()); +} diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 271f4523a44..3e1bc73d563 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -108,6 +108,11 @@ impl NativeProgramInstance { self.shared.program_image().time_precision() } + /// Whether the attached image executes with four-state values. + pub fn four_state(&self) -> bool { + self.shared.program_image().four_state() + } + /// Elaborated hierarchy and signal metadata embedded by the compiler. pub fn reflection(&self) -> &DesignReflection { self.shared.program_image().reflection() diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 1072ec8ad5f..36c5b0bc558 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -573,7 +573,7 @@ pub fn parse( pub fn parse_sv( sources: &[(&str, &std::path::Path)], top: &str, - parameter_overrides: &[(String, u64)], + parameter_overrides: &[(String, celox_frontend_sv::analyzer_ir::ConstExpr)], _config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), @@ -599,7 +599,7 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); - let scheduled = celox_frontend_sv::schedule_sources_with_force_signals( + let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions( sources, top, parameter_overrides, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 96414337517..89059ee1f19 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1081,6 +1081,7 @@ pub fn compile_sv_to_sir( &crate::DiagnosticPolicy::default(), crate::backend::memory_layout::MemoryLayoutMode::Packed, &[], + &[], ) } @@ -1110,7 +1111,24 @@ fn compile_sv_to_sir_with_layout_mode( diagnostic_policy: &crate::DiagnosticPolicy, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + let mut parameters = param_overrides + .iter() + .map(|(name, value)| { + ( + name.clone(), + celox_frontend_sv::analyzer_ir::ConstExpr::Literal(value.to_string()), + ) + }) + .collect::>(); + for (name, literal) in sv_param_literals { + let value = celox_frontend_sv::analyzer_typecheck::parse_parameter_literal(literal) + .ok_or_else(|| { + crate::CodegenError::message(format!("invalid SV parameter literal `{literal}`")) + })?; + parameters.push((name.clone(), value)); + } let metadata = metadata.unwrap_or_else(|| Metadata::create_default("prj").unwrap()); let mut build_config = BuildConfig::from(&metadata.build); if let Some(clock_type) = clock_type { @@ -1124,7 +1142,7 @@ fn compile_sv_to_sir_with_layout_mode( let sir = parser::parse_sv( sources, top, - param_overrides, + ¶meters, &build_config, ignored_loops, true_loops, @@ -1366,7 +1384,14 @@ fn compile_hdl_to_sir_with_layout_mode( allow_always_ff_function_effects: bool, file_dependencies: &celox_frontend_veryl::FileDependencyCollector, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + if !sv_param_literals.is_empty() && (!sources.is_empty() || sv_sources.is_empty()) { + return Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()); + } if !force_signals.is_empty() && !sources.is_empty() { return Err(crate::CodegenError::message( "force_signals currently require pure SystemVerilog sources", @@ -1438,6 +1463,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostic_policy, layout_mode, force_signals, + sv_param_literals, ), (false, false) => compile_mixed_to_sir_with_layout_mode( sources, @@ -1804,6 +1830,7 @@ mod host { clock_type: Option, reset_type: Option, param_overrides: Vec<(String, u64)>, + sv_param_literals: Vec<(String, String)>, live_signals: Vec<(Vec<(String, usize)>, Vec)>, injected_components: crate::InjectedComponents, frontend_artifact: Option, @@ -1885,10 +1912,22 @@ mod host { /// Override a top-level module parameter value. pub fn param(mut self, name: &str, value: u64) -> Self { + self.sv_param_literals.retain(|(key, _)| key != name); self.param_overrides.push((name.to_string(), value)); self } + /// Override a pure SV top parameter with a literal, such as `-8`, + /// `8'hff`, `'1`, or `"XILINX"`. The literal's width and signedness + /// are preserved. Invalid literals are reported when building. + pub fn param_literal(mut self, name: &str, literal: &str) -> Self { + self.param_overrides.retain(|(key, _)| key != name); + self.sv_param_literals.retain(|(key, _)| key != name); + self.sv_param_literals + .push((name.to_string(), literal.to_string())); + self + } + /// Make in-process component implementations available as `$comp::`. pub fn with_injected_components(mut self, components: crate::InjectedComponents) -> Self { self.injected_components = components; @@ -2332,6 +2371,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2353,6 +2393,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2375,6 +2416,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2402,6 +2444,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2428,6 +2471,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2455,6 +2499,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2509,7 +2554,13 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let compile_start = phase_timing.then(crate::timing::now); let injected_manifests = self.injected_components.manifests(); - let compiled = if let Some(artifact) = &self.frontend_artifact { + let compiled = if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() + { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { if self.sources.is_empty() { compile_frontend_to_sir_with_layout_mode( artifact, @@ -2568,6 +2619,7 @@ mod host { self.options.allow_always_ff_function_effects, &self.file_dependencies, &self.options.signal_access.force_signals, + &self.sv_param_literals, ) }; let (program, mut warnings) = compiled @@ -3162,23 +3214,52 @@ mod host { layout_mode }; let injected_manifests = self.injected_components.manifests(); - let program_res = if let Some(artifact) = &self.frontend_artifact { - if self.sources.is_empty() { - compile_frontend_to_sir_with_layout_mode( - artifact, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - &self.options.optimize_options, - &self.options.diagnostics, - layout_mode, + let program_res = + if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { + if self.sources.is_empty() { + compile_frontend_to_sir_with_layout_mode( + artifact, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + &self.options.optimize_options, + &self.options.diagnostics, + layout_mode, + ) + } else { + compile_frontend_testbench_to_sir_with_layout_mode( + artifact, + &self.sources, + self.top, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + self.metadata, + self.clock_type, + self.reset_type, + &self.options.optimize_options, + &self.options.diagnostics, + &self.options.diagnostic_policy, + &injected_manifests, + layout_mode, + !self.options.native_force_support, + self.options.allow_always_ff_function_effects, + &self.file_dependencies, + ) + } } else { - compile_frontend_testbench_to_sir_with_layout_mode( - artifact, + compile_hdl_to_sir_with_layout_mode( &self.sources, + &self.sv_sources, self.top, &self.ignored_loops, &self.true_loops, @@ -3188,6 +3269,7 @@ mod host { self.metadata, self.clock_type, self.reset_type, + &self.param_overrides, &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, @@ -3196,33 +3278,10 @@ mod host { !self.options.native_force_support, self.options.allow_always_ff_function_effects, &self.file_dependencies, + &self.options.signal_access.force_signals, + &self.sv_param_literals, ) - } - } else { - compile_hdl_to_sir_with_layout_mode( - &self.sources, - &self.sv_sources, - self.top, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - self.metadata, - self.clock_type, - self.reset_type, - &self.param_overrides, - &self.options.optimize_options, - &self.options.diagnostics, - &self.options.diagnostic_policy, - &injected_manifests, - layout_mode, - !self.options.native_force_support, - self.options.allow_always_ff_function_effects, - &self.file_dependencies, - &self.options.signal_access.force_signals, - ) - }; + }; let program_res = program_res .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); @@ -3336,6 +3395,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3357,6 +3417,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3380,6 +3441,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 87930fcef09..f1baf76a403 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -362,3 +362,28 @@ fn rejects_feedback_through_the_same_bit_of_child_input() { "#, ); } + +sv_backends! { + fn literal_parameter_api_preserves_width_sign_and_unknowns(sim) { + @setup { + let source = r#" + module Top #(parameter TEXT="default", parameter NEG=0, + parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) + && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) + && (FILL==12'hfff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7); + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("parameter_api.sv"))], "Top") + .param_literal("TEXT", "\"XILINX\"") + .param("NEG", 3).param_literal("NEG", "-8") + .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") + .param_literal("WIDE", "65'h10000000000000001") + .param_literal("FINAL", "-1").param("FINAL", 7) + .four_state(true).opt_level(celox::OptLevel::O2); + assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); + } +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index a8e5e399c5e..196f4527c89 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -33,8 +33,9 @@ target/release/celox run test/Top.veryl --top Top ``` For SystemVerilog, pass `.sv` or `.v` sources in compilation order. The command -uses two-state simulation by default (`--four-state` enables X/Z tracking) and runs until `$finish` or no scheduled events -remain. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` +uses two-state simulation by default and runs until `$finish` or no scheduled +events remain. Use `--four-state` or `four_state = true` in `celox.toml` to retain +X/Z values. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` and collects the project's sources and dependencies. A standalone Veryl file also works. Both languages default to two-state simulation. Select the native testbench module with `--top`. Veryl uses the existing native testbench executor; a test may also complete by diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index d0a26bd0fe6..0f37fae4f4b 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -30,8 +30,9 @@ target/release/celox run src/types.sv src/Dut.sv test/Top.sv --top Top target/release/celox run test/Top.veryl --top Top ``` -SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い(`--four-state`でX/Zを扱う4値に切り替え)、 +SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い、 `$finish`または実行待ちイベントがなくなるまで実行します。 +X/Zを保持する場合は`--four-state`または`celox.toml`の`four_state = true`を指定します。 Verylはプロジェクト内の1ファイルを指定すると、`Veryl.toml`から ソースと依存関係を収集します。単独のVerylファイルも使用でき、Verylも既定は2値です。 `--top`にはnative testbenchのモジュール名を指定します。