From 5469981e2c0f810453e01679a909414ea6371f71 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 11:18:07 +0900 Subject: [PATCH 1/3] feat(sv)!: support opt-in interface-array size queries Taxi uses $size(interface_array) in parameters and generate bounds. Resolve these queries from bound interface-array shapes, including formal ports, generated scopes, multiple dimensions and indexed subarrays. Preserve ordinary data-object shadowing and return a signed integer unknown for invalid numeric dimensions. Other interface data queries remain unsupported. Treat this as a compatibility extension: interface_array_query defaults to error and can be enabled with warn or allow through the existing CLI diagnostic option or celox.toml diagnostics table. Preserve located, deduplicated warnings, including when later analysis fails. Document the policy in both guides. Validation: - SystemVerilog suite: 4096 passed, 20 existing ignored. - Analyzer: 791 passed, 3 existing ignored; frontend: 4 passed. - Diagnostic policy: 33 passed; CLI integration: 5 policy combinations passed. - Formatting and affected library/test Clippy checks with -D warnings passed. - Verilator 5.052 passed the reference with assertions enabled. Slang 12 rejects the same interface query, supporting its classification as an extension. A paired frontend-only Taxi audit of 83 configurations on the master base finds that 32 of the 34 affected configurations reach their next blocker; two hit the 120-second limit. The 17 existing frontend passes remain unchanged. No additional configuration completes, and no new cocotb execution is claimed. All 299 resolved upstream source files are unchanged. This PR is independent of the assignment-pattern changes in #1772. BREAKING CHANGE: AnalyzerWarning and FrontendWarningKind gain an InterfaceArrayQuery variant; downstream exhaustive matches must handle it. Change-Id: Ie71c67508b89ab93b4b967e02d5734c7330be136 --- crates/celox-frontend-sv/src/warning.rs | 9 ++ crates/celox-sv-analyzer/src/ast.rs | 63 ++++++---- .../src/ast/const_functions.rs | 2 + .../src/ast/dimensions/query_binding.rs | 88 +++++++++++++ .../src/ast/interface_ast.rs | 1 + crates/celox-sv-analyzer/src/ast/packages.rs | 1 + crates/celox-sv-analyzer/src/ast/warnings.rs | 2 + crates/celox-vpi/tests/run_cli.rs | 61 +++++++++ crates/celox/src/diagnostic_policy.rs | 1 + crates/celox/tests/diagnostic_policy.rs | 119 ++++++++++++++++++ .../frontends/systemverilog/interfaces.rs | 56 +++++++++ docs/guide/celox-toml.md | 13 ++ docs/ja/guide/celox-toml.md | 9 ++ 13 files changed, 404 insertions(+), 21 deletions(-) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 464084d0d44..851b993d562 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -40,6 +40,8 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations. #[error("mixed explicit and default time units or precisions across design elements")] MixedTimescale, + #[error("`$size` on an interface array is a language extension")] + InterfaceArrayQuery, /// IEEE 1800-2023 9.2.2.4 restricts writes by other processes. #[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")] MultipleAlwaysFfDrivers { module: String, signal: String }, @@ -96,6 +98,9 @@ pub(crate) fn analyzer_warnings( found: &[celox_sv_analyzer::ir::AnalyzerWarning], ) -> impl Iterator + '_ { found.iter().map(|warning| match warning { + celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayQuery { site } => { + (FrontendWarningKind::InterfaceArrayQuery, site.clone()) + } celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => { (FrontendWarningKind::MixedTimescale, None) } @@ -149,6 +154,7 @@ impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", + FrontendWarningKind::InterfaceArrayQuery => "interface_array_query", FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers", FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::InferredLatch => "inferred_latch", @@ -166,6 +172,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::InferredLatch => { "assign every output on every path, or configure diagnostics.inferred_latch as warn or allow" } + FrontendWarningKind::InterfaceArrayQuery => { + "interface arrays are not data arrays in IEEE 1800-2023 20.7; set interface_array_query=warn or allow for compatibility" + } FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 6ab988df73b..4360e0dea28 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -27,6 +27,7 @@ pub(super) struct AnalysisState { root_subroutines: std::cell::Cell, next_call_site: std::rc::Rc>, timescales: timescales::State, + diagnostics: RefCell>, /// Classes laid out so far, by name. classes: std::cell::RefCell>>, } @@ -249,6 +250,7 @@ impl InterfaceLookup<'_> { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Source { modules: Vec, + diagnostics: Vec, } /// Overrides supplied by one instantiation. Types have been resolved in its scope. @@ -298,16 +300,21 @@ impl Source { &packages, packages.unit(Path::new("")), )?; - modules.push(Module::from_scope_with_parameter_overrides( - syntax_tree, - module_name, - ¶meter_overrides, - &InterfaceLookup { - local: &interfaces, - extra: &ModuleInterfaces::default(), - }, - Arc::new(imported), - )?); + modules.push( + Module::from_scope_with_parameter_overrides( + syntax_tree, + module_name, + ¶meter_overrides, + &InterfaceLookup { + local: &interfaces, + extra: &ModuleInterfaces::default(), + }, + Arc::new(imported), + ) + .map_err(|error| { + error.with_warnings(context.state.diagnostics.borrow().clone()) + })?, + ); } celox_sv_syntax::PortStyle::NonAnsi => { return Err(AnalyzerError::Unsupported( @@ -318,7 +325,10 @@ impl Source { } } - Ok(Self { modules }) + Ok(Self { + modules, + diagnostics: context.state.diagnostics.borrow().clone(), + }) } pub(crate) fn from_syntax_module_with_parameter_overrides( @@ -426,18 +436,26 @@ impl Source { }, &interfaces, imported.clone(), - )? { + ) + .map_err(|error| { + error.with_warnings(context.state.diagnostics.borrow().clone()) + })? { module.name = module_name.to_string(); modules.push(module); continue; } - modules.push(Module::from_scope_with_parameter_overrides( - syntax_tree, - module_name, - bindings.values, - &interfaces, - Arc::new(imported), - )?); + modules.push( + Module::from_scope_with_parameter_overrides( + syntax_tree, + module_name, + bindings.values, + &interfaces, + Arc::new(imported), + ) + .map_err(|error| { + error.with_warnings(context.state.diagnostics.borrow().clone()) + })?, + ); } celox_sv_syntax::PortStyle::NonAnsi if syntax_tree.root_name()? == module_name => { return Err(AnalyzerError::Unsupported( @@ -447,7 +465,10 @@ impl Source { _ => {} } } - Ok(Self { modules }) + Ok(Self { + modules, + diagnostics: context.state.diagnostics.borrow().clone(), + }) } pub(crate) fn module_names_from_syntax( @@ -492,7 +513,7 @@ impl Source { } pub(crate) fn warnings(&self) -> Vec { - let mut warnings = Vec::new(); + let mut warnings = self.diagnostics.clone(); for module in &self.modules { warnings::append(&mut warnings, module.constant_functions.warnings()); } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 18fe205b6fa..66c9f602e7e 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -175,6 +175,8 @@ impl ConstantFunctions { ) => std::cmp::Ordering::Equal, (super::warnings::AnalyzerWarning::MixedTimescale, _) => std::cmp::Ordering::Less, (_, super::warnings::AnalyzerWarning::MixedTimescale) => std::cmp::Ordering::Greater, + // This collector emits only ExitOutsideProgram warnings. + _ => std::cmp::Ordering::Equal, }); warnings } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 6778c863882..985c89c846e 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -88,6 +88,17 @@ pub(in crate::ast) fn query_value( let argument = arguments[0].value.unwrap(); let context = query_context_for_operand(argument, tree, context)?; reject_unbounded(argument, function, tree, &context)?; + if function == SystemFunction::Size + && let Some(value) = interface_array_size( + root, + argument, + arguments.get(1).and_then(|a| a.value), + tree, + &context, + )? + { + return Ok(Some(value)); + } let shape = shape(argument, tree, &context)?; let dimension = if let Some(argument) = arguments.get(1) { Some(expression_binding::bind( @@ -216,6 +227,83 @@ pub(in crate::ast) fn query_value( .ok_or_else(|| unsupported(format!("operand of `{}`", name.spelling))) } +/// Query interface array metadata without admitting interface handles as data +/// expressions. This extension supports `$size` only; it adds no packed rank. +fn interface_array_size( + call: ExprId, + mut argument: ExprId, + dimension: Option, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, +) -> Converted> { + let native = tree.declarations(); + let mut selected = Vec::new(); + loop { + argument = expression_binding::ungroup(argument, native); + match &native.expression(argument).kind { + ExprKind::Select { + expression, + dimension, + } => { + let DimensionKind::Index(index) = dimension.kind else { + return Ok(None); + }; + selected.push(index); + argument = *expression; + } + _ => break, + } + } + let Ok(handle) = interface_binding::actual_handle_key( + argument, + tree, + &context.const_env, + &context.type_aliases, + ) else { + return Ok(None); + }; + let receiver = handle.split(['.', '[']).next().unwrap_or(&handle); + if context.get(receiver).is_some() + || context.const_env.contains_key(receiver) + || context.parameter_values.contains_key(receiver) + { + return Ok(None); + } + let imported = scope::imported(&tree.state); + let Some(array) = imported.interface_arrays.get(&handle) else { + return Ok(None); + }; + let Some(shape) = array + .shape + .get(selected.len()..) + .filter(|shape| !shape.is_empty()) + else { + return Ok(None); + }; + for index in selected { + validate_index(index, tree, context)?; + } + let dimension = match dimension { + Some(id) => constant_binding::bind(id, tree, context)? + .and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env)) + .ok_or_else(|| unsupported("nonconstant interface array query dimension"))?, + None => 1, + }; + let value = usize::try_from(dimension) + .ok() + .and_then(|d| d.checked_sub(1)) + .and_then(|index| shape.get(index)) + .map(|size| integer(*size as i128)) + .unwrap_or_else(|| Expr::Literal("32'sbx".into())); + warnings::append( + &mut tree.state.diagnostics.borrow_mut(), + [warnings::AnalyzerWarning::InterfaceArrayQuery { + site: procedural::source_span(native.expression(call).tokens, tree), + }], + ); + Ok(Some(value)) +} + fn parameter_dimension_count( mut root: ExprId, tree: &AnalysisContext<'_>, diff --git a/crates/celox-sv-analyzer/src/ast/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs index cd8bb5e78bd..7ca95f5efca 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_ast.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -216,6 +216,7 @@ pub(super) fn signature( module.instances.clear(); let ir = crate::analyze::analyze_source(Source { modules: vec![module], + diagnostics: Vec::new(), })?; ir.modules() .first() diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 5f43c0845e1..18b69492bd8 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -535,6 +535,7 @@ fn analyze_package_scope( } else { let ir = crate::analyze::analyze_source(Source { modules: vec![module], + diagnostics: Vec::new(), })?; ir.modules().first().cloned() }; diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index 20761ddfaef..0b8994bb6e2 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -8,6 +8,8 @@ use crate::procedural::SourceSpan; pub enum AnalyzerWarning { /// Explicit and implementation-default time scales occur in one design. MixedTimescale, + /// `$size` on an interface array is a compatibility extension to 20.7. + InterfaceArrayQuery { site: Option }, /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). ExitOutsideProgram { site: Option }, } diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 7f180da6475..e68b2bfb196 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -540,3 +540,64 @@ fn source_file_is_relative_to_celox_manifest_from_another_directory() { .unwrap(); assert!(output.status.success(), "{output:?}"); } + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_array_query_policy_flows_through_manifest_and_cli_overrides() { + let project = tempfile::tempdir().unwrap(); + std::fs::write( + project.path().join("top.sv"), + r#" + interface Lane; logic v; endinterface + module Top; + Lane lanes[3:2](); + localparam N=$size(lanes); + initial begin + assert(N==2) else $fatal(1,"size"); + $display("size=%0d",N); + $finish; + end + endmodule + "#, + ) + .unwrap(); + let manifest = project.path().join("celox.toml"); + for (configured, overridden, success, warning) in [ + (None, None, false, false), + (Some("warn"), None, true, true), + (Some("allow"), None, true, false), + (Some("warn"), Some("error"), false, false), + (Some("error"), Some("allow"), true, false), + ] { + let mut config = "sources=['top.sv']\ntop='Top'\n".to_string(); + if let Some(level) = configured { + config.push_str(&format!("[diagnostics]\ninterface_array_query='{level}'\n")); + } + std::fs::write(&manifest, config).unwrap(); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_celox")); + cmd.args(["run", "--project"]) + .arg(&manifest) + .args(["--backend", "interpreter"]) + .env("RUST_LOG", "warn"); + if let Some(level) = overridden { + cmd.args(["--diagnostic", &format!("interface_array_query={level}")]); + } + let output = cmd.output().unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.success(), + success, + "{configured:?}/{overridden:?}: {output:?}" + ); + if success { + assert_eq!(output.stdout, b"size=2\n", "{output:?}"); + assert_eq!( + stderr.contains("interface_array_query"), + warning, + "{stderr}" + ); + } else { + assert!(stderr.contains("interface_array_query"), "{stderr}"); + } + } +} diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index cf4dac9b34c..dc58a639307 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -85,6 +85,7 @@ impl DiagnosticPolicy { if matches!( code, "mixed_timescale" + | "interface_array_query" | "unpacked_port_default" | "multiple_always_ff_drivers" | "inferred_latch" diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index da7893b2a38..49eb9853ce8 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -614,3 +614,122 @@ mod inferred_latch { ); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_array_queries_require_a_recoverable_diagnostic_override() { + use std::path::Path; + let source = "interface Lane; logic v; endinterface module Top(output wire [7:0] y); Lane lanes[3:2](); assign y=$size(lanes); endmodule"; + let build = + || Simulator::from_sv_sources(vec![(source, Path::new("size_extension.sv"))], "Top"); + let error = build().build_cranelift().err().unwrap(); + assert!( + matches!(error.kind(), SimulatorErrorKind::DiagnosticPolicy(_)), + "{error}" + ); + assert!( + error.to_string().contains("interface_array_query"), + "{error}" + ); + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let mut sim = build() + .diagnostic_policy(policy("interface_array_query", level)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("y")), 2u8.into()); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + if let Some(warning) = sim.warnings().first() { + let rendered = celox::render_diagnostic(warning); + assert!(rendered.contains("size_extension.sv"), "{rendered}"); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_array_extension_keeps_interfaces_out_of_data_expressions() { + use std::path::Path; + for expression in [ + "$bits(lanes)", + "$left(lanes)", + "$size(lanes[0])", + "$size(lanes,missing)", + "$size(lanes,dim)", + "lanes", + ] { + let source = format!( + "interface Lane; logic v; endinterface module Top(input int dim,output wire [31:0] y); Lane lanes[2](); assign y={expression}; endmodule" + ); + assert!( + Simulator::from_sv_sources(vec![(&source, Path::new("bad_interface_query.sv"))], "Top") + .diagnostic_policy(policy("interface_array_query", DiagnosticLevel::Allow)) + .build_cranelift() + .is_err(), + "{expression}" + ); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_array_query_warning_survives_a_later_analysis_error() { + use std::path::Path; + let source = "interface Lane; logic v; endinterface module Top(output wire y); Lane lanes[2](); localparam N=$size(lanes); assign y=missing; endmodule"; + let error = Simulator::from_sv_sources(vec![(source, Path::new("later_error.sv"))], "Top") + .diagnostic_policy(policy("interface_array_query", DiagnosticLevel::Warn)) + .build_cranelift() + .err() + .unwrap(); + assert!(error.to_string().contains("missing"), "{error}"); + assert_eq!(error.warnings().len(), 1, "{error}"); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_array_query_policy_covers_formals_and_generated_scopes() { + use std::path::Path; + for source in [ + "interface Lane; logic v; endinterface module Reader(Lane ports[2],output wire [7:0] y); assign y=$size(ports); endmodule module Top(output wire [7:0] y); Lane lanes[2](); Reader r(.ports(lanes),.y(y)); endmodule", + "interface Lane; logic v; endinterface module Top(output wire [7:0] y); if(1) begin: bank Lane lanes[2](); assign y=$size(lanes); end endmodule", + "interface Lane; logic v; endinterface module Top(output wire [7:0] y); Lane lanes[2](); function automatic int count(); return $size(lanes); endfunction assign y=count(); endmodule", + ] { + let error = Simulator::from_sv_sources(vec![(source, Path::new("query_scope.sv"))], "Top") + .build_cranelift() + .err() + .unwrap(); + assert!( + error.to_string().contains("interface_array_query"), + "{error}" + ); + let mut sim = + Simulator::from_sv_sources(vec![(source, Path::new("query_scope.sv"))], "Top") + .diagnostic_policy(policy("interface_array_query", DiagnosticLevel::Allow)) + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("y")), 2u8.into()); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn invalid_interface_array_query_dimensions_return_integer_unknowns() { + use std::path::Path; + let source = "interface Lane; logic v; endinterface module Top(output wire [31:0] zero,extra,output wire [63:0] wide); Lane lanes[2](); assign zero=$size(lanes,0); assign extra=$size(lanes,2); assign wide=$size(lanes,2); endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("query_rank.sv"))], "Top") + .four_state(true) + .diagnostic_policy(policy("interface_array_query", DiagnosticLevel::Allow)) + .build_cranelift() + .unwrap(); + let wide = sim.signal("wide"); + assert_eq!(sim.get_four_state(wide), (u64::MAX.into(), u64::MAX.into())); + for name in ["zero", "extra"] { + let signal = sim.signal(name); + assert_eq!( + sim.get_four_state(signal), + (u32::MAX.into(), u32::MAX.into()) + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index 20f54ade184..373ba9c845e 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -141,3 +141,59 @@ sv_backends! { } } } + +// Interface objects are not IEEE 20.7 data arrays. This opt-in compatibility +// behavior belongs to Celox's harness rather than the portable language suite. +sv_backends! { + fn queries_interface_array_sizes_as_an_explicit_extension(sim) { + @setup { + let source = r#" + interface Lane; logic value; endinterface + module Child #(parameter N=1)(output wire [7:0] y); assign y=N; endmodule + module Reader(Lane ports[3:2], output wire [7:0] y); + assign y=$size(ports); + endmodule + module Top(output wire [7:0] local_count, param_count, formal_count, + first_count, second_count, selected_count, generated_count, shadow_count, member_shadow_count, + output wire [1:0] generated); + Lane lanes[3:2](); + Lane matrix[1:0][4:2](); + localparam N=$size(lanes); + assign local_count=N; + Child #(.N($size(lanes))) c(.y(param_count)); + Reader r(.ports(lanes), .y(formal_count)); + assign first_count=$size(matrix,1); + assign second_count=$size(matrix,2); + assign selected_count=$size(matrix[0]); + for(genvar i=0;i<$size(lanes);i=i+1) begin: bits_out + assign generated[i]=1'b1; + end + if(1) begin: bank + Lane local_lanes[5:7](); + assign generated_count=$size(local_lanes); + end + function automatic int shadow(); + int lanes[5]; + return $size(lanes); + endfunction + assign shadow_count=shadow(); + function automatic int shadow_member(); + struct packed {logic [4:0] local_lanes;} bank; + return $size(bank.local_lanes); + endfunction + assign member_shadow_count=shadow_member(); + endmodule + "#; + let mut policy=celox::DiagnosticPolicy::default(); + policy.set("interface_array_query",celox::DiagnosticLevel::Warn); + } + @build Simulator::from_sv_sources(vec![(source,Path::new("interface_array_size.sv"))],"Top") + .diagnostic_policy(policy); + for (name,expected) in [("local_count",2u8),("param_count",2),("formal_count",2), + ("first_count",2),("second_count",3),("selected_count",3), + ("generated_count",3),("shadow_count",5),("member_shadow_count",5),("generated",3)] { + assert_eq!(sim.get(sim.signal(name)),BigUint::from(expected),"{name}"); + } + assert!(!sim.warnings().is_empty()); + } +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 4f9069df0d3..3b54313138e 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -170,6 +170,19 @@ explicit settings remain effective, and the global precision includes default scopes. Syntax errors, unsupported constructs and invalid precision declarations remain errors. +`interface_array_query` defaults to `error`. Set it to `warn` or `allow` to enable +`$size` on fixed-size interface arrays and index-selected subarrays as a compatibility +extension. IEEE 1800-2023 §20.7 specifies queries on data arrays; interface +instances are not data objects. The optional dimension must be a known integer constant. This +extension does not give interface handles a packed width or enable other queries. + +```toml +[diagnostics] +interface_array_query = "warn" +``` + +The CLI uses the same policy: `celox run top.sv --top Top --diagnostic interface_array_query=warn`. + `multiple_always_ff_drivers` defaults to `error` for shared memories written by an `always_ff` and another edge process (IEEE 1800-2023 §9.2.2.4). With `warn` or `allow`, Celox stages their nonblocking writes in sparse next-state storage diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 30be45aabe4..6443f46cdad 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -155,6 +155,15 @@ memory_file_word_count = "error" Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatches: true` は、 この診断の明示設定がない場合だけ `allow` を補います。明示した `error`・`warn`・`allow` が優先されます。 +`interface_array_query` の既定値は `error` です。`warn` または `allow` で、固定長の interface 配列と添字で選択した部分配列に対する `$size` を互換拡張として許可します。IEEE 1800-2023 §20.7 の対象はデータ配列であり、interface インスタンスはデータオブジェクトではありません。省略可能な次元引数は既知の整数定数に限ります。この拡張によって interface ハンドルに packed 幅が付いたり、他の配列クエリが使えるようになったりすることはありません。 + +```toml +[diagnostics] +interface_array_query = "warn" +``` + +CLI でも同じ設定を使います: `celox run top.sv --top Top --diagnostic interface_array_query=warn`。 + `multiple_always_ff_drivers` は、`always_ff` と別のエッジプロセスが同じメモリへ書く場合に既定で `error` になります(IEEE 1800-2023 §9.2.2.4)。`warn` または `allow` では、非ブロッキング代入の変更範囲を次状態領域に保持してコミットします。通常の `always` 同士による共有にはこの診断は出ません。異なるプロセスが同時に同じビットへ書く順序は、移植可能な動作として保証されません。 プロジェクトのシミュレータ生成時は `Veryl.toml` と同じ場所の設定を読み込みます。CLI は単独の SystemVerilog プロジェクトにも対応します。 From 96ac9c1f0a9b4881c9b662e8f7a2d64213373715 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 09:58:59 +0900 Subject: [PATCH 2/3] fix(sv): write the bits inside a part-select partly outside its vector A blocking, comb, always_ff or continuous write to a constant part-select partly outside the vector wrote nothing; it now writes the bits inside, taking the matching bits of the value (IEEE 1800-2023 11.5.1). A write wholly outside still has no effect, and a continuous one is no longer rejected as a run-time position. A run-time select within one array element whose position is known while the design is compiled, from a time-zero initial block or an unrolled loop, was folded to a constant position of the whole array and wrote into the neighbouring elements. Such a fold is kept only while it stays within the element. Verilator 5.052 writes these out-of-range bits; the three new cases join the existing part-select overhang exclusion. Icarus passes them. Fixes #1778 Change-Id: I85269ba41a9587ee1e8f159dde592f0ddb2061b6 --- crates/celox-frontend-sv/src/lowering.rs | 90 +++++++++++++++++ crates/celox-frontend-sv/src/lowering/comb.rs | 87 ++++++++++------ crates/celox-frontend-sv/src/lowering/ff.rs | 56 ++++++----- crates/celox-test-suite/LIMITATIONS.md | 2 +- .../src/sv/cases/indexed_select.vtest | 98 +++++++++++++++++++ .../sv/icarus/indexed_select.json | 33 +++++++ .../verification/sv/limitations.json | 5 +- .../sv/limitations/verilator.json | 26 ++++- .../sv/verilator/indexed_select.json | 73 +++++++++++++- .../frontends/systemverilog/indexed_select.rs | 38 +++++++ 10 files changed, 448 insertions(+), 60 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index ce9eeda9600..a54ed201836 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -7237,6 +7237,19 @@ fn packed_index_offset(variable: &SvVariable, index: i128) -> Option { .filter(|offset| *offset < variable.width) } +/// The bit position of declared index `index` of `variable`, which may lie +/// outside it; see [`packed_index_offset`]. +fn packed_index_position(variable: &SvVariable, index: i128) -> Option { + if !variable.array_dims.is_empty() { + return Some(index); + } + match variable.packed_ranges.as_slice() { + [(left, right)] if left >= right => index.checked_sub(*right), + [(_, right)] => right.checked_sub(index), + _ => Some(index), + } +} + fn unpacked_element_width(variable: &SvVariable) -> Option { if variable.array_dims.is_empty() { return None; @@ -7395,6 +7408,83 @@ fn sv_memory_offset(variable: &SvVariable, bit_offset: usize, width: usize) -> S } } +/// The bits of `variable` that a constant select from declared index `msb` +/// to `lsb` writes, and the number of low bits of the assigned value that +/// fall below the variable. A select partly outside the variable writes only +/// the bits inside, one wholly outside writes none (IEEE 1800-2023 11.5.1). +fn constant_select_write( + variable: &SvVariable, + msb: i128, + lsb: i128, +) -> Option<(Option, usize)> { + let (msb, lsb) = ( + packed_index_position(variable, msb)?, + packed_index_position(variable, lsb)?, + ); + let (low, high) = (msb.min(lsb), msb.max(lsb)); + let top = i128::try_from(variable.width).ok()? - 1; + let (start, end) = (low.max(0), high.min(top)); + if start > end { + return Some((None, 0)); + } + Some(( + Some(BitAccess::new( + usize::try_from(start).ok()?, + usize::try_from(end).ok()?, + )), + usize::try_from(start - low).ok()?, + )) +} + +/// `folded`, the select `original` with the values its position reads +/// substituted, unless that turned a run-time select within one array +/// element into a constant one reaching past the element: the run-time form +/// keeps its write within the element (see `dynamic_packed_write`), while +/// the constant position counts from bit 0 of the whole array. +fn keep_element_window( + original: &sv::ir::LValue, + folded: sv::ir::LValue, + variables: &HashMap, + name_to_id: &HashMap, + constants: &HashMap, + parameter_types: &HashMap, +) -> sv::ir::LValue { + let constant = + |expr| sv::typecheck::eval_const_expr_with_types(expr, constants, parameter_types); + let ( + sv::ir::LValue::Select { + msb: original_msb, + lsb: original_lsb, + .. + }, + sv::ir::LValue::Select { msb, lsb, .. }, + ) = (original, &folded) + else { + return folded; + }; + if constant(original_msb).is_some() && constant(original_lsb).is_some() { + return folded; + } + let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) else { + return folded; + }; + let Some(window) = + dynamic_packed_write(original, variables, name_to_id, constants, parameter_types) + .and_then(|write| write.window) + else { + return folded; + }; + let inside = |position: i128| { + usize::try_from(position) + .is_ok_and(|position| (window.lsb..=window.msb).contains(&position)) + }; + if inside(msb) && inside(lsb) { + folded + } else { + original.clone() + } +} + fn packed_expr_select_offsets( expr: &sv::ir::Expr, msb: i128, diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index afc4d89a998..17c328b0190 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -557,13 +557,20 @@ impl<'p, 'a> Comb<'p, 'a> { let sv::ir::Expr::Select { msb, lsb, .. } = self.propagate(store, &probe) else { unreachable!() }; - sv::ir::LValue::Select { - name: name.clone(), - msb, - lsb, - array_slice_width: array_slice_width.clone(), - array_slice_reversed: *array_slice_reversed, - } + keep_element_window( + lvalue, + sv::ir::LValue::Select { + name: name.clone(), + msb, + lsb, + array_slice_width: array_slice_width.clone(), + array_slice_reversed: *array_slice_reversed, + }, + self.m.variables, + self.m.name_to_id, + self.m.constants, + self.m.parameter_types, + ) } } } @@ -1529,8 +1536,7 @@ impl<'p, 'a> Comb<'p, 'a> { lvalue: &sv::ir::LValue, ) -> Result { Ok(match self.lvalue_target(store, lvalue)? { - Target::Static { access, .. } => access.msb - access.lsb + 1, - Target::Dynamic { width, .. } => width, + Target::Static { width, .. } | Target::Dynamic { width, .. } => width, }) } @@ -1551,6 +1557,8 @@ impl<'p, 'a> Comb<'p, 'a> { sv::ir::LValue::Ident(_) => Ok(Target::Static { id, access: full(var_width), + width: var_width, + drop: 0, lvalue, }), sv::ir::LValue::Select { msb, lsb, .. } => { @@ -1559,21 +1567,22 @@ impl<'p, 'a> Comb<'p, 'a> { let lsb_value = sv::typecheck::eval_const_expr_with_types(lsb, constants, parameter_types); if let (Some(msb), Some(lsb)) = (msb_value, lsb_value) { - let variable = self.m.var(id); - let (Some(msb), Some(lsb)) = ( - packed_index_offset(variable, msb), - packed_index_offset(variable, lsb), - ) else { + let width = usize::try_from(msb.abs_diff(lsb)).unwrap_or(0) + 1; + let (access, drop) = constant_select_write(self.m.var(id), msb, lsb) + .ok_or_else(|| unsupported("assignment position"))?; + let Some(access) = access else { // A constant select entirely outside the vector writes nothing. return Ok(Target::Dynamic { id, offset: Offset::Nothing, - width: usize::try_from(msb.abs_diff(lsb)).unwrap_or(0) + 1, + width, }); }; return Ok(Target::Static { id, - access: BitAccess::new(lsb.min(msb), lsb.max(msb)), + access, + width, + drop, lvalue: lvalue.clone(), }); } @@ -1638,11 +1647,14 @@ impl<'p, 'a> Comb<'p, 'a> { let lhs = &self.hoist_lvalue(store, frames, lhs)?; let target = self.lvalue_target(store, lhs)?; let width = match &target { - Target::Static { access, .. } => access.msb - access.lsb + 1, - Target::Dynamic { width, .. } => *width, + Target::Static { width, .. } | Target::Dynamic { width, .. } => *width, }; if self.continuous - && matches!(&target, Target::Dynamic { id, .. } if !self.m.is_hidden(*id)) + && matches!( + &target, + Target::Dynamic { id, offset, .. } + if !self.m.is_hidden(*id) && !matches!(offset, Offset::Nothing) + ) { return Err(unsupported(format!( "combinational assignment target `{}` at a run-time position", @@ -1703,8 +1715,7 @@ impl<'p, 'a> Comb<'p, 'a> { rhs: &sv::ir::Expr, ) -> Result<(), sv::AnalyzerError> { let (id, width) = match &target { - Target::Static { id, access, .. } => (*id, access.msb - access.lsb + 1), - Target::Dynamic { id, width, .. } => (*id, *width), + Target::Static { id, width, .. } | Target::Dynamic { id, width, .. } => (*id, *width), }; let (mut node, mut sources) = value; node = coerce_node_width(self.arena, node, Some(width), signed).map_err(slt_error)?; @@ -1713,8 +1724,14 @@ impl<'p, 'a> Comb<'p, 'a> { node = self.alloc(SLTNode::Unary(UnaryOp::ToTwoState, node))?; } match target { - Target::Static { id, access, lvalue } => { - let node = permute_reversed_lvalue_rhs_slt( + Target::Static { + id, + access, + drop, + lvalue, + .. + } => { + let mut node = permute_reversed_lvalue_rhs_slt( &lvalue, node, width, @@ -1723,6 +1740,13 @@ impl<'p, 'a> Comb<'p, 'a> { self.arena, ) .ok_or_else(|| unsupported("assignment lvalue order"))?; + let written = access.msb - access.lsb + 1; + if written != width { + node = self.alloc(SLTNode::Slice { + expr: node, + access: BitAccess::new(drop, drop + written - 1), + })?; + } self.write(store, id, access, (node, sources)) } Target::Dynamic { id, offset, width } => { @@ -3900,14 +3924,12 @@ impl Comb<'_, '_> { this.m.constants, this.m.parameter_types, )) - .and_then(|(msb, lsb)| { - Some(( - packed_index_offset(variable, msb)?, - packed_index_offset(variable, lsb)?, - )) - }); + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)); match bounds { - Some((msb, lsb)) => BitAccess::new(msb.min(lsb), msb.max(lsb)), + Some((Some(access), _)) => access, + // A constant select entirely outside the vector + // writes nothing. + Some((None, _)) => return, // A run-time select may write any bit; the written // value keeps the others, so it defines the whole // vector, or the one element its constant part names. @@ -3981,9 +4003,14 @@ enum Label { } enum Target { + /// A constant select: the select's `width` bits of the value from + /// `drop` up go to the bits `access` of the variable, the part of the + /// select inside it. Static { id: SourceVarId, access: BitAccess, + width: usize, + drop: usize, lvalue: sv::ir::LValue, }, Dynamic { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ba395190ed5..058fae53ecd 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -216,15 +216,8 @@ impl<'p, 'a> Ff<'p, 'a> { self.m.constants, self.m.parameter_types, )) - .and_then(|(msb, lsb)| { - Some(( - packed_index_offset(variable, msb)?, - packed_index_offset(variable, lsb)?, - )) - }) - .map_or(whole, |(msb, lsb)| { - BitAccess::new(msb.min(lsb), msb.max(lsb)) - }), + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0) + .unwrap_or(whole), }; self.targets.push((id, access)); } @@ -354,13 +347,20 @@ impl<'p, 'a> Ff<'p, 'a> { lsb, array_slice_width, array_slice_reversed, - } => sv::ir::LValue::Select { - name: name.clone(), - msb: substitute_overlay_const(msb, &self.overlay), - lsb: substitute_overlay_const(lsb, &self.overlay), - array_slice_width: array_slice_width.clone(), - array_slice_reversed: *array_slice_reversed, - }, + } => keep_element_window( + lvalue, + sv::ir::LValue::Select { + name: name.clone(), + msb: substitute_overlay_const(msb, &self.overlay), + lsb: substitute_overlay_const(lsb, &self.overlay), + array_slice_width: array_slice_width.clone(), + array_slice_reversed: *array_slice_reversed, + }, + self.m.variables, + self.m.name_to_id, + self.m.constants, + self.m.parameter_types, + ), } } @@ -2245,15 +2245,12 @@ impl<'p, 'a> Ff<'p, 'a> { sv::typecheck::eval_const_expr_with_types(msb, constants, parameter_types), sv::typecheck::eval_const_expr_with_types(lsb, constants, parameter_types), ) { - let variable = self.m.var(id); - let (Some(msb), Some(lsb)) = ( - packed_index_offset(variable, msb), - packed_index_offset(variable, lsb), - ) else { + let (access, drop) = constant_select_write(self.m.var(id), msb, lsb) + .ok_or_else(|| unsupported("assignment position"))?; + let Some(access) = access else { return Ok(()); }; - let low = msb.min(lsb); - let node = permute_reversed_lvalue_rhs_slt( + let mut node = permute_reversed_lvalue_rhs_slt( lhs, node, width, @@ -2262,9 +2259,18 @@ impl<'p, 'a> Ff<'p, 'a> { arena, ) .ok_or_else(|| unsupported("assignment lvalue order"))?; + let written = access.msb - access.lsb + 1; + if written != width { + node = arena + .alloc(SLTNode::Slice { + expr: node, + access: BitAccess::new(drop, drop + written - 1), + }) + .map_err(slt_error)?; + } let value = self.lower_slt(arena, node)?; - let offset = sv_memory_offset(self.m.var(id), low, width); - self.store(id, offset, width, value); + let offset = sv_memory_offset(self.m.var(id), access.lsb, written); + self.store(id, offset, written, value); return Ok(()); } if let Some((_, element_width, offset, access)) = dynamic_array_element_lvalue( diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 96838518417..f2a63888dbf 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -507,7 +507,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_verilator_short_circuit_calls` | execute | verilator | 1 | Verilator 5.052 runs a function call in the right operand of && in a select index when the left operand is false, so its output argument is written; IEEE 1800-2023 11.4.7 does not evaluate that operand. Icarus cannot compile the design (sv_icarus_function_outputs). | | `sv_verilator_function_outputs` | compile | verilator | 1 | Verilator 5.052 fails with an internal error (V3DfgSynthesize: Non-ReadOnly reference) on output and inout function arguments. | | `sv_verilator_generate_name_collision` | compile | verilator | 1 | Verilator 5.052 rejects a generate block named like a port with an "Unsupported" diagnostic instead of a duplicate-name error, so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 5.6.1, 23.9) and Icarus rejects it as a duplicate declaration. | -| `sv_verilator_part_select_write_overhang` | execute | verilator | 1 | Verilator 5.052 writes the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) into bit 7 instead of discarding it; IEEE 1800-2023 11.5.1 ignores writes to out-of-range bits. Icarus agrees with the expected value. | +| `sv_verilator_part_select_write_overhang` | execute | verilator | 4 | Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values. | | `sv_verilator_unpacked_array_extension` | compile | verilator | 2 | Verilator 5.052 rejects an unpacked array argument or assignment pattern item with a narrower element type through "EXTEND unexpected in assignment to unpacked array" (EXTENDS for a signed element), a diagnostic about its own width extension rather than the element types, so the run cannot count it as a language rejection. The designs are invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_dimensions_type_queries` | compile | icarus | 2 | Icarus 13.0 rejects data type arguments to `$dimensions`, with syntax/type-name errors and an assertion for a multidimensional cast. IEEE 1800-2023 20.7 permits these queries. Verilator passes the integral/string/real type case. | | `sv_verilator_chandle_dimensions` | execute | verilator | 1 | Verilator 5.052 returns 1 for `$dimensions(chandle)`; IEEE 1800-2023 6.14 and 20.7 require 0 for this nonarray pointer type. | diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 7a3c79395be..3be0427242b 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1860,3 +1860,101 @@ (assert_eq q 0x43) (modify (set addr 3)) (assert_eq q 0x44)) + +; IEEE 1800-2023 11.5.1: a write to a constant part-select partly outside the +; vector writes the bits inside, and one wholly outside writes nothing. +(case constant_part_selects_partly_outside_write_the_bits_inside + (source "partly_outside.sv" #" + module Top(input logic clk, input logic [3:0] v, + output logic [7:0] comb_hi, comb_out, ff_nb, ff_b); + always_comb begin + comb_hi = 8'h00; + comb_hi[9:6] = v; + comb_out = 8'h5a; + comb_out[11:8] = v; + end + always_ff @(posedge clk) begin + ff_nb <= 8'h00; + ff_nb[9:6] <= v; + end + always_ff @(posedge clk) begin + ff_b = 8'h00; + ff_b[9:6] = v; + end + endmodule + "#) + (top Top) + (modify (set clk 0) (set v 0xf)) + (assert_eq comb_hi 0xc0 "bits 7:6 take the low bits of the value") + (assert_eq comb_out 0x5a "a select wholly outside writes nothing") + (tick clk) + (assert_eq ff_nb 0xc0) + (assert_eq ff_b 0xc0) + (modify (set v 0x6)) + (assert_eq comb_hi 0x80) + (tick clk) + (assert_eq ff_nb 0x80) + (assert_eq ff_b 0x80)) + +; On an ascending vector the bits past the declared right end are the low +; bits of the select, so the bits inside take the high bits of the value. +(case ascending_part_selects_partly_outside_write_the_bits_inside + (source "ascending_partly_outside.sv" #" + module Top(input logic clk, input logic [3:0] v, + output logic [0:7] comb_up, ff_up); + always_comb begin + comb_up = 8'h00; + comb_up[6:9] = v; + end + always_ff @(posedge clk) begin + ff_up <= 8'h00; + ff_up[6:9] <= v; + end + endmodule + "#) + (top Top) + (modify (set clk 0) (set v 0x9)) + (assert_eq comb_up 0x02 "comb_up[6:7] take v[3:2]") + (tick clk) + (assert_eq ff_up 0x02)) + +; A run-time select within one array element stays within it even when the +; position is known while the design is compiled (IEEE 1800-2023 7.4.6, +; 11.5.1). +(case known_run_time_selects_stay_within_their_element + (source "known_element_selects.sv" #" + module Top(output logic [7:0] a0, a1, a2, l0, l1, l2, s0, s1, s2); + int k = 6, n = -2; + logic [7:0] a [0:2]; + logic [7:0] l [0:2]; + logic [7:0] s [0:2]; + initial begin + for (int i = 0; i < 3; i++) begin + a[i] = 8'd0; + l[i] = 8'd0; + s[i] = 8'd0; + end + a[1][k +: 4] = 4'b0101; + a[1][n +: 4] = 4'b1010; + for (int j = 6; j < 7; j++) l[1][j +: 4] = 4'b0101; + #1; + s[1][k +: 4] = 4'b0101; + s[1][n +: 4] = 4'b1010; + end + assign a0 = a[0]; + assign a1 = a[1]; + assign a2 = a[2]; + assign l0 = l[0]; + assign l1 = l[1]; + assign l2 = l[2]; + assign s0 = s[0]; + assign s1 = s[1]; + assign s2 = s[2]; + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq a0 0) (assert_eq a1 0x42) (assert_eq a2 0) + (assert_eq l0 0) (assert_eq l1 0x40) (assert_eq l2 0) + (run_until 1) + (assert_eq s0 0) (assert_eq s1 0x42) (assert_eq s2 0)) diff --git a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json index 1811d025379..b7efdc93a15 100644 --- a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json +++ b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json @@ -1,5 +1,16 @@ { "cases": [ + { + "category": "Arrays", + "detail": "", + "expectation": "Simulation", + "name": "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Arrays", "detail": "Icarus 13.0 rejects both packed array parameter declarations before the X/Z-index regression can execute. IEEE 1800-2023 11.5.1 requires sized X results for unknown indices of four-state operands and zero for two-state operands. Verilator cannot validate this case's four-state expectations.", @@ -47,6 +58,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Arrays", + "detail": "", + "expectation": "Simulation", + "name": "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Arrays", "detail": "", @@ -376,6 +398,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Arrays", + "detail": "", + "expectation": "Simulation", + "name": "indexed_select::known_run_time_selects_stay_within_their_element", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Arrays", "detail": "Icarus 13.0 flattens an out-of-range inner index of a multidimensional packed array into the neighbouring element: a read gives a known value instead of X, and a write lands in that element; IEEE 1800-2023 7.4.6 and 11.5.1 make the select out of range. Verilator cannot check four-state values, and it truncates out-of-range packed indices.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 05edcf2e6fe..8e32809d74e 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -642,7 +642,7 @@ "category": "simulator_disagreement", "phase": "execute", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "reason": "Verilator 5.052 writes the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) into bit 7 instead of discarding it; IEEE 1800-2023 11.5.1 ignores writes to out-of-range bits. Icarus agrees with the expected value.", + "reason": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", "upstream": [], "evidence": [ "verification/sv/limitations/verilator.json", @@ -650,6 +650,9 @@ ], "cases": { "verilator": [ + "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside", + "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside", + "indexed_select::known_run_time_selects_stay_within_their_element", "indexed_select::runtime_indexed_writes_keep_unselected_bits_and_clip_overhang" ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index fe8238160f7..a18b6d80f40 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -7,7 +7,7 @@ "passed": 0, "rejected": 0, "unexpected_accept": 0, - "mismatch": 21, + "mismatch": 24, "emission_error": 0, "compile_error": 18, "runtime_error": 2, @@ -426,6 +426,30 @@ "name": "class::inherited_methods_of_extended_interface_classes", "phase": "compile", "status": "compile_error" + }, + { + "category": "Arrays", + "detail": "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside at 1917:3: assert_eq comb_up: expected 0x2, got 0x40 (comb_up[6:7] take v[3:2])", + "expectation": "Simulation", + "name": "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Arrays", + "detail": "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside at 1889:3: assert_eq comb_out: expected 0x5a, got 0x5f (a select wholly outside writes nothing)", + "expectation": "Simulation", + "name": "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Arrays", + "detail": "indexed_select::known_run_time_selects_stay_within_their_element at 1957:20: assert_eq a1: expected 0x42, got 0x80", + "expectation": "Simulation", + "name": "indexed_select::known_run_time_selects_stay_within_their_element", + "phase": "execute", + "status": "mismatch" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/indexed_select.json b/crates/celox-test-suite/verification/sv/verilator/indexed_select.json index aa19e766679..219b54ee4c6 100644 --- a/crates/celox-test-suite/verification/sv/verilator/indexed_select.json +++ b/crates/celox-test-suite/verification/sv/verilator/indexed_select.json @@ -1,5 +1,51 @@ { "cases": [ + { + "category": "Arrays", + "detail": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_part_select_write_overhang", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "upstream": [] + }, + "name": "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Arrays", + "detail": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_part_select_write_overhang", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "upstream": [] + }, + "name": "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Arrays", "detail": "", @@ -265,6 +311,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Arrays", + "detail": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_part_select_write_overhang", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", + "upstream": [] + }, + "name": "indexed_select::known_run_time_selects_stay_within_their_element", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Arrays", "detail": "four-state expectations", @@ -355,7 +424,7 @@ }, { "category": "Arrays", - "detail": "Verilator 5.052 writes the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) into bit 7 instead of discarding it; IEEE 1800-2023 11.5.1 ignores writes to out-of-range bits. Icarus agrees with the expected value.", + "detail": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", "expectation": "Simulation", "known_issue": { "category": "simulator_disagreement", @@ -366,7 +435,7 @@ "id": "sv_verilator_part_select_write_overhang", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", "phase": "execute", - "reason": "Verilator 5.052 writes the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) into bit 7 instead of discarding it; IEEE 1800-2023 11.5.1 ignores writes to out-of-range bits. Icarus agrees with the expected value.", + "reason": "Verilator 5.052 writes bits that IEEE 1800-2023 11.5.1 discards: the out-of-range bit of a partially out-of-range indexed part-select (minus_write[i -: 2] with i = 0) lands in bit 7, a constant part-select wholly outside the vector (comb_out[11:8]) writes its low bits, a partly outside one of an ascending vector (comb_up[6:9]) takes the wrong end of the value, and run-time selects within one array element whose positions are known at compile time reach past it. Icarus agrees with the expected values.", "upstream": [] }, "name": "indexed_select::runtime_indexed_writes_keep_unselected_bits_and_clip_overhang", diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 7f38381d410..dad4f88d17a 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -331,3 +331,41 @@ fn rejects_unresolved_logical_parameter_type_queries() { .expect_err("unresolved operands must not acquire a logical result type"); } } + +sv_backends! { + fn constant_part_selects_partly_outside_write_the_bits_inside(sim) { + @case "indexed_select::constant_part_selects_partly_outside_write_the_bits_inside"; + } + fn ascending_part_selects_partly_outside_write_the_bits_inside(sim) { + @case "indexed_select::ascending_part_selects_partly_outside_write_the_bits_inside"; + } + fn known_run_time_selects_stay_within_their_element(sim) { + @case "indexed_select::known_run_time_selects_stay_within_their_element"; + } +} + +/// A continuous assignment to a part-select partly outside its vector drives +/// the bits inside, and one wholly outside drives nothing (IEEE 1800-2023 +/// 11.5.1). Icarus 13.0 aborts on the partial assignment, so this is no +/// suite case. +#[test] +fn continuous_part_selects_partly_outside_drive_the_bits_inside() { + let source = r#" + module Top(input logic [3:0] v, output logic [7:0] q, r); + assign q[9:6] = v; + assign q[5:0] = 6'h01; + assign r[11:8] = v; + assign r[7:0] = 8'h5a; + endmodule + "#; + let mut sim = Simulator::from_sv_sources( + vec![(source, Path::new("continuous_partly_outside.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let (v, q, r) = (sim.signal("v"), sim.signal("q"), sim.signal("r")); + sim.modify(|io| io.set(v, 0xfu8)).unwrap(); + assert_eq!(sim.get(q), 0xc1u8.into()); + assert_eq!(sim.get(r), 0x5au8.into()); +} From 1358eba8d08d40faf3d58b726d61ddbd2eb522b8 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 11:13:40 +0900 Subject: [PATCH 3/3] docs(sv): describe writes to part-selects partly outside their vector Change-Id: I479256f5f43fad0f27b36f979226b3abed2cd284 --- docs/guide/systemverilog-reference.md | 8 +++++++- docs/ja/guide/systemverilog-reference.md | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 97b12cef85b..0417b272d99 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -261,7 +261,13 @@ saving a state file fails while any variable holds an object. A run-time select that reaches past either end of a vector reads `X` for the missing bits (zero in two-state simulation) and -writes only the bits that exist. +writes only the bits that exist. A write to a constant part-select partly +outside the vector, by any procedural or continuous assignment, also writes +only the bits inside: `q[9:6] = v` on `logic [7:0] q` writes `v[1:0]` to +`q[7:6]`. A write wholly outside the vector has no effect. Reading such a +constant part-select, and writing one of an array element or of an inner +packed dimension that leaves its declared range, are rejected +([#88](https://github.com/celox-sim/celox/issues/88)). ### Wildcard comparisons diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f4a3e96b0a5..d26b8fa2491 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -184,7 +184,12 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 ### 範囲外の選択 ベクタの端を越える実行時の選択は、足りないビットを `X`(2 値シミュレーションでは 0) -として読み、書き込みは存在するビットだけを更新します。 +として読み、書き込みは存在するビットだけを更新します。ベクタから一部はみ出す定数の +パートセレクトへの書き込みも、手続き代入・継続代入のどちらでも内側のビットだけを更新します。 +`logic [7:0] q` への `q[9:6] = v` は `v[1:0]` を `q[7:6]` に書き込みます。ベクタから +完全に外れた書き込みは何もしません。このような定数のパートセレクトの読み出しと、配列要素や +内側の packed 次元の宣言範囲を越える定数のパートセレクトへの書き込みは拒否します +([#88](https://github.com/celox-sim/celox/issues/88))。 ### ワイルドカード比較