From dd474aa3ec0e20228a2fbf29c638e50937044c9e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:09:30 +0000 Subject: [PATCH 1/7] chore(deps): update rust toolchain to c7e9d51 --- flake.lock | 8 ++++---- flake.nix | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/flake.lock b/flake.lock index 11c01378c72..e08dfdd66da 100644 --- a/flake.lock +++ b/flake.lock @@ -51,17 +51,17 @@ ] }, "locked": { - "lastModified": 1793000331, - "narHash": "sha256-6sLQgHX/V/yF8VrhmsJroujeRua1GY3nDTEpnY7tHF4=", + "lastModified": 1793086596, + "narHash": "sha256-ObKS44vw4IIVpQ69YJzUGjZ0IwnpWoUlwjJSY7gefdo=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "0d0575988e4bb9ebc4cf1afb1cec1ceac0b5914e", + "rev": "c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "0d0575988e4bb9ebc4cf1afb1cec1ceac0b5914e", + "rev": "c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d", "type": "github" } }, diff --git a/flake.nix b/flake.nix index 0106c1de973..f33c6d7ea7a 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/0d0575988e4bb9ebc4cf1afb1cec1ceac0b5914e"; + url = "github:oxalica/rust-overlay/c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d"; inputs.nixpkgs.follows = "nixpkgs"; }; # The xezim reference simulator for the shared test suite, pinned by From a39a4eccf589d537d8972fb406718e4a9a1a1b13 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 15:18:36 +0900 Subject: [PATCH 2/7] feat(sv): support per-call inline class constraints Lower randomize() with blocks into call-specific solver methods. Inline predicates add to named constraints without persisting across calls, retain static receiver property lookup under dynamic dispatch, and preserve selection, check-only calls, hooks and UNSAT value preservation. Package methods and separate generated instances get distinct methods. This initial subset accepts unqualified receiver properties; caller-local captures, local::, qualified this/super and restricted with-name lists remain unsupported. Bound nested inline parsing before recursion. IEEE 1800-2023 18.6.3 and 18.7. Validation: 133 syntax tests, 840 analyzer tests (three existing ignored), 356 class backend tests and 20 final inline backend tests pass; affected all-target Clippy and formatting pass. Verilator passes the basic and package/instance cases. Retain observed Icarus compile limitations and standalone Verilator evidence for failed-call post hooks and hidden-property static scope, without weakening assertions. Retain bound inline requests in exported scope symbols, deduplicate them across imports and regenerate helper dispatch in the consumer scope. A package method called through a base handle now reaches module-defined subclasses, including their constraints and hooks. The package/multiple-instance regression covers this import boundary. Validation: 60 constrained backend tests, 841 analyzer tests (three existing ignored), Verilator and analyzer all-target Clippy pass; Icarus retains its known inline-syntax exclusion. Change-Id: I6ae718696957044ae716f778092c6106488086d6 --- crates/celox-sv-analyzer/src/ast.rs | 9 ++ crates/celox-sv-analyzer/src/ast/classes.rs | 2 +- .../src/ast/classes/constraints.rs | 37 ++++- .../src/ast/expression_binding/direct.rs | 13 ++ .../src/ast/expression_binding/objects.rs | 52 ++++++ .../src/ast/parameters/skipped.rs | 11 +- .../celox-sv-analyzer/src/ast/procedural.rs | 10 +- .../src/ast/procedural/randomization.rs | 113 +++++++++++-- crates/celox-sv-analyzer/src/ast/scope.rs | 11 ++ crates/celox-sv-analyzer/src/tests.rs | 16 +- crates/celox-sv-syntax/src/nodes.rs | 5 + crates/celox-sv-syntax/src/parser.rs | 2 + .../celox-sv-syntax/src/parser/expressions.rs | 39 +++++ .../celox-sv-syntax/src/parser/procedures.rs | 4 +- crates/celox-sv-syntax/src/parser/tests.rs | 23 +++ .../celox-test-suite/src/sv/cases/class.vtest | 119 ++++++++++++++ .../repros/sv_inline_constraint_scope.sv | 20 +++ .../repros/sv_inline_constraints.json | 55 +++++++ .../verification/sv/icarus/class.json | 153 +++++++++++++++--- .../verification/sv/limitations.json | 34 +++- .../verification/sv/verilator/class.json | 50 +++++- .../tests/frontends/systemverilog/class.rs | 13 ++ docs/guide/systemverilog-reference.md | 16 +- 23 files changed, 759 insertions(+), 48 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv create mode 100644 crates/celox-test-suite/verification/repros/sv_inline_constraints.json diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 9f87f573325..2f10142e623 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -25,6 +25,7 @@ pub(super) struct AnalysisState { interfaces: interface_ast::State, dimensions: dimensions::State, root_subroutines: std::cell::Cell, + inline_randomizations: RefCell>, next_call_site: std::rc::Rc>, timescales: timescales::State, diagnostics: RefCell>, @@ -1308,6 +1309,13 @@ impl Module { )?); (subroutines, comb_processes, ff_processes, initial_processes) }; + let (inline_subroutines, inline_randomizations) = + procedural::randomization::inline_subroutines( + syntax_tree, + &mut body_state, + &packed_dimensions, + )?; + subroutines.extend(inline_subroutines); // Static locals of the processes that keep their value are variables // of the module, initialized once with the declaration initializers. let statics: HashMap = body_state.statics.drain(..).collect(); @@ -1410,6 +1418,7 @@ impl Module { // A package keeps its symbols for the scopes that use it. let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols { classes: classes::scope_classes(syntax_tree, &const_env), + inline_randomizations, declarations_only: imported.declarations_only, type_parameter_bindings: HashMap::default(), pattern_parameter_bindings: HashMap::default(), diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index a3924547f9b..44f89baec5f 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -12,7 +12,7 @@ use std::rc::Rc; use super::*; use crate::system_functions::{HandleProperty, ObjectField, ObjectOp}; -mod constraints; +pub(super) mod constraints; pub(super) mod specializations; /// Bit width of a handle, see `celox_design::HANDLE_WIDTH`. diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs index d3d7d3296de..bd5ecf18c7a 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -110,7 +110,7 @@ fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr { } } -pub(super) fn bind( +pub(in crate::ast) fn bind( id: ExprId, tree: &AnalysisContext<'_>, properties: &[Property], @@ -324,3 +324,38 @@ impl Class { }) } } + +/// A generated call-specific method. Its immutable predicates never change the +/// object's persistent constraints, including during nested hook calls. +#[derive(Clone)] +pub(in crate::ast) struct Inline { + pub key: usize, + pub class: std::rc::Rc, + pub constraints: Vec, + pub dimensions: PackedDimensions, +} + +impl Inline { + pub fn name(&self, class: &str) -> String { + format!("{class}::$inline_randomize@{}", self.key) + } +} + +/// Bound inline predicates survive package imports without retaining syntax or +/// the declaring scope's dimensions. Consumer scopes can add dispatch targets. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::ast) struct InlineRequest { + pub key: usize, + pub class: Class, + pub constraints: Vec, +} + +impl Inline { + pub fn request(&self) -> InlineRequest { + InlineRequest { + key: self.key, + class: (*self.class).clone(), + constraints: self.constraints.clone(), + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index bc080e59848..736a4859252 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -903,6 +903,19 @@ pub(in crate::ast) fn bind_value( ExprKind::Concatenation(_) => { return Err(unsupported("empty unpacked array concatenation")); } + ExprKind::RandomizeWith { + expression, + constraints, + } => { + values.push(objects::randomize_with( + tree, + *expression, + constraints.as_deref(), + native, + dimensions, + )?); + continue; + } ExprKind::ArrayMethodWith { .. } => { return Err(unsupported("array method with expression")); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 86aae92e3b1..b438437f392 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -933,3 +933,55 @@ fn check_random_access( property.protected, ) } + +pub(super) fn randomize_with( + tree: &AnalysisContext<'_>, + expression: ExprId, + constraints: Option<&[ExprId]>, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted { + let (callee, arguments) = match &native.expression(ungroup(expression, native)).kind { + ExprKind::Call { + expression, + arguments, + } => (*expression, arguments.as_slice()), + _ => (expression, &[][..]), + }; + let (method_name, _, receiver) = method(tree, callee, native, dimensions)? + .filter(|(name, _, _)| name.ends_with("::randomize")) + .ok_or_else(|| unsupported("inline constraints require class randomize"))?; + let owner = method_name.strip_suffix("::randomize").unwrap(); + let class = class(tree, dimensions, owner)?; + // Inline constraints need the solver even on otherwise unconstrained classes. + class.constraint_program()?; + let constraints = constraints + .ok_or_else(|| unsupported("inline constraint form"))? + .iter() + .map(|&id| { + classes::constraints::bind(id, tree, &class.properties, &dimensions.const_env) + .map_err(|reason| unsupported(format!("inline constraints: {reason}"))) + }) + .collect::>>()?; + let selection = random_selection(tree, dimensions, &method_name, arguments, native)?; + let handle = match receiver { + Receiver::Handle(id) => bind_value(id, native, tree, dimensions, None)?, + Receiver::This => this(), + Receiver::Static => return Err(unsupported("inline randomize object receiver")), + }; + let key = tree.state.next_call_site.get(); + tree.state.next_call_site.set(key + 1); + let inline = classes::constraints::Inline { + key, + class, + constraints, + dimensions: dimensions.clone(), + }; + let name = inline.name(owner); + tree.state.inline_randomizations.borrow_mut().push(inline); + Ok(Expr::Call { + callee: Callee::Subroutine(name), + args: vec![Some(handle), Some(selection)], + arg_order: Vec::new(), + }) +} diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 1853cdc01ad..bfb477f6249 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -373,7 +373,7 @@ pub(in crate::ast) fn validate( ExprKind::Copy(_) => { return Err(unsupported("shallow copy in skipped operand")); } - ExprKind::ArrayMethodWith { .. } => { + ExprKind::ArrayMethodWith { .. } | ExprKind::RandomizeWith { .. } => { return Err(unsupported("array method with expression")); } ExprKind::Parameterized { .. } => { @@ -587,7 +587,7 @@ pub(in crate::ast) fn literal_widths( visited.push(id); let add = |jobs: &mut Vec<_>, id| jobs.push((id, evaluated, shape)); match &native.expression(id).kind { - ExprKind::ArrayMethodWith { .. } => { + ExprKind::ArrayMethodWith { .. } | ExprKind::RandomizeWith { .. } => { return Err(unsupported("array method with expression")); } ExprKind::Literal(text) if evaluated => { @@ -1164,6 +1164,13 @@ pub(in crate::ast) fn children( then_expression, else_expression, } => children.extend([*condition, *then_expression, *else_expression]), + ExprKind::RandomizeWith { + expression, + constraints, + } => { + children.push(*expression); + children.extend(constraints.iter().flatten()); + } ExprKind::ArrayMethodWith { expression, predicate, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 37b5b938a0d..7dd29c43dee 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -12,7 +12,7 @@ mod control; mod final_procedures; mod foreach; use foreach::ForeachLoop; -mod randomization; +pub(super) mod randomization; pub(super) mod timed_tasks; mod timing; use crate::procedural::{ @@ -1254,6 +1254,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); } + if matches!( + native.expression(query_root).kind, + celox_sv_syntax::ExprKind::RandomizeWith { .. } + ) { + let mut call = self.native_value(query_root)?; + self.rename_expr(&mut call); + return Ok(vec![Stmt::Eval(call)]); + } if let Some(call) = self.method_call_statement(query_root)? { return Ok(vec![call]); } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 06b9c0a3c8d..20c1bdd9e52 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -13,19 +13,45 @@ pub(super) fn lower( state: &mut BodyState<'_>, item: &generate::Item, ) -> Converted> { + lower_methods(class, tree, dimensions, state, Some(item), None) +} + +fn lower_methods( + class: &classes::Class, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + state: &mut BodyState<'_>, + item: Option<&generate::Item>, + inline: Option<&classes::constraints::Inline>, +) -> Converted> { + let env = item.map(|item| &*item.env).unwrap_or(&dimensions.const_env); + let aliases = item + .map(|item| item.type_aliases(&dimensions.type_aliases)) + .unwrap_or_else(|| std::borrow::Cow::Borrowed(&dimensions.type_aliases)); + let method_name = |class: &str, method: &str| { + if let Some(inline) = inline { + inline.name(class) + } else { + let name = classes::Class::subroutine_name(class, method); + item.map(|item| item.name(&name)).unwrap_or(name) + } + }; let handle = classes::handle_type(tree, &class.name) .ok_or_else(|| unsupported("class randomization receiver"))?; let convert_type = |ty| { crate::ir::Type::from_ast( ty, &const_functions::Environment { - constants: &*item.env, + constants: env, functions: &tree.state.const_functions, }, ) }; let mut result = Vec::new(); for method in ["randomize", "srandom", "rand_mode"] { + if inline.is_some() && method != "randomize" { + continue; + } if method == "randomize" && class.check_randomize().is_err() { continue; } @@ -133,12 +159,16 @@ pub(super) fn lower( else_body: Vec::new(), }); body.extend(hook("pre_randomize")); - if class.has_constraints { + if class.has_constraints || inline.is_some() { + let mut program = class.constraint_program()?; + if let Some(inline) = inline { + program.constraints.extend(inline.constraints.clone()); + } let success = builder.declare("$constraint_success", int_type()); body.push(Stmt::Assign { lhs: LValue::Ident(success.clone()), rhs: classes::object_call( - ObjectOp::Randomize(class.constraint_program()?), + ObjectOp::Randomize(program), vec![ Expr::Ident(this.clone()), Expr::Binary { @@ -216,19 +246,19 @@ pub(super) fn lower( // randomize is virtual, while its pre/post hooks are not (18.6.2). // Object-wide rand_mode also covers the dynamic object's members. let mut items = Vec::new(); - let aliases = item.type_aliases(&dimensions.type_aliases); for name in classes::visible_classes(tree) { if name == class.name { continue; } - let Ok(derived) = classes::class(tree, &name, &item.env, &aliases) else { + let Ok(derived) = classes::class(tree, &name, env, &aliases) else { continue; }; if derived.is_abstract || derived.is_interface { continue; } - if (method == "randomize" && derived.check_randomize().is_err()) - || !derived.derives_from(tree, &class.name, &item.env, &aliases) + if (inline.is_some() && derived.constraint_program().is_err()) + || (method == "randomize" && derived.check_randomize().is_err()) + || !derived.derives_from(tree, &class.name, env, &aliases) { continue; } @@ -236,7 +266,7 @@ pub(super) fn lower( Some(Expr::Ident(this.clone())), Some(Expr::Ident(argument.clone())), ]; - let name = classes::Class::subroutine_name(&name, method); + let name = method_name(&name, method); let call = if method == "randomize" { vec![Stmt::Return(Some(Expr::Call { callee: Callee::Subroutine(name), @@ -274,11 +304,13 @@ pub(super) fn lower( }, ); } - for stmt in &mut body { - qualify_stmt(item, stmt); + if let Some(item) = item { + for stmt in &mut body { + qualify_stmt(item, stmt); + } } result.push(Subroutine { - name: item.name(&classes::Class::subroutine_name(&class.name, method)), + name: method_name(&class.name, method), is_task: false, automatic_locals: builder.state.locals[first_local..] .iter() @@ -382,3 +414,62 @@ fn random_property( ))); body } + +pub(in crate::ast) fn inline_subroutines( + tree: &AnalysisContext<'_>, + state: &mut BodyState<'_>, + dimensions: &PackedDimensions, +) -> Converted<(Vec, Vec)> { + let mut requests = std::mem::take(&mut *tree.state.inline_randomizations.borrow_mut()); + for request in &scope::imported(&tree.state).inline_randomizations { + if !requests.iter().any(|known| known.key == request.key) { + requests.push(classes::constraints::Inline { + key: request.key, + class: std::rc::Rc::new(request.class.clone()), + constraints: request.constraints.clone(), + dimensions: dimensions.clone(), + }); + } + } + let exported = requests + .iter() + .map(classes::constraints::Inline::request) + .collect(); + let mut result = Vec::new(); + for inline in requests { + let dims = &inline.dimensions; + let mut classes = vec![inline.class.clone()]; + for name in classes::visible_classes(tree) { + if name == inline.class.name { + continue; + } + let Ok(class) = classes::class(tree, &name, &dims.const_env, &dims.type_aliases) else { + continue; + }; + if !class.is_abstract + && !class.is_interface + && class.check_randomize().is_ok() + && class.constraint_program().is_ok() + && class.derives_from( + tree, + &inline.class.name, + &dims.const_env, + &dims.type_aliases, + ) + { + classes.push(class); + } + } + for class in classes { + result.extend(lower_methods( + &class, + tree, + dims, + state, + None, + Some(&inline), + )?); + } + } + Ok((result, exported)) +} diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 9d68fa5589f..acda2b3deef 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -65,6 +65,7 @@ pub(super) struct ScopeSymbols { /// (IEEE 1800-2023 26.3): a scope that uses them may be analyzed from /// another source, without their declarations. pub classes: Vec, + pub inline_randomizations: Vec, } #[derive(Default)] @@ -184,6 +185,15 @@ pub(super) fn split_marker(key: &str) -> Option<(&str, &str)> { impl ScopeSymbols { /// Add the symbols of `other` that this scope does not already have. pub fn extend(&mut self, other: &ScopeSymbols) { + for request in &other.inline_randomizations { + if !self + .inline_randomizations + .iter() + .any(|known| known.key == request.key) + { + self.inline_randomizations.push(request.clone()); + } + } for class in &other.classes { if !self.classes.iter().any(|known| known.name == class.name) { self.classes.push(class.clone()); @@ -437,6 +447,7 @@ impl ScopeSymbols { ScopeSymbols { // Classes have their qualified names already. classes: self.classes.clone(), + inline_randomizations: self.inline_randomizations.clone(), declarations_only: self.declarations_only, interface_instances: self.interface_instances.clone(), interface_types: self.interface_types.clone(), diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 365d42c7165..985f96f74f9 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6636,7 +6636,7 @@ fn class_randomize_rejects_unsupported_semantics() { ), ( "rand int x;", - "c.randomize() with { x == 1; }", + "c.randomize() with { outside == 1; }", "unsupported", ), ("rand int x;", "c.randomize(x + 1)", "arguments"), @@ -7360,3 +7360,17 @@ fn class_randomize_bounds_nested_membership_expansion() { } } } + +#[test] +fn class_inline_randomize_retains_call_specific_constraints() { + let source = r#"module Top; + class C; rand int x; constraint c { x < 10; } endclass + C obj; + initial begin + obj = new; + if (!(obj.randomize() with { x == 2; })) $fatal; + obj.randomize() with { x == 3; }; + end + endmodule"#; + analyze_source(source, Path::new("inline_randomize.sv")).unwrap(); +} diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index 219e8a8fea3..753ff1ff74c 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -94,6 +94,11 @@ pub enum ExprKind { expression: ExprId, predicate: ExprId, }, + /// Per-call class constraints (IEEE 1800-2023 18.7). + RandomizeWith { + expression: ExprId, + constraints: Option>, + }, Parameterized { expression: ExprId, arguments: Vec, diff --git a/crates/celox-sv-syntax/src/parser.rs b/crates/celox-sv-syntax/src/parser.rs index 0d52b135058..a25d494f4bc 100644 --- a/crates/celox-sv-syntax/src/parser.rs +++ b/crates/celox-sv-syntax/src/parser.rs @@ -109,6 +109,7 @@ impl Declarations { indices, at: 0, next_parameter_id: 0, + inline_constraint_depth: 0, keyword_versions: Vec::new(), source_items: Vec::new(), expressions: Vec::new(), @@ -325,6 +326,7 @@ struct Parser<'a> { indices: Vec, at: usize, next_parameter_id: usize, + inline_constraint_depth: usize, keyword_versions: Vec, source_items: Vec, expressions: Vec, diff --git a/crates/celox-sv-syntax/src/parser/expressions.rs b/crates/celox-sv-syntax/src/parser/expressions.rs index 1d1ed656c0c..63fe34a8861 100644 --- a/crates/celox-sv-syntax/src/parser/expressions.rs +++ b/crates/celox-sv-syntax/src/parser/expressions.rs @@ -372,6 +372,13 @@ impl Parser<'_> { pending.extend(expressions); } ExprKind::Tagged { value, .. } => pending.extend(value), + ExprKind::RandomizeWith { + expression, + constraints, + } => { + pending.push(*expression); + pending.extend(constraints.iter().flatten()); + } ExprKind::ArrayMethodWith { expression, predicate, @@ -781,6 +788,38 @@ impl Parser<'_> { }); jobs.push(Job::Arguments); } + "with" if self.nth(1) == "{" => { + let callee = match &self.expressions[left.0].kind { + ExprKind::Call { expression, .. } => *expression, + _ => left, + }; + let is_randomize = match &self.expressions[callee.0].kind { + ExprKind::Name(name) | ExprKind::Member { name, .. } => { + name.value() == "randomize" + } + _ => false, + }; + if !is_randomize { + return Err(self.error("constraint with block requires randomize")); + } + self.at += 1; + if self.inline_constraint_depth != 0 { + return Err(self.unsupported("inline constraint nesting limit")); + } + self.inline_constraint_depth += 1; + let constraints = self.constraint_block(); + self.inline_constraint_depth -= 1; + let constraints = constraints?; + self.tail( + &mut jobs, + start, + minimum, + ExprKind::RandomizeWith { + expression: left, + constraints, + }, + )?; + } "with" if self.nth(1) == "(" => { let method = match &self.expressions[left.0].kind { ExprKind::Call { diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index 1fafa32b459..dd783708210 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -98,7 +98,7 @@ impl Parser<'_> { }; match &self.expressions[id.0].kind { ExprKind::Call { expression, .. } => callable(*expression), - ExprKind::ArrayMethodWith { .. } => true, + ExprKind::ArrayMethodWith { .. } | ExprKind::RandomizeWith { .. } => true, _ => callable(id), } } @@ -821,7 +821,7 @@ impl Parser<'_> { } // A parenthesis-free array method followed by `with` is a call, // not a declaration whose variable happens to be named `with`. - if word(cursor) == "with" && word(cursor + 1) == "(" { + if word(cursor) == "with" && matches!(word(cursor + 1), "(" | "{") { return None; } self.indices diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index efdf22c6581..2d264fea687 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -3060,3 +3060,26 @@ fn constraints_retain_simple_expressions_and_mark_other_forms() { assert!(blocks[2].expressions.is_none()); assert!(blocks[3].expressions.as_ref().unwrap().is_empty()); } + +#[test] +fn inline_constraints_retain_ownership_and_bound_nested_calls() { + let syntax = + parse("module M; initial obj.randomize() with { if (x) y == 1; else y == 2; }; endmodule"); + assert!( + syntax + .expression_nodes() + .any(|(_, node)| matches!(&node.kind, + ExprKind::RandomizeWith { constraints: Some(values), .. } if values.len() == 2)) + ); + let source = format!( + "module M; initial {}1;{} endmodule", + "obj.randomize() with { ".repeat(100), + " };".repeat(100) + ); + assert!( + Declarations::parse(&source, Path::new("nested_inline.sv")) + .unwrap_err() + .to_string() + .contains("inline constraint nesting limit") + ); +} diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index c153c186233..b4b2156e1ab 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -2128,3 +2128,122 @@ module Top(output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline + (source "inline_constraints.sv" #" +module Top(output bit done); + class Packet; + rand int x, y; + int limit, pre_count, post_count; + constraint c { x < 10; } + function void pre_randomize(); limit=3; pre_count++; endfunction + function void post_randomize(); post_count++; endfunction + endclass + Packet p; + initial begin + p = new; + if (!(p.randomize() with { x inside {[1:limit]}; y == x + 1; })) + $fatal(1, "inline success"); + if (p.x < 1 || p.x > 3 || p.y != p.x + 1) $fatal(1, "inline values"); + if (p.randomize() with { x == 12; }) $fatal(1, "lost class constraint"); + if (p.pre_count != 2 || p.post_count != 1) $fatal(1, "inline hooks"); + if (!(p.randomize() with { x == 7; if (x == 7) y == 8; })) $fatal(1, "inline leaked"); + if (!p.randomize(null)) $fatal(1, "ordinary check"); + if (p.randomize(null) with { x == 2; }) $fatal(1, "inline check"); + if (p.x != 7 || p.y != 8) $fatal(1, "check-only changed fields"); + if (!(p.randomize(x) with { x == y; })) $fatal(1, "inline selection"); + if (p.x != 8 || p.y != 8) $fatal(1, "unselected field changed"); + p.randomize() with { x == 4; y == 5; }; + if (p.x != 4 || p.y != 5) $fatal(1, "discarded call"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_inheritance + (source "inline_inheritance.sv" #" +module Top(output bit done); + class Base; + rand int x; + endclass + class Derived extends Base; + rand int x; + int hook; + constraint c { x == 9; } + function void pre_randomize(); hook++; endfunction + endclass + Base b; + Derived d; + initial begin + d = new; b = d; + if (!(b.randomize() with { x == 2; })) $fatal(1, "base inline scope"); + if (b.x != 2 || d.x != 9 || d.hook != 1) $fatal(1, "static scope or dynamic hooks"); + if (!(b.randomize() with { x == 5; })) $fatal(1, "second inline"); + if (b.x != 5 || d.x != 9 || d.hook != 2) $fatal(1, "inline persistence"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_basic + (source "inline_basic.sv" #" +module Top(output bit done); + class Packet; + rand int x; + constraint c { x inside {1, 2}; } + function int pick(); return randomize() with { x == 1; }; endfunction + endclass + Packet p; + initial begin + p = new; + if (!(p.randomize() with { x == 2; })) $fatal(1, "inline member"); + if (p.x != 2) $fatal(1, "inline value"); + if (!p.pick() || p.x != 1) $fatal(1, "unqualified inline call"); + if (p.randomize() with { x == 3; }) $fatal(1, "named constraint lost"); + if (p.x != 1) $fatal(1, "failed inline changed member"); + if (!(p.randomize() with { x == 2; })) $fatal(1, "inline not per-call"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_package_instances + (source "inline_package.sv" #" +package pkg; + class Packet; + rand int x; + function int pick(); return randomize() with { x == 2; }; endfunction + endclass +endpackage +module Child(output bit done); + class Derived extends pkg::Packet; + rand int y; + int calls; + constraint c { y == 7; } + function void pre_randomize(); calls++; endfunction + endclass + pkg::Packet p; + Derived d; + if (1) begin : g + initial begin + p = new; + if (!p.pick() || p.x != 2) $fatal(1, "package method inline"); + if (!(p.randomize() with { x == 3; }) || p.x != 3) $fatal(1, "instance inline"); + d = new; + p = d; + if (!p.pick() || p.x != 2 || d.y != 7 || d.calls != 1) + $fatal(1, "imported inline subclass dispatch"); + done = 1; + end + end +endmodule +module Top(output bit done); + wire a, b; + Child c0(a), c1(b); + assign done = a & b; +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv b/crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv new file mode 100644 index 00000000000..262cbadef21 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv @@ -0,0 +1,20 @@ +// IEEE 1800-2023 18.7: inline names start at the handle's declared class. +module top; + class Base; + rand int x; + endclass + class Derived extends Base; + rand int x; + constraint c { x == 9; } + endclass + Base b; + Derived d; + initial begin + d = new; + b = d; + if (!(b.randomize() with { x == 2; })) $fatal(1, "static inline scope"); + if (b.x != 2 || d.x != 9) $fatal(1, "hidden property binding"); + $display("PASS"); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_inline_constraints.json b/crates/celox-test-suite/verification/repros/sv_inline_constraints.json new file mode 100644 index 00000000000..de333c998b2 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_inline_constraints.json @@ -0,0 +1,55 @@ +{ + "specification": "IEEE 1800-2023 18.6.3, 18.7", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052", + "case": "class::constrained_randomize_inline", + "status": "runtime_error", + "log": "%Warning-UNSATCONSTR: /sv-verilator/class/constrained_randomize_inline/source_0.sv:6: Unsatisfied constraint: 'constraint c { x < 10; }'\n%Warning-UNSATCONSTR: /sv-verilator/class/constrained_randomize_inline/source_0.sv:16: Unsatisfied constraint: 'if (p.randomize() with { x == 12; }) $fatal(1, \"lost class constraint\");'\n[0] %Fatal: source_0.sv:17: Assertion failed in TOP.celox_suite_tb.dut: inline hooks\n%Error: /sv-verilator/class/constrained_randomize_inline/source_0.sv:17: Verilog $stop\nAborting...\n" + }, + { + "tool": "verilator", + "version": "Verilator 5.052", + "case": "class::constrained_randomize_inline_inheritance", + "status": "runtime_error", + "log": "%Warning-UNSATCONSTR: /sv-verilator/class/constrained_randomize_inline_inheritance/source_0.sv:9: Unsatisfied constraint: 'constraint c { x == 9; }'\n%Warning-UNSATCONSTR: /sv-verilator/class/constrained_randomize_inline_inheritance/source_0.sv:16: Unsatisfied constraint: 'if (!(b.randomize() with { x == 2; })) $fatal(1, \"base inline scope\");'\n[0] %Fatal: source_0.sv:16: Assertion failed in TOP.celox_suite_tb.dut: base inline scope\n%Error: /sv-verilator/class/constrained_randomize_inline_inheritance/source_0.sv:16: Verilog $stop\nAborting...\n" + }, + { + "tool": "verilator", + "version": "Verilator 5.052", + "source": "sv_inline_constraint_scope.sv", + "command": "verilator --binary --timing -Wno-fatal --top-module top --Mdir sv_inline_constraint_scope.sv; /Vtop", + "status": "runtime_error", + "log": "%Warning-UNSATCONSTR: crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv:8: Unsatisfied constraint: 'constraint c { x == 9; }'\n%Warning-UNSATCONSTR: crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv:15: Unsatisfied constraint: 'if (!(b.randomize() with { x == 2; })) $fatal(1, \"static inline scope\");'\n[0] %Fatal: sv_inline_constraint_scope.sv:15: Assertion failed in top: static inline scope\n%Error: crates/celox-test-suite/verification/repros/sv_inline_constraint_scope.sv:15: Verilog $stop\nAborting...\n" + }, + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline/source_0.sv:6: sorry: Constraint declarations not supported.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:13: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:13: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:14: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:13: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:16: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:16: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:18: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:20: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:20: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:22: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:22: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:22: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:22: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: syntax error\n/sv-icarus/class/constrained_randomize_inline/source_0.sv:24: error: Malformed statement\n" + }, + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline_inheritance", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:9: sorry: Constraint declarations not supported.\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:16: syntax error\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:16: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:16: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:16: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:18: syntax error\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:18: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:18: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inheritance/source_0.sv:18: error: Malformed conditional expression.\n" + }, + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline_basic", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:5: sorry: \"inside\" expressions not supported yet.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:5: sorry: Constraint declarations not supported.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:6: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:6: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:6: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:6: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:13: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:16: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:16: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:18: syntax error\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:18: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:18: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_basic/source_0.sv:18: error: Malformed conditional expression.\n" + }, + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline_package_instances", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:5: syntax error\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:5: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:5: syntax error\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:5: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:14: syntax error\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:14: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:14: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_package_instances/source_0.sv:14: error: Malformed conditional expression.\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 9156cb55242..c0cd8261b6a 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -186,7 +186,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -194,12 +194,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_conditionals", @@ -211,7 +212,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -219,12 +220,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_hooks", @@ -236,7 +238,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -244,12 +246,117 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_basic", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_inheritance", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_package_instances", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_inside", @@ -261,7 +368,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -269,12 +376,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_inside_widths", @@ -286,7 +394,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -294,12 +402,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_nested_guards", @@ -311,7 +420,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -319,12 +428,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_scalar", @@ -336,7 +446,7 @@ }, { "category": "Types", - "detail": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "expectation": "Simulation", "known_issue": { "category": "simulator_compile_limitation", @@ -344,12 +454,13 @@ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", "phase": "compile", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [] }, "name": "class::constrained_randomize_width_and_inheritance", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index ce96bbe13f3..607baebddef 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2601,13 +2601,14 @@ "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Icarus Verilog version 13.0 (devel)", - "reason": "Icarus rejects constraint declarations before elaboration. IEEE 1800-2023 18.5 defines these blocks. Celox retains all assertions; Verilator passes the scalar and width/inheritance cases.", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", "upstream": [], "evidence": [ "verification/repros/sv_scalar_constraints.json", "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", - "verification/repros/sv_conditional_constraints.json" + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json" ], "cases": { "icarus": [ @@ -2617,7 +2618,11 @@ "class::constrained_randomize_inside", "class::constrained_randomize_inside_widths", "class::constrained_randomize_conditionals", - "class::constrained_randomize_nested_guards" + "class::constrained_randomize_nested_guards", + "class::constrained_randomize_inline", + "class::constrained_randomize_inline_inheritance", + "class::constrained_randomize_inline_basic", + "class::constrained_randomize_inline_package_instances" ] } }, @@ -2630,11 +2635,30 @@ "upstream": [], "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inline_constraints.json" + ], + "cases": { + "verilator": [ + "class::constrained_randomize_hooks", + "class::constrained_randomize_inline" + ] + } + }, + { + "id": "sv_verilator_inline_constraint_static_scope", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Through a Base handle containing a Derived object that hides Base.x, Verilator binds inline x == 2 to Derived.x, conflicting with its x == 9 block. IEEE 1800-2023 18.7 starts inline name lookup in the class of the object handle used at the call. Base.x must be 2 and Derived.x must be 9. The standalone source reproduces UNSAT without the suite adapter. Assertions are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_inline_constraint_scope.sv", + "verification/repros/sv_inline_constraints.json" ], "cases": { "verilator": [ - "class::constrained_randomize_hooks" + "class::constrained_randomize_inline_inheritance" ] } } diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index d576761f5c8..cb0538712d6 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -109,7 +109,8 @@ "category": "simulator_disagreement", "evidence": [ "verification/repros/sv_scalar_constraints.json", - "LIMITATIONS.md#systemverilog-suite" + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inline_constraints.json" ], "id": "sv_verilator_post_randomize_unsat", "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", @@ -124,6 +125,53 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_verilator_post_randomize_unsat", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator invokes post_randomize unconditionally after an UNSAT ordinary randomize call. Generated C++ calls the post hook after constraint.next without testing its return. IEEE 1800-2023 18.6.3 requires skipping the post hook on failure. The case keeps its assertion and tests that pre_randomize updates state before solving.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Through a Base handle containing a Derived object that hides Base.x, Verilator binds inline x == 2 to Derived.x, conflicting with its x == 9 block. IEEE 1800-2023 18.7 starts inline name lookup in the class of the object handle used at the call. Base.x must be 2 and Derived.x must be 9. The standalone source reproduces UNSAT without the suite adapter. Assertions are retained.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_inline_constraint_scope.sv", + "verification/repros/sv_inline_constraints.json" + ], + "id": "sv_verilator_inline_constraint_static_scope", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Through a Base handle containing a Derived object that hides Base.x, Verilator binds inline x == 2 to Derived.x, conflicting with its x == 9 block. IEEE 1800-2023 18.7 starts inline name lookup in the class of the object handle used at the call. Base.x must be 2 and Derived.x must be 9. The standalone source reproduces UNSAT without the suite adapter. Assertions are retained.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_inheritance", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 38ae9074281..c622ad2a374 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -942,3 +942,16 @@ sv_backends! { fn constrained_randomize_conditionals(sim) { @case "class::constrained_randomize_conditionals"; } fn constrained_randomize_nested_guards(sim) { @case "class::constrained_randomize_nested_guards"; } } + +sv_backends! { + fn constrained_randomize_inline(sim) { @case "class::constrained_randomize_inline"; } + fn constrained_randomize_inline_inheritance(sim) { @case "class::constrained_randomize_inline_inheritance"; } +} + +sv_backends! { + fn constrained_randomize_inline_basic(sim) { @case "class::constrained_randomize_inline_basic"; } +} + +sv_backends! { + fn constrained_randomize_inline_package_instances(sim) { @case "class::constrained_randomize_inline_package_instances"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 877eb50794b..293906005e3 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -234,10 +234,22 @@ nested blocks. Both sides participate in solving: a required result can constrai the condition. These constructs do not choose a branch before solving. Constrained enums and `randc`, foreach/soft constraints, -`dist`, `solve before`, constraint modes, external/static blocks, typed parameters -in constraints, and inline `with` remain unsupported. Larger unconstrained `randc` +`dist`, `solve before`, constraint modes, external/static blocks and typed +parameters in constraints remain unsupported. Larger unconstrained `randc` domains, static random properties and random array/object/string properties also remain unsupported. Unsupported dynamic subclasses are rejected before draws. +`object.randomize() with { ... }` adds per-call scalar constraints to the +object's declared constraints. It supports the operators, membership and +conditional constraints above, explicit member selection and `randomize(null)`. +Unqualified property names resolve against the handle's declared class; derived +object constraints and hooks still apply. A failed solve preserves properties, +skips the post-hook and restores temporary selection modes. Inline constraints +do not remain installed for later calls. + +This initial inline subset accepts unqualified instance-property references. +Caller-local captures, `local::`, `this` / `super` qualified references, restricted +`with (names)` lookup and scope `std::randomize(...) with` remain unsupported. + A call through `null` is a runtime error. ### Time literal delays {#time-literal-delays} From dfac2b8f0a10122b24a5d3677d7c165d1d9f23f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 16:40:18 +0900 Subject: [PATCH 3/7] feat(heap): accept per-call scalar constraint inputs Allow constraint expressions to read width-checked, immutable input values supplied for one solve. Inputs are excluded from the solver projection and object state. Missing inputs fail before RNG draws, and check-only calls preserve object values and the random stream. Add a heap operation that consumes a binary input buffer, preserving zero bytes and releasing the buffer even if program decoding or solving fails. Existing ordinary randomization remains compatible and passes an empty input list. Validation: all 26 celox-heap tests and all-target Clippy pass. Regression covers successive input values, check-only UNSAT, missing input diagnostics, binary transport and malformed buffer lengths. Change-Id: Ib35948f9141eaa42af30ad9db9c9ad68a5e9b560 --- crates/celox-heap/src/ops.rs | 48 ++++++++++--- crates/celox-heap/src/randomization.rs | 99 +++++++++++++++++++++++--- 2 files changed, 131 insertions(+), 16 deletions(-) diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 8df747bd277..b90fac080f1 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -85,6 +85,9 @@ pub const OBJECT_RANDOM_CYCLIC: u64 = 62; pub const OBJECT_COPY: u64 = 63; /// Solve the scalar constraint program in string b for object a; c selects check-only. pub const OBJECT_RANDOMIZE: u64 = 64; +/// Program b for object a; c is an input buffer (check-only byte followed by +/// big-endian u64 values). The buffer is consumed, including on failure. +pub const OBJECT_RANDOMIZE_INPUTS: u64 = 65; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -195,16 +198,45 @@ impl Heap { 0 } OBJECT_CLASS => self.class_of(a as Handle).into(), - OBJECT_RANDOMIZE => { - match serde_json::from_slice::( - self.string(b as Handle), - ) { - Ok(program) => u64::from(self.randomize_object(a as Handle, &program, c != 0)), + op @ (OBJECT_RANDOMIZE | OBJECT_RANDOMIZE_INPUTS) => { + let input_bytes = (op == OBJECT_RANDOMIZE_INPUTS).then(|| self.take_buffer(c)); + let result = (|| -> Result<_, String> { + let program = serde_json::from_slice::( + self.string(b as Handle), + ) + .map_err(|error| error.to_string())?; + let (check_only, inputs) = if op == OBJECT_RANDOMIZE_INPUTS { + let bytes = input_bytes.as_ref().unwrap(); + let (&check, values) = bytes + .split_first() + .ok_or("missing constraint input buffer")?; + if check > 1 || values.len() % 8 != 0 { + return Err("invalid constraint input buffer".into()); + } + ( + check != 0, + values + .as_chunks::<8>() + .0 + .iter() + .map(|chunk| u64::from_be_bytes(*chunk)) + .collect::>(), + ) + } else { + (c != 0, Vec::new()) + }; + Ok(self.randomize_object_with_inputs( + a as Handle, + &program, + check_only, + &inputs, + )) + })(); + match result { + Ok(success) => u64::from(success), Err(error) => { self.fault - .get_or_insert(crate::Fault::ConstraintRandomization( - error.to_string(), - )); + .get_or_insert(crate::Fault::ConstraintRandomization(error)); 0 } } diff --git a/crates/celox-heap/src/randomization.rs b/crates/celox-heap/src/randomization.rs index 18980c30405..f0e2ade8091 100644 --- a/crates/celox-heap/src/randomization.rs +++ b/crates/celox-heap/src/randomization.rs @@ -16,6 +16,11 @@ pub struct Field { pub enum Expr { Literal(u32, u64), Field(usize), + /// Read-only scalar supplied by this call, never a solver variable. + Input { + index: usize, + width: u32, + }, Resize { value: Box, width: u32, @@ -50,9 +55,18 @@ fn boolean(value: Term) -> Term { } impl Expr { - fn term(&self, fields: &[Term]) -> Result { + fn term(&self, fields: &[Term], inputs: &[u64]) -> Result { Ok(match self { Self::Literal(width, value) => bv(*width, *value), + Self::Input { index, width } => { + if !(1..=64).contains(width) { + return Err("invalid constraint input width".into()); + } + bv( + *width, + *inputs.get(*index).ok_or("missing constraint input")?, + ) + } Self::Field(index) => fields .get(*index) .ok_or("invalid constraint field")? @@ -62,7 +76,7 @@ impl Expr { width, signed, } => { - let value = value.term(fields)?; + let value = value.term(fields, inputs)?; let Sort::Bv(old) = value.0.sort else { unreachable!() }; @@ -82,7 +96,7 @@ impl Expr { } } Self::Unary { op, value } => { - let value = value.term(fields)?; + let value = value.term(fields, inputs)?; match op.as_str() { "!" => boolean(not(truth(value))), "~" => node(value.0.sort.clone(), "bvnot", vec![value]), @@ -101,8 +115,8 @@ impl Expr { right, signed, } => { - let a = left.term(fields)?; - let b = right.term(fields)?; + let a = left.term(fields, inputs)?; + let b = right.term(fields, inputs)?; let relation = match op.as_str() { "==" => Some(eq(a.clone(), b.clone())), "!=" => Some(not(eq(a.clone(), b.clone()))), @@ -155,7 +169,19 @@ impl Heap { program: &Program, check_only: bool, ) -> bool { - self.randomize_object_with_limits(handle, program, check_only, Limits::default()) + self.randomize_object_with_inputs(handle, program, check_only, &[]) + } + + /// Solve using call-local, read-only scalar values. Inputs are not retained + /// in the object or its RNG state and are never included in the projection. + pub fn randomize_object_with_inputs( + &mut self, + handle: Handle, + program: &Program, + check_only: bool, + inputs: &[u64], + ) -> bool { + self.randomize_object_with_limits(handle, program, check_only, inputs, Limits::default()) } fn randomize_object_with_limits( @@ -163,6 +189,7 @@ impl Heap { handle: Handle, program: &Program, check_only: bool, + inputs: &[u64], limits: Limits, ) -> bool { if !self.check_object(handle, 0) { @@ -194,7 +221,7 @@ impl Heap { terms.push(term); } for constraint in &program.constraints { - formula = and(formula, truth(constraint.term(&terms)?)); + formula = and(formula, truth(constraint.term(&terms, inputs)?)); } let seed = if projection.is_empty() { 0 @@ -261,6 +288,62 @@ mod tests { } } + #[test] + fn per_call_inputs_are_read_only_checked_and_not_retained() { + let mut heap = Heap::new(); + let object = heap.new_object(1, 1); + let mut program = program(); + program.constraints = vec![Expr::Binary { + op: "==".into(), + left: Box::new(Expr::Field(0)), + right: Box::new(Expr::Input { index: 0, width: 4 }), + signed: false, + }]; + for value in [3, 12] { + assert!(heap.randomize_object_with_inputs(object, &program, false, &[value])); + assert_eq!(heap.load(object, 0, 1), value); + } + let mut before = heap.clone(); + assert!(!heap.randomize_object_with_inputs(object, &program, true, &[3])); + assert_eq!(heap.load(object, 0, 1), 12); + assert_eq!(heap.random_object(object), before.random_object(object)); + assert!(!heap.randomize_object(object, &program, false)); + assert!(matches!( + heap.take_fault(), + Some(Fault::ConstraintRandomization(_)) + )); + let json = heap.intern(&serde_json::to_vec(&program).unwrap()); + let mut bytes = vec![0]; + bytes.extend(5u64.to_be_bytes()); + let inputs = heap.new_buffer(bytes); + assert_eq!( + heap.call( + crate::ops::OBJECT_RANDOMIZE_INPUTS, + object.into(), + json.into(), + inputs + ), + 1, + "{:?}", + heap.take_fault() + ); + assert_eq!(heap.load(object, 0, 1), 5); + let bad = heap.new_buffer(vec![0, 1]); + assert_eq!( + heap.call( + crate::ops::OBJECT_RANDOMIZE_INPUTS, + object.into(), + json.into(), + bad + ), + 0 + ); + assert!(matches!( + heap.take_fault(), + Some(Fault::ConstraintRandomization(_)) + )); + } + #[test] fn modes_unsat_faults_and_snapshot_replay() { let mut heap = Heap::new(); @@ -279,7 +362,7 @@ mod tests { max_work: 0, ..Limits::default() }; - assert!(!heap.randomize_object_with_limits(object, &program, false, limits)); + assert!(!heap.randomize_object_with_limits(object, &program, false, &[], limits)); assert_eq!(heap.load(object, 0, 1), 9); assert!(matches!( heap.take_fault(), From af696fe805d52949a2ec8dd47acf9a21da5f3c0d Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 16:45:41 +0900 Subject: [PATCH 4/7] feat(sv): bind caller scalar inputs in inline constraints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve inline constraint names against the receiver class first, then the calling scope. Support local::name to bypass the receiver explicitly. Pass 1–64-bit two-state scalar variables and arguments as read-only call inputs, retaining width and signedness through solving, dynamic subclass dispatch and imported package methods. Keep local:: out of package dependency discovery. Four-state and unpacked inputs, typed parameter inputs, qualified this/super references and restricted with-name lists remain unsupported. IEEE 1800-2023 18.7 and 18.7.1. Validation: 70 constrained-randomization backend cases, 842 analyzer tests (three existing ignored), affected all-target Clippy, formatting, four retained-report tests and seven report checker tests pass. Both new shared cases pass Verilator. Icarus rejects the constraint/inline syntax; observed diagnostics extend the existing reviewed exclusion. Cases cover shadowed locals, signed values, repeated calls, range inputs, check-only calls, selected-member UNSAT preservation and imported inherited methods. Prepare the receiver (selection and pre-hook) before reading caller inputs, then solve and run the post-hook once. Receiver static members reject before caller fallback, while explicit local:: remains valid. Accept the official CI-observed fail-to-pass transition for 18.7.1--local-scope-resolution_0 in both state modes; both were rechecked with the pinned source and debug driver. Review validation: 75 constrained backend tests, three focused analyzer regressions, affected Clippy, four retained-report tests and seven report checker tests pass. The new hook case exposes Verilator 5.052 sampling inline inputs before the pre-hook; preserve the assertions and record observed evidence in the reviewed limitation. Change-Id: I65f528d40633d4cbbe253c55c98f0039c01f82aa --- conformance/sv-tests/expected.tsv | 4 +- .../src/lowering/ff/objects.rs | 14 +- .../src/ast/classes/constraints.rs | 53 ++++- .../src/ast/expression_binding/objects.rs | 106 ++++++++- crates/celox-sv-analyzer/src/ast/imports.rs | 5 + .../src/ast/procedural/randomization.rs | 215 +++++++++++------- crates/celox-sv-analyzer/src/tests.rs | 39 ++++ .../celox-test-suite/src/sv/cases/class.vtest | 92 ++++++++ .../repros/sv_inline_input_hooks.json | 17 ++ .../repros/sv_inline_input_icarus.json | 19 ++ .../verification/sv/icarus/class.json | 128 ++++++++++- .../verification/sv/limitations.json | 25 +- .../verification/sv/verilator/class.json | 22 ++ .../tests/frontends/systemverilog/class.rs | 9 + docs/guide/systemverilog-reference.md | 16 +- 15 files changed, 653 insertions(+), 111 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_inline_input_hooks.json create mode 100644 crates/celox-test-suite/verification/repros/sv_inline_input_icarus.json diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 1645eeadf6a..7682b9d7c17 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -649,8 +649,8 @@ chapter-18/18.7--in-line-constraints--randomize_5.sv 2state fail chapter-18/18.7--in-line-constraints--randomize_5.sv 4state fail chapter-18/18.7--in-line-constraints--randomize_6.sv 2state fail chapter-18/18.7--in-line-constraints--randomize_6.sv 4state fail -chapter-18/18.7.1--local-scope-resolution_0.sv 2state fail -chapter-18/18.7.1--local-scope-resolution_0.sv 4state fail +chapter-18/18.7.1--local-scope-resolution_0.sv 2state pass +chapter-18/18.7.1--local-scope-resolution_0.sv 4state pass chapter-18/18.7.1--local-scope-resolution_1.sv 2state fail chapter-18/18.7.1--local-scope-resolution_1.sv 4state fail chapter-18/18.8--disabling-random-variables-with-rand_mode_0.sv 2state fail diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index e2d499dae70..d7d455b940c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -38,7 +38,19 @@ impl Ff<'_, '_> { buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, value, count]); } let program = self.heap_call(ops::FREEZE, &[buffer]); - self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check]) + if args.len() == 2 { + self.heap_call(ops::OBJECT_RANDOMIZE, &[object, program, check]) + } else { + let mut inputs = self.heap_call(ops::NEW, &[]); + let one = self.constant64(1); + inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, check, one]); + for value in &args[2..] { + let value = self.integer_of_width(value, 64, false)?; + let eight = self.constant64(8); + inputs = self.heap_call(ops::APPEND_BYTES, &[inputs, value, eight]); + } + self.heap_call(ops::OBJECT_RANDOMIZE_INPUTS, &[object, program, inputs]) + } } ObjectOp::Container { .. } => unreachable!("handled by container_call"), ObjectOp::New { diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs index bd5ecf18c7a..9ecf0d40229 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -115,12 +115,23 @@ pub(in crate::ast) fn bind( tree: &AnalysisContext<'_>, properties: &[Property], env: &HashMap, +) -> Result { + bind_inputs(id, tree, properties, env, &HashMap::default()) +} + +pub(in crate::ast) fn bind_inputs( + id: ExprId, + tree: &AnalysisContext<'_>, + properties: &[Property], + env: &HashMap, + inputs: &HashMap, ) -> Result { fn expression( id: ExprId, tree: &AnalysisContext<'_>, properties: &[Property], env: &HashMap, + inputs: &HashMap, depth: usize, budget: &std::cell::Cell, ) -> Result { @@ -128,7 +139,7 @@ pub(in crate::ast) fn bind( return Err("constraint expression nesting limit".into()); } charge(budget)?; - let recurse = |id| expression(id, tree, properties, env, depth + 1, budget); + let recurse = |id| expression(id, tree, properties, env, inputs, depth + 1, budget); let native = tree.declarations(); Ok(match &native.expression(id).kind { ExprKind::Group(id) => return recurse(*id), @@ -145,6 +156,12 @@ pub(in crate::ast) fn bind( width: property.field.width, signed: property.field.signed, } + } else if let Some(&(index, width, signed)) = inputs.get(&name) { + Typed { + kind: Kind::Leaf(ConstraintExpr::Input { index, width }), + width, + signed, + } } else if env.contains_key(&name) { // Parameter type reconstruction belongs to the general expression binder. // Do not guess its width/sign here. @@ -153,6 +170,21 @@ pub(in crate::ast) fn bind( return Err(format!("constraint variable `{name}`")); } } + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" + && matches!(&native.expression(*expression).kind, ExprKind::Name(root) if root.spelling == "local") => + { + let key = format!("local::{}", instances::normalize_identifier(&name.spelling)); + let &(index, width, signed) = inputs.get(&key).ok_or("inline local variable")?; + Typed { + kind: Kind::Leaf(ConstraintExpr::Input { index, width }), + width, + signed, + } + } ExprKind::Literal(text) => { if text.starts_with("'0") || text.starts_with("'1") { return Err("unbased unsized constraint literal".into()); @@ -286,8 +318,16 @@ pub(in crate::ast) fn bind( _ => return Err("unsupported scalar constraint expression".into()), }) } - expression(id, tree, properties, env, 0, &std::cell::Cell::new(16_384)) - .map(|value| emit(value, None)) + expression( + id, + tree, + properties, + env, + inputs, + 0, + &std::cell::Cell::new(16_384), + ) + .map(|value| emit(value, None)) } impl Class { @@ -332,10 +372,15 @@ pub(in crate::ast) struct Inline { pub key: usize, pub class: std::rc::Rc, pub constraints: Vec, + pub inputs: Vec, pub dimensions: PackedDimensions, } impl Inline { + pub fn prepare_name(&self, class: &str) -> String { + format!("{}$prepare", self.name(class)) + } + pub fn name(&self, class: &str) -> String { format!("{class}::$inline_randomize@{}", self.key) } @@ -348,6 +393,7 @@ pub(in crate::ast) struct InlineRequest { pub key: usize, pub class: Class, pub constraints: Vec, + pub inputs: Vec, } impl Inline { @@ -356,6 +402,7 @@ impl Inline { key: self.key, class: (*self.class).clone(), constraints: self.constraints.clone(), + inputs: self.inputs.clone(), } } } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index b438437f392..714fae46d06 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -955,12 +955,96 @@ pub(super) fn randomize_with( let class = class(tree, dimensions, owner)?; // Inline constraints need the solver even on otherwise unconstrained classes. class.constraint_program()?; - let constraints = constraints - .ok_or_else(|| unsupported("inline constraint form"))? + let constraint_ids = constraints.ok_or_else(|| unsupported("inline constraint form"))?; + let mut inputs = HashMap::default(); + let mut input_types = Vec::new(); + let mut input_values = Vec::new(); + let mut pending = constraint_ids.to_vec(); + while let Some(id) = pending.pop() { + let candidate = match &native.expression(id).kind { + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + if class.properties.iter().any(|p| p.name == name) { + None + } else if class.statics.iter().any(|p| p.name == name) { + return Err(unsupported("static properties in inline constraints")); + } else { + Some((name.clone(), name)) + } + } + ExprKind::Member { + expression, + separator, + name, + } if separator == "::" + && matches!(&native.expression(*expression).kind, ExprKind::Name(root) if root.spelling == "local") => + { + let name = instances::normalize_identifier(&name.spelling); + Some((format!("local::{name}"), name)) + } + ExprKind::Group(id) | ExprKind::Unary { expression: id, .. } => { + pending.push(*id); + None + } + ExprKind::Binary { left, right, .. } => { + pending.extend([*right, *left]); + None + } + ExprKind::Set(items) => { + for item in items { + match item.kind { + celox_sv_syntax::DimensionKind::Index(id) => pending.push(id), + celox_sv_syntax::DimensionKind::Range { left, right } => { + pending.extend([right, left]) + } + _ => {} + } + } + None + } + _ => None, + }; + let Some((key, name)) = candidate else { + continue; + }; + if inputs.contains_key(&key) { + continue; + } + let variable = dimensions + .get(&name) + .ok_or_else(|| unsupported(format!("inline local variable `{name}`")))?; + if variable.real + || variable.string + || variable.class.is_some() + || variable.container.is_some() + || !variable.unpacked.is_empty() + || !variable.is_2state + { + return Err(unsupported( + "inline inputs require two-state scalar variables", + )); + } + let value = Expr::Ident(name); + let width = expr_static_width(&tree.state, &value, dimensions) + .filter(|width| (1..=64).contains(width)) + .ok_or_else(|| unsupported("inline input width"))?; + let mut ty = classes::unsigned_type(width); + ty.is_signed = variable.signed; + inputs.insert(key, (input_types.len(), width as u32, variable.signed)); + input_types.push(ty); + input_values.push(Some(value)); + } + let constraints = constraint_ids .iter() .map(|&id| { - classes::constraints::bind(id, tree, &class.properties, &dimensions.const_env) - .map_err(|reason| unsupported(format!("inline constraints: {reason}"))) + classes::constraints::bind_inputs( + id, + tree, + &class.properties, + &dimensions.const_env, + &inputs, + ) + .map_err(|reason| unsupported(format!("inline constraints: {reason}"))) }) .collect::>>()?; let selection = random_selection(tree, dimensions, &method_name, arguments, native)?; @@ -975,13 +1059,25 @@ pub(super) fn randomize_with( key, class, constraints, + inputs: input_types, dimensions: dimensions.clone(), }; let name = inline.name(owner); + // Argument evaluation is left-to-right. Prepare the receiver and run its + // pre-hook before sampling any caller-scope input. Evaluate the receiver once. + let handle = if input_values.is_empty() { + handle + } else { + Expr::Call { + callee: Callee::Subroutine(inline.prepare_name(owner)), + args: vec![Some(handle), Some(selection.clone())], + arg_order: Vec::new(), + } + }; tree.state.inline_randomizations.borrow_mut().push(inline); Ok(Expr::Call { callee: Callee::Subroutine(name), - args: vec![Some(handle), Some(selection)], + args: [vec![Some(handle), Some(selection)], input_values].concat(), arg_order: Vec::new(), }) } diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index d0279b3bd7e..fc5feacd2d1 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -123,6 +123,11 @@ impl ScopeImports { if package == "std" && normalize_identifier(&name.spelling) == "randomize" { continue; } + // Inline constraint local:: lookup bypasses the receiver class, + // not through a package dependency (18.7.1). + if package == "local" { + continue; + } // `C::name` names a member of class `C` (IEEE 1800-2023 8.23). if visible_class(tree, &package) { continue; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 20c1bdd9e52..7cf4e43d484 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -13,7 +13,7 @@ pub(super) fn lower( state: &mut BodyState<'_>, item: &generate::Item, ) -> Converted> { - lower_methods(class, tree, dimensions, state, Some(item), None) + lower_methods(class, tree, dimensions, state, Some(item), None, false) } fn lower_methods( @@ -23,6 +23,7 @@ fn lower_methods( state: &mut BodyState<'_>, item: Option<&generate::Item>, inline: Option<&classes::constraints::Inline>, + prepare: bool, ) -> Converted> { let env = item.map(|item| &*item.env).unwrap_or(&dimensions.const_env); let aliases = item @@ -30,7 +31,11 @@ fn lower_methods( .unwrap_or_else(|| std::borrow::Cow::Borrowed(&dimensions.type_aliases)); let method_name = |class: &str, method: &str| { if let Some(inline) = inline { - inline.name(class) + if prepare { + inline.prepare_name(class) + } else { + inline.name(class) + } } else { let name = classes::Class::subroutine_name(class, method); item.map(|item| item.name(&name)).unwrap_or(name) @@ -66,7 +71,7 @@ fn lower_methods( _ => ("on_off", classes::unsigned_type(1)), }; let argument = builder.declare(argument, argument_type.clone()); - let params = vec![ + let mut params = vec![ SubroutineParam { name: this.clone(), source_name: classes::THIS.into(), @@ -82,6 +87,20 @@ fn lower_methods( default: None, }, ]; + let mut input_values = Vec::new(); + if let Some(inline) = inline.filter(|_| !prepare) { + for (index, ty) in inline.inputs.iter().enumerate() { + let name = builder.declare(&format!("$input{index}"), ty.clone()); + params.push(SubroutineParam { + name: name.clone(), + source_name: name.clone(), + direction: ParamDirection::Input, + r#type: convert_type(ty.clone()), + default: None, + }); + input_values.push(Expr::Ident(name)); + } + } // Faults are consumed after the kernel completes. Return immediately // on rejection, before hooks, draws or property/mode updates. let mut body = vec![Stmt::If { @@ -153,93 +172,105 @@ fn lower_methods( vec![Expr::Ident(this.clone()), selected], ))); } - body.push(Stmt::If { - condition: Expr::Ident(argument.clone()), - then_body: select, - else_body: Vec::new(), - }); - body.extend(hook("pre_randomize")); - if class.has_constraints || inline.is_some() { - let mut program = class.constraint_program()?; - if let Some(inline) = inline { - program.constraints.extend(inline.constraints.clone()); - } - let success = builder.declare("$constraint_success", int_type()); - body.push(Stmt::Assign { - lhs: LValue::Ident(success.clone()), - rhs: classes::object_call( - ObjectOp::Randomize(program), - vec![ - Expr::Ident(this.clone()), - Expr::Binary { - left: Box::new(Expr::Ident(argument.clone())), - op: BinaryOp::Eq, - right: Box::new(Expr::Literal("1".into())), - }, - ], - ), - nonblocking: false, - }); + if prepare || inline.is_none_or(|inline| inline.inputs.is_empty()) { body.push(Stmt::If { - condition: Expr::Ident(success), - then_body: Vec::new(), - else_body: vec![ - Stmt::If { - condition: Expr::Ident(argument.clone()), - then_body: vec![Stmt::Eval(classes::object_call( - ObjectOp::ModePop, - vec![Expr::Ident(this.clone())], - ))], - else_body: Vec::new(), - }, - Stmt::Return(Some(Expr::Literal("32'sd0".into()))), - ], + condition: Expr::Ident(argument.clone()), + then_body: select, + else_body: Vec::new(), }); + body.extend(hook("pre_randomize")); + } + if prepare { + body.push(Stmt::Return(Some(Expr::Ident(this.clone())))); + Some(builder.declare("$prepared", handle.clone())) } else { - for property in &class.properties { - if property.constant - || property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none()) - { - continue; + if class.has_constraints || inline.is_some() { + let mut program = class.constraint_program()?; + if let Some(inline) = inline { + program.constraints.extend(inline.constraints.clone()); } + let success = builder.declare("$constraint_success", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(success.clone()), + rhs: classes::object_call( + ObjectOp::Randomize(program), + [ + vec![ + Expr::Ident(this.clone()), + Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal("1".into())), + }, + ], + input_values.clone(), + ] + .concat(), + ), + nonblocking: false, + }); body.push(Stmt::If { - condition: Expr::Binary { - left: Box::new(Expr::Binary { - left: Box::new(Expr::Ident(argument.clone())), - op: BinaryOp::Ne, - right: Box::new(Expr::Literal("1".into())), - }), - op: BinaryOp::LogicAnd, - right: Box::new(classes::object_call( - ObjectOp::ModeGet( - property.field.offset, - property.rand || property.randc, - ), - vec![Expr::Ident(this.clone())], - )), - }, - then_body: random_property(&mut builder, property, &this), - else_body: Vec::new(), + condition: Expr::Ident(success), + then_body: Vec::new(), + else_body: vec![ + Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePop, + vec![Expr::Ident(this.clone())], + ))], + else_body: Vec::new(), + }, + Stmt::Return(Some(Expr::Literal("32'sd0".into()))), + ], }); + } else { + for property in &class.properties { + if property.constant + || property.field.handle.is_some() + || (property.r#type.is_enum + && property.r#type.enum_values.is_none()) + { + continue; + } + body.push(Stmt::If { + condition: Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(argument.clone())), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1".into())), + }), + op: BinaryOp::LogicAnd, + right: Box::new(classes::object_call( + ObjectOp::ModeGet( + property.field.offset, + property.rand || property.randc, + ), + vec![Expr::Ident(this.clone())], + )), + }, + then_body: random_property(&mut builder, property, &this), + else_body: Vec::new(), + }); + } } + body.extend(hook("post_randomize")); + body.push(Stmt::If { + condition: Expr::Ident(argument.clone()), + then_body: vec![Stmt::Eval(classes::object_call( + ObjectOp::ModePop, + vec![Expr::Ident(this.clone())], + ))], + else_body: Vec::new(), + }); + let returned = builder.declare("randomize", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(returned.clone()), + rhs: Expr::Literal("32'sd1".into()), + nonblocking: false, + }); + Some(returned) } - body.extend(hook("post_randomize")); - body.push(Stmt::If { - condition: Expr::Ident(argument.clone()), - then_body: vec![Stmt::Eval(classes::object_call( - ObjectOp::ModePop, - vec![Expr::Ident(this.clone())], - ))], - else_body: Vec::new(), - }); - let returned = builder.declare("randomize", int_type()); - body.push(Stmt::Assign { - lhs: LValue::Ident(returned.clone()), - rhs: Expr::Literal("32'sd1".into()), - nonblocking: false, - }); - Some(returned) } }; if method != "srandom" { @@ -262,10 +293,11 @@ fn lower_methods( { continue; } - let args = vec![ + let mut args = vec![ Some(Expr::Ident(this.clone())), Some(Expr::Ident(argument.clone())), ]; + args.extend(input_values.iter().cloned().map(Some)); let name = method_name(&name, method); let call = if method == "randomize" { vec![Stmt::Return(Some(Expr::Call { @@ -317,7 +349,9 @@ fn lower_methods( .map(|local| local.name.clone()) .collect(), persistent_locals: Vec::new(), - return_type: return_var.as_ref().map(|_| convert_type(int_type())), + return_type: return_var + .as_ref() + .map(|_| convert_type(if prepare { handle.clone() } else { int_type() })), params, return_var, body, @@ -427,6 +461,7 @@ pub(in crate::ast) fn inline_subroutines( key: request.key, class: std::rc::Rc::new(request.class.clone()), constraints: request.constraints.clone(), + inputs: request.inputs.clone(), dimensions: dimensions.clone(), }); } @@ -468,7 +503,19 @@ pub(in crate::ast) fn inline_subroutines( state, None, Some(&inline), + false, )?); + if !inline.inputs.is_empty() { + result.extend(lower_methods( + &class, + tree, + dims, + state, + None, + Some(&inline), + true, + )?); + } } } Ok((result, exported)) diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 985f96f74f9..641dbb8670d 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -7374,3 +7374,42 @@ fn class_inline_randomize_retains_call_specific_constraints() { endmodule"#; analyze_source(source, Path::new("inline_randomize.sv")).unwrap(); } + +#[test] +fn class_inline_randomize_binds_local_inputs() { + let source = r#"module Top; + class C; rand bit [7:0] x; endclass + C obj; + bit [7:0] wanted, x; + initial begin + obj = new; + wanted = 2; x = 3; + obj.randomize() with { x == wanted; }; + obj.randomize() with { x == local::x; }; + end + endmodule"#; + analyze_source(source, Path::new("inline_inputs.sv")).unwrap(); +} + +#[test] +fn class_inline_randomize_static_names_do_not_capture_caller_locals() { + for (expression, supported) in [("x == limit", false), ("x == local::limit", true)] { + let source = format!( + r#"module Top; + class C; rand bit [7:0] x; static bit [7:0] limit = 5; endclass + C obj; bit [7:0] limit; + initial begin obj = new; limit = 3; obj.randomize() with {{ {expression}; }}; end + endmodule"# + ); + let result = analyze_source(&source, Path::new("inline_static_scope.sv")); + if supported { + result.unwrap(); + } else { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("static properties in inline constraints"), + "{error}" + ); + } + } +} diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index b4b2156e1ab..185ea735a99 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -2247,3 +2247,95 @@ module Top(output bit done); endmodule "#) (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_inputs + (source "inline_inputs.sv" #" +module Top(output bit done); + class Packet; + rand bit signed [7:0] x; + rand bit [15:0] y; + constraint c { y == 7; } + endclass + Packet p; + bit signed [7:0] wanted; + bit signed [7:0] x; + initial begin + p = new; + wanted = -2; + x = -3; + if (!(p.randomize() with { x == wanted; })) $fatal(1, "fallback input"); + if (p.x != -2 || p.y != 7 || wanted != -2) $fatal(1, "signed readonly input"); + if (!(p.randomize() with { x == local::x; })) $fatal(1, "local qualifier"); + if (p.x != -3 || x != -3) $fatal(1, "shadowed local"); + wanted = 4; + if (!(p.randomize() with { x inside {[wanted:6]}; })) $fatal(1, "input range"); + if (p.x < 4 || p.x > 6) $fatal(1, "new call input"); + wanted = p.x; + if (!(p.randomize(null) with { x == wanted; })) $fatal(1, "input check"); + wanted = 12; + if (p.randomize(y) with { y == wanted; }) $fatal(1, "input unsat"); + if (p.x < 4 || p.x > 6 || p.y != 7) $fatal(1, "unsat changed object"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_input_methods + (source "inline_input_methods.sv" #" +package pkg; + class Base; + rand bit [7:0] x; + function int pick(bit [7:0] wanted); + return randomize() with { x == wanted; }; + endfunction + endclass +endpackage +module Top(output bit done); + class Derived extends pkg::Base; + rand bit [7:0] y; + constraint c { y == 9; } + endclass + Derived d; + pkg::Base b; + initial begin + d = new; b = d; + if (!b.pick(2) || d.x != 2 || d.y != 9) $fatal(1, "imported input"); + if (!b.pick(5) || d.x != 5 || d.y != 9) $fatal(1, "repeated method input"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) + +(case constrained_randomize_inline_input_hooks + (source "inline_input_hooks.sv" #" +module Top(output bit done); + bit [7:0] wanted; + class Base; + rand bit [7:0] x; + int pre_calls, post_calls; + function void pre_randomize(); wanted = 5; pre_calls++; endfunction + function void post_randomize(); post_calls++; endfunction + endclass + class Derived extends Base; + function void pre_randomize(); wanted = 6; pre_calls++; endfunction + endclass + Base p; + Derived d; + initial begin + p = new; wanted = 2; + if (!(p.randomize(x) with { x == wanted; })) $fatal(1, "hook input solve"); + if (p.x != 5 || wanted != 5 || p.pre_calls != 1 || p.post_calls != 1) + $fatal(1, "input sampled before hook"); + wanted = 2; + if (p.randomize(x) with { x == wanted; x == 2; }) $fatal(1, "hook unsat"); + if (p.x != 5 || p.pre_calls != 2 || p.post_calls != 1) $fatal(1, "hook failure state"); + d = new; p = d; wanted = 2; + if (!(p.randomize() with { x == wanted; }) || p.x != 6 || p.pre_calls != 1 || p.post_calls != 1) + $fatal(1, "dynamic input hook"); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_inline_input_hooks.json b/crates/celox-test-suite/verification/repros/sv_inline_input_hooks.json new file mode 100644 index 00000000000..f7c9f1714b8 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_inline_input_hooks.json @@ -0,0 +1,17 @@ +{ + "specification": "IEEE 1800-2023 18.6.2, 18.7", + "observations": [ + { + "tool": "icarus", + "case": "class::constrained_randomize_inline_input_hooks", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:17: syntax error\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:17: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:17: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:17: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:21: syntax error\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:21: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:24: syntax error\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:24: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:25: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_input_hooks/source_0.sv:24: error: Malformed conditional expression.\n" + }, + { + "tool": "verilator", + "case": "class::constrained_randomize_inline_input_hooks", + "status": "runtime_error", + "log": "[0] %Fatal: source_0.sv:19: Assertion failed in TOP.celox_suite_tb.dut: input sampled before hook\n%Error: /sv-verilator/class/constrained_randomize_inline_input_hooks/source_0.sv:19: Verilog $stop\nAborting...\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_inline_input_icarus.json b/crates/celox-test-suite/verification/repros/sv_inline_input_icarus.json new file mode 100644 index 00000000000..453dae87fb7 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_inline_input_icarus.json @@ -0,0 +1,19 @@ +{ + "specification": "IEEE 1800-2023 18.7, 18.7.1", + "observations": [ + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline_inputs", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:6: sorry: Constraint declarations not supported.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:15: syntax error\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:15: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:15: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:15: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:17: syntax error\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:17: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:17: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:17: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:20: syntax error\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:20: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:20: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:20: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:23: syntax error\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:23: error: Operand of unary ! is not a primary expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:23: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:23: error: Malformed conditional expression.\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:25: syntax error\n/sv-icarus/class/constrained_randomize_inline_inputs/source_0.sv:25: error: Malformed conditional expression.\n" + }, + { + "tool": "icarus", + "version": "Icarus 13.0", + "case": "class::constrained_randomize_inline_input_methods", + "status": "compile_error", + "log": "/sv-icarus/class/constrained_randomize_inline_input_methods/source_0.sv:6: syntax error\n/sv-icarus/class/constrained_randomize_inline_input_methods/source_0.sv:6: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_input_methods/source_0.sv:6: syntax error\n/sv-icarus/class/constrained_randomize_inline_input_methods/source_0.sv:6: error: Malformed statement\n/sv-icarus/class/constrained_randomize_inline_input_methods/source_0.sv:13: sorry: Constraint declarations not supported.\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index c0cd8261b6a..05ab75a150e 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -195,7 +195,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -221,7 +223,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -247,7 +251,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -273,7 +279,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -299,7 +307,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -325,7 +335,93 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_input_hooks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_input_methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" + ], + "id": "sv_icarus_scalar_constraints", + "observed_version": "Icarus Verilog version 13.0 (devel)", + "phase": "compile", + "reason": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_inputs", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus rejects constraint declarations and inline randomize with blocks before elaboration. IEEE 1800-2023 18.5 and 18.7 define these constructs. Celox retains all assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_scalar_constraints.json", + "LIMITATIONS.md#systemverilog-suite", + "verification/repros/sv_inside_constraints.json", + "verification/repros/sv_conditional_constraints.json", + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -351,7 +447,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -377,7 +475,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -403,7 +503,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -429,7 +531,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", @@ -455,7 +559,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "id": "sv_icarus_scalar_constraints", "observed_version": "Icarus Verilog version 13.0 (devel)", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 607baebddef..3134fa38015 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2608,7 +2608,9 @@ "LIMITATIONS.md#systemverilog-suite", "verification/repros/sv_inside_constraints.json", "verification/repros/sv_conditional_constraints.json", - "verification/repros/sv_inline_constraints.json" + "verification/repros/sv_inline_constraints.json", + "verification/repros/sv_inline_input_icarus.json", + "verification/repros/sv_inline_input_hooks.json" ], "cases": { "icarus": [ @@ -2622,7 +2624,10 @@ "class::constrained_randomize_inline", "class::constrained_randomize_inline_inheritance", "class::constrained_randomize_inline_basic", - "class::constrained_randomize_inline_package_instances" + "class::constrained_randomize_inline_package_instances", + "class::constrained_randomize_inline_inputs", + "class::constrained_randomize_inline_input_methods", + "class::constrained_randomize_inline_input_hooks" ] } }, @@ -2661,5 +2666,21 @@ "class::constrained_randomize_inline_inheritance" ] } + }, + { + "id": "sv_verilator_inline_inputs_before_pre_hook", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator copies caller-scope inline inputs into its generated helper before pre_randomize. When the hook changes wanted from 2 to 5, the solve still assigns x = 2. IEEE 1800-2023 18.6.2 invokes the pre-hook before randomization, and 18.7 permits references to caller-scope state variables. The regression retains the post-hook value and single-invocation assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_inline_input_hooks.json" + ], + "cases": { + "verilator": [ + "class::constrained_randomize_inline_input_hooks" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index cb0538712d6..2cf1b0997f6 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -172,6 +172,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator copies caller-scope inline inputs into its generated helper before pre_randomize. When the hook changes wanted from 2 to 5, the solve still assigns x = 2. IEEE 1800-2023 18.6.2 invokes the pre-hook before randomization, and 18.7 permits references to caller-scope state variables. The regression retains the post-hook value and single-invocation assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_inline_input_hooks.json" + ], + "id": "sv_verilator_inline_inputs_before_pre_hook", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator copies caller-scope inline inputs into its generated helper before pre_randomize. When the hook changes wanted from 2 to 5, the solve still assigns x = 2. IEEE 1800-2023 18.6.2 invokes the pre-hook before randomization, and 18.7 permits references to caller-scope state variables. The regression retains the post-hook value and single-invocation assertions.", + "upstream": [] + }, + "name": "class::constrained_randomize_inline_input_hooks", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index c622ad2a374..96ff7dad702 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -955,3 +955,12 @@ sv_backends! { sv_backends! { fn constrained_randomize_inline_package_instances(sim) { @case "class::constrained_randomize_inline_package_instances"; } } + +sv_backends! { + fn constrained_randomize_inline_inputs(sim) { @case "class::constrained_randomize_inline_inputs"; } + fn constrained_randomize_inline_input_methods(sim) { @case "class::constrained_randomize_inline_input_methods"; } +} + +sv_backends! { + fn constrained_randomize_inline_input_hooks(sim) { @case "class::constrained_randomize_inline_input_hooks"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 293906005e3..c858387fd96 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -246,9 +246,19 @@ object constraints and hooks still apply. A failed solve preserves properties, skips the post-hook and restores temporary selection modes. Inline constraints do not remain installed for later calls. -This initial inline subset accepts unqualified instance-property references. -Caller-local captures, `local::`, `this` / `super` qualified references, restricted -`with (names)` lookup and scope `std::randomize(...) with` remain unsupported. +If an unqualified name is not an instance property, inline lookup falls back to +scalar variables and arguments in the calling scope. `local::name` bypasses the +receiver's properties explicitly (18.7, 18.7.1). These read-only call inputs support +1–64-bit two-state integral values, including signed values. They are read after +`pre_randomize()` and are not randomized or retained on the object. Package methods preserve their inputs through dynamic +dispatch to subclasses defined by the consumer. + +Receiver static-property references are currently rejected; they do not fall back +to caller variables of the same name. + +Four-state and aggregate inputs, typed parameter inputs, qualified `this` / `super` +references, restricted `with (names)` lookup and scope `std::randomize(...) with` +remain unsupported. A call through `null` is a runtime error. From 80fe8bade99ee7ebced3e94c0153e64f15bb1aa2 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 15:44:04 +0900 Subject: [PATCH 5/7] fix(sv): preserve X/Z in two-state exact comparisons Two-state lowering converted X/Z operands to zero before ===, !== and ordinary case matching. A parity check against X could therefore accept a known zero and clear an instruction-loader byte (#2136). Retain literal unknowns inside exact-comparison operands and project their value and mask into ordinary two-state SLT expressions before backend lowering. Apply the same rules to combinational/procedural expressions and case matching, including width extension and conditional/arithmetic operands. Storage stays two-state, calls keep their effects, and known-only comparisons reuse their interned graph (IEEE 1800-2023 11.4.5 and 12.5). Preserve actual startup unknowns too: encode default four-state function locals as X rather than Z (6.8, Table 6-7), and keep partially driven nets out of constant-variable inlining when any read touches undriven bits. Merge sparse driver intervals to check coverage without a full-width bit mask. Fully covered constant reads remain eligible for inlining. Test interior gaps, high undriven bits, contiguous fragments and dependency preservation. The existing startup API regressions now explicitly check both state modes and verify that comparison results have no unknown bits. Add five shared regressions for operand order, signed/wide patterns, X versus Z, conversion, FF/timed execution, loaded bytes, call effects and unknown intermediates. Icarus passes all five unchanged cases. Verilator passes the timed effects case and rejects four with unsupported tristate constructs; retain the actual diagnostics, check their named cases, status, phase and diagnostic, and keep them executable without exclusions. Validation: 5,868 SV integration tests passed (20 existing ignored tests), 4,619 Veryl shared executions across native, native-parallel, Cranelift, Cranelift-parallel, WASM and the interpreter passed, as did 186 SLT unit tests, 9 frontend unit tests and all 4 retained-report integration tests. Changed crates/test targets pass clippy, formatting and workspace checks. The native NAPI addon builds and all 116 JS boundary tests pass. The companion performance-stack PR #2233 maintains the correction for the base's CodegenError::message feature gating in host-runtime-disabled SV builds. A pre-existing case-coverage false positive remains: an exhaustive case on {b, 1'bx} with only 2'b0x and 2'b1x labels is diagnosed as a latch. Both reproduce on the unchanged base and are not duplicated or broadened into this patch. Fixes #2136 Change-Id: I2b96b81844d9977a40668002b257c8bf845a249b --- crates/celox-frontend-sv/src/lowering.rs | 12 + .../src/lowering/case_equality.rs | 445 ++++++++++++++++++ crates/celox-frontend-sv/src/lowering/comb.rs | 84 +++- crates/celox-frontend-sv/src/lowering/ff.rs | 21 + .../src/lowering/procedural.rs | 2 +- crates/celox-slt/src/const_inline.rs | 144 +++++- crates/celox-test-suite/LIMITATIONS.md | 12 + .../src/sv/cases/operators.vtest | 164 +++++++ .../tests/retained_reports.rs | 14 + .../verification/sv/verilator/operators.json | 44 ++ .../frontends/systemverilog/operators.rs | 15 + .../systemverilog/review_regressions.rs | 40 +- 12 files changed, 968 insertions(+), 29 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/case_equality.rs diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 77e3c065724..9df4b36e034 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -37,6 +37,7 @@ use celox_sv_analyzer as sv; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use num_bigint::BigUint; +mod case_equality; mod comb; mod comb_retention; mod ff; @@ -5015,6 +5016,17 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr { op: *op, expr: Box::new(expr_for_state_mode(expr, four_state)), }, + sv::ir::Expr::Binary { left, op, right } + if !four_state && matches!(op, sv::ir::BinaryOp::EqCase | sv::ir::BinaryOp::NeCase) => + { + // Storage remains two-state; exact comparison operands retain + // literal X/Z until value and mask are compared (11.4.5). + sv::ir::Expr::Binary { + left: Box::new(expr_for_state_mode(left, true)), + op: *op, + right: Box::new(expr_for_state_mode(right, true)), + } + } sv::ir::Expr::Binary { left, op, right } => sv::ir::Expr::Binary { left: Box::new(expr_for_state_mode(left, four_state)), op: *op, diff --git a/crates/celox-frontend-sv/src/lowering/case_equality.rs b/crates/celox-frontend-sv/src/lowering/case_equality.rs new file mode 100644 index 00000000000..4555d5cfe87 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/case_equality.rs @@ -0,0 +1,445 @@ +//! Exact comparisons retain literal X/Z even when runtime storage has one plane. +use super::procedural::{ConstCache, node_is_signed, slt_const4}; +use super::*; +use num_traits::Zero; + +type Planes = (NodeId, NodeId); + +pub(super) fn compare( + arena: &mut SLTNodeArena, + left: NodeId, + op: BinaryOp, + right: NodeId, +) -> Result { + let width = celox_slt::get_width(left, arena).max(celox_slt::get_width(right, arena)); + let signed = node_is_signed(arena, left) && node_is_signed(arena, right); + let left = coerce_node_width(arena, left, Some(width), signed)?; + let right = coerce_node_width(arena, right, Some(width), signed)?; + let mut builder = Builder { + arena, + values: HashMap::default(), + constants: ConstCache::default(), + }; + let l = builder.project(left)?; + let r = builder.project(right)?; + if builder.zero(l.1) && builder.zero(r.1) { + return builder.node(SLTNode::Binary(l.0, op, r.0)); + } + builder.exact(l, r, op == BinaryOp::NeCase) +} + +pub(super) fn is_known( + arena: &mut SLTNodeArena, + node: NodeId, +) -> Result { + let mut builder = Builder { + arena, + values: HashMap::default(), + constants: ConstCache::default(), + }; + let (_, mask) = builder.project(node)?; + Ok(builder.zero(mask)) +} + +struct Builder<'a, A: std::hash::Hash + Eq + Clone> { + arena: &'a mut SLTNodeArena, + values: HashMap, + constants: ConstCache, +} + +impl Builder<'_, A> { + fn node(&mut self, node: SLTNode) -> Result { + self.arena.alloc(node) + } + fn constant( + &mut self, + value: BigUint, + width: usize, + ) -> Result { + self.node(SLTNode::Constant(value, BigUint::default(), width, false)) + } + fn zeros(&mut self, width: usize) -> Result { + self.constant(BigUint::default(), width) + } + fn ones(&mut self, width: usize) -> Result { + self.constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( + &mut self, + a: NodeId, + op: BinaryOp, + b: NodeId, + ) -> Result { + self.node(SLTNode::Binary(a, op, b)) + } + fn unary(&mut self, op: UnaryOp, a: NodeId) -> Result { + self.node(SLTNode::Unary(op, a)) + } + fn mux( + &mut self, + cond: NodeId, + yes: NodeId, + no: NodeId, + ) -> Result { + self.node(SLTNode::Mux { + cond, + then_expr: yes, + else_expr: no, + }) + } + fn zero(&mut self, node: NodeId) -> bool { + slt_const4(self.arena, &mut self.constants, node) + .is_some_and(|(v, m, _)| v.is_zero() && m.is_zero()) + } + fn any(&mut self, node: NodeId) -> Result { + self.unary(UnaryOp::Or, node) + } + fn expanded( + &mut self, + flag: NodeId, + width: usize, + ) -> Result { + let one = self.ones(width)?; + let zero = self.zeros(width)?; + self.mux(flag, one, zero) + } + fn exact( + &mut self, + l: Planes, + r: Planes, + negate: bool, + ) -> Result { + let payload = self.binary(l.0, BinaryOp::Eq, r.0)?; + let mask = self.binary(l.1, BinaryOp::Eq, r.1)?; + let equal = self.binary(payload, BinaryOp::And, mask)?; + if negate { + self.unary(UnaryOp::LogicNot, equal) + } else { + Ok(equal) + } + } + fn truth(&mut self, p: Planes) -> Result { + let not_mask = self.unary(UnaryOp::BitNot, p.1)?; + let known = self.binary(p.0, BinaryOp::And, not_mask)?; + let known_one = self.any(known)?; + let unknown = self.any(p.1)?; + let no_one = self.unary(UnaryOp::LogicNot, known_one)?; + let unknown = self.binary(no_one, BinaryOp::And, unknown)?; + let value = self.binary(known_one, BinaryOp::Or, unknown)?; + Ok((value, unknown)) + } + fn arithmetic( + &mut self, + value: NodeId, + mask: NodeId, + width: usize, + ) -> Result { + let mask = self.expanded(mask, width)?; + let value = self.binary(value, BinaryOp::Or, mask)?; + Ok((value, mask)) + } + fn project(&mut self, root: NodeId) -> Result { + // Append-only node IDs let this worklist retain sharing without cloning + // the arena or using the native call stack for deeply nested operands. + let mut work = vec![(root, false)]; + while let Some((id, expanded)) = work.pop() { + if self.values.contains_key(&id) { + continue; + } + let node = self.arena.get(id).clone(); + let width = celox_slt::get_width(id, self.arena); + if let Some((value, mask, _)) = slt_const4(self.arena, &mut self.constants, id) { + let signed = node_is_signed(self.arena, id); + let value = + self.node(SLTNode::Constant(value, BigUint::default(), width, signed))?; + let mask = self.constant(mask, width)?; + self.values.insert(id, (value, mask)); + continue; + } + let children = match &node { + SLTNode::Unary(_, a) + | SLTNode::Slice { expr: a, .. } + | SLTNode::Capture { expr: a, .. } => vec![*a], + SLTNode::Binary(a, _, b) => vec![*a, *b], + SLTNode::Concat(parts) => parts.iter().map(|p| p.0).collect(), + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => vec![*cond, *then_expr, *else_expr], + // Calls/folds and inputs cross a runtime storage boundary. + // Their result is two-state; explicit literal operands remain + // visible in the structural and arithmetic nodes above. + _ => Vec::new(), + }; + if !expanded && !children.is_empty() { + work.push((id, true)); + for child in children.into_iter().rev() { + if !self.values.contains_key(&child) { + work.push((child, false)); + } + } + continue; + } + let result = match node { + SLTNode::Binary(a, op, b) => { + let l = self.values[&a]; + let r = self.values[&b]; + self.binary_planes(id, l, op, r, width)? + } + SLTNode::Unary(op, inner) => { + let p = self.values[&inner]; + if self.zero(p.1) { + (self.unary(op, p.0)?, self.zeros(width)?) + } else { + match op { + UnaryOp::Ident => p, + UnaryOp::ToTwoState => { + let not = self.unary(UnaryOp::BitNot, p.1)?; + (self.binary(p.0, BinaryOp::And, not)?, self.zeros(width)?) + } + UnaryOp::BitNot => { + let not = self.unary(op, p.0)?; + (self.binary(not, BinaryOp::Or, p.1)?, p.1) + } + UnaryOp::LogicNot => { + let truth = self.truth(p)?; + let not = self.unary(UnaryOp::LogicNot, truth.0)?; + (self.binary(not, BinaryOp::Or, truth.1)?, truth.1) + } + UnaryOp::Or => self.truth(p)?, + UnaryOp::And => { + let candidate = self.binary(p.0, BinaryOp::Or, p.1)?; + let value = self.unary(op, candidate)?; + let unknown = self.any(p.1)?; + (value, self.binary(value, BinaryOp::And, unknown)?) + } + UnaryOp::Xor | UnaryOp::Minus => { + let value = self.unary(op, p.0)?; + let unknown = self.any(p.1)?; + self.arithmetic(value, unknown, width)? + } + UnaryOp::PopCount => { + let not = self.unary(UnaryOp::BitNot, p.1)?; + let known = self.binary(p.0, BinaryOp::And, not)?; + (self.unary(op, known)?, self.zeros(width)?) + } + _ => { + let value = self.unary(op, p.0)?; + let unknown = self.any(p.1)?; + self.arithmetic(value, unknown, width)? + } + } + } + } + SLTNode::Slice { expr, access } => { + let p = self.values[&expr]; + ( + self.node(SLTNode::Slice { expr: p.0, access })?, + self.node(SLTNode::Slice { expr: p.1, access })?, + ) + } + SLTNode::Concat(parts) => { + let payload = parts.iter().map(|(p, w)| (self.values[p].0, *w)).collect(); + let mask = parts.iter().map(|(p, w)| (self.values[p].1, *w)).collect(); + ( + self.node(SLTNode::Concat(payload))?, + self.node(SLTNode::Concat(mask))?, + ) + } + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => { + let c = self.truth(self.values[&cond])?; + let t = self.values[&then_expr]; + let e = self.values[&else_expr]; + let value = self.mux(c.0, t.0, e.0)?; + let mask = self.mux(c.0, t.1, e.1)?; + if self.zero(c.1) { + (value, mask) + } else { + // An unknown condition merges equal bits and makes + // only differing bits X, retaining equal X/Z bits. + let dv = self.binary(t.0, BinaryOp::Xor, e.0)?; + let dm = self.binary(t.1, BinaryOp::Xor, e.1)?; + let diff = self.binary(dv, BinaryOp::Or, dm)?; + let merged_value = self.binary(t.0, BinaryOp::Or, diff)?; + let merged_mask = self.binary(t.1, BinaryOp::Or, diff)?; + ( + self.mux(c.1, merged_value, value)?, + self.mux(c.1, merged_mask, mask)?, + ) + } + } + SLTNode::Capture { expr, key } => { + let p = self.values[&expr]; + ( + self.node(SLTNode::Capture { expr: p.0, key })?, + self.node(SLTNode::Capture { expr: p.1, key })?, + ) + } + _ => (id, self.zeros(width)?), + }; + self.values.insert(id, result); + } + Ok(self.values[&root]) + } + fn binary_planes( + &mut self, + original: NodeId, + l: Planes, + op: BinaryOp, + r: Planes, + width: usize, + ) -> Result { + if self.zero(l.1) + && self.zero(r.1) + && !matches!( + op, + BinaryOp::DivU | BinaryOp::DivS | BinaryOp::RemU | BinaryOp::RemS + ) + { + return Ok((self.binary(l.0, op, r.0)?, self.zeros(width)?)); + } + match op { + BinaryOp::EqCase | BinaryOp::NeCase => { + Ok((self.exact(l, r, op == BinaryOp::NeCase)?, self.zeros(1)?)) + } + BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { + let masks = self.binary(l.1, BinaryOp::Or, r.1)?; + let value = self.binary(l.0, op, r.0)?; + let mask = if op == BinaryOp::Xor { + masks + } else { + let (a, b) = if op == BinaryOp::And { + ( + self.unary(UnaryOp::BitNot, l.0)?, + self.unary(UnaryOp::BitNot, r.0)?, + ) + } else { + (l.0, r.0) + }; + let lm = self.unary(UnaryOp::BitNot, l.1)?; + let rm = self.unary(UnaryOp::BitNot, r.1)?; + let a = self.binary(a, BinaryOp::And, lm)?; + let b = self.binary(b, BinaryOp::And, rm)?; + let known = self.binary(a, BinaryOp::Or, b)?; + let not = self.unary(UnaryOp::BitNot, known)?; + self.binary(masks, BinaryOp::And, not)? + }; + Ok((self.binary(value, BinaryOp::Or, mask)?, mask)) + } + BinaryOp::LogicAnd | BinaryOp::LogicOr => { + let a = self.truth(l)?; + let b = self.truth(r)?; + self.binary_planes( + original, + a, + if op == BinaryOp::LogicAnd { + BinaryOp::And + } else { + BinaryOp::Or + }, + b, + 1, + ) + } + BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqWildcard | BinaryOp::NeWildcard => { + let masks = self.binary(l.1, BinaryOp::Or, r.1)?; + let not = self.unary(UnaryOp::BitNot, masks)?; + let diff = self.binary(l.0, BinaryOp::Xor, r.0)?; + let diff = self.binary(diff, BinaryOp::And, not)?; + let mismatch = self.any(diff)?; + let ambiguous = if matches!(op, BinaryOp::EqWildcard | BinaryOp::NeWildcard) { + let care = self.unary(UnaryOp::BitNot, r.1)?; + let lm = self.binary(l.1, BinaryOp::And, care)?; + self.any(lm)? + } else { + self.any(masks)? + }; + let no_diff = self.unary(UnaryOp::LogicNot, mismatch)?; + let mask = self.binary(no_diff, BinaryOp::And, ambiguous)?; + let value = if matches!(op, BinaryOp::Ne | BinaryOp::NeWildcard) { + self.binary(mismatch, BinaryOp::Or, mask)? + } else { + no_diff + }; + Ok((value, mask)) + } + BinaryOp::Shl | BinaryOp::Shr | BinaryOp::Sar => { + let value = self.binary(l.0, op, r.0)?; + let mask = self.binary(l.1, op, r.0)?; + let unknown = self.any(r.1)?; + let all = self.expanded(unknown, width)?; + Ok(( + self.binary(value, BinaryOp::Or, all)?, + self.binary(mask, BinaryOp::Or, all)?, + )) + } + BinaryOp::Float { .. } => Ok((original, self.zeros(width)?)), + _ => { + let lm = self.any(l.1)?; + let rm = self.any(r.1)?; + let mut unknown = self.binary(lm, BinaryOp::Or, rm)?; + if matches!( + op, + BinaryOp::DivU | BinaryOp::DivS | BinaryOp::RemU | BinaryOp::RemS + ) { + let zero = self.zeros(celox_slt::get_width(r.0, self.arena))?; + let zero = self.binary(r.0, BinaryOp::Eq, zero)?; + unknown = self.binary(unknown, BinaryOp::Or, zero)?; + } + let value = self.binary(l.0, op, r.0)?; + self.arithmetic(value, unknown, width) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deep_known_operands_reuse_the_original_comparison() { + let mut arena = SLTNodeArena::::new(); + let mut value = arena + .alloc(SLTNode::Input { + variable: SourceVarId::default(), + signed: false, + index: Vec::new(), + access: BitAccess::new(0, 31), + }) + .unwrap(); + for i in 0..512u32 { + let constant = arena + .alloc(SLTNode::Constant(i.into(), BigUint::default(), 32, false)) + .unwrap(); + value = arena + .alloc(SLTNode::Binary(value, BinaryOp::Xor, constant)) + .unwrap(); + } + let zero = arena + .alloc(SLTNode::Constant( + BigUint::default(), + BigUint::default(), + 32, + false, + )) + .unwrap(); + let expected = arena + .alloc(SLTNode::Binary(value, BinaryOp::EqCase, zero)) + .unwrap(); + let before = arena.len(); + assert_eq!( + compare(&mut arena, value, BinaryOp::EqCase, zero).unwrap(), + expected + ); + assert!( + arena.len() <= before + 1, + "known operands allocated shadow work for every node" + ); + } +} diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 246447ad5c8..0d066423299 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -583,7 +583,18 @@ impl<'p, 'a> Comb<'p, 'a> { expr: &sv::ir::Expr, context: Option<(usize, bool)>, ) -> Result { - let expr = expr_for_state_mode(expr, self.m.four_state); + self.eval_mode(store, frames, expr, context, false) + } + + fn eval_mode( + &mut self, + store: &mut Store, + frames: &[Frame], + expr: &sv::ir::Expr, + context: Option<(usize, bool)>, + preserve_literals: bool, + ) -> Result { + let expr = expr_for_state_mode(expr, self.m.four_state || preserve_literals); let expr = if self.m.calls(&expr) { self.hoist(store, frames, &expr)? } else { @@ -847,11 +858,14 @@ impl<'p, 'a> Comb<'p, 'a> { } } sources.extend(r_sources); - let rebuilt = if l == left && r == right { - node - } else { - self.alloc(SLTNode::Binary(l, op, r))? - }; + let rebuilt = + if !self.m.four_state && matches!(op, BinaryOp::EqCase | BinaryOp::NeCase) { + super::case_equality::compare(self.arena, l, op, r).map_err(slt_error)? + } else if l == left && r == right { + node + } else { + self.alloc(SLTNode::Binary(l, op, r))? + }; (rebuilt, sources) } SLTNode::Unary(op, inner) => { @@ -2285,7 +2299,13 @@ impl<'p, 'a> Comb<'p, 'a> { return Ok(conditions); } let selector_signed = self.expr_signed(selector); - let (selector_node, selector_sources) = self.eval(store, frames, selector, None)?; + let (selector_node, selector_sources) = self.eval_mode( + store, + frames, + selector, + None, + kind == sv::ir::CaseKind::Exact, + )?; let mut labels = Vec::with_capacity(items.len()); let mut width = self.width(selector_node); let mut all_signed = selector_signed; @@ -2296,7 +2316,8 @@ impl<'p, 'a> Comb<'p, 'a> { return Err(unsupported("range label outside case inside")); }; all_signed &= self.expr_signed(value); - let (node, sources) = self.eval(store, frames, value, None)?; + let (node, sources) = + self.eval_mode(store, frames, value, None, kind == sv::ir::CaseKind::Exact)?; width = width.max(self.width(node)); item_labels.push((node, sources)); } @@ -2307,8 +2328,14 @@ impl<'p, 'a> Comb<'p, 'a> { // equality: an unsigned operand also turns the others' operands // unsigned (11.8.2). let selector_node = if self.width(selector_node) < width || selector_signed != all_signed { - self.eval(store, frames, selector, Some((width, all_signed)))? - .0 + self.eval_mode( + store, + frames, + selector, + Some((width, all_signed)), + kind == sv::ir::CaseKind::Exact, + )? + .0 } else { selector_node }; @@ -2322,7 +2349,13 @@ impl<'p, 'a> Comb<'p, 'a> { && (self.width(*node) < width || self.expr_signed(value) != all_signed) { *node = self - .eval(store, frames, value, Some((width, all_signed)))? + .eval_mode( + store, + frames, + value, + Some((width, all_signed)), + kind == sv::ir::CaseKind::Exact, + )? .0; } } @@ -2337,7 +2370,12 @@ impl<'p, 'a> Comb<'p, 'a> { for (node, mut sources) in item_labels { let node = coerce_node_width(self.arena, node, Some(width), all_signed) .map_err(slt_error)?; - let matched = self.alloc(SLTNode::Binary(selector_node, op, node))?; + let matched = if !self.m.four_state && kind == sv::ir::CaseKind::Exact { + super::case_equality::compare(self.arena, selector_node, op, node) + .map_err(slt_error)? + } else { + self.alloc(SLTNode::Binary(selector_node, op, node))? + }; let matched = if kind == sv::ir::CaseKind::X { // A wildcard comparison returns X when only selector // unknowns prevent a definite match. casex ignores those @@ -2538,11 +2576,21 @@ impl<'p, 'a> Comb<'p, 'a> { ) -> Result, sv::AnalyzerError> { let none = vec![false; items.len()]; let mut probe = store.fork(); - let (selector_node, _) = self.eval(&mut probe, frames, selector, None)?; + let (selector_node, _) = self.eval_mode( + &mut probe, + frames, + selector, + None, + kind == sv::ir::CaseKind::Exact, + )?; let selector_width = self.width(selector_node); // A four-state selector also takes X and Z bits; only exact // comparisons of a narrow selector are enumerated. - let four_state_selector = !self.two_state(selector_node); + let four_state_selector = if self.m.four_state { + !self.two_state(selector_node) + } else { + !super::case_equality::is_known(self.arena, selector_node).map_err(slt_error)? + }; if four_state_selector && (kind != sv::ir::CaseKind::Exact || selector_width > 6) { return Ok(none); } @@ -2558,7 +2606,13 @@ impl<'p, 'a> Comb<'p, 'a> { sv::AnalyzerError, > { let signed = this.expr_signed(expr); - let (node, _) = this.eval(&mut probe, frames, expr, None)?; + let (node, _) = this.eval_mode( + &mut probe, + frames, + expr, + None, + kind == sv::ir::CaseKind::Exact, + )?; Ok(slt_const4(this.arena, &mut this.consts, node) .map(|(value, mask, width)| (value, mask, width, signed))) }; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6056876e786..06b4e932c0d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -969,6 +969,27 @@ impl<'p, 'a> Ff<'p, 'a> { stable(*id) } }; + if !self.m.four_state { + // Node IDs are topological. Cache exact comparisons before mapping + // their parents, reusing the existing graph/loop remapper. + for (index, expression) in arena.iter().enumerate() { + if let SLTNode::Binary(left, op @ (BinaryOp::EqCase | BinaryOp::NeCase), right) = + expression + { + let left = arena + .get(*left) + .map_addr(*left, arena, &mut mapped_arena, &mut cache, &map) + .map_err(slt_error)?; + let right = arena + .get(*right) + .map_addr(*right, arena, &mut mapped_arena, &mut cache, &map) + .map_err(slt_error)?; + let equal = super::case_equality::compare(&mut mapped_arena, left, *op, right) + .map_err(slt_error)?; + cache.insert(NodeId(index), equal); + } + } + } let mapped = arena .get(node) .map_addr(node, arena, &mut mapped_arena, &mut cache, &map) diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 1f445fb33a2..3b8390d9a8b 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2211,7 +2211,7 @@ pub(super) fn slt_unknown( ) -> Result { let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); arena - .alloc(SLTNode::Constant(BigUint::default(), mask, width, false)) + .alloc(SLTNode::Constant(mask.clone(), mask, width, false)) .map_err(slt_error) } diff --git a/crates/celox-slt/src/const_inline.rs b/crates/celox-slt/src/const_inline.rs index 172056809e7..720faf7836c 100644 --- a/crates/celox-slt/src/const_inline.rs +++ b/crates/celox-slt/src/const_inline.rs @@ -1,8 +1,9 @@ //! Constant variable inlining for combinational logic paths. //! //! Detects variables whose *every* LogicPath target is a constant expression -//! (no runtime inputs), then rewrites all `SLTNode::Input` references to those -//! variables with `SLTNode::Constant` nodes containing the precomputed value. +//! (no runtime inputs), whose reads are all covered by those drivers, then +//! rewrites their `SLTNode::Input` references to precomputed constants. +//! Variables with reads of undriven ranges retain their state dependencies. //! This eliminates the Store→Load memory roundtrip for compile-time constants //! such as genvar-expanded parity-check matrices. @@ -226,6 +227,17 @@ struct ConstVar { payload: BigUint, /// Combined 4-state mask. mask: BigUint, + /// Sorted, merged driven ranges. Bits outside them retain their state. + written: Vec, +} + +impl ConstVar { + fn covers(&self, access: BitAccess) -> bool { + let index = self.written.partition_point(|range| range.msb < access.lsb); + self.written + .get(index) + .is_some_and(|range| range.lsb <= access.lsb && range.msb >= access.msb) + } } /// Inline constant variables: rewrite Input references → Constant nodes. @@ -305,9 +317,42 @@ pub fn inline_constant_variables( if mask != BigUint::from(0u32) { continue; } - const_vars.insert(var.clone(), ConstVar { payload, mask }); + // Do not invent zeroes for undriven bits. Keep coverage as ranges, + // so a sparse driver does not allocate a mask up to its bit offset. + let mut written: Vec<_> = entries.iter().map(|(access, _)| *access).collect(); + written.sort_unstable_by_key(|access| access.lsb); + written.dedup_by(|next, previous| { + if next.lsb <= previous.msb.saturating_add(1) { + previous.msb = previous.msb.max(next.msb); + true + } else { + false + } + }); + const_vars.insert( + var.clone(), + ConstVar { + payload, + mask, + written, + }, + ); } + // All reads must be covered before removing a variable's dependency + // edges. A read can include undriven bits even above the highest driver, + // or a hole between drivers; those bits retain their initial state. + for node in arena.iter() { + if let SLTNode::Input { + variable, access, .. + } = node + && const_vars + .get(variable) + .is_some_and(|cv| !cv.covers(*access)) + { + const_vars.remove(variable); + } + } if const_vars.is_empty() { return Ok(false); } @@ -559,6 +604,99 @@ mod tests { use super::eval_const_expr; + #[test] + fn only_inlines_reads_covered_by_constant_drivers() { + use crate::{LogicPath, LogicPathTarget}; + use celox_design::{BitAccess, VarAtomBase}; + + for bridge_gap in [false, true] { + for access in [ + BitAccess::new(2, 3), + BitAccess::new(0, 3), + BitAccess::new(4, 7), + BitAccess::new(0, 7), + ] { + let mut arena = SLTNodeArena::::new(); + let one = arena + .alloc(SLTNode::Constant(1u8.into(), 0u8.into(), 1, false)) + .unwrap(); + let zero = arena + .alloc(SLTNode::Constant(0u8.into(), 0u8.into(), 1, false)) + .unwrap(); + let three = arena + .alloc(SLTNode::Constant(3u8.into(), 0u8.into(), 2, false)) + .unwrap(); + let make_path = |variable, access, expr, sources: crate::HashSet<_>| LogicPath { + transparent_copy: false, + target: LogicPathTarget::Var(VarAtomBase { + id: variable, + access, + }), + previous_sources: sources.clone(), + address_sources: sources.clone(), + sources, + local_inputs: vec![], + order_before: Default::default(), + comb_capture_enable_sites: vec![], + comb_capture_enable_always: false, + pre_lower_nodes: vec![], + expr, + }; + // Non-sorted fragments. Filling bit 1 makes 0..=3 contiguous, + // but never covers higher bits. Unobserved gaps do not stop + // reads confined to the driven bits from being inlined. + let mut paths = vec![ + make_path(1, BitAccess::new(2, 3), three, Default::default()), + make_path(1, BitAccess::new(0, 0), one, Default::default()), + ]; + if bridge_gap { + paths.push(make_path(1, BitAccess::new(1, 1), zero, Default::default())); + } + let input = arena + .alloc(SLTNode::Input { + variable: 1, + signed: false, + index: vec![], + access, + }) + .unwrap(); + let source = VarAtomBase { id: 1, access }; + paths.push(make_path( + 2, + BitAccess::new(0, access.msb - access.lsb), + input, + [source].into_iter().collect(), + )); + let inlined = access == BitAccess::new(2, 3) + || (access == BitAccess::new(0, 3) && bridge_gap); + assert_eq!( + super::inline_constant_variables(&mut paths, &mut arena).unwrap(), + inlined + ); + let path = paths.last().unwrap(); + if inlined { + let expected = if access.lsb == 2 { 3u8 } else { 13u8 }; + assert_eq!( + super::eval_const_expr(path.expr, &arena), + (expected.into(), 0u8.into(), access.msb - access.lsb + 1) + ); + } else { + assert_eq!( + path.expr, input, + "read of an undriven bit became a constant" + ); + } + for edges in [&path.sources, &path.previous_sources, &path.address_sources] { + assert_eq!( + edges.contains(&source), + !inlined, + "dependency of an unrewritten read was removed" + ); + } + } + } + } + #[test] fn floating_operations_fold_ieee_payloads_and_result_widths() { use celox_design::{BinaryOp, FloatBinaryOp, FloatPrecision, FloatUnaryOp}; diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index a523b192871..4057357db90 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -869,3 +869,15 @@ Verilator 5.052 records 2 passes, 3 mismatches, 3 compiler faults, and 1 unsupported four-state case; Icarus 13.0 records 9 compile errors. In the Reactive-wakeup case, xezim loses the matured Observed report, while Verilator also emits the Final report that the wait resumption must flush. + +### Z expressions inside exact comparisons in Verilator + +The `operators::two_state_case_equality_*` regressions keep runtime storage +two-state while testing literal X/Z in expressions (IEEE 1800-2023 11.4.5 +and 12.5; issue #2136). Icarus 13.0 passes all five cases. Verilator 5.052 +passes `keeps_call_effects_and_loaded_bytes`, but rejects the other four +with `Unsupported tristate construct` or `Unsupported: tristate in top-level IO`. +Their actual compile diagnostics are retained in +[the Verilator operators report](verification/sv/verilator/operators.json); +they remain executed cases rather than exclusions. Reproduce with +`verify-sv-verilator --filter two_state_case_equality --jobs 1`. diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index fceded314db..352e9b1e1dc 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1900,3 +1900,167 @@ endmodule (assert_eq a_count 1) (assert_eq b_count 1) (assert_eq y 0)) + +(case two_state_case_equality_preserves_unknown_literals + ; IEEE 1800-2023 11.4.5 and 12.5: X/Z participate in exact comparisons. + (source "two_state_case_literals.sv" #" + module Top(input bit clk, input bit [7:0] b, + output logic parity_x, reversed_x, exact_z, different_x, + output logic ordinary_case, output logic [3:0] registered, + output logic [7:0] guarded); + assign parity_x = ((^b) === 1'bx); + assign reversed_x = (1'bx === (^b)); + assign exact_z = (b === 8'b1001_011z); + assign different_x = (b !== 8'b1001_011x); + assign guarded = ((^b) === 1'bx) ? 8'b0 : b; + always_comb begin + case (b) + 8'b1001_011z: ordinary_case = 1; + default: ordinary_case = 0; + endcase + end + always_ff @(posedge clk) begin + registered[0] <= ((^b) === 1'bx); + registered[1] <= (b === 8'b1001_011x); + registered[2] <= (b !== 8'b1001_011z); + case (b) + 8'b1001_011x: registered[3] <= 1; + default: registered[3] <= 0; + endcase + end + endmodule + "#) + (top Top) + (set b 0x96) + (assert_eq parity_x 0) + (assert_eq reversed_x 0) + (assert_eq exact_z 0) + (assert_eq different_x 1) + (assert_eq ordinary_case 0) + (assert_eq guarded 0x96) + (tick clk) + (assert_eq registered 4) + (set b 0x97) + (assert_eq parity_x 0) + (assert_eq different_x 1) + (assert_eq guarded 0x97) + (tick clk) + (assert_eq registered 4) + (set b 0) + (assert_eq parity_x 0) + (assert_eq guarded 0)) + +(case two_state_case_equality_compares_literal_structure + (source "two_state_case_structure.sv" #" + module Top(input bit [7:0] b, input bit [128:0] wide, + output logic same_x, x_vs_z, mixed_equal, signed_x, signed_z, + output logic unsigned_x, wide_x, bit_cast); + function automatic bit to_bit(input logic value); return value; endfunction + assign same_x = ({b,1'bx} === {b,1'bx}); + assign x_vs_z = ({b,1'bx} === {b,1'bz}); + assign mixed_equal = ({b,1'bx} === {8'h96,1'bx}); + assign signed_x = (4'sbx001 === 8'sbxxxxx001); + assign signed_z = (4'sbz001 === 8'sbzzzzz001); + assign unsigned_x = (4'sbx001 === 8'bxxxxx001); + assign wide_x = (wide === {64'd0,1'bx,64'd0}); + assign bit_cast = (to_bit(1'bx) === 1'b0); + endmodule + "#) + (top Top) + (modify (set b 0x96) (set wide 0)) + (assert_eq same_x 1) + (assert_eq x_vs_z 0) + (assert_eq mixed_equal 1) + (assert_eq signed_x 1) + (assert_eq signed_z 1) + (assert_eq unsigned_x 0) + (assert_eq wide_x 0) + (assert_eq bit_cast 1) + (set b 0x97) + (assert_eq mixed_equal 0)) + +(case two_state_case_equality_preserves_conditional_unknowns + (source "two_state_case_mux.sv" #" + module Top(input bit s, output logic x_match, z_match, same_known, + output logic ordinary_case); + assign x_match = ((s ? 1'bx : 1'b0) === 1'bx); + assign z_match = ((s ? 1'bz : 1'b0) === 1'bz); + assign same_known = ((s ? 1'bx : 1'b0) === 1'b0); + always_comb begin + case (s ? 1'bz : 1'b0) + 1'bz: ordinary_case = 1; + default: ordinary_case = 0; + endcase + end + endmodule + "#) + (top Top) + (set s 0) + (assert_eq x_match 0) + (assert_eq z_match 0) + (assert_eq same_known 1) + (assert_eq ordinary_case 0) + (set s 1) + (assert_eq x_match 1) + (assert_eq z_match 1) + (assert_eq same_known 0) + (assert_eq ordinary_case 1)) + +(case two_state_case_equality_keeps_call_effects_and_loaded_bytes + (source "two_state_case_effects.sv" #" + module Top(input bit [7:0] b, output int calls, + output logic compared, selected, output logic [7:0] loaded); + function automatic logic [7:0] mark(); + calls = calls + 1; + return b; + endfunction + initial begin + calls = 0; + #1; + compared = (mark() === 8'b1001_011x); + case (mark()) + 8'b1001_011z: selected = 1; + default: selected = 0; + endcase + loaded = ((^b) === 1'bx) ? 8'b0 : b; + #1 $finish; + end + endmodule + "#) + (top Top) + (run_until 0) + (set b 0x96) + (run_until 1) + (assert_eq calls 2) + (assert_eq compared 0) + (assert_eq selected 0) + (assert_eq loaded 0x96) + (run_to_finish)) + +(case two_state_case_equality_keeps_unknown_expression_bits + (source "two_state_case_expression.sv" #" + module Top(input bit b, output logic [16:0] q); + assign q[0] = ((b & 1'bx) === 1'bx); + assign q[1] = ((b | 1'bx) === 1'bx); + assign q[2] = ((b ^ 1'bz) === 1'bx); + assign q[3] = ((b && 1'bx) === 1'bx); + assign q[4] = ((b || 1'bx) === 1'bx); + assign q[5] = (({b,b} + 2'b0x) === 2'bxx); + assign q[6] = (({b,b} >> 1'bx) === 2'bxx); + assign q[7] = ((^{b,1'bx}) === 1'bx); + assign q[8] = ((&{b,1'bx}) === 1'bx); + assign q[9] = ((|{b,1'bz}) === 1'bx); + assign q[10] = ((!{b,1'bz}) === 1'bx); + assign q[11] = ((~{b,1'bz}) === {~b,1'bx}); + assign q[12] = ((b == 1'bx) === 1'bx); + assign q[13] = (({b,1'b0} == {1'bx,1'b1}) === 1'b0); + assign q[14] = ((1'b1 / b) === 1'bx); + assign q[15] = ((1'bx ? {b,1'bz} : {b,1'bz}) === {b,1'bz}); + assign q[16] = ((1'bx ? b : ~b) === 1'bx); + endmodule + "#) + (top Top) + (set b 0) + (assert_eq q 0x1fef6) + (set b 1) + (assert_eq q 0x1b9ed)) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index fd791951f59..a99e9df55c4 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -322,6 +322,20 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { "compile", "packed array parameters are not supported yet", ), + ( + "verilator", + "operators::two_state_case_equality_compares_literal_structure" + | "operators::two_state_case_equality_preserves_conditional_unknowns" + | "operators::two_state_case_equality_keeps_unknown_expression_bits", + ) => ("compile_error", "compile", "Unsupported tristate construct"), + ( + "verilator", + "operators::two_state_case_equality_preserves_unknown_literals", + ) => ( + "compile_error", + "compile", + "Unsupported: tristate in top-level IO", + ), _ => panic!("unreviewed failure: {tool} {name}: {status}"), }; assert_eq!(status, expected_status, "{name}"); diff --git a/crates/celox-test-suite/verification/sv/verilator/operators.json b/crates/celox-test-suite/verification/sv/verilator/operators.json index a71785fcc6f..a9fd197737d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/operators.json +++ b/crates/celox-test-suite/verification/sv/verilator/operators.json @@ -386,6 +386,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHEXPAND: /source_0.sv:9:35: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbx001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 9 | assign signed_x = (4'sbx001 === 8'sbxxxxx001);\n | ^~~\n ... For warning description see https://verilator.org/warn/WIDTHEXPAND?v=5.052\n ... Use \"/* verilator lint_off WIDTHEXPAND */\" and lint_on around source to disable this message.\n%Warning-WIDTHEXPAND: /source_0.sv:10:35: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbz001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 10 | assign signed_z = (4'sbz001 === 8'sbzzzzz001);\n | ^~~\n%Warning-WIDTHEXPAND: /source_0.sv:11:37: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbx001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 11 | assign unsigned_x = (4'sbx001 === 8'bxxxxx001);\n | ^~~\n%Error-UNSUPPORTED: /source_0.sv:7:33: Unsupported tristate construct: EQCASE\n : ... note: In instance 'celox_suite_tb.dut'\n 7 | assign x_vs_z = ({b,1'bx} === {b,1'bz});\n | ^~~\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_compares_literal_structure", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:13:24: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's REPLICATE generates 2 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 13 | assign q[10] = ((!{b,1'bz}) === 1'bx);\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHTRUNC?v=5.052\n ... Use \"/* verilator lint_off WIDTHTRUNC */\" and lint_on around source to disable this message.\n%Error-UNSUPPORTED: /source_0.sv:5:25: Unsupported tristate construct: XOR\n : ... note: In instance 'celox_suite_tb.dut'\n 5 | assign q[2] = ((b ^ 1'bz) === 1'bx);\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error-UNSUPPORTED: /source_0.sv:14:24: Unsupported tristate construct: NOT\n : ... note: In instance 'celox_suite_tb.dut'\n 14 | assign q[11] = ((~{b,1'bz}) === {~b,1'bx});\n | ^\n%Error-UNSUPPORTED: /source_0.sv:18:52: Unsupported tristate construct: EQCASE\n : ... note: In instance 'celox_suite_tb.dut'\n 18 | assign q[15] = ((1'bx ? {b,1'bz} : {b,1'bz}) === {b,1'bz});\n | ^~~\n%Error: Exiting due to 3 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_keeps_unknown_expression_bits", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:5:28: Unsupported tristate construct: NOT\n : ... note: In instance 'celox_suite_tb.dut'\n 5 | assign z_match = ((s ? 1'bz : 1'b0) === 1'bz);\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error-UNSUPPORTED: /source_0.sv:8:17: Unsupported tristate construct (not in propagation graph): AND\n : ... note: In instance 'celox_suite_tb.dut'\n 8 | case (s ? 1'bz : 1'b0)\n | ^\n%Error-UNSUPPORTED: /source_0.sv:8:9: Unsupported tristate construct: CASE\n : ... note: In instance 'celox_suite_tb.dut'\n 8 | case (s ? 1'bz : 1'b0)\n | ^~~~\n%Error: Exiting due to 3 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_preserves_conditional_unknowns", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /testbench.sv:14:26: Unsupported: tristate in top-level IO: 'b'\n : ... note: In instance 'celox_suite_tb'\n 14 | Top dut (.clk(i_clk), .b(i_b), .parity_x(), .reversed_x(), .exact_z(), .different_x(), .ordinary_case(), .registered(), .guarded());\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_preserves_unknown_literals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Operators", "detail": "four-state expectations", diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 7be6789e3d7..ce52b3583be 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -205,4 +205,19 @@ sv_backends! { fn wide_reduction_and_respects_partial_storage_words(sim) { @case "operators::wide_reduction_and_respects_partial_storage_words"; } + fn two_state_case_equality_preserves_unknown_literals(sim) { + @case "operators::two_state_case_equality_preserves_unknown_literals"; + } + fn two_state_case_equality_compares_literal_structure(sim) { + @case "operators::two_state_case_equality_compares_literal_structure"; + } + fn two_state_case_equality_preserves_conditional_unknowns(sim) { + @case "operators::two_state_case_equality_preserves_conditional_unknowns"; + } + fn two_state_case_equality_keeps_call_effects_and_loaded_bytes(sim) { + @case "operators::two_state_case_equality_keeps_call_effects_and_loaded_bytes"; + } + fn two_state_case_equality_keeps_unknown_expression_bits(sim) { + @case "operators::two_state_case_equality_keeps_unknown_expression_bits"; + } } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 5c9d4afab27..687fd7cea73 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -838,11 +838,20 @@ fn initializes_partially_driven_internal_nets_to_z() { assign undriven_bits_are_z = (w[7:1] === 7'bzzzzzzz); endmodule "#; - let mut sim = - Simulator::from_sv_sources(vec![(source, Path::new("partial_internal_net.sv"))], "Top") - .build_cranelift() - .unwrap(); - assert_eq!(sim.get(sim.signal("undriven_bits_are_z")), 1u8.into()); + // Runtime storage retains X/Z only in four-state mode. Literal X/Z + // in exact comparisons remain distinct from zero in both modes. + for four_state in [false, true] { + let mut sim = + Simulator::from_sv_sources(vec![(source, Path::new("partial_internal_net.sv"))], "Top") + .four_state(four_state) + .build_cranelift() + .unwrap(); + assert_eq!( + sim.get_four_state(sim.signal("undriven_bits_are_z")), + (u8::from(four_state).into(), BigUint::default()), + "four_state={four_state}", + ); + } } #[test] @@ -893,11 +902,22 @@ fn initializes_shadowing_function_locals_to_unknown() { assign local_is_unknown = (f() === 1'bx); endmodule "#; - let mut sim = - Simulator::from_sv_sources(vec![(source, Path::new("function_local_shadow.sv"))], "Top") - .build_cranelift() - .unwrap(); - assert_eq!(sim.get(sim.signal("local_is_unknown")), 1u8.into()); + // Runtime storage retains X/Z only in four-state mode. Literal X/Z + // in exact comparisons remain distinct from zero in both modes. + for four_state in [false, true] { + let mut sim = Simulator::from_sv_sources( + vec![(source, Path::new("function_local_shadow.sv"))], + "Top", + ) + .four_state(four_state) + .build_cranelift() + .unwrap(); + assert_eq!( + sim.get_four_state(sim.signal("local_is_unknown")), + (u8::from(four_state).into(), BigUint::default()), + "four_state={four_state}", + ); + } } #[test] From 05cf8e292f2a684a0807da0b36e51e30de5a160f Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:05:26 +0900 Subject: [PATCH 6/7] refactor(native): support state-aware outlined kernel calls Add an internal image-local call ABI with a hidden state pointer, signed status propagation, and preservation of pinned host state. Treat these callees as opaque state effects in SIR memory passes and invalidate cached load origins across calls. Ordinary DPI imports keep their existing ABI. Validation: SIR, optimizer and x86 unit suites; native-call regressions cover zero, positive and negative status values, pinned R15/GS state, tick-loop state and live vector values. Memory regressions prevent forwarding or reloading overwritten state across a kernel call. Owning-crate clippy and formatting pass. Generated-kernel callers now require explicit complete callee arena bounds; emission without them is rejected. The direct emit_with_callees entry and X86BackendOptions::with_native_callees reserve the caller above every callee's full required_state_size, including nested reservations. Existing explicit arena placements remain supported by the prepared pipeline. A regression reproduced the review finding with two generated functions emitted at the same 4096-byte semantic state size: the caller's last seven spilled values became zero. The fixed test supplies the actual emitted callee extent. Three-level generated call regressions force spills at every level, cover R15/GS and tick-loop entry, propagate zero, positive and wide negative status values, and reject missing or overflowing arena bounds. All 623 x86 unit tests and owning-crate clippy pass. Change-Id: Ia444d9f7754e3f118e5a3945b32360c2acd7298d --- .../src/backend/native/emit.rs | 97 +++++- .../src/backend/native/emit/extern_call.rs | 26 +- .../src/backend/native/emit/pipeline.rs | 8 + .../backend/native/emit/tests/extern_calls.rs | 305 ++++++++++++++++++ .../src/backend/native/isel/slice.rs | 5 + .../src/backend/native/isel/tests/slice.rs | 8 +- .../src/backend/native/regalloc/assignment.rs | 10 +- crates/celox-backend-x86/src/lib.rs | 16 +- .../optimizer/passes/analysis/state_ssa.rs | 89 +++++ .../pass_eliminate_working_round_trip.rs | 13 + .../pass_global_store_load_forwarding.rs | 13 + .../memory/pass_store_load_forwarding.rs | 63 ++++ crates/celox-sir/src/extern_abi.rs | 15 + crates/celox-sir/src/verify.rs | 10 + 14 files changed, 661 insertions(+), 17 deletions(-) diff --git a/crates/celox-backend-x86/src/backend/native/emit.rs b/crates/celox-backend-x86/src/backend/native/emit.rs index 39a76440b4e..329e4c68f77 100644 --- a/crates/celox-backend-x86/src/backend/native/emit.rs +++ b/crates/celox-backend-x86/src/backend/native/emit.rs @@ -815,6 +815,32 @@ pub fn emit( ) } +/// Emit a caller with disjoint storage above every generated callee's arena. +/// Pass `required_state_size` from each reachable callee's `EmitResult`; +/// each callee must itself have been emitted with its own callees' extents. +/// `state_size` describes the common semantic state, not an arena reservation. +pub fn emit_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + callee_ends: &[usize], +) -> Result { + verify_emission_inputs(func, assignment, spill_frame_size, false)?; + let plan = SsaDestructionPlan::build(func, assignment)?; + plan.verify(func, assignment, spill_frame_size)?; + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + &plan, + false, + false, + callee_ends, + ) +} + /// Direct emitter tests do not carry a complete `MemoryLayout`. Place their /// native arena beyond every statically named SimState byte plus a guard so /// test-owned sentinel bytes cannot alias prologue/scratch storage. @@ -845,11 +871,12 @@ pub(crate) fn emit_with_plan( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, false)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -857,6 +884,7 @@ pub(crate) fn emit_with_plan( plan, false, false, + callee_ends, ) } @@ -865,12 +893,13 @@ fn emit_with_plan_tick_loop( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, check_runtime_events: bool, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, true)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -878,6 +907,7 @@ fn emit_with_plan_tick_loop( plan, true, check_runtime_events, + callee_ends, ) } @@ -1043,6 +1073,45 @@ fn emit_planned( tick_loop: bool, check_runtime_events: bool, ) -> Result { + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + plan, + tick_loop, + check_runtime_events, + &[], + ) +} + +/// Callee extents include their own recursively reserved callees. The state +/// pointer stays unchanged; only the caller's private arena is placed above +/// those complete extents. Merely using the same semantic state size for both +/// functions is not sufficient to isolate live spills and pinned saves. +fn emit_planned_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + plan: &SsaDestructionPlan, + tick_loop: bool, + check_runtime_events: bool, + callee_ends: &[usize], +) -> Result { + let has_kernels = func.blocks.iter().flat_map(|b| &b.insts).any(|inst| + matches!(inst, MInst::CallExtern { func, .. } if celox_sir::extern_abi::native_kernel_index(*func).is_some())); + if has_kernels && (callee_ends.is_empty() || callee_ends.contains(&0)) { + return Err(EmitInputError::new( + "EMIT.NATIVE_CALLEE_ARENA", + None, + None, + None, + "generated kernel calls require the callees' complete required_state_size extents", + ) + .into()); + } + let state_size = callee_ends.iter().copied().fold(state_size, usize::max); let mut uses_bmi2 = false; let mut uses_avx = false; let mut uses_popcnt = false; @@ -1297,6 +1366,30 @@ fn emit_planned( asm.jmp(epilogue_label)?; } } + MInst::CallExtern { func, arg_count } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + extern_call::emit_call_extern(&mut asm, *func, *arg_count)?; + // The call restored our state base and pinned registers. + // RAX still holds the complete signed callee status. + asm.test(rax, rax)?; + if tick_loop { + let mut success = asm.create_label(); + asm.jz(success)?; + // Match ReturnError's completed-tick accounting while + // retaining RAX for the common epilogue. + asm.movq(r10, xmm15)?; + asm.dec(r10)?; + asm.movq(xmm15, r10)?; + asm.jmp(epilogue_label)?; + asm.set_label(&mut success)?; + // A following MIR block may start here; code_asm + // cannot bind two labels to the same instruction. + asm.nop()?; + } else { + asm.jnz(epilogue_label)?; + } + } MInst::ReturnError { code } => { if tick_loop { asm.movq(rax, xmm15)?; diff --git a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs index 3c40c1e1030..35867c2a8a5 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs @@ -50,8 +50,10 @@ pub(super) fn set_call_area( } /// The XMM registers a call must save: pinned ones the callee may change. -fn saved_xmms(context: &EmissionContext) -> impl Iterator { - let saved = context.pinned_xmms & !C_PRESERVED_XMMS; +fn saved_xmms(context: &EmissionContext, native_kernel: bool) -> impl Iterator { + // Generated x86 functions use SysV on every host, including Windows. + let preserved = if native_kernel { 0 } else { C_PRESERVED_XMMS }; + let saved = context.pinned_xmms & !preserved; (0..16).filter(move |index| saved & (1 << index) != 0) } @@ -98,11 +100,12 @@ pub(super) fn emit_call_extern( let context = asm.context; let area = call_area(&context); let strategy = state_base_strategy(&context); + let kernel = celox_sir::extern_abi::native_kernel_index(func); // RBX is callee-saved in every C ABI and free here: it holds the state // pointer while the segment base belongs to C code. emit_state_base(asm, rbx)?; - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), xmm_register(index), @@ -119,14 +122,15 @@ pub(super) fn emit_call_extern( StateBaseStrategy::R15 => {} } - let (registers, shadow): (&[AsmRegister64], i32) = if cfg!(target_os = "windows") { - (&[rcx, rdx, r8, r9], 32) - } else { - (&[rdi, rsi, rdx, rcx, r8, r9], 0) - }; + let (registers, shadow): (&[AsmRegister64], i32) = + if cfg!(target_os = "windows") && kernel.is_none() { + (&[rcx, rdx, r8, r9], 32) + } else { + (&[rdi, rsi, rdx, rcx, r8, r9], 0) + }; // The heap helper takes the state pointer before the staged arguments. let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; - let leading = usize::from(heap); + let leading = usize::from(heap || kernel.is_some()); let arg_count = usize::from(arg_count) + leading; let stack_args = arg_count.saturating_sub(registers.len()) as i32; // Generated code is entered with RSP = 8 (mod 16) and never moves it. @@ -158,7 +162,7 @@ pub(super) fn emit_call_extern( } else if heap { -16 } else { - i32::try_from(u64::from(func) * 8).expect("extern function index") + i32::try_from(u64::from(kernel.unwrap_or(func)) * 8).expect("extern function index") }; asm.mov(rax, qword_ptr(rax + offset))?; asm.call(rax)?; @@ -170,7 +174,7 @@ pub(super) fn emit_call_extern( StateBaseStrategy::Gs => asm.wrgsbase(rbx)?, StateBaseStrategy::R15 => {} } - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( xmm_register(index), qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), diff --git a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs index 73fc6a8af8c..92855fcad1b 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs @@ -336,12 +336,19 @@ fn emit_prepared_eu_inner( let state_size = options .arena_base .map_or(semantic_size, |base| base.max(semantic_size)); + let native_callee_end = [options.arena_base.unwrap_or(0)]; + let callee_ends = if options.arena_base.is_some() { + &native_callee_end[..] + } else { + &[] + }; let result = if label == "eval_comb_apply_ff" && options.native_tick_loop { emit_with_plan_tick_loop( &mfunc, &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, check_runtime_events, )? @@ -351,6 +358,7 @@ fn emit_prepared_eu_inner( &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, )? }; diff --git a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs index 94d09772410..93aa15c764e 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs @@ -172,3 +172,308 @@ fn extern_calls_preserve_live_values_with_a_segment_state_base() { run(StateBaseStrategy::Gs, false); run(StateBaseStrategy::Gs, true); } + +/// The implicit state argument and signed status must survive ABI register +/// clobbers, spills across the call, and both state-base strategies. +extern "sysv64" fn kernel_with_status(state: *mut u8) -> i64 { + let _ = trashing_weighted_sum(1, 2, 3, 4, 5, 6, 7, 8); + // SAFETY: the generated caller passes this test's complete state buffer. + unsafe { *state.add(RESULT + 16).cast::() } +} + +#[test] +fn native_kernel_calls_preserve_live_values_and_propagate_signed_status() { + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + let mut function = live_across_calls(strategy); + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG; + *arg_count = 0; + } + } + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let emitted = emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + RESULT + 24, + &plan, + tick_loop, + false, + &[RESULT + 24], // This Rust ABI surrogate uses no private native arena. + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let table = [kernel_with_status as *const () as usize]; + let event_sequence = 0u64; + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut memory = vec![0u64; emitted.required_state_size as usize / 8 + 1]; + memory[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + memory[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&event_sequence as *const u64) as u64; + memory[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + memory[(RESULT + 16) / 8] = status as u64; + let values = (1..=LIVE as u64).collect::>(); + memory[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&values); + let calls = CALLS.get(); + assert_eq!(unsafe { (jit.fn_ptr)(memory.as_mut_ptr().cast()) }, status); + assert_eq!(CALLS.get() - calls, if status == 0 { 2 } else { 1 }); + if status == 0 { + assert_eq!(&memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &values); + } else { + assert!( + memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE] + .iter() + .all(|&v| v == 0) + ); + } + } + } + } +} + +fn generated_kernel( + strategy: StateBaseStrategy, + input_base: usize, + callee: Option, +) -> MFunction { + let mut function = live_across_calls(strategy); + for inst in &mut function.blocks[0].insts { + if let MInst::Load { offset, .. } = inst { + *offset += input_base as i32 - BASE as i32; + } + } + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + match callee { + Some(callee) => { + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | callee; + *arg_count = 0; + } + } + } + None => { + instructions.retain(|inst| !matches!(inst, MInst::CallExtern { .. })); + for inst in instructions.iter_mut() { + if let MInst::ExternResult { dst } = inst { + *inst = MInst::LoadImm { + dst: *dst, + value: 0, + }; + } + } + // Prevent memory-backed reload recipes: each loaded value must + // survive an overwrite of its source before it is published. + let position = instructions + .iter() + .position(|inst| matches!(inst, MInst::LoadImm { .. })) + .unwrap(); + let MInst::LoadImm { dst: zero, .. } = instructions[position] else { + unreachable!() + }; + instructions.splice( + position + 1..position + 1, + (0..LIVE).map(|index| MInst::Store { + base: BaseReg::SimState, + offset: (input_base + index * 8) as i32, + src: zero, + size: OpSize::S64, + }), + ); + } + } + function +} + +#[test] +fn generated_callee_spills_do_not_overwrite_live_caller_values() { + const STATE_SIZE: usize = 4096; + let mut child = generated_kernel(StateBaseStrategy::R15, 1024, None); + let allocation = regalloc::run_regalloc(&mut child).unwrap(); + assert!(allocation.spill_frame_size > 0, "callee must really spill"); + let plan = SsaDestructionPlan::build(&child, &allocation.assignment).unwrap(); + let child_code = emit_planned( + &child, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &plan, + false, + false, + ) + .unwrap(); + let child_jit = JitCode::new(&child_code.code).unwrap(); + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "caller must retain real spilled values" + ); + assert!( + matches!(emit(&caller, &allocation.assignment, allocation.spill_frame_size), + Err(EmitError::Input(ref error)) if error.rule == "EMIT.NATIVE_CALLEE_ARENA") + ); + let caller_code = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &[child_code.required_state_size as usize], + ) + .unwrap(); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [child_jit.fn_ptr as usize]; + let mut state = vec![ + 0u64; + caller_code + .required_state_size + .max(child_code.required_state_size) as usize + / 8 + + 1 + ]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!(unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, 0); + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); +} + +fn compile_generated( + mut function: MFunction, + state_size: usize, + callees: &[usize], + tick_loop: bool, +) -> EmitResult { + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "every generated level must really spill" + ); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let options = crate::X86BackendOptions::default().with_native_callees(callees.iter().copied()); + let bounds = options.arena_base.into_iter().collect::>(); + emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + state_size, + &plan, + tick_loop, + false, + &bounds, + ) + .unwrap() +} + +#[test] +fn nested_generated_kernels_have_disjoint_arenas_and_propagate_status() { + const STATE_SIZE: usize = 4096; + const COMPLETED: usize = 2048; + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut leaf = generated_kernel(strategy, 1024, None); + if status != 0 { + *leaf.blocks[0].insts.last_mut().unwrap() = MInst::ReturnError { code: status }; + } + let leaf_code = compile_generated(leaf, STATE_SIZE, &[], false); + let leaf_jit = JitCode::new(&leaf_code.code).unwrap(); + let middle = generated_kernel(strategy, 512, Some(0)); + let middle_code = compile_generated( + middle, + STATE_SIZE, + &[leaf_code.required_state_size as usize], + false, + ); + let middle_jit = JitCode::new(&middle_code.code).unwrap(); + let mut caller = generated_kernel(strategy, BASE, Some(1)); + let marker = caller.vregs.alloc(); + caller.spill_descs.push(SpillDesc::remat(0x51)); + let instructions = &mut caller.blocks[0].insts; + let end = instructions.len() - 1; + instructions.splice( + end..end, + [ + MInst::LoadImm { + dst: marker, + value: 0x51, + }, + MInst::Store { + base: BaseReg::SimState, + offset: COMPLETED as i32, + src: marker, + size: OpSize::S64, + }, + ], + ); + let caller_code = compile_generated( + caller, + STATE_SIZE, + &[middle_code.required_state_size as usize], + tick_loop, + ); + assert!(middle_code.required_state_size > leaf_code.required_state_size); + assert!(caller_code.required_state_size > middle_code.required_state_size); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [leaf_jit.fn_ptr as usize, middle_jit.fn_ptr as usize]; + let mut state = vec![0u64; caller_code.required_state_size as usize / 8 + 1]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let sequence = 0u64; + state[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&sequence as *const u64) as u64; + state[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[512 / 8 + i] = 1000 + i as u64; + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!( + unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, + status, + "{strategy:?}, tick={tick_loop}" + ); + assert_eq!(state[COMPLETED / 8], if status == 0 { 0x51 } else { 0 }); + if status == 0 { + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); + } + } + } + } +} + +#[test] +fn generated_callee_arena_overflow_is_rejected() { + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + let result = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + 4096, + &[usize::MAX], + ); + assert!( + matches!(result, Err(EmitError::Input(ref error)) if error.rule=="EMIT.NATIVE_ARENA_RANGE") + ); +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/slice.rs index 3f9787c512a..4e96c282003 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/slice.rs @@ -7,6 +7,11 @@ impl ISelContext<'_> { &mut self, inst: &SIRInstruction, ) { + if matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + { + self.reg_addrs.clear(); + } if let Some(write) = inst.memory_write() && write.width != 0 { diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs index 116d86e88b2..591039fb94c 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs @@ -140,8 +140,14 @@ fn slice_preserves_loaded_value_across_store() { ); } if overlapping { - // Dynamic stores and commits also invalidate a static load. + // Dynamic stores, commits and opaque kernels invalidate + // a static load before any direct slice reload. for write in [ + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: vec![], + }, SIRInstruction::Store( input, SIROffset::Dynamic(replacement), diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs index cc6c401f0bd..e376073f7f8 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs @@ -98,8 +98,7 @@ pub const ALLOCATABLE_REGS: &[PhysReg] = &[ /// The registers an extern call changes: those a C function need not /// preserve, and RBX, which holds the state pointer during the call sequence. -#[cfg(not(target_os = "windows"))] -const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ +const NATIVE_KERNEL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, PhysReg::RCX, PhysReg::RDX, @@ -111,6 +110,8 @@ const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::R11, PhysReg::RBX, ]; +#[cfg(not(target_os = "windows"))] +const EXTERN_CALL_CLOBBERS: &[PhysReg] = NATIVE_KERNEL_CLOBBERS; #[cfg(target_os = "windows")] const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, @@ -223,6 +224,11 @@ pub fn clobbers(inst: &MInst) -> &'static [PhysReg] { // Return. Model the clobber at the allocation boundary instead so // only genuinely live-through values are moved to their homes. MInst::SparseCommitWorklist { .. } => ALLOCATABLE_REGS, + MInst::CallExtern { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + NATIVE_KERNEL_CLOBBERS + } MInst::CallExtern { .. } => EXTERN_CALL_CLOBBERS, _ => &[], } diff --git a/crates/celox-backend-x86/src/lib.rs b/crates/celox-backend-x86/src/lib.rs index 6d35faf9394..91afba2f67c 100644 --- a/crates/celox-backend-x86/src/lib.rs +++ b/crates/celox-backend-x86/src/lib.rs @@ -59,11 +59,25 @@ pub struct X86BackendOptions { pub native_tick_loop: bool, /// Physical state offset where the function's private spill, scratch, /// and save arena begins. `None` places it directly after the semantic - /// state. Functions that may run concurrently need disjoint arenas. + /// state. Functions that may run concurrently or call generated kernels + /// need disjoint arenas. Kernel callers must reserve at least every + /// callee's complete `required_state_size`; use `with_native_callees`. pub arena_base: Option, pub diagnostics: NativeDiagnostics, } +impl X86BackendOptions { + /// Place this function's private arena above all generated callees. + /// Sizes must be their complete emitted `required_state_size`, including + /// reservations for nested callees, rather than the semantic state size. + pub fn with_native_callees(mut self, sizes: impl IntoIterator) -> Self { + if let Some(end) = sizes.into_iter().max() { + self.arena_base = Some(self.arena_base.map_or(end, |base| base.max(end))); + } + self + } +} + impl Default for X86BackendOptions { fn default() -> Self { Self { diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs index b776566c169..6eb245ae5be 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs @@ -578,6 +578,29 @@ impl StateSsa { for (instruction_index, instruction) in block.instructions.iter().enumerate() { let mut instruction_effects = InstructionEffects::default(); match instruction { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + // An outlined native callee observes the old state and + // may replace every slot, including pending FF state. + for (slot, fact) in facts.iter_mut().enumerate() { + fact.escapes = true; + fact.has_kill = true; + fact.def_blocks.insert(block_id); + if !defined.contains(&slot) { + fact.upward_use_blocks.insert(block_id); + } + defined.insert(slot); + instruction_effects.uses.push(UseEffect { + slot, + destination: None, + }); + instruction_effects.defs.push(DefEffect { + slot, + kind: DefEffectKind::Kill, + }); + } + } SIRInstruction::Load(destination, addr, offset, width) if addr.region == region => { @@ -1314,6 +1337,72 @@ mod tests { .expect("destination has a StateSSA use") } + #[test] + fn native_kernel_call_observes_and_kills_every_state_region() { + for region in [STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION] { + let addr = address(region, 0); + let eu = unit( + vec![block( + 0, + vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(3u8)), + SIRInstruction::Store( + addr, + SIROffset::Static(0), + 8, + RegisterId(0), + Vec::new(), + Vec::new(), + ), + SIRInstruction::Load(RegisterId(1), addr, SIROffset::Static(0), 8), + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }, + SIRInstruction::Load(RegisterId(2), addr, SIROffset::Static(0), 8), + ], + SIRTerminator::Return, + )], + (0..3).map(|i| (RegisterId(i), bit(8))), + ); + eu.verify_result().unwrap(); + let cfg = SirCfg::analyze(&eu).unwrap(); + let state = StateSsa::analyze_all_loads(&eu, &cfg, region).unwrap(); + let MemoryAccessKind::Use { + reaching: before, .. + } = use_access(&state, RegisterId(1)).kind + else { + panic!("load") + }; + let MemoryAccessKind::Use { + reaching: after, .. + } = use_access(&state, RegisterId(2)).kind + else { + panic!("load") + }; + assert_ne!(before, after); + assert!(matches!( + state.accesses[after.0].kind, + MemoryAccessKind::Kill { .. } + )); + assert!(state.slots[0].escapes && state.slots[0].has_kill); + assert!( + state + .accesses + .iter() + .any(|access| access.instruction == Some(3) + && matches!( + access.kind, + MemoryAccessKind::Use { + destination: None, + .. + } + )) + ); + } + } + #[test] fn version_snapshots_preserve_versions_across_multiple_checkpoints() { let stable = address(STABLE_REGION, 0); 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 066d74dd102..5f020e0d092 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 @@ -29,6 +29,19 @@ pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit, partial: bool) { use crate::HashMap; + // An image-local callee can observe or publish any working slot. Its + // contents are outside this function's proof of independent publication. + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + return; + } // Phase 1: Scan — collect info about each WORKING variable struct VarInfo { diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs index 53d462dd880..7036ac44bc9 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs @@ -865,6 +865,19 @@ pub(crate) fn promote_eval_apply_working_round_trips_with_mode( eu: &mut ExecutionUnit, two_state: bool, ) -> bool { + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + // The callee can consume pending values or publish working state. + // Keep this function's memory form until StateSSA models that callee. + return false; + } let Ok(cfg) = SirCfg::analyze(eu) else { return false; }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs index b9254cab4e3..7379d0dc3f1 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs @@ -140,6 +140,11 @@ fn forward_and_simplify( // are always inserted after this rewrite, so one lookup is sufficient. apply_aliases_to_inst(inst, &aliases); match inst { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + known_stores.clear(); + } SIRInstruction::Store(addr, offset, width, src, _triggers, _) if offset.constant_bit_offset().is_some() => { @@ -469,6 +474,64 @@ mod tests { } } + #[test] + fn native_kernel_call_invalidates_prior_state_stores() { + let mut builder = celox_sir::SIRBuilder::new(); + let before = builder.alloc_bit(8, false); + let after = builder.alloc_bit(8, false); + builder.emit(SIRInstruction::Imm(before, SIRValue::new(42u8))); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(0), + 8, + before, + Vec::new(), + Vec::new(), + )); + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }); + builder.emit(SIRInstruction::Load( + after, + address(), + SIROffset::Static(0), + 8, + )); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(8), + 8, + after, + Vec::new(), + Vec::new(), + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + StoreLoadForwardingPass.run(&mut unit, &PassOptions::default()); + unit.verify_result().unwrap(); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .any(|inst| matches!(inst, SIRInstruction::Load(dst, ..) if *dst == after)) + ); + let saved = unit.clone(); + super::super::pass_eliminate_working_round_trip::eliminate_working_round_trip( + &mut unit, + &[], + ); + assert_eq!(unit.blocks, saved.blocks); + assert!(!super::super::pass_global_store_load_forwarding::promote_eval_apply_working_round_trips(&mut unit)); + assert_eq!(unit.blocks, saved.blocks); + } + #[test] fn removes_deep_dead_producer_chain_and_preserves_live_store() { let mut instructions = vec![ diff --git a/crates/celox-sir/src/extern_abi.rs b/crates/celox-sir/src/extern_abi.rs index 8956d1f4b86..61474070b68 100644 --- a/crates/celox-sir/src/extern_abi.rs +++ b/crates/celox-sir/src/extern_abi.rs @@ -17,6 +17,21 @@ use crate::RegisterType; /// user extern function table. pub const HEAP_HELPER_ID: u32 = u32::MAX - 1; +/// Native-only call to another compiled function in the same image. The low +/// 30 bits index the extern address table. It takes the implicit state pointer, +/// no explicit arguments or result, and propagates a nonzero status to its +/// caller. The callee may read and write arbitrary simulation state. +pub const NATIVE_KERNEL_CALL_TAG: u32 = 0x8000_0000; + +/// Decode a native kernel call, excluding the heap and floating-point helpers. +pub const fn native_kernel_index(function: u32) -> Option { + if function & 0xc000_0000 == NATIVE_KERNEL_CALL_TAG { + Some(function & 0x3fff_ffff) + } else { + None + } +} + /// The number of arguments of an extern call to [`HEAP_HELPER_ID`]. pub const HEAP_HELPER_ARGUMENTS: usize = 4; diff --git a/crates/celox-sir/src/verify.rs b/crates/celox-sir/src/verify.rs index b5d4acd8c0d..82d442b791a 100644 --- a/crates/celox-sir/src/verify.rs +++ b/crates/celox-sir/src/verify.rs @@ -632,6 +632,16 @@ fn verify_instruction_types( same_width(*old, *new, "TYPE.CAPTURE_COMPARE_OPERANDS")?; } SIRInstruction::ExternCall { dst, func, args } => { + if crate::extern_abi::native_kernel_index(*func).is_some() + && (dst.is_some() || !args.is_empty()) + { + return Err(SirVerifyError::instruction( + "TYPE.NATIVE_KERNEL_CALL_SIGNATURE", + block, + index, + "a native kernel call has only an implicit state pointer", + )); + } if *func == crate::extern_abi::HEAP_HELPER_ID && args.len() != crate::extern_abi::HEAP_HELPER_ARGUMENTS { From 37e28d66ef095bedb0560fb1358828e2f54b028c Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 18:55:06 +0900 Subject: [PATCH 7/7] ci: protect Rust test caches from release target churn Rust Tests lost its 2 GB cache while multi-target NAPI release caches occupied about 6.2 GiB of repository cache storage. The same restore key hit at 07:47 UTC and missed at 08:46 UTC; compilation grew from 12m35s to 31m20s while test execution remained roughly 14 minutes. Keep only downloaded Cargo dependencies for NAPI publication, share the cache across targets, and save only on the default branch to avoid develop duplicates. Use a new prefix so old compiled-target caches cannot be restored under the download-only policy. Release builds trade compiled-dependency reuse for preserving pull-request CI capacity. Run the existing dependency warmer hourly as well as on dependency changes and manual dispatch. Eviction alone changes no Cargo files, so the previous path-filtered trigger could not recover the missing cache. Exact hits still skip all compilation; warming never executes the test suite. Preserve trusted default-branch checks and existing Rust Tests cache keys. Validation: 38 CI workflow/classifier tests pass, both workflow YAML files parse successfully, and diff checks pass. Regression coverage enforces download-only release caching, default-branch-only writes, scheduled recovery and hit-gated builds. Change-Id: I39b2469c2fece08abdd5cfc4d2738411605b98f7 --- .github/workflows/ci-napi.yml | 14 ++++++++------ .github/workflows/rust-cache.yml | 6 +++++- scripts/ci-workflow.test.mjs | 26 ++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci-napi.yml b/.github/workflows/ci-napi.yml index 76645afad97..947190c258c 100644 --- a/.github/workflows/ci-napi.yml +++ b/.github/workflows/ci-napi.yml @@ -185,13 +185,15 @@ jobs: - uses: Swatinem/rust-cache@v2 with: - # Keep compiled dependencies, but start a separate publication cache. - prefix-key: celox-napi-release-v1 - shared-key: napi-${{ matrix.target }} - # Reinstall Cargo tools instead of restoring executable binaries. + # Release target matrices previously consumed most of the repository + # quota and evicted the shared Rust Tests cache. Share downloads only; + # never retain target/ artifacts for each release target and lane. + prefix-key: celox-napi-downloads-v1 + shared-key: napi-downloads + cache-targets: false cache-bin: false - # Tag/ad-hoc branch runs may restore, but only release lanes populate it. - save-if: ${{ (github.event_name == 'repository_dispatch' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop')) }} + # All lanes can restore the default-branch cache. Avoid develop copies. + save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - name: Install ziglang (musl targets) if: matrix.zigbuild diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index b60213d58e9..43539a20be3 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -1,7 +1,8 @@ name: Warm Rust dependency cache # PR merge-ref caches cannot be reused by other PRs. Populate the default -# branch cache once per toolchain/dependency key, without running tests twice. +# branch cache on dependency changes and periodically repair eviction. Cache hits +# skip compilation, and warming never executes the test suite. on: push: branches: [master] @@ -14,6 +15,9 @@ on: - ".github/workflows/rust-cache.yml" - ".github/workflows/ci.yml" - "scripts/run-vtest.mjs" + # Eviction does not change Cargo files, so push path filters cannot repair it. + schedule: + - cron: "17 * * * *" workflow_dispatch: permissions: diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index ce4381e8131..e18b2ef2713 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -578,3 +578,29 @@ test("sv-tests generates the pinned main corpus before running and retains its s assert.ok(sv.indexOf("conformance/sv-tests/prepare.py") < sv.indexOf("conformance/sv-tests/run.py")); assert.match(sv, /sv-tests-report\.summary\.json/); }); + + +test("release builds share download-only caches and cannot retain target matrices", () => { + const release = readFileSync(new URL("../.github/workflows/ci-napi.yml", import.meta.url), "utf8"); + const caches = [...release.matchAll(/ - uses: Swatinem\/rust-cache@v2\n([\s\S]*?)(?=\n -|$)/g)]; + assert.equal(caches.length, 1); + const cache = caches[0][1]; + assert.match(cache, /prefix-key: celox-napi-downloads-v1/); + assert.match(cache, /shared-key: napi-downloads/); + assert.match(cache, /cache-targets: false/); + assert.match(cache, /cache-bin: false/); + assert.match(cache, /save-if: \$\{\{ github.ref == format\('refs\/heads\/\{0\}', github.event.repository.default_branch\) \}\}/); + assert.doesNotMatch(cache, /matrix.target|refs\/heads\/develop/); +}); + +test("evicted default-branch dependency caches recover without dependency changes", () => { + const warm = readFileSync(new URL("../.github/workflows/rust-cache.yml", import.meta.url), "utf8"); + assert.match(warm, /schedule:\n - cron: "17 \* \* \* \*"/); + assert.match(warm, /workflow_dispatch:/); + for (const id of ["rust-tests", "rust-default-tests", "napi-windows"]) { + const block = warm.split(` ${id}:\n`)[1].split(/\n [a-z][a-z-]*:/)[0]; + assert.match(block, /if: github.ref == format\('refs\/heads\/\{0\}', github.event.repository.default_branch\)/); + assert.match(block, /if: steps.cache.outputs.cache-hit != 'true'/); + } + assert.doesNotMatch(warm, /pull_request_target:|workflow_run:/); +});