From abc4ac69133422d4e2bc1081d5ae15c23099972c Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 11:22:48 +0900 Subject: [PATCH 1/4] feat(sv): support non-ANSI module port declarations A non-ANSI header lists port names, and port declarations in the body give their direction and type; a net or variable declaration of the same name may complete a port declaration without a type (IEEE 1800-2023 23.2.2.1). When every header port is a simple name, the parser now folds the body declarations into the header ports and gives the unit the ANSI form, so analysis sees one declaration per port. A vector net or variable declaration must repeat the port declaration's range; the port declaration's range and signing carry over to a scalar one. A net declaration assignment of a port stays a continuous assignment (10.3.1). A header port without a port declaration, a port declared twice, a port declaration that names no header port, differing ranges, a second declaration of a port whose port declaration has a net or variable type, and a variable initializer on a completed port are rejected by name. Headers with port expressions (selects, concatenations, named or empty ports) stay unsupported and are tracked in #1953. Closes #426 Change-Id: I548cd471cd50819374b833c057bc2bfa39355e6a --- crates/celox-sv-analyzer/src/ast.rs | 4 +- crates/celox-sv-analyzer/src/lib.rs | 2 +- crates/celox-sv-analyzer/src/parsed.rs | 2 +- crates/celox-sv-syntax/src/parser.rs | 1 + .../src/parser/declarations.rs | 1 + crates/celox-sv-syntax/src/parser/non_ansi.rs | 403 ++++++++++++++++++ crates/celox-sv-syntax/src/parser/tests.rs | 27 ++ .../src/sv/cases/hierarchy.vtest | 45 ++ .../frontends/systemverilog/hierarchy.rs | 51 +++ .../systemverilog/review_regressions.rs | 4 +- docs/guide/systemverilog-reference.md | 4 +- docs/ja/guide/systemverilog-reference.md | 4 +- 12 files changed, 538 insertions(+), 10 deletions(-) create mode 100644 crates/celox-sv-syntax/src/parser/non_ansi.rs diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index d3e2c0329e6..e59ae8fc339 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -332,7 +332,7 @@ impl Source { } celox_sv_syntax::PortStyle::NonAnsi => { return Err(AnalyzerError::Unsupported( - "non-ANSI module port declarations".to_string(), + "non-ANSI port expressions".to_string(), )); } _ => {} @@ -495,7 +495,7 @@ impl Source { } celox_sv_syntax::PortStyle::NonAnsi if syntax_tree.root_name()? == module_name => { return Err(AnalyzerError::Unsupported( - "non-ANSI module port declarations".to_string(), + "non-ANSI port expressions".to_string(), )); } _ => {} diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 19ec606ecd2..35997a2c289 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -183,7 +183,7 @@ pub const SV_FRONTEND_TRACKING_ISSUE: u32 = 88; /// Dedicated tracking issues, keyed by the leading text of the construct name /// carried by [`AnalyzerError::Unsupported`]. const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ - ("non-ANSI module port declarations", 426), + ("non-ANSI port expressions", 1953), ("ref port direction", 427), ("nonblocking assignment inside always_latch", 431), ( diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 102832162c1..143a76ffce4 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -740,7 +740,7 @@ mod tests { module \escaped.name (output logic y); assign y = 1'b0; endmodule module Duplicate; endmodule module Duplicate; endmodule - module Legacy(y); output y; endmodule + module Legacy({y}); output y; endmodule "#, Path::new("index.sv"), ) diff --git a/crates/celox-sv-syntax/src/parser.rs b/crates/celox-sv-syntax/src/parser.rs index 7cca39d37ab..0d52b135058 100644 --- a/crates/celox-sv-syntax/src/parser.rs +++ b/crates/celox-sv-syntax/src/parser.rs @@ -17,6 +17,7 @@ mod instances; mod keywords; mod modports; mod nets; +mod non_ansi; mod numbers; mod packages; mod procedures; diff --git a/crates/celox-sv-syntax/src/parser/declarations.rs b/crates/celox-sv-syntax/src/parser/declarations.rs index 9b16ce4c5fa..607f5e0fc67 100644 --- a/crates/celox-sv-syntax/src/parser/declarations.rs +++ b/crates/celox-sv-syntax/src/parser/declarations.rs @@ -538,6 +538,7 @@ impl Parser<'_> { return Err(self.error("unfinished generate body item")); } frame.unit.items = std::mem::take(&mut frame.builder.roots); + self.adopt_non_ansi_ports(&mut frame.unit)?; self.declare_implicit_nets(&mut frame.unit)?; frame.unit.body = self.range(frame.body_start); if !frame.unit.external { diff --git a/crates/celox-sv-syntax/src/parser/non_ansi.rs b/crates/celox-sv-syntax/src/parser/non_ansi.rs new file mode 100644 index 00000000000..1a1560d916d --- /dev/null +++ b/crates/celox-sv-syntax/src/parser/non_ansi.rs @@ -0,0 +1,403 @@ +//! Non-ANSI module ports (IEEE 1800-2023 23.2.2.1). +//! +//! A non-ANSI header lists the ports; port declarations in the body give +//! their direction and type, and a net or variable declaration may give the +//! type of a port whose port declaration has none. When every header port is +//! a simple identifier, the declarations are folded into the header ports and +//! the unit takes the ANSI form, so that semantic consumers see one port +//! declaration per port. Other port expressions keep the non-ANSI form. +use super::*; + +/// A port declaration of a non-ANSI module body. +struct PortDeclaration { + direction: Direction, + net_type: Option, + variable: bool, + data_type: TypeId, + dimensions: Vec, + default: Option, + tokens: TokenRange, +} + +impl Parser<'_> { + /// Fold the body port declarations of a non-ANSI `unit` into its header. + pub(super) fn adopt_non_ansi_ports(&mut self, unit: &mut Unit) -> Result<()> { + if unit.port_style != PortStyle::NonAnsi + || !unit + .ports + .iter() + .all(|port| matches!(port.kind, PortKind::Named(_))) + { + return Ok(()); + } + let resume = self.at; + let mut declarations: Vec<(String, PortDeclaration)> = Vec::new(); + let mut items = Vec::with_capacity(unit.items.len()); + for &item in &unit.items { + let BodyItem { kind, tokens } = &self.body_items[item.0]; + let BodyItemKind::Unconverted { category, .. } = kind else { + items.push(item); + continue; + }; + let direction = match category.as_str() { + "input" => Direction::Input, + "output" => Direction::Output, + "inout" => Direction::Inout, + "ref" => Direction::Ref, + _ => { + items.push(item); + continue; + } + }; + let tokens = *tokens; + self.at = self.indices.partition_point(|&index| index < tokens.start); + for (name, declaration) in self.port_declaration(direction)? { + if declarations.iter().any(|(declared, _)| *declared == name) { + self.at = resume; + return Err(self.error(format!("port `{name}` is declared more than once"))); + } + declarations.push((name, declaration)); + } + } + for port in &mut unit.ports { + let PortKind::Named(name) = &port.kind else { + unreachable!("checked above") + }; + let name = name.value().to_string(); + let Some(index) = declarations + .iter() + .position(|(declared, _)| *declared == name) + else { + self.at = resume; + return Err(self.error(format!("port `{name}` has no port declaration"))); + }; + let (_, declaration) = declarations.swap_remove(index); + let (net_type, variable, data_type) = if declaration.net_type.is_some() + || declaration.variable + || !matches!( + self.types[declaration.data_type.0].kind, + DataTypeKind::Implicit + ) { + // The port is completely declared (IEEE 1800-2023 23.2.2.1). + if self.declares_object(&items, &name) { + self.at = resume; + return Err(self.error(format!( + "port `{name}` with a net or variable type is declared again" + ))); + } + ( + declaration.net_type, + declaration.variable, + declaration.data_type, + ) + } else { + // The port is completed by a net or variable declaration of + // the same name, if there is one. + match self.take_port_object( + &mut items, + ( + &mut unit.net_declarations, + &mut unit.data_declarations, + &mut unit.assign_statements, + ), + &name, + declaration.data_type, + )? { + Some(object) => object, + None => (None, false, declaration.data_type), + } + }; + port.direction = Some(declaration.direction); + port.net_type = net_type; + port.variable = variable; + port.data_type = Some(data_type); + port.dimensions = declaration.dimensions; + port.default = declaration.default; + port.tokens = declaration.tokens; + } + self.at = resume; + if let Some((name, _)) = declarations.first() { + return Err(self.error(format!("port declaration `{name}` names no port"))); + } + unit.items = items; + unit.port_style = PortStyle::Ansi; + Ok(()) + } + + /// The names a port declaration starting at the cursor declares. + fn port_declaration(&mut self, direction: Direction) -> Result> { + let start = self.at; + self.attributes()?; + self.at += 1; + let net_type = if matches!( + self.peek(), + "wire" + | "tri" + | "tri0" + | "tri1" + | "supply0" + | "supply1" + | "wand" + | "triand" + | "wor" + | "trior" + | "trireg" + | "uwire" + | "interconnect" + ) { + let word = self.peek().to_owned(); + self.at += 1; + Some(word) + } else { + None + }; + let variable = self.eat("var"); + let data_type = if self.starts_type() { + self.data_type()? + } else { + self.implicit_type()? + }; + let mut declared = Vec::new(); + loop { + let name = self.name()?; + let dimensions = self.dimensions()?; + let default = if self.eat("=") { + Some(self.expression(0)?) + } else { + None + }; + declared.push(( + name.value().to_string(), + PortDeclaration { + direction, + net_type: net_type.clone(), + variable, + data_type, + dimensions, + default, + tokens: self.range(start), + }, + )); + if !self.eat(",") { + break; + } + } + self.expect(";")?; + Ok(declared) + } + + /// Remove the declarator of `name` from the module-scope net or variable + /// declarations, returning the port's net type, `var` and type. The + /// port declaration's packed range and signing carry over to a type + /// that has neither (IEEE 1800-2023 23.2.2.1). A net declaration + /// assignment stays as the continuous assignment it is (10.3.1). + fn take_port_object( + &mut self, + items: &mut Vec, + (unit_nets, unit_data, unit_assigns): ( + &mut Vec, + &mut Vec, + &mut Vec, + ), + name: &str, + port_type: TypeId, + ) -> Result, bool, TypeId)>> { + let qualified = items + .iter() + .any(|&item| match self.body_items[item.0].kind { + BodyItemKind::Net(id) => { + let net = &self.net_declarations[id.0]; + (net.strength.is_some() || net.delay.is_some() || net.vector.is_some()) + && net + .variables + .iter() + .any(|variable| variable.name.value() == name) + } + _ => false, + }); + if qualified { + return Err(self.error(format!( + "net declaration of non-ANSI port `{name}` with a strength, delay or \ + `vectored`/`scalared`" + ))); + } + let found = items.iter().enumerate().find_map(|(position, &item)| { + let (declarators, object) = match self.body_items[item.0].kind { + BodyItemKind::Net(id) => { + let net = &self.net_declarations[id.0]; + if net.strength.is_some() || net.delay.is_some() || net.vector.is_some() { + return None; + } + ( + &net.variables, + (Some(net.net_type.clone()), false, net.data_type), + ) + } + BodyItemKind::Data(id) => match &self.data_declarations[id.0] { + DataDeclaration::Variables(variables) if !variables.constant => { + (&variables.variables, (None, true, variables.data_type)) + } + _ => return None, + }, + _ => return None, + }; + let index = declarators + .iter() + .position(|declarator| declarator.name.value() == name)?; + let declarator = declarators[index].clone(); + Some(( + position, + item, + index, + object, + declarator, + declarators.len() == 1, + )) + }); + let Some((position, item, index, (net_type, variable, object_type), declarator, last)) = + found + else { + return Ok(None); + }; + if !declarator.dimensions.is_empty() || (variable && declarator.value.is_some()) { + return Err(self.error(format!( + "variable declaration of non-ANSI port `{name}` with an initializer, or net or \ + variable declaration of it with unpacked dimensions" + ))); + } + let assign = match declarator.value { + Some(right) => Some(self.declaration_assignment(&declarator, right)?), + None => None, + }; + if let Some((id, _)) = assign { + unit_assigns.push(id); + } + match self.body_items[item.0].kind { + BodyItemKind::Net(id) => { + self.net_declarations[id.0].variables.remove(index); + if last { + unit_nets.retain(|&net| net != id); + } + } + BodyItemKind::Data(id) => { + if let DataDeclaration::Variables(variables) = &mut self.data_declarations[id.0] { + variables.variables.remove(index); + } + if last { + unit_data.retain(|&data| data != id); + } + } + _ => unreachable!("found above"), + } + match (assign, last) { + (Some((_, assign)), true) => items[position] = assign, + (Some((_, assign)), false) => items.insert(position + 1, assign), + (None, true) => { + items.remove(position); + } + (None, false) => {} + } + Ok(Some(( + net_type, + variable, + self.merge_port_type(port_type, object_type)?, + ))) + } + + /// The continuous assignment `name = right` of a net declaration + /// assignment, as an assignment and its body item. + fn declaration_assignment( + &mut self, + declarator: &VariableDeclarator, + right: ExprId, + ) -> Result<(AssignId, BodyItemId)> { + let start = self + .indices + .partition_point(|&index| index < declarator.tokens.start); + self.at = start + 1; + let left = self.node(start, ExprKind::Name(declarator.name.clone()))?; + let id = AssignId(self.assign_statements.len()); + self.assign_statements.push(AssignSyntax { + strength: None, + delay: None, + assignments: vec![AssignmentSyntax { + left, + right, + tokens: declarator.tokens, + }], + tokens: declarator.tokens, + }); + if self.body_items.len() >= 1_000_000 { + return Err(self.unsupported("native body-item arena exceeds one million entries")); + } + let item = BodyItemId(self.body_items.len()); + self.body_items.push(BodyItem { + kind: BodyItemKind::Assign(id), + tokens: declarator.tokens, + }); + Ok((id, item)) + } + + /// Whether a net or variable declaration among `items` declares `name`. + fn declares_object(&self, items: &[BodyItemId], name: &str) -> bool { + items.iter().any(|&item| { + let declarators = match self.body_items[item.0].kind { + BodyItemKind::Net(id) => &self.net_declarations[id.0].variables, + BodyItemKind::Data(id) => match &self.data_declarations[id.0] { + DataDeclaration::Variables(variables) + | DataDeclaration::Constructed(variables) => &variables.variables, + DataDeclaration::Unconverted(_) => return false, + }, + _ => return false, + }; + declarators + .iter() + .any(|declarator| declarator.name.value() == name) + }) + } + + /// The type of a port declared by a port declaration of type + /// `port_type` and a net or variable declaration of type `object_type`. + fn merge_port_type(&mut self, port_type: TypeId, object_type: TypeId) -> Result { + let port = self.types[port_type.0].clone(); + let mut object = self.types[object_type.0].clone(); + let mut changed = false; + if object.packed_dimensions.is_empty() { + changed |= !port.packed_dimensions.is_empty(); + object.packed_dimensions = port.packed_dimensions.clone(); + } else { + // A vector net or variable repeats the port's range exactly. + let text = |dimensions: &[Dimension]| { + dimensions + .iter() + .map(|dimension| { + self.tokens[dimension.tokens.range()] + .iter() + .filter(|token| !token.is_trivia()) + .map(|token| token.text.as_str()) + .collect::() + }) + .collect::>() + }; + if text(&port.packed_dimensions) != text(&object.packed_dimensions) { + return Err(self.error( + "the ranges of a non-ANSI port declaration and its net or variable \ + declaration differ", + )); + } + } + if port.signed == Some(true) && object.signed != Some(true) { + object.signed = Some(true); + changed = true; + } + if !changed { + return Ok(object_type); + } + if self.types.len() >= 1_000_000 { + return Err(self.unsupported("native type arena exceeds one million nodes")); + } + let id = TypeId(self.types.len()); + self.types.push(object); + Ok(id) + } +} diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index 7372cf06afb..c047f060e8c 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2873,3 +2873,30 @@ fn class_random_qualifiers_and_constraints_are_preserved() { assert!(class.properties[1].qualifiers.randc); assert!(!class.properties[1].qualifiers.rand); } + +#[test] +fn non_ansi_port_declarations_fold_into_the_header() { + let syntax = parse( + "module M(a, b, q);\n input [7:0] a;\n input wire b;\n output reg [7:0] q;\n \ + wire [7:0] a;\n always @(posedge b) q <= a;\nendmodule\n", + ); + let unit = &syntax.units[0]; + assert_eq!(unit.port_style, PortStyle::Ansi); + let ports: Vec<_> = unit + .ports + .iter() + .map(|port| (port.direction, port.net_type.as_deref(), port.variable)) + .collect(); + assert_eq!( + ports, + [ + (Some(Direction::Input), Some("wire"), false), + (Some(Direction::Input), Some("wire"), false), + (Some(Direction::Output), None, false), + ] + ); + // The port declarations and the completing net declaration are gone + // from the body. + assert!(unit.net_declarations.is_empty()); + assert_eq!(unit.items.len(), 1); +} diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 307729ae1be..25b0a4d8715 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1463,6 +1463,51 @@ (assert_eq y (+ (<< 1 128) (+ (<< 2 43) 1))) (assert_eq width 129)) +; Non-ANSI module ports (IEEE 1800-2023 23.2.2.1): a header of port names, +; port declarations in the body, and net or variable declarations that +; complete them (`reg [7:0] q;`, `wire signed [3:0] a;`), including a net +; declaration assignment, connected by position and by name. +(case non_ansi_ports_take_body_declarations + (source "non_ansi.sv" #" + module Reg(clk, rst, d, q, qn); + input clk, rst; + input [7:0] d; + output [7:0] q; + output reg [7:0] qn; + reg [7:0] q; + always @(posedge clk or posedge rst) + if (rst) begin q <= 8'd0; qn <= 8'hff; end + else begin q <= d; qn <= ~d; end + endmodule + module Add(a, b, s, neg); + input signed [3:0] a; + input [3:0] b; + output [4:0] s; + output neg; + wire signed [3:0] a; + wire [4:0] s = a + b; + assign neg = a < 0; + endmodule + module Top; + reg clk = 0, rst = 1; + reg [7:0] d = 8'h5a; + wire [7:0] q, qn; + wire [4:0] s; + wire neg; + Reg r(clk, rst, d, q, qn); + Add x(.a(4'hd), .b(4'd4), .s(s), .neg(neg)); + always #5 clk = ~clk; + initial begin + #2 rst = 0; + #10 $display("%h %h %0d %b", q, qn, s, neg); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "5a a5 17 1\n")) + ; A child's output port depends only on the bits of its input port that ; the child reads, so a parent may feed other bits of that output back into ; the port without a combinational loop (#1955). diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index ca63ad3c551..f50db145ec4 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -700,6 +700,9 @@ fn array_parameter_elements_check_unselected_conditional_branch_types() { } sv_backends! { + fn non_ansi_ports_take_body_declarations(sim) { + @case "hierarchy::non_ansi_ports_take_body_declarations"; + } fn child_ports_keep_the_bit_ranges_they_read(sim) { @case "hierarchy::child_ports_keep_the_bit_ranges_they_read"; } @@ -707,3 +710,51 @@ sv_backends! { @case "hierarchy::child_ports_keep_the_bit_ranges_of_selected_connections"; } } + +#[test] +fn rejects_malformed_non_ansi_port_declarations() { + for (source, message) in [ + ( + "module Top(a, y); input a; endmodule", + "port `y` has no port declaration", + ), + ( + "module Top(a); input a; input a; endmodule", + "port `a` is declared more than once", + ), + ( + "module Top(a); input a; output b; endmodule", + "port declaration `b` names no port", + ), + ( + "module Top(a); input [3:0] a; wire [7:0] a; endmodule", + "its net or variable declaration differ", + ), + ( + "module Top(a); input a; wire [3:0] a; endmodule", + "its net or variable declaration differ", + ), + ( + "module Top(q); output reg q; reg q; endmodule", + "port `q` with a net or variable type is declared again", + ), + ( + "module Top(q); output q; reg q = 1'b1; endmodule", + "variable declaration of non-ANSI port `q` with an initializer", + ), + ( + "module Top({y, z}); output y, z; assign y = 1'b1; assign z = 1'b0; endmodule", + "non-ANSI port expressions", + ), + ] { + let error = Simulator::from_sv_sources(vec![(source, Path::new("ports.sv"))], "Top") + .build_cranelift() + .expect_err(source) + .to_string() + .replace('│', " ") + .split_whitespace() + .collect::>() + .join(" "); + assert!(error.contains(message), "{source}: {error}"); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 7c6b4f10ca6..fd1af0408f6 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5358,9 +5358,9 @@ fn rejects_constructs_that_are_not_yet_lowered() { "#, ), ( - "non-ANSI module port declarations", + "non-ANSI port expressions", r#" - module Top(y); output y; assign y = 1'b1; endmodule + module Top({y, z}); output y, z; assign y = 1'b1; assign z = 1'b0; endmodule "#, ), ( diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 79e3ef8a4a5..779e2e7260e 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -16,7 +16,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Modules | ANSI ports, `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | +| Modules | ANSI ports, non-ANSI ports (a header of port names and body `input` / `output` / `inout` declarations, optionally completed by a net or variable declaration of the same name), `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | | Programs | `program` declarations with ports and parameters, instantiated from modules like a module; their `initial` procedures run in the reactive region set (see [Programs](#programs)) | | Generate | `for` (with `genvar`), `if`, `case`; constant expressions including `**` | | Hierarchical references | reads of nets and variables of other instances, and procedural writes of their variables, including selects of unpacked array elements (`u.mem[i][7:0] = v`), through names that start at an instance of the module (also of a generate block or an instance array element), at the module's own name, at an enclosing module's name (upward) or at `$root`; see [Hierarchical references](#hierarchical-references) | @@ -196,7 +196,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: `wait` or event expressions reading a static task argument. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. -- Ports and instances: non-ANSI port declarations ([#426](https://github.com/celox-sim/celox/issues/426)), `ref` ports +- Ports and instances: non-ANSI port expressions such as `module m({a, b}, c[3:0], .p(d))` ([#1953](https://github.com/celox-sim/celox/issues/1953)), `ref` ports ([#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 diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index fec9ec48260..efe68525764 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -15,7 +15,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| モジュール | ANSI ポート、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割) | +| モジュール | ANSI ポート、non-ANSI ポート(ヘッダのポート名と本体の `input` / `output` / `inout` 宣言。同名のネットまたは変数の宣言で型を補える)、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割) | | プログラム | ポートとパラメータを持つ `program` 宣言。モジュールと同じくモジュールからインスタンス化し、その `initial` 手続きはリアクティブ領域セットで実行します(下記の「プログラム」を参照) | | generate | `for`(`genvar`)、`if`、`case`。`**` を含む定数式 | | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | @@ -174,7 +174,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 static task 引数を読む `wait` 条件とイベント式。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `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))、 +- ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`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、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` での From 7c97e183df5f27d6f8e56002912ab4f598d0e6f3 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 09:04:31 +0900 Subject: [PATCH 2/4] feat(sv): accept loop temporaries shared by plain edge always blocks Several plain edge-triggered `always` processes may write one variable, such as the `integer i` that C906's aq_biu_req_arbiter uses as the index of two `always @(posedge clk)` loops. Only always_comb, always_latch and always_ff restrict a variable to one process (IEEE 1800-2023 9.2.2.2, 9.2.2.4); otherwise the last write determines the value (6.5). Celox rejected the design with "multiple variable drivers for `i`". A variable other than an unpacked array that only plain edge processes write, and only by blocking assignments, is now accepted. Those processes read and write its stable state directly, as a blocking assignment updates the variable at once (10.4.1): a process reads its own preceding writes, a later edge sees the other process's writes, and the last write stays even when a coincident process does not write the variable. The usual per-process working seed and commit would let such a process commit the pre-edge value over another process's write. The handling is per variable; designs without such variables lower as before. always_ff overlap and nonblocking writes from several processes stay rejected. Closes #1945 Change-Id: I2bcf163f2ca3ebc3b62c1e6c8fad0c4720f54958 --- crates/celox-frontend-sv/src/lowering.rs | 65 ++++++++- crates/celox-frontend-sv/src/lowering/ff.rs | 37 ++++- .../src/sv/cases/procedural.vtest | 137 ++++++++++++++++++ .../frontends/systemverilog/procedural.rs | 12 ++ .../systemverilog/review_regressions.rs | 42 ++++++ 5 files changed, 284 insertions(+), 9 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0202c7f5c14..a7e271a6439 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1117,6 +1117,60 @@ fn shared_edge_memories( memories } +/// Variables, other than unpacked arrays, that several plain edge-triggered +/// `always` processes write only by blocking assignments, such as a loop +/// index they share. A variable may have several procedural writers, and the +/// last write determines its value (IEEE 1800-2023 6.5); only always_comb, +/// always_latch and always_ff restrict it to one process (9.2.2.2, 9.2.2.4). +/// The processes read and write the variable's stable state directly (see +/// `Ff::with_shared_variables`). +fn shared_edge_variables( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, +) -> HashSet { + let first_ff = module.comb_processes().len(); + let end_ff = first_ff + module.ff_processes().len(); + let mut nonblocking = HashSet::default(); + for process in module.ff_processes() { + for stmt in process.body() { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { + lhs, + nonblocking: true, + .. + } => { + nonblocking.insert(lhs.name()); + } + sv::ir::Stmt::AssignConcat { + parts, + nonblocking: true, + .. + } => nonblocking.extend(parts.iter().map(sv::ir::LValue::name)), + _ => {} + }); + } + } + module + .signals() + .iter() + .filter(|signal| { + !signal.is_net() + && signal.r#type().unpacked_ranges().is_empty() + && !nonblocking.contains(signal.name()) + }) + .filter(|signal| { + let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); + drivers.iter().any(|(id, _)| drivers[0].0 != *id) + && drivers.iter().all(|(id, _)| { + (first_ff..end_ff).contains(id) + && !module.ff_processes()[id - first_ff].is_always_ff() + }) + }) + .map(|signal| signal.name().to_string()) + .collect() +} + /// The unpacked arrays that only edge-triggered processes of `module` drive. /// A process that writes one of them only by nonblocking assignments, at /// least one of them at a run-time element, publishes just the elements it @@ -1399,7 +1453,7 @@ fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, parameter_types: &HashMap, - shared_memories: &HashSet, + shared: &HashSet, ) -> Result<(), sv::AnalyzerError> { for port in module .ports() @@ -1448,7 +1502,7 @@ fn validate_variable_driver_ranges( && net_driver_ranges_overlap(left.1, right.1) }) }); - if overlapping_continuous || (has_overlap && !shared_memories.contains(signal_name)) { + if overlapping_continuous || (has_overlap && !shared.contains(signal_name)) { return Err(sv::AnalyzerError::Unsupported(format!( "multiple variable drivers for `{signal_name}`" ))); @@ -3303,7 +3357,9 @@ fn lower_module_with_overrides( foreign_writes, warnings, ); - validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; + let shared_variables = shared_edge_variables(module, &constants, ¶meter_types); + let shared_all = shared_memories.union(&shared_variables).cloned().collect(); + validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_all)?; validate_foreign_drivers( module, &constants, @@ -3651,6 +3707,7 @@ fn lower_module_with_overrides( &ff_event_roles, &shared_memories, foreign_writes, + &shared_variables, &mut repeated_ff_writes, )?; ( @@ -9141,6 +9198,7 @@ fn lower_ff_processes( ff_event_roles: &[FfEventRole], shared_memories: &HashSet, foreign_writes: &HashMap, + shared_variables: &HashSet, repeated_writes: &mut Vec, ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); @@ -9269,6 +9327,7 @@ fn lower_ff_processes( staged, } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) + .with_shared_variables(shared_variables) .with_sparse_candidates(&edge_memories) .with_window_writes(&window_writes) .lower_process(process.body())?; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6058fabcc4a..3220791f75c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -53,6 +53,9 @@ pub(super) struct Ff<'p, 'a> { /// Variables a process kernel may write between the evaluation of this /// process and the NBA region (see `kernel_window_writes`). window_writes: HashSet, + /// Variables several edge processes write by blocking assignments (see + /// `with_shared_variables`). + shared: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -129,6 +132,7 @@ impl<'p, 'a> Ff<'p, 'a> { element_writes: HashSet::default(), other_writes: HashSet::default(), window_writes: HashSet::default(), + shared: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -255,10 +259,23 @@ impl<'p, 'a> Ff<'p, 'a> { self } + /// Variables other edge processes also write by blocking assignments. + /// The process reads and writes their stable state directly, as a + /// blocking assignment updates the variable at once (IEEE 1800-2023 + /// 10.4.1): its reads see its own preceding writes, and the last write of + /// any process stays, even when a later process does not write it. A + /// working value seeded by each process would instead be committed by + /// every one of them. + pub fn with_shared_variables(mut self, names: &HashSet) -> Self { + self.shared = names.iter().filter_map(|name| self.m.id(name)).collect(); + self + } + /// Where a write of `id`, and a read of a value the process wrote, go: - /// the working region, or stable state in a process kernel. + /// the working region, or stable state in a process kernel and for a + /// shared variable. fn target(&self, id: SourceVarId) -> Addr { - if self.kernel.is_some() || self.direct { + if self.kernel.is_some() || self.direct || self.shared.contains(&id) { stable(id) } else { working(id) @@ -475,9 +492,11 @@ impl<'p, 'a> Ff<'p, 'a> { let working_set = &self.working; let variables = &*self.m.variables; let direct = self.kernel.is_some() || self.direct; + let shared = &self.shared; let map = |id: &SourceVarId| -> Addr { - if direct { - stable(*aliases.get(id).unwrap_or(id)) + let var = aliases.get(id).unwrap_or(id); + if direct || shared.contains(var) { + stable(*var) } else if let Some(var) = aliases.get(id) { working(*var) } else if working_set.contains(id) @@ -4268,6 +4287,11 @@ impl<'p, 'a> Ff<'p, 'a> { }) .collect(); self.sparse_memories.extend(sparse); + if self.nonblocking.iter().any(|id| self.shared.contains(id)) { + return Err(unsupported( + "nonblocking writes to a variable several edge processes write", + )); + } if self .working .iter() @@ -4333,11 +4357,12 @@ impl<'p, 'a> Ff<'p, 'a> { stage_nonblocking(body, &staged, self.m) }; // A variable staged for an exact publication has no next state of - // its own: only its merge publishes it. + // its own: only its merge publishes it. A shared variable is written + // in stable state. let published: Vec<_> = targets .iter() .copied() - .filter(|target| !exact.contains(&target.id)) + .filter(|target| !exact.contains(&target.id) && !self.shared.contains(&target.id)) .collect(); let ordinary_targets: Vec<_> = published .iter() diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 26f8a919e5c..867a5ff44e3 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -70,6 +70,143 @@ (assert_eq x 7) (assert_eq r 2)) +; Plain always processes may share a variable, such as a loop index; the last +; write determines its value (IEEE 1800-2023 6.5, 9.2.2.4). A process reads its +; own preceding blocking writes. Which process of one edge runs first is not +; defined, so the assertions avoid reads that depend on it. +(case edge_processes_share_a_blocking_loop_variable + (source "shared_index.sv" #" + module Top(input logic clk, input logic en, input logic [7:0] x, input logic [7:0] y, + output logic [7:0] a, output logic [7:0] b, + output integer last_a, output integer last_b, output integer prev, + output integer i_q); + integer i; + logic [7:0] ra = 8'd0; + logic [7:0] rb = 8'd0; + always @(posedge clk) begin + for (i = 0; i < 8; i = i + 1) ra[i] <= x[7 - i]; + last_a <= i; + end + always @(posedge clk) begin + prev <= i; + if (en) begin + for (i = 0; i < 4; i = i + 1) rb[i] <= y[i]; + last_b <= i; + end + end + assign a = ra; + assign b = rb; + assign i_q = i; + endmodule + "#) + (top Top) + (modify (set en 0) (set x 0x01) (set y 0xff)) + (tick clk) + (assert_eq a 0x80) + (assert_eq b 0) + (assert_eq last_a 8) + (assert_eq i_q 8) + (tick clk) + (assert_eq prev 8 "a read before the process writes sees the earlier write") + (modify (set en 1) (set x 0x80)) + (tick clk) + (assert_eq a 0x01) + (assert_eq b 0x0f) + (assert_eq last_a 8) + (assert_eq last_b 4 "a read after the loop sees the process's own write") + (assert_eq prev 8) + (modify (set en 0) (set y 0x05)) + (tick clk) + (assert_eq i_q 8 "the write stays when the other process does not write") + (assert_eq b 0x0f) + (tick clk) + (assert_eq prev 8) + (assert_eq i_q 8)) + +; Processes of different clocks share a variable. A write at one edge is +; visible to a process of a later edge, and survives a coincident edge whose +; process does not write the variable. +(case edge_processes_of_two_clocks_share_a_blocking_variable + (source "shared_clocks.sv" #" + module Top(input logic ca, input logic cb, input logic en, + output integer qa, output integer qb, output integer i_q); + integer i; + integer sa = 0; + integer sb = 0; + always @(posedge ca) begin + for (i = 0; i < 3; i = i + 1) sa = sa + i; + qa <= i + sa; + end + always @(posedge cb) begin + qb <= i; + if (en) for (i = 0; i < 5; i = i + 1) sb = sb + i; + end + assign i_q = i; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set ca 0) (set cb 0) (set en 1)) + (modify (set ca 1)) + (run_until 1) + (assert_eq qa 6) + (assert_eq i_q 3) + (modify (set ca 0) (set cb 1)) + (run_until 2) + (assert_eq qb 3 "a later edge sees the other process's write") + (assert_eq i_q 5) + (modify (set cb 0) (set en 0)) + (modify (set ca 1) (set cb 1)) + (run_until 3) + (assert_eq qa 9) + (assert_eq i_q 3 "a coincident process that does not write keeps the write") + (modify (set ca 0) (set cb 0)) + (modify (set cb 1)) + (run_until 4) + (assert_eq qb 3) + (assert_eq i_q 3)) + +; The loop index of two asynchronously reset processes (from the C906 +; aq_biu_req_arbiter), which select bits of separate registers. +(case reset_processes_share_a_loop_index + (source "shared_reset_index.sv" #" + module Top(input logic clk, input logic rst_b, input logic we, + input logic [2:0] ptr, input logic sel, input logic hit, + output logic [7:0] fifo, output logic [7:0] apb); + reg [7:0] wsel_fifo; + reg [7:0] apbif_sel; + integer i; + always @(posedge clk or negedge rst_b) + if (!rst_b) + for (i = 0; i < 8; i = i + 1) wsel_fifo[i] <= 1'b0; + else + for (i = 0; i < 8; i = i + 1) + if (we & ptr == i) wsel_fifo[i] <= sel; + else wsel_fifo[i] <= wsel_fifo[i]; + always @(posedge clk or negedge rst_b) + if (!rst_b) + for (i = 0; i < 8; i = i + 1) apbif_sel[i] <= 1'b0; + else + for (i = 0; i < 8; i = i + 1) + if (we & ptr == i) apbif_sel[i] <= hit; + else apbif_sel[i] <= apbif_sel[i]; + assign fifo = wsel_fifo; + assign apb = apbif_sel; + endmodule + "#) + (top Top) + (modify (set rst_b 1) (set we 0) (set ptr 0) (set sel 0) (set hit 0)) + (modify (set rst_b 0)) + (modify (set rst_b 1)) + (assert_eq fifo 0) + (assert_eq apb 0) + (for (write position s h f a) + (list (1 3 1 0 0x08 0x00) (1 5 0 1 0x08 0x20) (0 1 1 1 0x08 0x20) (1 3 0 1 0x00 0x28)) + (modify (set we write) (set ptr position) (set sel s) (set hit h)) + (tick clk) + (assert_eq fifo f) + (assert_eq apb a))) + (case constant_functions_size_parameters_and_ports (source "constant_functions.sv" #" module Child #(parameter int unsigned ENTRIES = 2, diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index a9b5632084c..11835e6e428 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -98,6 +98,18 @@ sv_backends! { @case "procedural::mixed_blocking_and_nonblocking_writes_keep_their_regions"; } + fn edge_processes_share_a_blocking_loop_variable(sim) { + @case "procedural::edge_processes_share_a_blocking_loop_variable"; + } + + fn edge_processes_of_two_clocks_share_a_blocking_variable(sim) { + @case "procedural::edge_processes_of_two_clocks_share_a_blocking_variable"; + } + + fn reset_processes_share_a_loop_index(sim) { + @case "procedural::reset_processes_share_a_loop_index"; + } + fn constant_functions_size_parameters_and_ports(sim) { @case "procedural::constant_functions_size_parameters_and_ports"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 7c6b4f10ca6..80586dfa2ed 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -320,6 +320,48 @@ fn rejects_overlapping_always_ff_variable_drivers() { ); } +#[test] +fn rejects_loop_indices_shared_with_always_ff() { + // Only plain always processes may share a variable (IEEE 1800-2023 + // 9.2.2.4); nonblocking writes from several processes stay rejected. + for (first, second) in [ + ("always_ff", "always_ff"), + ("always_ff", "always"), + ("always", "always_ff"), + ] { + let error = cranelift_build_error(&format!( + r#" + module Top(input logic clk, input logic [3:0] a, b, output wire [3:0] y, z); + integer i; + logic [3:0] p, q; + {first} @(posedge clk) for (i = 0; i < 4; i = i + 1) p[i] <= a[i]; + {second} @(posedge clk) for (i = 0; i < 4; i = i + 1) q[i] <= b[i]; + assign y = p; + assign z = q; + endmodule + "# + )); + assert!( + error.contains("multiple variable drivers for `i`"), + "{first}/{second}: unexpected error: {error}" + ); + } + let error = cranelift_build_error( + r#" + module Top(input logic clk, a, b, output wire y); + logic q; + always @(posedge clk) q <= a; + always @(posedge clk) q = b; + assign y = q; + endmodule + "#, + ); + assert!( + error.contains("multiple variable drivers for `q`"), + "unexpected error: {error}" + ); +} + #[test] fn rejects_variables_also_written_through_output_arguments() { // A called subroutine writes its output actual for the calling process From 58b7e660d192c85f06cc21b6cb278205fc75e386 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 16:19:16 +0900 Subject: [PATCH 3/4] fix(native): retain FF publication from other lane tasks A lane task can update one array element while publishing another element computed by a different task. Applying the complete-event working-memory rewrite to that task removed the other producer's Commit, leaving a four-stage pipeline stuck after its second stage. Use a partial-event entry point for lane compilation. Track possibly uninitialized access fragments through the CFG and preserve external pending reads and publications. Retain direct updates when all paths define the observed fragments, and keep complete-event optimization unchanged. Carry NativeMergeKind from task construction through compilation so partial and fused comb/FF optimization decisions are independent of diagnostic labels. Use an exhaustive match for the working-state rewrite. Add five optimizer regressions and a portable generate-if pipeline case covering ascending and descending arrays with one, two and four stages. Validation on master feba1a583c, with this commit checked out alone: - Generate-if pipeline regression: all five backends passed. - Native parallel common regressions: 303 passed. - SIR optimizer: 473 passed, one existing ignored, plus its doctest. - Native image and differential scheduler regressions: 50 passed. - Clippy for celox-sir-opt and celox, including SV test registrations, passed. The unchanged shared pipeline case also passed Icarus and Verilator during validation on master 644beacb20; external adapters and this case are unchanged. With the stacked SV fix, rebuilt NAPI and passed the threads E2E test and all three runtime-event addon tests. Workspace check (excluding lydite-celox), formatting, lint and submodule checks passed. After replacing label-based dispatch with NativeMergeKind, 2,283 Native regressions passed on this commit alone, including the common parallel suite, image/differential scheduler tests and the Native SV variants. Affected-crate clippy also passed. Change-Id: I14a726b2bd25a3b561d230855cd9bcb81dd52da2 --- .../src/optimizer/passes/memory/commit_ops.rs | 109 ++++++++++++++ .../pass_eliminate_working_round_trip.rs | 141 +++++++++++++++++- .../src/sv/cases/indexed_select.vtest | 56 +++++++ crates/celox/src/backend/native/backend.rs | 48 +++++- crates/celox/src/backend/native/lanes.rs | 5 +- .../frontends/systemverilog/indexed_select.rs | 6 + 6 files changed, 354 insertions(+), 11 deletions(-) diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs index bfd4f3b2822..94fdee5616b 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs @@ -234,10 +234,35 @@ struct PendingSegments { impl PendingSegments { fn build(eu: &ExecutionUnit) -> Self { + Self::build_with_working_inputs(eu, false) + } + + fn build_with_working_inputs(eu: &ExecutionUnit, inputs: bool) -> Self { let mut endpoints: HashMap> = HashMap::default(); for block in eu.blocks.values() { for instruction in &block.instructions { match instruction { + SIRInstruction::Load(_, addr, offset, bits) + if inputs && addr.region == WORKING_REGION => + { + let (start, end) = instruction_range(&eu.register_map, offset, *bits); + endpoints + .entry(addr.absolute_addr()) + .or_default() + .extend([start, end]); + } + SIRInstruction::Commit(src, dst, offset, bits, _) + if inputs + && src.region == STABLE_REGION + && dst.region == WORKING_REGION + && src.absolute_addr() == dst.absolute_addr() => + { + let (start, end) = instruction_range(&eu.register_map, offset, *bits); + endpoints + .entry(dst.absolute_addr()) + .or_default() + .extend([start, end]); + } SIRInstruction::Store(addr, offset, bits, _, _, _) if addr.region == WORKING_REGION || addr.region == SPARSE_WORKING_REGION => @@ -348,6 +373,90 @@ fn update_segments(bits: &mut [u64], range: std::ops::Range, set: bool) { } } +/// A partial event can read pending values produced by another task. Such +/// values cannot be redirected to STABLE or have their publication removed. +/// Track possibly uninitialized access fragments, rather than bits of the +/// declared object, so large arrays with sparse accesses remain sparse. +pub(crate) fn uninitialized_working_observations( + eu: &ExecutionUnit, +) -> DirectStableStoreHazards { + use std::collections::VecDeque; + let segments = PendingSegments::build_with_working_inputs(eu, true); + let mut hazards = DirectStableStoreHazards::default(); + if segments.count == 0 { + return hazards; + } + let words = segments.count.div_ceil(64); + let mut incoming = HashMap::default(); + incoming.insert(eu.entry_block_id, vec![u64::MAX; words]); + let mut queue = VecDeque::from([eu.entry_block_id]); + while let Some(id) = queue.pop_front() { + let block = &eu.blocks[&id]; + let mut undefined = incoming[&id].clone(); + for instruction in &block.instructions { + let observed = match instruction { + SIRInstruction::Load(_, address, offset, width) + if address.region == WORKING_REGION => + { + Some((*address, offset, *width)) + } + SIRInstruction::Commit(source, _, offset, width, _) + if source.region == WORKING_REGION => + { + Some((*source, offset, *width)) + } + _ => None, + }; + if let Some((address, offset, width)) = observed { + let (start, end) = instruction_range(&eu.register_map, offset, width); + segments.record_observation( + &mut hazards, + &undefined, + address.absolute_addr(), + start, + end, + ); + } + let defined = match instruction { + SIRInstruction::Store(address, offset, width, ..) + if address.region == WORKING_REGION => + { + Some((*address, offset, *width)) + } + SIRInstruction::Commit(source, destination, offset, width, _) + if source.region == STABLE_REGION + && destination.region == WORKING_REGION + && source.absolute_addr() == destination.absolute_addr() => + { + Some((*destination, offset, *width)) + } + _ => None, + }; + if let Some((address, offset, width)) = defined + && let Some(start) = offset.constant_bit_offset() + && let Some(end) = start.checked_add(width) + && let Some(range) = segments.segment_range(address.absolute_addr(), start, end) + { + update_segments(&mut undefined, range, false); + } + } + for successor in crate::ir::cfg::terminator_successors(&block.terminator) { + let is_new = !incoming.contains_key(&successor); + let entry = incoming.entry(successor).or_insert_with(|| vec![0; words]); + let mut changed = is_new; + for (destination, source) in entry.iter_mut().zip(&undefined) { + let merged = *destination | *source; + changed |= merged != *destination; + *destination = merged; + } + if changed { + queue.push_back(successor); + } + } + } + hazards +} + /// Bit ranges for which replacing a WORKING/SPARSE write with an immediate /// STABLE write could change an observation in this complete event CFG. /// diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs index 2d1c5932ce1..066d74dd102 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs @@ -17,6 +17,17 @@ pub fn eliminate_working_round_trip( eu: &mut ExecutionUnit, _eu_boundary_blocks: &[BlockId], ) { + eliminate_working_round_trip_impl(eu, false); +} + +/// Optimize one partial event task. Pending values can have producers outside +/// this function, so publication requires proof of a local definition on every +/// path. Sparse publication can also consume dirty entries from other tasks. +pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit) { + eliminate_working_round_trip_impl(eu, true); +} + +fn eliminate_working_round_trip_impl(eu: &mut ExecutionUnit, partial: bool) { use crate::HashMap; // Phase 1: Scan — collect info about each WORKING variable @@ -140,9 +151,16 @@ pub fn eliminate_working_round_trip( .collect(); let unsafe_after_store = super::commit_ops::direct_stable_store_hazards(eu); + let uninitialized = (partial && !eligible.is_empty()) + .then(|| super::commit_ops::uninitialized_working_observations(eu)); let eligible: crate::HashSet = eligible .into_iter() - .filter(|addr| !unsafe_after_store.contains_addr(*addr)) + .filter(|addr| { + !unsafe_after_store.contains_addr(*addr) + && !uninitialized + .as_ref() + .is_some_and(|undefined| undefined.contains_addr(*addr)) + }) .collect(); // Sparse state has no per-EU seed: every producer writes the same pending @@ -151,7 +169,8 @@ pub fn eliminate_working_round_trip( let sparse_eligible: crate::HashSet = sparse_vars .iter() .filter(|(addr, info)| { - info.has_store + !partial + && info.has_store && info.stable_addr.is_some() && !info.invalid_apply && !unsafe_after_store.contains_addr(**addr) @@ -627,4 +646,122 @@ mod tests { SIRInstruction::Commit(..) )); } + #[test] + fn partial_event_keeps_publication_of_another_producers_fragment() { + let mut unit = eu(vec![block( + 0, + vec![ + working_seed(SIROffset::Static(24), 8), + SIRInstruction::Store( + addr(WORKING_REGION), + SIROffset::Static(24), + 8, + RegisterId(1), + Vec::new(), + Vec::new(), + ), + working_apply(SIROffset::Static(16), 8), + working_apply(SIROffset::Static(24), 8), + ], + SIRTerminator::Return, + )]); + let before = unit.clone(); + eliminate_partial_working_round_trip(&mut unit); + assert_eq!(unit, before); + } + + #[test] + fn partial_event_requires_a_definition_on_every_branch() { + for both_paths in [false, true] { + let store = || { + SIRInstruction::Store( + addr(WORKING_REGION), + SIROffset::Static(0), + 8, + RegisterId(1), + Vec::new(), + Vec::new(), + ) + }; + let mut unit = eu(vec![ + block( + 0, + vec![], + SIRTerminator::Branch { + cond: RegisterId(3), + true_block: (BlockId(1), vec![]), + false_block: (BlockId(2), vec![]), + }, + ), + block(1, vec![store()], SIRTerminator::Jump(BlockId(3), vec![])), + block( + 2, + if both_paths { vec![store()] } else { vec![] }, + SIRTerminator::Jump(BlockId(3), vec![]), + ), + block( + 3, + vec![working_apply(SIROffset::Static(0), 8)], + SIRTerminator::Return, + ), + ]); + let before = unit.clone(); + eliminate_partial_working_round_trip(&mut unit); + if both_paths { + assert!(unit.blocks[&BlockId(3)].instructions.is_empty()); + assert!( + matches!(unit.blocks[&BlockId(1)].instructions[0],SIRInstruction::Store(address,..) if address.region==STABLE_REGION) + ); + } else { + assert_eq!(unit, before); + } + } + } + + #[test] + fn partial_event_keeps_unseeded_dynamic_pending_values() { + let mut unit = eu(vec![block( + 0, + vec![ + indexed_working_store(), + working_apply(SIROffset::Static(0), 64), + ], + SIRTerminator::Return, + )]); + let before = unit.clone(); + eliminate_partial_working_round_trip(&mut unit); + assert_eq!(unit, before); + } + + #[test] + fn partial_event_can_redirect_a_locally_seeded_dynamic_update() { + let mut unit = eu(vec![block( + 0, + vec![ + working_seed(SIROffset::Static(0), 64), + indexed_working_store(), + working_apply(SIROffset::Static(0), 64), + ], + SIRTerminator::Return, + )]); + eliminate_partial_working_round_trip(&mut unit); + assert!( + matches!(unit.blocks[&BlockId(0)].instructions.as_slice(),[SIRInstruction::Store(address,SIROffset::Element {..},..)] if address.region==STABLE_REGION) + ); + } + #[test] + fn partial_event_keeps_reads_of_another_producers_pending_fragment() { + let mut unit = eu(vec![block( + 0, + vec![ + working_seed(SIROffset::Static(0), 8), + SIRInstruction::Load(RegisterId(2), addr(WORKING_REGION), SIROffset::Static(8), 8), + working_apply(SIROffset::Static(0), 8), + ], + SIRTerminator::Return, + )]); + let before = unit.clone(); + eliminate_partial_working_round_trip(&mut unit); + assert_eq!(unit, before); + } } 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 3be0427242b..36ba67285b4 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1958,3 +1958,59 @@ (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)) + +(case generated_pipeline_with_explicit_generate_branches + ; Separate FF producers may share one array. Removing a task's staging + ; must preserve publication of elements computed by other tasks (10.4.2). + (source "generated_pipeline.sv" #" + module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d, + output logic [7:0] q); + if (N>0) begin : pipe + logic [7:0] r[3:N+2]; + for(genvar n=0;n0) begin : pipe + logic [7:0] r[N+2:3]; + for(genvar n=0;n cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) + (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 28811acbea5..b452f9474b6 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -821,11 +821,24 @@ pub(crate) struct NativeCodegenTrace { pub state_layout: String, } +/// Optimization context of a merged native function. Diagnostic labels do +/// not describe whether pending values can be produced outside this function. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum NativeMergeKind { + /// A complete sequential group of execution units. + Complete, + /// Combinational settling followed by an FF event in the same function. + FusedCombAndFf, + /// One task of a partitioned kernel; other tasks may define pending state. + Partial, +} + fn prepare_merged_sir( units: &[&crate::ir::ExecutionUnit], layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, diagnostics: &crate::optimizer::SirDiagnostics, cancel: Option<&CompileCancel>, @@ -900,7 +913,7 @@ fn prepare_merged_sir( } } report_phase("comb_state_dse"); - if label == "eval_comb_apply_ff" + if merge_kind == NativeMergeKind::FusedCombAndFf && crate::optimizer::sir::promote_fused_comb_static_slots(&mut sir_eu).map_err( |source| { codegen_err(CodegenError::Optimization { @@ -914,10 +927,17 @@ fn prepare_merged_sir( verify(&sir_eu, "after final fused comb StateSSA promotion")?; } report_phase("comb_state_ssa"); - crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_working_round_trip( - &mut sir_eu, - &boundaries, - ); + match merge_kind { + NativeMergeKind::Partial => { + crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_partial_working_round_trip(&mut sir_eu); + } + NativeMergeKind::Complete | NativeMergeKind::FusedCombAndFf => { + crate::optimizer::sir::pass_eliminate_working_round_trip::eliminate_working_round_trip( + &mut sir_eu, + &boundaries, + ); + } + } verify(&sir_eu, "after x86 direct working rewrite")?; if cancelled(cancel) { return Err(cancelled_error()); @@ -937,7 +957,7 @@ fn prepare_merged_sir( &mut sir_eu, layout, four_state, - label == "eval_comb_apply_ff", + merge_kind == NativeMergeKind::FusedCombAndFf, diagnostics, || cancelled(cancel), ) @@ -972,6 +992,7 @@ fn compile_units( layout, four_state, label, + NativeMergeKind::Complete, None, x86_options, capture_trace, @@ -985,6 +1006,7 @@ pub(super) fn compile_unit_refs( layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, x86_options: &crate::backend::X86BackendOptions, capture_trace: bool, @@ -996,6 +1018,7 @@ pub(super) fn compile_unit_refs( layout, four_state, label, + merge_kind, first_ff_unit, x86_options, capture_trace, @@ -1014,6 +1037,7 @@ pub(super) fn compile_unit_refs_inspected( layout: &MemoryLayout, four_state: bool, label: &str, + merge_kind: NativeMergeKind, first_ff_unit: Option, x86_options: &crate::backend::X86BackendOptions, capture_trace: bool, @@ -1103,6 +1127,7 @@ pub(super) fn compile_unit_refs_inspected( layout, four_state, label, + merge_kind, first_ff_unit, diagnostics, cancel, @@ -1288,6 +1313,7 @@ pub(super) fn native_function_at( struct NativeCompileTask<'a> { units: Vec<&'a crate::ir::ExecutionUnit>, label: &'static str, + merge_kind: NativeMergeKind, first_ff_unit: Option, bindings: Vec, } @@ -1343,7 +1369,9 @@ fn collect_comb_apply_compile_tasks<'a>( }; let binding = format!("{LABEL} trigger={}", sir.get_path(addr)); let index = if let Some(index) = tasks.iter().position(|task| { - task.label == LABEL && task.first_ff_unit == first_ff_unit && task.units == unit_refs + task.merge_kind == NativeMergeKind::FusedCombAndFf + && task.first_ff_unit == first_ff_unit + && task.units == unit_refs }) { tasks[index].bindings.push(binding); index @@ -1352,6 +1380,7 @@ fn collect_comb_apply_compile_tasks<'a>( tasks.push(NativeCompileTask { units: unit_refs, label: LABEL, + merge_kind: NativeMergeKind::FusedCombAndFf, first_ff_unit, bindings: vec![binding], }); @@ -1382,6 +1411,7 @@ fn collect_ff_compile_tasks_from<'a>( tasks.push(NativeCompileTask { units: unit_refs, label, + merge_kind: NativeMergeKind::Complete, first_ff_unit: None, bindings: vec![binding], }); @@ -2037,6 +2067,7 @@ fn compile_program( layout, options.four_state, task.label, + task.merge_kind, task.first_ff_unit, &options.x86_options, capture_trace, @@ -2087,6 +2118,7 @@ fn compile_program( layout, four_state, task.label, + task.merge_kind, task.first_ff_unit, x86_options, capture_trace, @@ -2146,6 +2178,7 @@ fn compile_program( layout, options.four_state, &format!("eval_comb_unit[{index}]"), + NativeMergeKind::Complete, None, &options.x86_options, false, @@ -2168,6 +2201,7 @@ fn compile_program( layout, options.four_state, &format!("process[{index}]"), + NativeMergeKind::Complete, None, &options.x86_options, false, diff --git a/crates/celox/src/backend/native/lanes.rs b/crates/celox/src/backend/native/lanes.rs index f5df76649e0..ac2882c4f48 100644 --- a/crates/celox/src/backend/native/lanes.rs +++ b/crates/celox/src/backend/native/lanes.rs @@ -13,8 +13,8 @@ use celox_sir_opt::parallel::Footprint; use serde::{Deserialize, Serialize}; use super::backend::{ - CompiledNativeFunction, NativeCodeEntry, NativeCodeSymbol, NativeSimFunc, append_native_code, - codegen_message, compile_unit_refs_inspected, native_function_at, + CompiledNativeFunction, NativeCodeEntry, NativeCodeSymbol, NativeMergeKind, NativeSimFunc, + append_native_code, codegen_message, compile_unit_refs_inspected, native_function_at, }; use super::jit_mem; use crate::backend::compile_cancel::CompileCancel; @@ -242,6 +242,7 @@ pub(super) fn compile_lane_kernels( layout, options.four_state, "lane_task", + NativeMergeKind::Partial, None, &lane_options, false, diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index dad4f88d17a..f1816a8b4ab 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -369,3 +369,9 @@ fn continuous_part_selects_partly_outside_drive_the_bits_inside() { assert_eq!(sim.get(q), 0xc1u8.into()); assert_eq!(sim.get(r), 0x5au8.into()); } + +sv_backends! { + fn generated_pipeline_with_explicit_generate_branches(sim) { + @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; + } +} From 1bd8785a16c0edbbc86ab051e51e054af48c2709 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 18:25:46 +0900 Subject: [PATCH 4/4] fix(sir-opt): preserve live operands of shared bit-extract shifts When two bit-extract replacements share a dead shift, the cleanup visits that shift twice and decrements its operand use counts twice. This can delete the shift amount even when another live shift still uses it, producing invalid SSA. Only decrement a dead instruction's operands when it is first inserted into the removal set. Add a regression with two masked uses of one shift and a separate live shift sharing its amount; verify SSA before and after the actual pass. This isolates the concrete bug fix found during formal-verification work. It contains no extraction refactors and does not claim a universal pass proof. Validation: the new regression fails before the fix with SSA.USE_HAS_DEFINITION (r1 is used but never defined). After the fix, celox-sir-opt has 469 passing unit tests (1 ignored) and 1 passing doctest; cargo clippy --locked -p celox-sir-opt --all-targets -- -D warnings and cargo fmt --all -- --check pass. The existing masked_shift_fields_keep_expression_width regression also passes on Wasm, native, Cranelift, native parallel and Cranelift parallel backends (5 tests). Shared cases and external simulator adapters are unchanged. Change-Id: I9e413552cce93def93a0ef57f46d82ac323a8d7f --- .../dataflow/pass_bit_extract_peephole.rs | 69 ++++++++++++++++++- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs b/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs index 96eec63be7a..10ca02176c5 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs @@ -200,15 +200,15 @@ fn optimize_bit_extracts( | SIRInstruction::Load(dst, _, _, _) => *dst, _ => continue, }; - if use_count.get(&def_reg).copied().unwrap_or(0) == 0 { - // Also decrement use counts for operands of this dead instruction + if use_count.get(&def_reg).copied().unwrap_or(0) == 0 && dead_set.insert(dead_idx) { + // Multiple replacements may share this definition. Removing + // it consumes its operands once, not once per replacement. if let SIRInstruction::Binary(_, lhs, _, rhs) = &instructions[dead_idx] { *use_count.entry(*lhs).or_default() = use_count.get(lhs).copied().unwrap_or(0).saturating_sub(1); *use_count.entry(*rhs).or_default() = use_count.get(rhs).copied().unwrap_or(0).saturating_sub(1); } - dead_set.insert(dead_idx); } } } @@ -399,6 +399,69 @@ mod tests { } } + #[test] + fn preserves_ssa_when_replacements_share_a_shift() { + let addr = test_addr(); + let other = RegionedAbsoluteAddr { + instance_id: InstanceId(1), + ..addr + }; + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks: [( + BlockId(0), + BasicBlock { + id: BlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), 8), + SIRInstruction::Load(RegisterId(8), other, SIROffset::Static(0), 8), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(2u64)), + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Shr, + RegisterId(1), + ), + SIRInstruction::Imm(RegisterId(3), SIRValue::new(3u64)), + SIRInstruction::Binary( + RegisterId(4), + RegisterId(2), + BinaryOp::And, + RegisterId(3), + ), + SIRInstruction::Imm(RegisterId(5), SIRValue::new(15u64)), + SIRInstruction::Binary( + RegisterId(6), + RegisterId(2), + BinaryOp::And, + RegisterId(5), + ), + SIRInstruction::Binary( + RegisterId(7), + RegisterId(8), + BinaryOp::Shr, + RegisterId(1), + ), + SIRInstruction::RuntimeEvent { + site_id: 0, + args: vec![RegisterId(4), RegisterId(6), RegisterId(7)], + }, + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: (0..9) + .map(|id| (RegisterId(id), RegisterType::Logic { width: 8 })) + .collect(), + }; + unit.verify_result().unwrap(); + BitExtractPeepholePass.run(&mut unit, &PassOptions::default()); + unit.verify_result().unwrap(); + } + #[test] fn keeps_shift_result_used_by_runtime_event() { let addr = test_addr();