From 84e50ef2c5b4d21e9d96364cae2ba4de077dda53 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 09:43:40 +0900 Subject: [PATCH] feat(sv): support soft packed unions Support `union soft` and `union soft packed` with differently sized integral members. Members share their least significant bits, storage uses the largest member width, and narrow writes preserve the upper bits. Retain hard packed unions' equal-width requirement. Add shared regressions for nested overlays, partial blocking/nonblocking writes, signed package-qualified ports, mixed bit/logic members, and 130-bit four-state values. Document the supported subset and external simulator limitations; tagged and unpacked unions remain unsupported. Validation: syntax tests (121 passed), analyzer tests (795 passed, 3 existing ignores), union integration tests across native/Cranelift/Wasm and parallel modes (26 passed), packed-struct regressions (54 passed), formatting and affected-crate/integration Clippy passed. Verilator 5.052: 3 passing cases, 2 unsupported four-state cases. Icarus 13.0: 1 passing case, 3 soft-union syntax rejections, and 1 mixed-state read mismatch independently reproduced outside the harness. IEEE 1800-2023 7.3.1 requires conversion when reading a two-state union member; Icarus retains X. Assertions remain enabled with no exclusions. Retain the reviewed Icarus union evidence, including exact diagnostics, so full-suite/release validation accepts those known failures while rejecting changed diagnostics or new failures. The focused fresh report reproduces all four failures and passes the external-report gate with the retained evidence. The baseline regression asserts the exact four reviewed SV Icarus case IDs; all 273 repository script tests pass after adding the evidence. Follow-up CI validation: update the Rust retained-report contract to validate the four executable Icarus failures by case, status, phase, diagnostic and absence of exclusions. All celox-test-suite tests with verilator/icarus features pass (78 passed, 12 existing ignores), including retained reports and doctests; focused Clippy and the nine JavaScript report tests pass. Change-Id: Icba1d4eb64ecba665a391b04033473259f921029 --- .../src/ast/packed_structs.rs | 2 +- .../src/ast/packed_structs/layout.rs | 20 ++- .../src/ast/packed_structs/tests.rs | 9 ++ .../src/ast/type_binding/binding.rs | 14 +- crates/celox-sv-syntax/src/nodes.rs | 1 + crates/celox-sv-syntax/src/parser/tests.rs | 6 + crates/celox-sv-syntax/src/parser/types.rs | 10 +- crates/celox-test-suite/LIMITATIONS.md | 24 +++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../src/sv/cases/unions.vtest | 146 ++++++++++++++++++ .../tests/retained_reports.rs | 31 +++- .../verification/sv/icarus.json | 3 +- .../verification/sv/icarus/unions.json | 59 +++++++ .../tests/frontends/systemverilog/unions.rs | 17 ++ crates/celox/tests/systemverilog.rs | 3 + docs/guide/systemverilog-reference.md | 23 ++- docs/internals/compiler-crate-architecture.md | 4 +- docs/ja/guide/systemverilog-reference.md | 23 ++- scripts/check-external-suite-report.test.mjs | 19 ++- 19 files changed, 393 insertions(+), 25 deletions(-) create mode 100644 crates/celox-test-suite/src/sv/cases/unions.vtest create mode 100644 crates/celox-test-suite/verification/sv/icarus/unions.json create mode 100644 crates/celox/tests/frontends/systemverilog/unions.rs diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index eb684292cb3..55f7b038349 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -7,7 +7,7 @@ mod selects; #[cfg(test)] mod tests; -pub(super) use layout::native_type; +pub(super) use layout::{AggregateKind, native_type}; pub(super) use selects::{select_member, whole_member}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index c3908e74344..c7cda41d379 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -2,6 +2,13 @@ use super::*; +#[derive(Clone, Copy)] +pub(in crate::ast) enum AggregateKind { + Struct, + HardUnion, + SoftUnion, +} + /// Freeze member bounds in the declaration environment before generated scopes /// can shadow their parameter names. Shared by both syntax owners. pub(in crate::ast) fn capture_member_type( @@ -30,7 +37,7 @@ pub(in crate::ast) fn capture_member_type( /// Syntax-independent IEEE7.2.1/7.3.1 layout kernel. pub(in crate::ast) fn native_type( state: &AnalysisState, - union: bool, + kind: AggregateKind, signed: bool, owner: Arc, fields: Vec<(String, Type)>, @@ -52,11 +59,11 @@ pub(in crate::ast) fn native_type( }) }) .collect::>>()?; - finish_type(state, union, signed, members, ranges, env) + finish_type(state, kind, signed, members, ranges, env) } fn finish_type( state: &AnalysisState, - union: bool, + kind: AggregateKind, signed: bool, mut members: Vec, ranges: Vec, @@ -66,13 +73,14 @@ fn finish_type( // The first declared member occupies the most significant bits. for member in members.iter_mut().rev() { let member_width = expr_type_from_type(state, &member.r#type, const_env)?.width; - if union { + if !matches!(kind, AggregateKind::Struct) { // IEEE 1800-2023 7.3.1: hard packed members share all bits // and must have the same width. - if width != 0 && width != member_width { + if matches!(kind, AggregateKind::HardUnion) && width != 0 && width != member_width { return None; } - width = member_width; + // Soft members are right-justified in the largest member width. + width = width.max(member_width); } else { member.offset = width; width = width.checked_add(member_width)?; diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs index 95def768938..a9a0fd594aa 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs @@ -12,6 +12,9 @@ fn preserves_layout_signedness_and_state_kind() { mixed_t mixed; union packed signed { logic signed [7:0] a; bit [7:0] b; } mixed_union; union packed { bit [129:0] a; bit [129:0] b; } wide_union; + union soft { bit [3:0] narrow_value; bit [15:0] wide_value; } soft_union; + union soft packed signed { logic [15:0] wide_value; bit [3:0] narrow_value; } signed_soft; + union soft { bit [2:0] narrow_value; union soft { bit [129:0] wide; bit flag; } nested; } nested_soft; signed_t signed_value; struct packed { byte a; shortint b; int c; longint d; } atoms; endmodule @@ -26,6 +29,9 @@ fn preserves_layout_signedness_and_state_kind() { ("atoms", 120, false, ir::TypeKind::Bit), ("mixed_union", 8, true, ir::TypeKind::Logic), ("wide_union", 130, false, ir::TypeKind::Bit), + ("soft_union", 16, false, ir::TypeKind::Bit), + ("signed_soft", 16, true, ir::TypeKind::Logic), + ("nested_soft", 130, false, ir::TypeKind::Bit), ] { let ty = signals .iter() @@ -44,6 +50,9 @@ fn rejects_invalid_or_unsupported_struct_shapes() { "struct { logic a; } value;", "union packed { logic a; logic [1:0] b; } value;", "union tagged packed { logic a; logic b; } value;", + "union soft { real a; bit [63:0] b; } value;", + "union soft { logic a[2]; logic b; } value;", + "union soft { logic a; logic a; } value;", "union packed { logic a; logic b; } value; always_comb value = '{a: 1'b1, b: 1'b0};", "struct packed { real a; } value;", "struct packed { logic a[2]; } value;", diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 6f96b7edded..30e61323785 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -22,6 +22,7 @@ pub(in crate::ast) fn bind_in( Aggregate { owner: Arc, union: bool, + soft: bool, signed: bool, names: Vec, ranges: Vec, @@ -89,11 +90,12 @@ pub(in crate::ast) fn bind_in( } DataTypeKind::Struct { union, + soft, tagged, packed, fields, } => { - if !packed || *tagged { + if (!packed && !soft) || *tagged { return Ok(None); } let mut names = Vec::new(); @@ -125,6 +127,7 @@ pub(in crate::ast) fn bind_in( jobs.push(Job::Aggregate { owner, union: *union, + soft: *soft, signed: data.signed.unwrap_or(false), names, ranges, @@ -169,6 +172,7 @@ pub(in crate::ast) fn bind_in( Job::Aggregate { owner, union, + soft, signed, names, ranges, @@ -180,7 +184,13 @@ pub(in crate::ast) fn bind_in( let fields = names.into_iter().zip(values.split_off(start)).collect(); let Some(ty) = packed_structs::native_type( &tree.state, - union, + if soft { + packed_structs::AggregateKind::SoftUnion + } else if union { + packed_structs::AggregateKind::HardUnion + } else { + packed_structs::AggregateKind::Struct + }, signed, owner, fields, diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index b52c7abebc2..4840e19a39f 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -183,6 +183,7 @@ pub enum DataTypeKind { TypeOf(ExprId), Struct { union: bool, + soft: bool, tagged: bool, packed: bool, fields: Vec, diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index d66393e16f5..a2de23d0dad 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2003,6 +2003,10 @@ fn datatype_contexts_reject_general_dimension_and_signing_grammar() { "struct signed {int x;}", "struct packed {int x;} unsigned", "struct tagged {int x;}", + "struct soft {int x;}", + "union soft signed {int x;}", + "union soft tagged {int x;}", + "union tagged soft {int x;}", "struct packed {}", "union {}", "enum real {A}", @@ -2036,6 +2040,8 @@ fn datatype_contexts_preserve_enum_ranges_and_aggregate_qualifiers() { "struct packed signed {logic[3:0] x;}", "union packed unsigned {int x; bit[31:0] y;}", "union tagged {int x; void nothing;}", + "union soft {int x; bit y;}", + "union soft packed signed {int x; bit y;}", "enum {A}", "enum int unsigned {A}", "enum logic [3:0] {A}", diff --git a/crates/celox-sv-syntax/src/parser/types.rs b/crates/celox-sv-syntax/src/parser/types.rs index 5a0e1c38bd6..1d90a9287fb 100644 --- a/crates/celox-sv-syntax/src/parser/types.rs +++ b/crates/celox-sv-syntax/src/parser/types.rs @@ -4,6 +4,7 @@ use super::*; pub(super) struct Aggregate { start: usize, union: bool, + soft: bool, tagged: bool, packed: bool, signed: Option, @@ -166,7 +167,11 @@ impl Parser<'_> { if !union { self.expect("struct")?; } - let tagged = self.eat("tagged"); + let soft = self.eat("soft"); + if soft && !union { + return Err(self.error("only a union can be soft")); + } + let tagged = !soft && self.eat("tagged"); let packed = self.eat("packed"); let signed = self.signing(); if tagged && !union { @@ -179,6 +184,7 @@ impl Parser<'_> { jobs.push(Job::Type(TypeJob::StructNext(Aggregate { start, union, + soft, tagged, packed, signed, @@ -424,6 +430,7 @@ impl Parser<'_> { let Aggregate { start, union, + soft, tagged, packed, signed, @@ -434,6 +441,7 @@ impl Parser<'_> { start, kind: DataTypeKind::Struct { union, + soft, tagged, packed, fields, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 51e04377b4c..74c9ea08b5f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -669,3 +669,27 @@ Verilator 5.052 has two narrower exclusions, recorded in the The setter's formal is `bit` (18.8), so the required conversion truncates 2 to 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, inline member selection and pre-hook control cases pass Verilator. + +## SystemVerilog packed unions + +The `unions` shared group covers hard and soft packed untagged unions. With +Verilator 5.052, `packed_overlay`, `soft_overlay`, and `soft_signed_ports` pass; +the two four-state cases report `unsupported` through the existing state-mode +check. + +Icarus 13.0 rejects `union soft` declarations in `soft_overlay`, +`soft_signed_ports`, and `soft_wide_four_state` during compilation. +`packed_overlay` passes. `packed_mixed_state` fails when reading a `bit` member +from mixed `logic`/`bit` union storage: for `8'b1010xxxx`, it returns +`8'b1010xxxx` instead of `8'b10100000`. A direct procedural probe reproduces +this independently of the shared harness; writing through the `bit` member +converts X to zero correctly. IEEE 1800-2023 7.3.1 requires conversion from +four-state to two-state when reading a two-state member. + +These cases remain enabled with their original assertions and no exclusions. +The [retained Icarus evidence](verification/sv/icarus/unions.json) records the +three compilation failures and the read mismatch with their exact diagnostics; +the full-suite gate accepts only those unchanged failures, never a passing +result in their place. Reproduce with `verify-sv-verilator` or +`verify-sv-icarus` and `--filter unions::`. Normal reports are written under +`target/sv-verilator/` and `target/sv-icarus/`. diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 8adeddf9279..66a5ad1db5a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/sv/cases/unions.vtest", + text: include_str!("unions.vtest"), + }, Group { file: "src/sv/cases/real_extensions.vtest", text: include_str!("real_extensions.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/unions.vtest b/crates/celox-test-suite/src/sv/cases/unions.vtest new file mode 100644 index 00000000000..edb2f605c72 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/unions.vtest @@ -0,0 +1,146 @@ +(group unions (category types)) + +(case packed_overlay + (source "union.sv" #" +module Top(input bit clk, input logic [15:0] raw, input logic [3:0] nibble, + output logic [15:0] value, saved, output logic [7:0] low, + output logic signed [31:0] extended); + typedef union packed signed { + logic [15:0] bits; + struct packed { logic [7:0] hi, lo; } parts; + } overlay_t; + overlay_t data, stored; + always_comb begin + data.bits = raw; + data.parts.lo[3:0] = nibble; + end + always_ff @(posedge clk) stored <= data; + assign value = data.bits; + assign low = data.parts.lo; + assign extended = data; + assign saved = stored.parts; +endmodule +"#) + (top Top) + (for (r n) (list (0 15) (0xa53c 6) (0x7fff 0) (0xffff 1)) + (modify (set raw r) (set nibble n)) + (let expected (| (& r 0xfff0) n)) + (assert_eq value expected) + (assert_eq low (& expected 255)) + (if (& expected 0x8000) + (assert_eq extended (| expected 0xffff0000)) + (assert_eq extended expected)) + (tick clk) + (assert_eq saved expected))) + +(case soft_overlay + (source "soft_union.sv" #" +module Top(input bit clk, input logic [15:0] raw, input logic [3:0] nibble, + output logic [15:0] value, saved, output logic [7:0] low, + output logic [31:0] width); + typedef union soft packed { + logic [15:0] bits; + union soft { logic [7:0] byte_value; logic [3:0] nibble_value; } nested; + } overlay_t; + overlay_t data, stored; + always_comb begin + data.bits = raw; + data.nested.nibble_value = nibble; + end + always_ff @(posedge clk) begin + stored.bits <= raw; + stored.nested.nibble_value <= nibble; + end + assign value = data; + assign low = data.nested.byte_value; + assign saved = stored; + assign width = $bits(overlay_t); +endmodule +"#) + (top Top) + (assert_eq width 16) + (for (r n) (list (0 15) (0xa53c 6) (0x7fff 0) (0xffff 1)) + (modify (set raw r) (set nibble n)) + (let expected (| (& r 0xfff0) n)) + (assert_eq value expected) + (assert_eq low (& expected 255)) + (tick clk) + (assert_eq saved expected))) + +(case packed_mixed_state + (four_state) + (source "union_state.sv" #" +module Top(input logic [7:0] raw, output logic [7:0] four, two, written); + union packed { logic [7:0] four_value; bit [7:0] two_value; } data, clean; + assign data.four_value = raw; + assign clean.two_value = raw; + assign four = data.four_value; + assign two = data.two_value; + assign written = clean.four_value; +endmodule +"#) + (top Top) + (for (v m) (list (0xa5 0) (0xa5 0x0f) (0xff 0xff) (0 0xff)) + (modify (set raw (fourstate v m))) + (assert_eq four (fourstate v m)) + (assert_eq two (& v (^ m 255))) + (assert_eq written (& v (^ m 255))))) + +(case soft_wide_four_state + (four_state) + (source "soft_union_wide.sv" #" +module Top(input bit clk, input logic [129:0] raw, input logic [7:0] byte_value, + output logic [129:0] value, saved); + union soft { logic [129:0] wide; logic [7:0] narrow_value; } data, stored; + always_comb begin + data.wide = raw; + data.narrow_value = byte_value; + end + always_ff @(posedge clk) stored <= data; + assign value = data.wide; + assign saved = stored.wide; +endmodule +"#) + (top Top) + (for bit (list 0 7 8 63 64 127 128 129) + (let v (| (<< 1 bit) 0x5a)) + (let m (<< 1 bit)) + (modify (set raw (fourstate v m)) (set byte_value (fourstate 0xa5 0x0f))) + (let upper_mask (- (<< 1 130) 256)) + (let expected (fourstate (| (& v upper_mask) 0xa5) (| (& m upper_mask) 0x0f))) + (assert_eq value expected) + (tick clk) + (assert_eq saved expected))) + +(case soft_signed_ports + (source "soft_union_ports.sv" #" +package Types; + typedef union soft packed signed { + logic signed [3:0] nibble_value; + logic [7:0] byte_value; + } overlay_t; +endpackage +module Update(input Types::overlay_t incoming, input logic [3:0] nibble, + output Types::overlay_t outgoing); + always_comb begin + outgoing = incoming; + outgoing.nibble_value = nibble; + end +endmodule +module Top(input logic [7:0] raw, input logic [3:0] nibble, + output logic [15:0] extended, member_extended, + output logic [7:0] value); + Types::overlay_t incoming, outgoing; + assign incoming = raw; + Update update_value(.incoming(incoming), .nibble(nibble), .outgoing(outgoing)); + assign value = outgoing; + assign extended = outgoing; + assign member_extended = outgoing.nibble_value; +endmodule +"#) + (top Top) + (for (r n e me) (list (0xa5 6 0xffa6 6) (0x75 15 0x7f 0xffff) (0 8 8 0xfff8)) + (modify (set raw r) (set nibble n)) + (assert_eq value (& e 255)) + (assert_eq extended e) + (assert_eq member_extended me))) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 2f60a838b46..a071551e694 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -122,7 +122,7 @@ fn retained_reports_are_valid_historical_evidence_for_the_live_catalogue() { } #[test] -fn systemverilog_retained_reports_explain_every_recorded_exclusion() { +fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { let catalogue: BTreeSet<_> = celox_test_suite::sv::cases() .map(|case| case.name) .collect(); @@ -159,8 +159,8 @@ fn systemverilog_retained_reports_explain_every_recorded_exclusion() { let name = row["name"].as_str().unwrap(); let case = celox_test_suite::sv::case(name).unwrap(); let status = row["status"].as_str().unwrap(); - // Every case passes, is rejected as expected, needs four-state - // simulation the tool lacks, or has a reviewed exclusion. + // Reviewed failures stay executable and retain their diagnostics; + // they are distinct from exclusions and passing cases. match status { "passed" => { assert_eq!(case.expectation, celox_test_suite::Expectation::Simulation) @@ -186,6 +186,31 @@ fn systemverilog_retained_reports_explain_every_recorded_exclusion() { ); } } + "compile_error" | "mismatch" => { + assert_eq!(tool, "icarus", "{name}"); + let (expected_status, phase, diagnostic) = match name { + "unions::packed_mixed_state" => ( + "mismatch", + "execute", + "assert_eq two: expected 0xa0, got 0xaX", + ), + "unions::soft_overlay" + | "unions::soft_signed_ports" + | "unions::soft_wide_four_state" => { + ("compile_error", "compile", "syntax error") + } + _ => panic!("unreviewed failure: {tool} {name}: {status}"), + }; + assert_eq!(status, expected_status, "{name}"); + assert_eq!(row["phase"], phase, "{name}"); + assert!( + row["detail"].as_str().unwrap().contains(diagnostic), + "{name}" + ); + assert_eq!(case.expectation, celox_test_suite::Expectation::Simulation); + assert!(row.get("known_issue").is_none(), "{name}"); + assert!(celox_test_suite::sv::verification::known_issue(tool, name).is_none()); + } _ => panic!("{tool} {name}: {status}"), } } diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index da5488b278d..cca4d440665 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -17,7 +17,8 @@ "icarus/synthesizable.json", "icarus/system_functions.json", "icarus/timing.json", - "icarus/types.json" + "icarus/types.json", + "icarus/unions.json" ], "exclude_stronger_than_sv": false, "include_ignored": false, diff --git a/crates/celox-test-suite/verification/sv/icarus/unions.json b/crates/celox-test-suite/verification/sv/icarus/unions.json new file mode 100644 index 00000000000..555e15b3ba4 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/unions.json @@ -0,0 +1,59 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "unions::packed_mixed_state at 86:5: assert_eq two: expected 0xa0, got 0xaX", + "expectation": "Simulation", + "name": "unions::packed_mixed_state", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unions::packed_overlay", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 10; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in typedef clause.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "unions::soft_overlay", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in typedef clause.\n/source_0.sv:6: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "unions::soft_signed_ports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n", + "expectation": "Simulation", + "name": "unions::soft_wide_four_state", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/tests/frontends/systemverilog/unions.rs b/crates/celox/tests/frontends/systemverilog/unions.rs new file mode 100644 index 00000000000..724237db369 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/unions.rs @@ -0,0 +1,17 @@ +sv_backends! { + fn soft_signed_ports(sim) { + @case "unions::soft_signed_ports"; + } + fn packed_overlay(sim) { + @case "unions::packed_overlay"; + } + fn soft_overlay(sim) { + @case "unions::soft_overlay"; + } + fn packed_mixed_state(sim) { + @case "unions::packed_mixed_state"; + } + fn soft_wide_four_state(sim) { + @case "unions::soft_wide_four_state"; + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 52af4da8702..5edb5ce8c0b 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -237,3 +237,6 @@ mod floating_point; #[path = "frontends/systemverilog/real_extensions.rs"] mod real_extensions; + +#[path = "frontends/systemverilog/unions.rs"] +mod unions; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..12e9b3fd06d 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -25,7 +25,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs and hard packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | +| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, hard and soft packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | @@ -182,7 +182,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: ([#427](https://github.com/celox-sim/celox/issues/427)), wildcard `.*` connections ([#442](https://github.com/celox-sim/celox/issues/442)), gate primitives ([#457](https://github.com/celox-sim/celox/issues/457)), `bind`. - Declarations: variable declaration initializers of members of an interface - array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), + array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) in event lists, and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit @@ -367,10 +367,27 @@ parameters; recursive specializations and nesting beyond 64 levels are rejected. Block-local variables have lexical scope in `always_comb` and `always_ff`. Locals may shadow module signals and reuse names in separate blocks or processes. -### Hard packed untagged unions +### Packed untagged unions Hard packed untagged unions share one bit vector between all members; every member must have the same width (IEEE 1800-2023 7.3.1). +Soft packed unions (`union soft` or `union soft packed`) allow different member +widths. Their size is the largest member width, each member starts at the least +significant bit, and writing a smaller member preserves the remaining upper +bits. Nested packed unions and structures use the same layout rules. + +```systemverilog +union soft packed { + logic [15:0] word_value; + logic [7:0] byte_value; +} data; +// After data.word_value = 16'h1234, data.byte_value = 8'hab leaves data = 16'h12ab. +``` + +Whole-union operations use the declared signedness (unsigned by default). +Mixed `bit`/`logic` unions retain four-state storage, with X/Z converted to zero +when reading or writing a two-state member. Tagged and unpacked unions remain +unsupported. ### Named subroutine arguments diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index c2ec6c42dbe..304d2ff25a1 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -84,7 +84,9 @@ signedness, and mixed two-state/four-state member conversions follow IEEE This first structure extension supports constant in-range member selections. Arrays of structures with member access, dynamic or out-of-range member selections, struct-valued parameter member evaluation, assignment patterns, -unpacked structures, and unions remain unsupported. Member access on function +unpacked structures, and tagged/unpacked unions remain unsupported. +Hard and soft packed untagged unions share offset-zero member storage; soft +unions use the largest member width and preserve upper bits on narrower writes. Member access on function formals is also deferred. These forms must be diagnosed rather than silently lowered as accesses to the entire structure. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..eefef7e2588 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -24,7 +24,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | @@ -164,7 +164,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 @@ -257,10 +257,27 @@ package が `p` から実際に import した名前だけです。export を経 ブロックローカル変数は、`always_comb` と `always_ff` で字句スコープを持ちます。 モジュールの信号と同名の変数や、別のブロック・プロセスでの同名変数を扱えます。 -### hard packed untagged union +### packed untagged union hard packed untagged union のメンバーは、同じビットベクタを共有します。 全メンバーの幅が一致する必要があります(IEEE 1800-2023 7.3.1)。 +`union soft` / `union soft packed` は幅の異なるメンバーを許容します。 +全体の幅は最大メンバーの幅となり、各メンバーは最下位ビットから配置されます。 +小さいメンバーへの書き込みでは残りの上位ビットを保持します。 +packed union と packed 構造体の入れ子にも対応します。 + +```systemverilog +union soft packed { + logic [15:0] word_value; + logic [7:0] byte_value; +} data; +// data.word_value = 16'h1234 の後で data.byte_value = 8'hab とすると data = 16'h12ab。 +``` + +union 全体の演算は宣言時の符号指定に従います(既定は unsigned)。 +`bit` / `logic` 混在時は 4-state の領域を共有し、2-state メンバーを +読み書きする際には X/Z を 0 に変換します。 +tagged union と unpacked union は未対応です。 ### 名前付きサブルーチン引数 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index af96eddb62d..4013d41a552 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -271,10 +271,21 @@ test("all four retained baselines accept only their existing failures", () => { exitStatus, suite, ); - assert.equal( - result.accepted_failures.length, - suite === "sv" ? 0 : tool === "icarus" ? 11 : 2, - ); + if (suite === "sv") { + assert.deepEqual( + result.accepted_failures, + tool === "icarus" + ? [ + "unions::packed_mixed_state", + "unions::soft_overlay", + "unions::soft_signed_ports", + "unions::soft_wide_four_state", + ] + : [], + ); + } else { + assert.equal(result.accepted_failures.length, tool === "icarus" ? 11 : 2); + } } } });