From a1ff9d5b757cec0b199651b93040a4d7f5c13f32 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 13:01:06 +0900 Subject: [PATCH 1/3] fix(sv): preserve inherited constants in parameter alias evaluation Taxi DMA address masks lost their initializers when their replication counts used local aliases of interface parameters. Prefix evaluation only saw locally collected numbers, so it could not resolve an alias of an inherited constant even though that constant was available for declaration lowering. Seed a separate incremental evaluation environment with inherited values and types, masking names owned by the current scope before rebinding the local prefix. Preserve imported X/Z literals and use the existing initializer shape context for constant binding. Retain the separate range projection and update only each declaration's binding keys. Add shared coverage for package aliases, wide replication masks, generate scopes, signedness and X/Z. Extend the existing interface specialization case with the same mask pattern. Structural checks at 16, 64 and 256 declarations verify one binding per declaration and no per-declaration range-environment copies. Validation: - Shared SV suite: 3297 passed, 90 existing ignores across backend variants. - SV analyzer: 772 passed, 3 existing ignores; project CLI: 17 passed. - Verilator passes the numeric package case and extended interface case; its adapter does not support the four-state case. Icarus passes both package cases; its existing interface-port exclusion is retained. - Affected-crate all-target Clippy, formatting and diff checks pass. - Original Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1 at O1, cocotb 2.0.1, seed 12345: AXI CDMA [8-0] passes all 4 tests and AXI DMA [0-8] passes all 8 tests. Sources and upstream parameters are unchanged; this does not cover every DMA configuration. Change-Id: Id0a3d57a401cd41a228a26cd9a256b9b12e8884f --- .../celox-sv-analyzer/src/ast/declarations.rs | 8 +- crates/celox-sv-analyzer/src/ast/generate.rs | 5 ++ .../celox-sv-analyzer/src/ast/parameters.rs | 74 +++++++++++++++--- .../src/ast/parameters/ownership.rs | 28 +++++++ .../src/ast/parameters/tests.rs | 78 +++++++++++++++++-- .../src/sv/cases/interfaces.vtest | 4 +- .../celox-test-suite/src/sv/cases/types.vtest | 54 +++++++++++++ .../tests/frontends/systemverilog/types.rs | 9 +++ 8 files changed, 243 insertions(+), 17 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index e983092529e..82e85341f73 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -160,8 +160,12 @@ pub(super) fn parameters_from_scope( parameter_overrides: &HashMap, ) -> Result, AnalyzerError> { let mut parameters = Vec::new(); - let mut environment = - parameters::ParameterEnvironment::new(&syntax_tree.state, ¶meters, base_const_env); + let mut environment = parameters::ParameterEnvironment::new( + &syntax_tree.state, + ¶meters, + base_const_env, + ¶meters::ownership::scope_names(syntax_tree)?, + ); let header = syntax_tree .scope_handle() .unit(syntax_tree.declarations()) diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index d2ebefd8a09..bade7219443 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -1066,6 +1066,11 @@ impl<'a> Elaborator<'a, '_> { &self.tree.state, &scope.parameters, &base, + &pending + .iter() + .flatten() + .map(|(name, _, _, _)| name.clone()) + .collect::>(), ); let mut types = parameter_types_from_const_env(&base); let mut next = index; diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 77f6b969d1d..acb4accd989 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -149,7 +149,15 @@ pub(super) fn parameters_from_native( type_aliases: &HashMap, parameter_overrides: &HashMap, ) -> Result<(), AnalyzerError> { - let mut environment = ParameterEnvironment::new(&syntax_tree.state, parameters, base_const_env); + let mut environment = ParameterEnvironment::new( + &syntax_tree.state, + parameters, + base_const_env, + &authored + .iter() + .map(|parameter| instances::normalize_identifier(¶meter.name.spelling)) + .collect::>(), + ); parameters_from_native_with_environment( authored, syntax_tree, @@ -168,6 +176,9 @@ pub(super) fn parameters_from_native( pub(super) struct ParameterEnvironment<'a> { base: &'a HashMap, values: HashMap, + // Evaluation sees inherited constants except declarations of this scope. + // Keep it incremental, while `values` remains the local prefix projection. + bindings: HashMap, types: HashMap, constants: HashMap, // Only a nonnumeric prefix binding with an inherited numeric value makes @@ -184,12 +195,42 @@ impl<'a> ParameterEnvironment<'a> { state: &AnalysisState, parameters: &[Parameter], base: &'a HashMap, + shadowed: &[String], ) -> Self { + let shadowed: HashSet<&str> = shadowed + .iter() + .map(String::as_str) + .chain(parameters.iter().map(Parameter::name)) + .collect(); + let mut bindings = base.clone(); + for name in &shadowed { + for key in binding_keys(name, &bindings, 0) { + bindings.remove(&key); + } + } let mut values = HashMap::default(); - let mut types = HashMap::default(); - let mut literals = HashMap::default(); + let mut types = parameter_types_from_const_env(&bindings); + let mut literals = scope::imported(state) + .parameter_values + .iter() + .filter(|(name, value)| { + let mut literal = *value; + while let Expr::Resize { expr, .. } = literal { + literal = expr; + } + matches!(literal, Expr::Literal(_)) + && !bindings.contains_key(*name) + && !shadowed.contains(name.as_str()) + }) + .map(|(name, value)| (name.clone(), value.clone())) + .collect(); for parameter in parameters { - bind_parameter(state, &mut values, &mut types, &mut literals, parameter); + bind_parameter(state, &mut bindings, &mut types, &mut literals, parameter); + for key in binding_keys(parameter.name(), &bindings, parameter.packed_ranges.len()) { + if let Some(value) = bindings.get(&key) { + values.insert(key, *value); + } + } } let mut constants = base.clone(); let has_inherited_literal_shadow = parameters.iter().any(|parameter| { @@ -204,6 +245,7 @@ impl<'a> ParameterEnvironment<'a> { Self { base, values, + bindings, types, constants, has_inherited_literal_shadow, @@ -214,11 +256,27 @@ impl<'a> ParameterEnvironment<'a> { fn append(&mut self, state: &AnalysisState, parameter: &Parameter) { let bound = bind_parameter( state, - &mut self.values, + &mut self.bindings, &mut self.types, &mut self.literals, parameter, ); + for key in binding_keys( + parameter.name(), + &self.values, + parameter.packed_ranges.len(), + ) { + self.values.remove(&key); + } + for key in binding_keys( + parameter.name(), + &self.bindings, + parameter.packed_ranges.len(), + ) { + if let Some(value) = self.bindings.get(&key) { + self.values.insert(key, *value); + } + } for key in binding_keys( parameter.name(), &self.constants, @@ -422,14 +480,12 @@ pub(super) fn parameters_from_native_with_environment( Err(_) => None, } } else { - constant_binding::expression( + constant_binding::bind( ownership::default(native).ok_or_else(|| { AnalyzerError::Parse("native parameter default is missing".into()) })?, - syntax_tree.declarations(), syntax_tree, - const_env, - type_aliases, + &proof_context, )? } } else { diff --git a/crates/celox-sv-analyzer/src/ast/parameters/ownership.rs b/crates/celox-sv-analyzer/src/ast/parameters/ownership.rs index b4f374e1a5f..b8d46cc92ac 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/ownership.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/ownership.rs @@ -26,3 +26,31 @@ pub(in crate::ast) fn body(id: BodyItemId, tree: &SyntaxTree) -> Converted Converted> { + let mut names = Vec::new(); + if let Some(unit) = tree.scope_handle().unit(tree.declarations()) { + names.extend( + unit.parameters + .iter() + .flatten() + .filter(|parameter| matches!(parameter.kind, ParameterKind::Value { .. })) + .map(|parameter| instances::normalize_identifier(¶meter.name.spelling)), + ); + } + for id in tree.body_membership()? { + if matches!( + tree.declarations().body_item(id).kind, + BodyItemKind::Parameter(_) + ) { + names.extend( + body(id, tree)? + .iter() + .map(|parameter| instances::normalize_identifier(¶meter.name.spelling)), + ); + } + } + Ok(names) +} diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index 3ea1ba6bf94..eb7f60a7c83 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -400,10 +400,10 @@ fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() let overrides = HashMap::from_iter([("N".into(), ConstExpr::Literal(n.to_string()))]); let mut borrowed = Vec::new(); let mut copied = Vec::new(); - let mut borrowed_env = ParameterEnvironment::new(state, &borrowed, &base); + let mut borrowed_env = ParameterEnvironment::new(state, &borrowed, &base, &[]); // The same contents at a different address deliberately select the // former copy-and-mask path, providing an independent width context. - let mut copied_env = ParameterEnvironment::new(state, &copied, &copied_base); + let mut copied_env = ParameterEnvironment::new(state, &copied, &copied_base, &[]); DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); for id in tree.body_membership().unwrap() { if !matches!( @@ -534,8 +534,8 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha let copied_base = base.clone(); let mut borrowed = Vec::new(); let mut copied = Vec::new(); - let mut borrowed_env = ParameterEnvironment::new(state, &borrowed, &base); - let mut copied_env = ParameterEnvironment::new(state, &copied, &copied_base); + let mut borrowed_env = ParameterEnvironment::new(state, &borrowed, &base, &[]); + let mut copied_env = ParameterEnvironment::new(state, &copied, &copied_base, &[]); for id in tree.body_membership().unwrap() { if !matches!( tree.declarations().body_item(id).kind, @@ -565,7 +565,7 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha &mut copied_env, ) .unwrap(); - let rebuilt = ParameterEnvironment::new(state, &borrowed, &base); + let rebuilt = ParameterEnvironment::new(state, &borrowed, &base, &[]); assert_eq!( borrowed_env.has_inherited_literal_shadow, rebuilt.has_inherited_literal_shadow @@ -1416,3 +1416,71 @@ fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() } } } + +#[test] +fn inherited_alias_prefixes_bind_once_without_copying_declaration_environments() { + for count in [16, 64, 256] { + let mut code = String::from("module Top;\n"); + for index in 0..count { + writeln!(code, "localparam logic [31:0] A{index}=EXTERNAL + {index};").unwrap(); + } + code.push_str("endmodule"); + let tree = crate::source_tree::parse_scope_fixture(&code, Path::new("inherited_prefix.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let mut base = HashMap::from_iter([("EXTERNAL".into(), 16)]); + insert_parameter_type_markers( + &mut base, + "EXTERNAL", + ExprType { + width: 32, + signed: false, + }, + ); + PARAMETER_BINDINGS.with(|count| count.set(0)); + DECLARATION_ENV_COPIES.with(|count| count.set(0)); + let parameters = + parameters_from_scope(&tree, &HashMap::default(), &base, &HashMap::default()).unwrap(); + assert_eq!(PARAMETER_BINDINGS.with(|count| count.get()), count); + assert_eq!(DECLARATION_ENV_COPIES.with(|count| count.get()), 0); + for (index, parameter) in parameters.iter().enumerate() { + assert_eq!( + parameter.resolved_value( + &tree.state, + &base, + ¶meter_types_from_const_env(&base) + ), + Some(16 + index as i128) + ); + } + } +} + +#[test] +fn inherited_evaluation_masks_pending_local_names_and_their_type_markers() { + let mut base = HashMap::from_iter([("EXTERNAL".into(), 8), ("LOCAL".into(), 99)]); + insert_parameter_type_markers( + &mut base, + "LOCAL", + ExprType { + width: 4, + signed: false, + }, + ); + let state = AnalysisState::default(); + let mut environment = + ParameterEnvironment::new(&state, &[], &base, &["LOCAL".into(), "ALIAS".into()]); + let alias = Parameter::new( + "ALIAS".into(), + Some(ConstExpr::Ident("LOCAL".into())), + None, + None, + false, + false, + true, + ); + environment.append(&state, &alias); + assert!(!environment.values.contains_key("ALIAS")); + assert!(!environment.types.contains_key("LOCAL")); + assert_eq!(environment.bindings.get("EXTERNAL"), Some(&8)); +} diff --git a/crates/celox-test-suite/src/sv/cases/interfaces.vtest b/crates/celox-test-suite/src/sv/cases/interfaces.vtest index 44f83a53f50..3e0b40af11b 100644 --- a/crates/celox-test-suite/src/sv/cases/interfaces.vtest +++ b/crates/celox-test-suite/src/sv/cases/interfaces.vtest @@ -38,9 +38,11 @@ assign bus.data = v[$bits(bus.data)-1:0]; endmodule module Reader(Bus.r bus, output logic [15:0] o); + localparam WIDTH = bus.W; + localparam MASK = {WIDTH{1'b1}}; always_comb begin o = '0; - o[$bits(bus.data)-1:0] = bus.data; + o[$bits(bus.data)-1:0] = bus.data & MASK; end endmodule module Top(input logic [15:0] v, output logic [15:0] o12, output logic [15:0] o4); diff --git a/crates/celox-test-suite/src/sv/cases/types.vtest b/crates/celox-test-suite/src/sv/cases/types.vtest index 36039be5839..ebeb518f33f 100644 --- a/crates/celox-test-suite/src/sv/cases/types.vtest +++ b/crates/celox-test-suite/src/sv/cases/types.vtest @@ -354,3 +354,57 @@ (assert_eq large_count 6) (assert_eq small_left 0) (assert_eq large_right 5)) + +(case inherited_parameter_aliases_materialize_replication_masks + (source "inherited_replication.sv" #" + package Config; + parameter W = 58; + endpackage + module Top(input logic [63:0] data, output logic [63:0] y, generated, procedural); + import Config::*; + localparam WIDTH = W; + localparam MASK = {WIDTH{1'b1}} << 3; + always_comb y = data & MASK; + always_comb begin + localparam COPY_W = WIDTH, LOCAL_MASK = {COPY_W{1'b1}}; + procedural = data & LOCAL_MASK; + end + if (1) begin : g + localparam COPY_W = WIDTH; + localparam G_MASK = {COPY_W{1'b1}}; + assign generated = data & G_MASK; + end + endmodule + "#) + (top Top) + (for value (list 0 0xffffffffffffffff 0x0123456789abcdef) + (modify (set data value)) + (assert_eq y (& value 0x3fffffffffffff8)) + (assert_eq generated (& value 0x3ffffffffffffff)) + (assert_eq procedural (& value 0x3ffffffffffffff)))) + +(case inherited_parameter_aliases_preserve_types_and_unknowns + (four_state) + (source "inherited_parameter_types.sv" #" + package Config; + parameter logic signed [7:0] NEG = -1; + parameter logic [7:0] UNSIGNED = 8'h80; + parameter logic [3:0] UNKNOWN = 4'bx; + parameter logic [3:0] HIGH_Z = 4'bz; + endpackage + module Top(output logic matched); + import Config::*; + localparam SIGNED_ALIAS = NEG; + localparam UNSIGNED_ALIAS = UNSIGNED; + localparam X_ALIAS = UNKNOWN; + localparam Z_ALIAS = HIGH_Z; + localparam XX = {2{X_ALIAS}}; + localparam ZZ = {2{Z_ALIAS}}; + assign matched = (SIGNED_ALIAS < 0) && ($bits(SIGNED_ALIAS) == 8) + && ((SIGNED_ALIAS >>> 1) == -1) && ((UNSIGNED_ALIAS >>> 1) == 8'h40) + && (XX === 8'bx) && (ZZ === 8'bz); + endmodule + "#) + (top Top) + (eval) + (assert_eq matched 1)) diff --git a/crates/celox/tests/frontends/systemverilog/types.rs b/crates/celox/tests/frontends/systemverilog/types.rs index 1de590fbf14..c9aa52725b6 100644 --- a/crates/celox/tests/frontends/systemverilog/types.rs +++ b/crates/celox/tests/frontends/systemverilog/types.rs @@ -1,3 +1,12 @@ +sv_backends! { + fn inherited_parameter_aliases_materialize_replication_masks(sim) { + @case "types::inherited_parameter_aliases_materialize_replication_masks"; + } + fn inherited_parameter_aliases_preserve_types_and_unknowns(sim) { + @case "types::inherited_parameter_aliases_preserve_types_and_unknowns"; + } +} + sv_backends! { fn constant_functions_in_unpacked_port_dimensions(sim) { @case "types::constant_functions_in_unpacked_port_dimensions"; From ed3261e3964814caf1018232c77a0153e58e0b65 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:13:59 +0900 Subject: [PATCH 2/3] feat(testbench)!: keep strings in a heap referenced from state memory Testbench string variables now hold 32-bit handles into a per-simulator heap instead of keys into a side table. This is the first step of the shared string/class runtime design (#1400): one heap, handles that stay position independent, and a collector whose roots are the typed handle slots of state memory. - Add `celox-heap`: interned, immutable strings, so equal contents have equal handles and stores, commits, change detection and `==` stay integer operations. Handle 0 is `""`, the value of zero-initialized memory. A mark-sweep collection frees strings no root refers to. - Record each state object's value kind in `VariableMetadata`. Veryl `string` elements become 32-bit two-state handle slots. - The testbench VM loads and stores handles in those slots. Collections run between sequential statements and between concurrent process polls, with the saved temporaries of suspended processes as extra roots. This also gives each process its own string temporaries, which the old side table shared. - Checkpoints keep the heap. State files record referenced strings by contents in a new strings section and re-intern them on load, so they no longer reject testbench strings and stay portable between builds. - VCD output leaves handle slots out until strings have a waveform representation. BREAKING CHANGE: `celox_testbench::TestbenchStrings` and `CompiledExpr::eval_with_strings` are removed; evaluate with `CompiledExpr::eval_with_heap` and a `celox_heap::Heap`. State files that contain strings set a new flag and are not readable by older builds. Refs #1400 Change-Id: Idff2d83dfd8e9a4e706f73087b77d6292a1b990a --- Cargo.lock | 9 + Cargo.toml | 2 + crates/celox-design/src/lib.rs | 26 +++ crates/celox-frontend-core/src/sdk.rs | 2 + crates/celox-frontend-core/src/watch.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-frontend-veryl/src/artifact.rs | 5 + .../src/lowering/bitaccess.rs | 5 +- .../src/lowering/types.rs | 11 +- crates/celox-frontend-veryl/src/testbench.rs | 3 +- crates/celox-heap/Cargo.toml | 16 ++ crates/celox-heap/src/lib.rs | 217 ++++++++++++++++++ crates/celox-runtime/src/state_file.rs | 40 ++++ crates/celox-testbench/Cargo.toml | 1 + crates/celox-testbench/src/lib.rs | 7 +- crates/celox-testbench/src/vm.rs | 66 ++++-- crates/celox-vpi/src/bin/celox.rs | 1 + crates/celox/Cargo.toml | 1 + crates/celox/src/simulator.rs | 21 +- crates/celox/src/simulator/checkpoint.rs | 9 +- crates/celox/src/simulator/heap.rs | 73 ++++++ crates/celox/src/simulator/state_file.rs | 94 ++++++-- crates/celox/src/testbench.rs | 65 ++++-- crates/celox/tests/testbench_string.rs | 159 ++++++++++++- crates/lydite-celox/src/tests.rs | 1 + .../tests/fixtures/array_read_write2.json | 2 +- docs/internals/compiler-crate-architecture.md | 1 + scripts/publish-crates.sh | 1 + 28 files changed, 771 insertions(+), 69 deletions(-) create mode 100644 crates/celox-heap/Cargo.toml create mode 100644 crates/celox-heap/src/lib.rs create mode 100644 crates/celox/src/simulator/heap.rs diff --git a/Cargo.lock b/Cargo.lock index d76de844ab8..9638a70c314 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -404,6 +404,7 @@ dependencies = [ "celox-frontend-sdk", "celox-frontend-sv", "celox-frontend-veryl", + "celox-heap", "celox-macros", "celox-runtime", "celox-sir", @@ -648,6 +649,13 @@ dependencies = [ "veryl-parser", ] +[[package]] +name = "celox-heap" +version = "0.11.0" +dependencies = [ + "fxhash", +] + [[package]] name = "celox-macros" version = "0.11.0" @@ -800,6 +808,7 @@ name = "celox-testbench" version = "0.11.0" dependencies = [ "celox-design", + "celox-heap", "num-bigint", "num-traits", "serde", diff --git a/Cargo.toml b/Cargo.toml index 853335b6b46..76c0db9690d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "crates/celox-frontend-sdk", "crates/celox-frontend-sv", "crates/celox-frontend-veryl", + "crates/celox-heap", "crates/celox-sir", "crates/celox-sir-opt", "crates/celox-slt", @@ -65,6 +66,7 @@ celox-frontend-core = { version = "=0.11.0", path = "crates/celox-frontend-c celox-frontend-sdk = { version = "=0.11.0", path = "crates/celox-frontend-sdk" } # x-release-please-version celox-frontend-sv = { version = "=0.11.0", path = "crates/celox-frontend-sv" } # x-release-please-version celox-frontend-veryl = { version = "=0.11.0", path = "crates/celox-frontend-veryl" } # x-release-please-version +celox-heap = { version = "=0.11.0", path = "crates/celox-heap" } # x-release-please-version celox-macros = { version = "=0.11.0", path = "crates/celox-macros" } # x-release-please-version celox-napi = { version = "=0.11.0", path = "crates/celox-napi" } # x-release-please-version celox-runtime = { version = "=0.11.0", path = "crates/celox-runtime" } # x-release-please-version diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7fcb09250fb..3345562329c 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -54,6 +54,28 @@ pub struct VariableMetadata { /// Per-dimension sizes for array ports (for example, `[4]` for `logic<32>[4]`). /// Empty means scalar. pub array_dims: Vec, + /// What each element holds. Handle elements are 32-bit two-state slots. + #[serde(default)] + pub value_kind: ValueKind, +} + +/// Bit width of a handle element in state memory. +pub const HANDLE_WIDTH: usize = 32; + +/// What a state element holds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ValueKind { + /// Packed bits. + #[default] + Bits, + /// A handle of a string in the simulator's heap. + StrRef, +} + +impl ValueKind { + pub fn is_handle(self) -> bool { + self != Self::Bits + } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -1534,6 +1556,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: vec![4], + value_kind: Default::default(), }; assert_eq!(metadata.width, 32); @@ -1551,6 +1574,7 @@ mod tests { kind: DomainKind::ClockPosedge, type_kind: PortTypeKind::Clock, array_dims: Vec::new(), + value_kind: Default::default(), }, ); design.events.aliases.insert(11, 10); @@ -1579,6 +1603,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } @@ -1611,6 +1636,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index c5056045cb6..d965bf15485 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1058,6 +1058,7 @@ impl HiddenObjects<'_> { PortTypeKind::Bit }, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![width], @@ -1817,6 +1818,7 @@ pub fn lower_frontend_artifact( kind, type_kind, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![signal.value_type().width()], diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index ce6ca4bf68e..8884c591f01 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -475,6 +475,7 @@ pub fn declare_counter_slots( kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![EVENT_COUNTER_WIDTH], diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0bc6ac9085b..15472a5a829 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -93,6 +93,7 @@ impl SvVariable { kind: self.domain_kind, type_kind: self.type_kind, array_dims: self.array_dims.clone(), + value_kind: Default::default(), }, unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 572c817eb7a..a990dca5cad 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -444,6 +444,11 @@ pub(crate) fn project_module_with_ids( .iter() .filter_map(|value| *value) .collect(), + value_kind: if variable.r#type.is_string() { + celox_design::ValueKind::StrRef + } else { + celox_design::ValueKind::Bits + }, }, packed_dims, unpacked_ranges: Vec::new(), diff --git a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs index 3f6ee374de7..50e53826b44 100644 --- a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs +++ b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs @@ -228,7 +228,10 @@ fn collect_dims(module: &Module, var_id: VarId) -> Result, ParserErro // Enums and aggregates encode their packed width in TypeKind rather // than the width Shape. Even a one-bit struct/union needs that dimension: // Veryl represents member access as a select into the packed aggregate. - if width.is_empty() { + if var_type.is_string() { + // A string element is a handle into the simulator's heap. + dims.push(celox_design::HANDLE_WIDTH); + } else if width.is_empty() { if let Some(kind_width) = var_type.kind.width() && (kind_width > 1 || (kind_width == 1 && var_type.is_struct_union())) { diff --git a/crates/celox-frontend-veryl/src/lowering/types.rs b/crates/celox-frontend-veryl/src/lowering/types.rs index 78134de525d..562cc3527cb 100644 --- a/crates/celox-frontend-veryl/src/lowering/types.rs +++ b/crates/celox-frontend-veryl/src/lowering/types.rs @@ -4,9 +4,14 @@ use crate::ParserError; /// Resolve the total storage size of a variable. pub fn resolve_total_width(module: &Module, variable: &Variable) -> Result { - let width = variable.total_width().ok_or_else(|| { - ParserError::unresolved_width(module, variable, variable.r#type.to_string()) - })?; + // A string element is a handle into the simulator's heap. + let width = if variable.r#type.is_string() { + celox_design::HANDLE_WIDTH + } else { + variable.total_width().ok_or_else(|| { + ParserError::unresolved_width(module, variable, variable.r#type.to_string()) + })? + }; let array = variable.r#type.total_array().ok_or_else(|| { ParserError::unresolved_width(module, variable, variable.r#type.to_string()) })?; diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index b427e7f8268..11a0b377b6e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -1556,7 +1556,7 @@ impl ExprCompiler<'_> { } ops.push(TbOpcode::LoadString { location: Self::state_location_at(address, 0), - elements: info.width, + elements: info.width / celox_design::HANDLE_WIDTH, }); } @@ -3922,6 +3922,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, }; diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml new file mode 100644 index 00000000000..477e1d8a232 --- /dev/null +++ b/crates/celox-heap/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "celox-heap" +version.workspace = true +publish = ["crates-io"] +authors.workspace = true +repository.workspace = true +license.workspace = true +description = "Runtime heap of dynamic values referenced by handles in Celox state" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +fxhash = { workspace = true } + +[lints] +workspace = true diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs new file mode 100644 index 00000000000..d52b3b146d9 --- /dev/null +++ b/crates/celox-heap/src/lib.rs @@ -0,0 +1,217 @@ +//! The runtime heap of a simulator. +//! +//! Dynamic values live here and state memory refers to them by 32-bit +//! handles, never by address, so state images stay position independent. +//! Strings are interned and immutable: equal contents have equal handles, so +//! stores, commits, change detection and `==` compare handles as integers. +//! +//! References from state memory are not counted. A collection marks the +//! entries reachable from the handles the caller passes as roots and frees +//! the rest; callers collect only where every copy of a handle is in a place +//! they can enumerate. + +use std::sync::Arc; + +use fxhash::FxHashMap as HashMap; + +/// A reference to a heap entry, as stored in state memory. +pub type Handle = u32; + +/// Byte width of a handle slot in state memory. +pub const HANDLE_BYTES: usize = 4; + +/// The handle of `""`, the value of zero-initialized state memory. +pub const EMPTY_STRING: Handle = 0; + +/// Entries created since the last collection before another one is due, +/// unless the live set is larger. +const MIN_COLLECTION_INTERVAL: usize = 1024; + +/// Dynamic strings referenced by [`Handle`]. +#[derive(Clone, Debug)] +pub struct Heap { + strings: Vec>>, + lookup: HashMap, Handle>, + free: Vec, + /// Entries below this handle are never collected. + pinned: usize, + created: usize, + live_after_collection: usize, +} + +impl Default for Heap { + fn default() -> Self { + Self::new() + } +} + +impl Heap { + pub fn new() -> Self { + let empty: Arc<[u8]> = Arc::from(&[][..]); + let mut lookup = HashMap::default(); + lookup.insert(empty.clone(), EMPTY_STRING); + Self { + strings: vec![Some(empty)], + lookup, + free: Vec::new(), + pinned: 1, + created: 0, + live_after_collection: 1, + } + } + + /// The handle of the string `bytes`, creating it if needed. NUL bytes are + /// removed first, as assigning a literal to a string does (IEEE 1800-2023 + /// 6.16). + pub fn intern(&mut self, bytes: &[u8]) -> Handle { + if bytes.contains(&0) { + let stripped: Vec = bytes.iter().copied().filter(|&byte| byte != 0).collect(); + return self.intern_stripped(&stripped); + } + self.intern_stripped(bytes) + } + + fn intern_stripped(&mut self, bytes: &[u8]) -> Handle { + if let Some(&handle) = self.lookup.get(bytes) { + return handle; + } + let value: Arc<[u8]> = Arc::from(bytes); + let handle = match self.free.pop() { + Some(handle) => { + self.strings[handle as usize] = Some(value.clone()); + handle + } + None => { + let handle = Handle::try_from(self.strings.len()) + .expect("the heap has more strings than handles can name"); + self.strings.push(Some(value.clone())); + handle + } + }; + self.lookup.insert(value, handle); + self.created += 1; + handle + } + + /// The contents of `handle`. A handle that names no string reads as `""`, + /// so a value written into a handle slot by the host cannot crash a read. + pub fn string(&self, handle: Handle) -> &[u8] { + self.strings + .get(handle as usize) + .and_then(Option::as_deref) + .unwrap_or_default() + } + + /// Whether `handle` names a live string. + pub fn contains(&self, handle: Handle) -> bool { + self.strings + .get(handle as usize) + .is_some_and(Option::is_some) + } + + /// The number of live strings, including `""`. + pub fn len(&self) -> usize { + self.strings.len() - self.free.len() + } + + pub fn is_empty(&self) -> bool { + false + } + + /// Bytes of string contents, excluding allocator overhead. + pub fn content_size(&self) -> usize { + self.strings.iter().flatten().map(|value| value.len()).sum() + } + + /// Whether enough entries were created since the last collection to make + /// another worthwhile. The interval grows with the live set, so the cost + /// of collecting stays proportional to the allocation that triggered it. + pub fn should_collect(&self) -> bool { + self.created >= MIN_COLLECTION_INTERVAL.max(self.live_after_collection) + } + + /// Free every unpinned entry that no handle in `roots` refers to. Roots + /// that name no entry are ignored. + pub fn collect(&mut self, roots: impl IntoIterator) { + let mut marked = vec![false; self.strings.len()]; + marked[..self.pinned].fill(true); + for root in roots { + if let Some(mark) = marked.get_mut(root as usize) { + *mark = true; + } + } + for (handle, live) in marked.into_iter().enumerate() { + if live { + continue; + } + if let Some(value) = self.strings[handle].take() { + self.lookup.remove(&value); + self.free.push(handle as Handle); + } + } + self.created = 0; + self.live_after_collection = self.len(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interning_gives_equal_contents_equal_handles() { + let mut heap = Heap::new(); + let a = heap.intern(b"abc"); + assert_eq!(heap.intern(b"abc"), a); + assert_ne!(heap.intern(b"abd"), a); + assert_eq!(heap.intern(b""), EMPTY_STRING); + assert_eq!(heap.string(a), b"abc"); + } + + #[test] + fn nul_bytes_are_removed() { + let mut heap = Heap::new(); + let a = heap.intern(b"a\0b\0"); + assert_eq!(heap.string(a), b"ab"); + assert_eq!(heap.intern(b"ab"), a); + assert_eq!(heap.intern(b"\0\0"), EMPTY_STRING); + } + + #[test] + fn unknown_handles_read_as_empty() { + let heap = Heap::new(); + assert_eq!(heap.string(12345), b""); + assert!(!heap.contains(12345)); + } + + #[test] + fn collection_frees_unreachable_strings_and_reuses_handles() { + let mut heap = Heap::new(); + let kept = heap.intern(b"kept"); + let dropped = heap.intern(b"dropped"); + heap.collect([kept, 999]); + assert_eq!(heap.string(kept), b"kept"); + assert!(!heap.contains(dropped)); + assert!(heap.contains(EMPTY_STRING)); + // A freed handle is reused, and its old contents are gone from the + // intern table. + let again = heap.intern(b"new"); + assert_eq!(again, dropped); + assert_eq!(heap.string(again), b"new"); + assert_ne!(heap.intern(b"dropped"), kept); + } + + #[test] + fn collection_is_due_after_enough_allocation() { + let mut heap = Heap::new(); + for index in 0..MIN_COLLECTION_INTERVAL - 1 { + heap.intern(index.to_string().as_bytes()); + } + assert!(!heap.should_collect()); + heap.intern(b"one more"); + assert!(heap.should_collect()); + heap.collect([]); + assert!(!heap.should_collect()); + assert_eq!(heap.len(), 1); + } +} diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index a377679d3ba..98c61ea0cf8 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -34,11 +34,16 @@ //! counted count u32, then per signal: signal str | 3 × counter u32 //! write count u32, then per host write: signal str | value bytes | mask bytes //! host pending u8 | finished u8 +//! strings (only with FLAG_STRINGS): count u32, then per string: bytes //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 //! bytes: byte length u32 | little-endian bytes //! ``` //! +//! The value of a string object is one little-endian u32 per element: 0 for +//! `""`, otherwise one more than the index of its contents in the strings +//! section. Files without strings keep the earlier encoding. +//! //! Version 1 files, which have no process section, still load. A file whose //! processes have nothing to record is written as version 1, which older //! builds read too. @@ -52,6 +57,8 @@ const FLAG_SCHEDULE: u16 = 1 << 1; /// The schedule lists events whose signal was x or z. Set only when there are /// any, so other files keep their earlier encoding. const FLAG_UNKNOWN_EVENTS: u16 = 1 << 2; +/// String objects refer to a strings section after the schedule. +const FLAG_STRINGS: u16 = 1 << 3; /// How a state object gets its value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -175,6 +182,8 @@ pub struct StateFile { pub four_state: bool, pub objects: Vec, pub schedule: Option, + /// Contents of the strings that string objects refer to. + pub strings: Vec>, } /// A state file that could not be read. @@ -225,6 +234,9 @@ impl StateFile { flags |= FLAG_UNKNOWN_EVENTS; } } + if !self.strings.is_empty() { + flags |= FLAG_STRINGS; + } put_u16(w, flags)?; put_len(w, self.objects.len())?; for object in &self.objects { @@ -276,6 +288,12 @@ impl StateFile { put_processes(w, processes)?; } } + if !self.strings.is_empty() { + put_len(w, self.strings.len())?; + for string in &self.strings { + put_bytes(w, string)?; + } + } Ok(()) } @@ -364,6 +382,13 @@ impl StateFile { } else { None }; + let strings = if flags & FLAG_STRINGS != 0 { + (0..get_u32(r)?) + .map(|_| get_len_bytes(r)) + .collect::>()? + } else { + Vec::new() + }; let mut rest = [0; 1]; if r.read(&mut rest)? != 0 { return Err(StateFileError::Malformed( @@ -374,6 +399,7 @@ impl StateFile { four_state, objects, schedule, + strings, }) } @@ -741,9 +767,23 @@ mod tests { finished: false, }, }), + strings: Vec::new(), } } + #[test] + fn strings_round_trip_after_the_schedule() { + let mut file = sample(); + file.strings = vec![b"abc".to_vec(), Vec::new(), b"\xff".to_vec()]; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + file.schedule = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + #[test] fn files_without_process_state_are_version_1() { let mut file = sample(); diff --git a/crates/celox-testbench/Cargo.toml b/crates/celox-testbench/Cargo.toml index 2c373de4040..866bf086d7d 100644 --- a/crates/celox-testbench/Cargo.toml +++ b/crates/celox-testbench/Cargo.toml @@ -11,6 +11,7 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-heap = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } serde = { workspace = true } diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 5d5c95342a1..24217b7e149 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -16,9 +16,6 @@ pub use format::{ }; pub use vm::{CompiledExpr, TestbenchValue}; -/// Dynamic string values, addressed by a bound variable and flattened array index. -pub type TestbenchStrings = std::collections::BTreeMap<(usize, usize), Vec>; - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { pub address: A, @@ -521,10 +518,14 @@ pub enum ExprOpcode { byte_size: usize, }, ConstString(Vec), + /// Pop the bit offset of a string element within the variable at + /// `location`, which holds `elements` heap handles, and push its contents. + /// An offset past the last element reads `""`. LoadString { location: L, elements: usize, }, + /// Pop a string and store its heap handle at `location`. StoreString { location: L, }, diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs index 3bba0da9720..fcd6d4e0444 100644 --- a/crates/celox-testbench/src/vm.rs +++ b/crates/celox-testbench/src/vm.rs @@ -110,15 +110,16 @@ impl CompiledExpr { memory: *mut u8, on_write: impl FnMut(usize, usize), ) -> TestbenchValue { - self.eval_with_strings(memory, &mut crate::TestbenchStrings::new(), on_write) + self.eval_with_heap(memory, None, on_write) } - /// Evaluate using the simulator-owned string storage. Values are copied on - /// load so assigning another variable cannot alias a mutable string. - pub fn eval_with_strings( + /// Evaluate with the simulator's heap, which string variables refer to. + /// Without a heap, string variables read as `""` and string stores are + /// dropped instead of writing a handle no heap knows. + pub fn eval_with_heap( &self, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + mut heap: Option<&mut celox_heap::Heap>, mut on_write: impl FnMut(usize, usize), ) -> TestbenchValue { let mut stack: Vec = Vec::with_capacity(16); @@ -126,7 +127,7 @@ impl CompiledExpr { let ops = self.bytecode.ops(); while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, strings, &mut on_write); + self.exec_at(ops, &mut pc, &mut stack, memory, &mut heap, &mut on_write); } stack.pop().unwrap_or_else(|| { debug_assert!(false, "testbench bytecode: stack empty after evaluation"); @@ -143,7 +144,7 @@ impl CompiledExpr { pc: &mut usize, stack: &mut Vec, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + heap: &mut Option<&mut celox_heap::Heap>, on_write: &mut impl FnMut(usize, usize), ) { match &ops[*pc] { @@ -152,14 +153,17 @@ impl CompiledExpr { *pc += 1; } TbOpcode::LoadString { location, elements } => { - let index = stack.pop().expect("string index").to_u64() as usize; - let value = if index < *elements { - strings - .get(&(*location, index)) - .cloned() - .unwrap_or_default() - } else { - Vec::new() + let index = stack.pop().expect("string element offset").to_u64() as usize + / celox_design::HANDLE_WIDTH; + let value = match heap { + Some(heap) if index < *elements => { + let offset = location + index * celox_heap::HANDLE_BYTES; + // SAFETY: bound bytecode addresses a handle slot of + // `elements` handles in this memory image. + let handle = unsafe { read_handle(memory, offset) }; + heap.string(handle).to_vec() + } + _ => Vec::new(), }; stack.push(TestbenchValue::String(value)); *pc += 1; @@ -168,7 +172,19 @@ impl CompiledExpr { let TestbenchValue::String(value) = stack.pop().expect("string store value") else { unreachable!("string store requires a string value"); }; - strings.insert((*location, 0), value); + if let Some(heap) = heap { + let handle = heap.intern(&value); + // SAFETY: bound bytecode addresses a handle slot in this + // memory image. + unsafe { + std::ptr::copy_nonoverlapping( + handle.to_le_bytes().as_ptr(), + memory.add(*location), + celox_heap::HANDLE_BYTES, + ); + } + on_write(*location, celox_heap::HANDLE_BYTES); + } *pc += 1; } TbOpcode::ConstU64(v) => { @@ -326,14 +342,14 @@ impl CompiledExpr { if !cond.is_zero() { let then_end = *pc + then_len; while *pc < then_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } *pc += else_len; // skip else block } else { *pc += then_len; // skip then block let else_end = *pc + else_len; while *pc < else_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } } } @@ -998,6 +1014,20 @@ fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { } } +/// Read the handle stored at `offset`. +/// +/// # Safety +/// +/// `memory + offset` must be valid for reading a handle. +unsafe fn read_handle(memory: *const u8, offset: usize) -> celox_heap::Handle { + let mut bytes = [0; celox_heap::HANDLE_BYTES]; + // SAFETY: guaranteed by the caller. + unsafe { + std::ptr::copy_nonoverlapping(memory.add(offset), bytes.as_mut_ptr(), bytes.len()); + } + celox_heap::Handle::from_le_bytes(bytes) +} + #[cfg(test)] mod float_tests { use super::*; diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 399a7fd538a..78161e8e44f 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -943,6 +943,7 @@ mod tests { object("next", StateRole::Comb, stale, 0), ], schedule: None, + strings: Vec::new(), } } diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index bddbd054b93..2a6c3e241dc 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -52,6 +52,7 @@ celox-sir-opt = { workspace = true, default-features = false } celox-slt = { workspace = true } celox-state-layout = { workspace = true } celox-runtime = { workspace = true } +celox-heap = { workspace = true } celox-testbench = { workspace = true } fxhash = { workspace = true } thiserror = { workspace = true } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d415dda73ab..fe8c8da2eb5 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2,6 +2,8 @@ mod builder; #[cfg(feature = "host-runtime")] mod checkpoint; mod error; +#[cfg(feature = "host-runtime")] +mod heap; #[cfg(feature = "systemverilog")] pub(crate) mod mixed; #[cfg(feature = "host-runtime")] @@ -114,8 +116,10 @@ mod host { /// cross-codegen builds or unsupported hosts. pub struct Simulator { pub(crate) backend: B, - /// Dynamic testbench strings, keyed by the bound variable location. - pub(crate) testbench_strings: celox_testbench::TestbenchStrings, + /// Dynamic values that handle slots in state memory refer to. + pub(crate) heap: celox_heap::Heap, + /// Byte offsets of every handle slot in state memory. + pub(super) handle_slots: std::sync::OnceLock>, file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, @@ -819,7 +823,8 @@ mod host { sv_vcd: SvVcdControl::default(), dirty: false, warnings, - testbench_strings: Default::default(), + heap: Default::default(), + handle_slots: Default::default(), file_io: Default::default(), pending_host_events: Default::default(), components: Default::default(), @@ -2154,6 +2159,16 @@ mod host { .iter() .filter_map(|address| self.program.design.variable(address)) .filter(|variable| instance.resolves_path_to(&variable.path, variable.address)) + // A handle slot holds a heap reference, not a value to + // show; strings have no VCD representation yet. + .filter(|variable| { + !self + .program + .design + .state_objects + .get(&variable.address) + .is_some_and(|metadata| metadata.value_kind.is_handle()) + }) .collect(); sorted_vars.sort_by(|a, b| a.path.cmp(&b.path)); diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index b5a16a235a5..e3de65e94e6 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -92,7 +92,7 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - testbench_strings: celox_testbench::TestbenchStrings, + heap: celox_heap::Heap, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. @@ -102,7 +102,7 @@ pub struct Checkpoint { impl Checkpoint { /// Bytes in the saved memory image and string contents, excluding allocator overhead. pub fn state_size(&self) -> usize { - self.image.len() + self.testbench_strings.values().map(Vec::len).sum::() + self.image.len() + self.heap.content_size() } } @@ -159,7 +159,7 @@ impl Simulator { } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), - testbench_strings: self.testbench_strings.clone(), + heap: self.heap.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, frozen: self.frozen, @@ -179,8 +179,7 @@ impl Simulator { checkpoint .image .restore_into(&mut self.backend, fingerprint)?; - self.testbench_strings - .clone_from(&checkpoint.testbench_strings); + self.heap.clone_from(&checkpoint.heap); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs new file mode 100644 index 00000000000..accc54b560d --- /dev/null +++ b/crates/celox/src/simulator/heap.rs @@ -0,0 +1,73 @@ +//! Collecting the heap that handle slots in state memory refer to. + +use std::sync::Arc; + +use celox_heap::{HANDLE_BYTES, Handle}; + +use super::host::Simulator; +use crate::backend::SimBackend; + +impl Simulator { + /// Byte offsets of every handle slot in the stable and working regions. + pub(crate) fn handle_slots(&self) -> Arc<[usize]> { + self.handle_slots + .get_or_init(|| { + let layout = self.backend.layout(); + let mut slots = Vec::new(); + for (address, metadata) in &self.program.design.state_objects { + if !metadata.value_kind.is_handle() { + continue; + } + debug_assert!( + !layout.sparse_offsets.contains_key(address), + "handle slots are never sparse FF targets" + ); + let elements = metadata.width / celox_design::HANDLE_WIDTH; + let bases = layout.offsets.get(address).copied().into_iter().chain( + layout + .working_offsets + .get(address) + .map(|offset| layout.working_base_offset + offset), + ); + for base in bases { + slots.extend((0..elements).map(|index| base + index * HANDLE_BYTES)); + } + } + slots.sort_unstable(); + slots.into() + }) + .clone() + } + + /// The handles held by the handle slots of state memory. + pub(crate) fn handle_roots(&self) -> Vec { + let (memory, len) = self.backend.memory_as_ptr(); + self.handle_slots() + .iter() + .filter(|&&offset| offset + HANDLE_BYTES <= len) + .map(|&offset| { + let mut bytes = [0; HANDLE_BYTES]; + // SAFETY: the slot lies inside the `len` bytes of the image. + unsafe { + std::ptr::copy_nonoverlapping( + memory.add(offset), + bytes.as_mut_ptr(), + HANDLE_BYTES, + ); + } + Handle::from_le_bytes(bytes) + }) + .collect() + } + + /// Collect the heap if enough was allocated since the last collection. + /// State memory and `extra_roots` must hold every live handle: the + /// caller runs this only where no copy of a handle is anywhere else. + pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { + if !self.heap.should_collect() { + return; + } + let roots = self.handle_roots(); + self.heap.collect(roots.into_iter().chain(extra_roots)); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index b7b465d948e..96f30a45e94 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -40,6 +40,8 @@ pub enum StateError { /// matching code keeps compiling. #[error("the state of the simulation's processes could not be recorded")] Processes, + /// Not returned: state files record strings by their contents. Kept so + /// that matching code keeps compiling. #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] TestbenchStrings, } @@ -105,6 +107,9 @@ struct NamedObject { path: String, signal: SignalRef, role: StateRole, + /// Whether the elements are string handles, which a file records as + /// references to its strings section. + strings: bool, } /// The state objects of a built design, with the paths and roles that state @@ -121,8 +126,22 @@ pub struct StateSchema { impl StateSchema { /// Save the value of every state object of `backend` as last evaluated. + /// String objects read as `""`; use [`Self::capture_with_heap`] for a + /// backend whose strings live in a heap. pub fn capture(&self, backend: &B) -> StateFile { - let objects = self + self.capture_with_heap(backend, &celox_heap::Heap::new()) + } + + /// Save the value of every state object of `backend`, with the contents + /// of its strings from `heap`. + pub fn capture_with_heap( + &self, + backend: &B, + heap: &celox_heap::Heap, + ) -> StateFile { + let mut strings = Vec::new(); + let mut file_ids: HashMap = HashMap::default(); + let mut objects: Vec = self .objects .iter() .map(|object| { @@ -149,10 +168,36 @@ impl StateSchema { } }) .collect(); + // Number strings by first use in path order, so equal states save + // equal files. + for (object, named) in objects.iter_mut().zip(&self.objects) { + if !named.strings { + continue; + } + for element in object + .value + .as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>() + .0 + { + let handle = celox_heap::Handle::from_le_bytes(*element); + let contents = heap.string(handle); + let id = if contents.is_empty() { + 0 + } else { + // Interning gives each contents one handle. + *file_ids.entry(handle).or_insert_with(|| { + strings.push(contents.to_vec()); + strings.len() as u32 + }) + }; + element.copy_from_slice(&id.to_le_bytes()); + } + } StateFile { four_state: self.four_state, objects, schedule: None, + strings, } } @@ -166,6 +211,16 @@ impl StateSchema { &self, backend: &mut B, file: &StateFile, + ) -> Result<(), StateMismatch> { + self.load_with_heap(backend, &mut celox_heap::Heap::new(), file) + } + + /// Like [`Self::load`], creating the file's strings in `heap`. + pub fn load_with_heap( + &self, + backend: &mut B, + heap: &mut celox_heap::Heap, + file: &StateFile, ) -> Result<(), StateMismatch> { let saved: BTreeMap<&str, &StateObject> = file .objects @@ -184,7 +239,7 @@ impl StateSchema { if let Some(saved) = saved.get(object.path.as_str()) && saved.width == object.signal.width { - seeds.push((object.signal, *saved)); + seeds.push((object, *saved)); } continue; } @@ -197,7 +252,7 @@ impl StateSchema { object.signal.width, )); } - Some(saved) => writes.push((object.signal, *saved)), + Some(saved) => writes.push((object, *saved)), } } let declared: std::collections::BTreeSet<&str> = self @@ -213,8 +268,22 @@ impl StateSchema { if !mismatch.is_empty() { return Err(mismatch); } - for (signal, object) in seeds.into_iter().chain(writes) { - let value = BigUint::from_bytes_le(&object.value); + for (named, object) in seeds.into_iter().chain(writes) { + let signal = named.signal; + let value = if named.strings { + let mut value = object.value.clone(); + for element in value.as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>().0 { + let id = u32::from_le_bytes(*element) as usize; + let contents = id + .checked_sub(1) + .and_then(|index| file.strings.get(index)) + .map_or(&[][..], Vec::as_slice); + element.copy_from_slice(&heap.intern(contents).to_le_bytes()); + } + BigUint::from_bytes_le(&value) + } else { + BigUint::from_bytes_le(&object.value) + }; let mask = object .mask .as_deref() @@ -246,9 +315,6 @@ impl Simulator { /// a read would return. pub fn save_state(&mut self) -> Result { self.check_host_checkpoint_support()?; - if !self.testbench_strings.is_empty() { - return Err(StateError::TestbenchStrings); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -256,7 +322,9 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - Ok(self.state_schema().capture(&self.backend)) + Ok(self + .state_schema() + .capture_with_heap(&self.backend, &self.heap)) } /// Load the state saved in `file`, matching objects by path. @@ -279,9 +347,6 @@ impl Simulator { file: &StateFile, time: u64, ) -> Result<(), StateError> { - if !self.testbench_strings.is_empty() { - return Err(StateError::TestbenchStrings); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -289,7 +354,7 @@ impl Simulator { // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; self.state_schema() - .load(&mut self.backend, file) + .load_with_heap(&mut self.backend, &mut self.heap, file) .map_err(StateError::Mismatch)?; for address in &self.program.runtime_schema.time_slots { self.backend.set( @@ -355,6 +420,9 @@ impl Simulator { } else { StateRole::State }, + strings: self.program.design.state_objects.get(address).is_some_and( + |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, + ), }); } index = end; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 1c305ebff5d..23fb0943e78 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -99,18 +99,14 @@ fn eval_expr( ) -> TbValue { let (memory, _) = sim.backend.memory_as_ptr(); let trace = sim.backend.layout().trace.as_ref(); - expr.eval_with_strings( - memory.cast_mut(), - &mut sim.testbench_strings, - |offset, len| { - if let Some(trace) = trace { - // SAFETY: bytecode is bound to this simulator's memory layout. - unsafe { - trace.mark_range(memory.cast_mut(), offset, len); - } + expr.eval_with_heap(memory.cast_mut(), Some(&mut sim.heap), |offset, len| { + if let Some(trace) = trace { + // SAFETY: bytecode is bound to this simulator's memory layout. + unsafe { + trace.mark_range(memory.cast_mut(), offset, len); } - }, - ) + } + }) } pub(crate) fn eval_backend_expr( @@ -253,12 +249,19 @@ fn sim_set_target( value: TbValue, ) { if let TbValue::String(bytes) = value { + // A selection names a string element by its bit offset. let index = target.selection.as_ref().map_or(0, |selection| { - eval_expr(sim, &selection.offset).to_u64() as usize + eval_expr(sim, &selection.offset).to_u64() as usize / celox_design::HANDLE_WIDTH }); - if index < target.signal.width { - sim.testbench_strings - .insert((target.signal.offset, index), bytes); + if index < target.signal.width / celox_design::HANDLE_WIDTH { + let handle = sim.heap.intern(&bytes); + let element = SignalRef { + offset: target.signal.offset + index * celox_heap::HANDLE_BYTES, + width: celox_design::HANDLE_WIDTH, + is_4state: false, + array_layout: None, + }; + sim.set(element, handle); } return; } @@ -290,6 +293,32 @@ fn sim_set_target( ); } +/// Collect the heap between concurrent process polls. The saved temporaries of +/// suspended processes are outside state memory, so their handles are roots. +fn collect_testbench_heap( + sim: &mut Simulator, + private_signals: &[SignalRef], + locals: &[Vec<(BigUint, BigUint)>], +) { + if !sim.heap.should_collect() { + return; + } + let slots = sim.handle_slots(); + let saved_roots: Vec = private_signals + .iter() + .enumerate() + .filter(|(_, signal)| slots.binary_search(&signal.offset).is_ok()) + .flat_map(|(index, signal)| { + let elements = signal.width / celox_design::HANDLE_WIDTH; + locals.iter().flat_map(move |process| { + let digits = process[index].0.to_u32_digits(); + (0..elements).map(move |element| digits.get(element).copied().unwrap_or(0)) + }) + }) + .collect(); + sim.maybe_collect_heap(saved_roots); +} + fn execution_random_seed(seed: Option) -> u64 { seed.unwrap_or_else(rand::random) } @@ -1797,6 +1826,9 @@ fn exec_testbench( Poll::Pending => debug_assert!(wait.borrow().is_some()), } } + // No process is running, so every string handle is in state memory or + // in a suspended process's saved temporaries. + collect_testbench_heap(&mut sim.borrow_mut(), testbench.private_signals(), &locals); for wait in &waits { if let Some(wait) = wait.borrow().as_ref() && wait.remaining != 0 @@ -1973,6 +2005,9 @@ fn exec_detailed( ) -> ExecResult { for stmt in stmts { let r = exec_one_detailed(sim, stmt, ctx); + // Only a single process runs here, so between statements every string + // handle is in state memory. + sim.maybe_collect_heap([]); // Stop on control-flow transfers or hard errors. Assertion failures that // are allowed to continue return `Continue` and are recorded in `ctx`. if matches!( diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 2736f0d1198..574530a26d4 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -146,12 +146,6 @@ fn checkpoint_restores_string_values() { ); let saved = sim.checkpoint().unwrap(); assert_eq!(saved.state_size(), empty_size + b"saved string".len()); - assert!( - sim.save_state() - .unwrap_err() - .to_string() - .contains("dynamic testbench strings") - ); sim.set(mode, 1u32); assert_eq!( run_compiled_testbench(&mut sim, &program), @@ -165,6 +159,159 @@ fn checkpoint_restores_string_values() { ); } +#[test] +fn state_files_restore_string_values_by_contents() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let source = r#" + #[test(Top)] module Top { + var text: string; + var names: string[3]; + var mode: u32; + initial { + if mode == 0 { + text = "saved string"; + names[1] = "one"; + names[2] = "two"; + } else if mode == 1 { + text = "replacement"; + names[1] = "uno"; + } else { + $assert(text == "saved string", "[%s]", text); + $assert(names[0] == "", "[%s]", names[0]); + $assert(names[1] == "one", "[%s]", names[1]); + $assert(names[2] == "two", "[%s]", names[2]); + } + $finish(); + } + } + "#; + let mut sim = celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let mode = sim.signal("mode"); + sim.set(mode, 0u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let saved = sim.save_state().unwrap(); + assert_eq!( + saved.strings, + [b"one".to_vec(), b"two".to_vec(), b"saved string".to_vec()] + ); + let mut bytes = Vec::new(); + saved.write_to(&mut bytes).unwrap(); + let saved = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + + sim.set(mode, 1u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // A fresh simulator has none of the saved strings in its heap, so the + // file must carry their contents. + for target in [ + &mut sim, + &mut celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(), + ] { + target.load_state(&saved).unwrap(); + let mode = target.signal("mode"); + target.set(mode, 2u32); + assert_eq!( + run_compiled_testbench(target, &program), + celox::TestResult::Pass + ); + } +} + +#[test] +fn collected_heap_keeps_reachable_strings() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + // More distinct strings than one collection interval. + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = \"{value}\"; clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + inst clk: $tb::clock_gen; + initial {{ + kept = "kept"; + {assignments} + $assert(kept == "kept", "[%s]", kept); + $assert(text == "value 1499", "[%s]", text); + $finish(); + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // Without a collection the heap would hold every value. + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + +#[test] +fn concurrent_processes_keep_strings_across_collections() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = identity(\"{value}\"); clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + var done: bit; + inst clk: $tb::clock_gen; + function identity(value: input string) -> string {{ + return value; + }} + initial {{ + kept = identity("kept"); + clk.next(1600); + $assert(kept == "kept", "[%s]", kept); + $assert(done == 1); + $finish(); + }} + initial {{ + {assignments} + $assert(text == "value 1499", "[%s]", text); + done = 1; + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + #[test] fn unsupported_string_concatenation_is_rejected() { for expression in ["{a, b}", "{a repeat 2}"] { diff --git a/crates/lydite-celox/src/tests.rs b/crates/lydite-celox/src/tests.rs index 92f08e7a69d..0dc77c141c7 100644 --- a/crates/lydite-celox/src/tests.rs +++ b/crates/lydite-celox/src/tests.rs @@ -462,6 +462,7 @@ fn exported_array_width_is_total_not_per_element() { kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: array_dims.to_vec(), + value_kind: Default::default(), }) }; assert_eq!(shape(64, &[2]).unwrap(), (32, 2)); diff --git a/crates/lydite-celox/tests/fixtures/array_read_write2.json b/crates/lydite-celox/tests/fixtures/array_read_write2.json index 0ab8cb5adb8..26d02f21004 100644 --- a/crates/lydite-celox/tests/fixtures/array_read_write2.json +++ b/crates/lydite-celox/tests/fixtures/array_read_write2.json @@ -1 +1 @@ -{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} +{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 2afc09c893b..c2ec6c42dbe 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -186,6 +186,7 @@ for. | `celox-backend-x86` | x86 MIR, instruction selection, target allocation policy, and machine-code emission | Frontend or runtime policy | | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | +| `celox-heap` | Dynamic values referenced by handles from state memory, and their collection | Root discovery, layouts, or scheduling | | `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | | `celox-runtime` | Events, timed scheduling, VCD output, testbench execution, and backend contracts | Frontend, SIR optimization, or concrete backend internals | | `celox` | Public API, compilation orchestration, and backend selection | New reusable compiler algorithms | diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 4e8b5afe6ef..4751671c3c4 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -25,6 +25,7 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen + celox-heap celox-testbench celox-sir celox-state-layout From 73b5653667abd9d2aa6496e454f5cf4995e012f5 Mon Sep 17 00:00:00 2001 From: mergify <37929162+mergify@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:30:12 +0000 Subject: [PATCH 3/3] chore(deps): update mbx to 1.26.0 --- flake.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flake.lock b/flake.lock index df9a372e0e9..688e74b2e90 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792488653, - "narHash": "sha256-6mDIj7DP6kHQAdT0B7N8QpC3KBrY6W8LEenKg3GGfM0=", + "lastModified": 1792542234, + "narHash": "sha256-485fkwc2ZSHqtC+FpF2CrtuynntL4fm378pF0nBRZHQ=", "owner": "tignear", "repo": "nix-packages", - "rev": "683234e1ef474a6fbb653ce7ec11aa4657d49975", + "rev": "d0eff0edac65dd338f780e84882a4dc7e473ec28", "type": "github" }, "original": {