diff --git a/.github/workflows/ci-napi.yml b/.github/workflows/ci-napi.yml index f900d6aba48..76645afad97 100644 --- a/.github/workflows/ci-napi.yml +++ b/.github/workflows/ci-napi.yml @@ -211,17 +211,17 @@ jobs: working-directory: crates/celox-napi env: CARGO_BUILD_TARGET: ${{ matrix.target }} - run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --target ${{ matrix.target }} --use-napi-cross + run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --features wasm-component --target ${{ matrix.target }} --use-napi-cross - name: Build (zigbuild) if: matrix.zigbuild working-directory: crates/celox-napi - run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --target ${{ matrix.target }} -x + run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --features wasm-component --target ${{ matrix.target }} -x - name: Build (native) if: ${{ !matrix.napi-cross && !matrix.zigbuild }} working-directory: crates/celox-napi - run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --target ${{ matrix.target }} + run: npx napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --features wasm-component --target ${{ matrix.target }} - name: Upload artifact uses: actions/upload-artifact@v7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 86607a1b55e..c55dba1bb18 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -149,7 +149,7 @@ jobs: - name: cargo clippy if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' - run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim --no-deps + run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim --no-deps - name: Lint the crates this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '' @@ -259,7 +259,7 @@ jobs: if: needs.changes.outputs.rust_full != 'false' run: >- cargo nextest run --locked --workspace --exclude 'lydite*' --profile ci - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases + --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases - name: Run the tests this pull request can affect id: scoped-tests @@ -305,7 +305,7 @@ jobs: if: needs.changes.outputs.rust_full != 'false' run: >- cargo test --locked --workspace --exclude 'lydite*' --doc - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases + --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases - name: Run the documentation tests of the changed libraries if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_libraries != '' @@ -722,7 +722,7 @@ jobs: - name: Test partial-word reduction AND on AArch64 run: >- - cargo test --locked -p celox --features systemverilog + cargo test --locked -p celox --features systemverilog,cranelift,wasm-runtime,wasm-component,veryl-reference --test systemverilog wide_reduction_and_respects_partial_storage_words::native - name: Check x86-64 cross-codegen from AArch64 diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index 5bd5f9becc4..b60213d58e9 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -54,7 +54,7 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' run: >- cargo nextest list --locked --workspace --exclude 'lydite*' --message-format json - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases + --features celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases > /dev/null rust-default-tests: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a0f4e9c930..32e53fcd12e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,6 +4,31 @@ Use the locked environment described in [docs/development.md](docs/development.m Cargo builds use the workspace's default `target/`, managed by mbx. Do not set an ad-hoc `CARGO_TARGET_DIR` or `--target-dir`. +## Optional execution backends + +Ordinary workspace commands select Celox, NAPI and the CLI. Their default native +and tiered runtimes do not compile Cranelift or Wasmtime. Use `--workspace` +explicitly to include backend development and comparison crates. + +Enable only the backend needed for the task: + +- `--features celox/veryl-reference`: upstream Veryl simulator comparisons (its WASM host also depends on Wasmtime). +- `--features celox/cranelift`: Cranelift JIT and its comparison tests. +- `--features celox/wasm-runtime`: execute generated WASM with Wasmtime. +- `--features celox/wasm-component`: load Veryl `.wasm` component libraries. + +The CLI forwards all three features; NAPI forwards `cranelift` and +`wasm-component`. Native component libraries and browser WASM generation do +not require Wasmtime. Published native NAPI bindings explicitly enable +`wasm-component`; local debug builds leave it disabled. A disabled WASM component host reports the required +feature when a `.wasm` library is requested. + +Common test matrices use the enabled backends. Binaries that directly compare +optional backends declare required features. To run the complete Celox suite, +use `cargo test -p celox --features systemverilog,cranelift,wasm-runtime,wasm-component,veryl-reference`. +CI explicitly enables these features to retain backend coverage. +Host cross-codegen features also enable Cranelift for their fallback runtime. + ## Select checks from the change Before running checks, identify the behavior that changed and the code that @@ -44,7 +69,7 @@ For repeated local vtest runs, use the optimized shared executor: ```sh node scripts/run-vtest.mjs --test counter -node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' +CELOX_TEST_FEATURES=cranelift,wasm-runtime node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' ``` This builds `vtest-exec` with the `vtest` Cargo profile (`opt-level = 1`, diff --git a/Cargo.lock b/Cargo.lock index ad69b908def..ae3aff84d83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -396,6 +396,7 @@ dependencies = [ "bit-set", "celox-analysis", "celox-backend-arm64", + "celox-backend-common", "celox-backend-cranelift", "celox-backend-wasm", "celox-backend-x86", @@ -483,6 +484,7 @@ dependencies = [ name = "celox-backend-cranelift" version = "0.11.0" dependencies = [ + "celox-backend-common", "celox-design", "celox-sir", "celox-state-layout", diff --git a/Cargo.toml b/Cargo.toml index 2b9681999dd..03951a942f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,6 @@ [workspace] +# Keep optional backend and comparison crates out of ordinary local builds. +default-members = ["crates/celox", "crates/celox-napi", "crates/celox-vpi"] members = [ "crates/celox", "crates/celox-analysis", diff --git a/crates/celox-backend-common/src/cranelift_options.rs b/crates/celox-backend-common/src/cranelift_options.rs new file mode 100644 index 00000000000..3cedc7cbe67 --- /dev/null +++ b/crates/celox-backend-common/src/cranelift_options.rs @@ -0,0 +1,106 @@ +//! Cranelift-owned compilation policy. + +/// Cranelift backend optimization level. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CraneliftOptLevel { + /// No Cranelift-level optimizations. + None, + /// Optimize for execution speed (default). + #[default] + Speed, + /// Optimize for both speed and code size. + SpeedAndSize, +} + +impl CraneliftOptLevel { + /// Returns the Cranelift settings string for this level. + pub fn as_cranelift_str(self) -> &'static str { + match self { + CraneliftOptLevel::None => "none", + CraneliftOptLevel::Speed => "speed", + CraneliftOptLevel::SpeedAndSize => "speed_and_size", + } + } +} + +/// Register allocator algorithm for the Cranelift backend. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RegallocAlgorithm { + /// Backtracking allocator with range splitting. + /// Slower compilation but generates better code with fewer spills. + #[default] + Backtracking, + /// Single-pass allocator. + /// Much faster compilation but generates code with more register spills and moves. + SinglePass, +} + +impl RegallocAlgorithm { + /// Returns the Cranelift settings string for this algorithm. + pub fn as_cranelift_str(self) -> &'static str { + match self { + RegallocAlgorithm::Backtracking => "backtracking", + RegallocAlgorithm::SinglePass => "single_pass", + } + } +} + +/// Fine-grained Cranelift backend options beyond the optimization level. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CraneliftDiagnostics { + pub pass_timing: bool, +} + +/// Fine-grained Cranelift backend options beyond the optimization level. +#[derive(Debug, Clone, Copy)] +pub struct CraneliftOptions { + /// Optimization level (default: Speed). + pub opt_level: CraneliftOptLevel, + /// Register allocator algorithm (default: Backtracking). + pub regalloc_algorithm: RegallocAlgorithm, + /// Enable alias analysis during egraph optimization (default: true). + /// Only effective when `opt_level` is not `None`. + pub enable_alias_analysis: bool, + /// Enable the Cranelift IR verifier (default: true). + /// Disabling saves compile time at the cost of less validation. + pub enable_verifier: bool, + /// Enable backend-owned splitting for oversized functions. + pub tail_call_split: bool, + pub diagnostics: CraneliftDiagnostics, +} + +impl Default for CraneliftOptions { + fn default() -> Self { + Self { + opt_level: CraneliftOptLevel::default(), + regalloc_algorithm: RegallocAlgorithm::default(), + enable_alias_analysis: true, + enable_verifier: true, + tail_call_split: true, + diagnostics: CraneliftDiagnostics::default(), + } + } +} + +impl CraneliftOptions { + /// Fast compilation preset: no optimizations, single-pass regalloc, no verifier. + pub fn fast_compile() -> Self { + Self { + opt_level: CraneliftOptLevel::None, + regalloc_algorithm: RegallocAlgorithm::SinglePass, + enable_alias_analysis: false, + enable_verifier: false, + tail_call_split: true, + diagnostics: CraneliftDiagnostics::default(), + } + } + + /// Select backend defaults without importing the facade's optimization policy. + pub fn for_speed_optimization(enabled: bool) -> Self { + if enabled { + Self::default() + } else { + Self::fast_compile() + } + } +} diff --git a/crates/celox-backend-common/src/lib.rs b/crates/celox-backend-common/src/lib.rs index 80ff5b4be29..b5434f8969b 100644 --- a/crates/celox-backend-common/src/lib.rs +++ b/crates/celox-backend-common/src/lib.rs @@ -1,3 +1,5 @@ //! Target-independent building blocks shared by native machine-code backends. pub mod regalloc; + +pub mod cranelift_options; diff --git a/crates/celox-backend-cranelift/Cargo.toml b/crates/celox-backend-cranelift/Cargo.toml index 171b7166c46..957eafbf01d 100644 --- a/crates/celox-backend-cranelift/Cargo.toml +++ b/crates/celox-backend-cranelift/Cargo.toml @@ -10,6 +10,7 @@ edition.workspace = true rust-version.workspace = true [dependencies] +celox-backend-common = { workspace = true } tracing = { workspace = true } celox-design = { workspace = true } celox-sir = { workspace = true } diff --git a/crates/celox-backend-cranelift/src/cranelift_options.rs b/crates/celox-backend-cranelift/src/cranelift_options.rs index 3cedc7cbe67..7febb891e0a 100644 --- a/crates/celox-backend-cranelift/src/cranelift_options.rs +++ b/crates/celox-backend-cranelift/src/cranelift_options.rs @@ -1,106 +1 @@ -//! Cranelift-owned compilation policy. - -/// Cranelift backend optimization level. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CraneliftOptLevel { - /// No Cranelift-level optimizations. - None, - /// Optimize for execution speed (default). - #[default] - Speed, - /// Optimize for both speed and code size. - SpeedAndSize, -} - -impl CraneliftOptLevel { - /// Returns the Cranelift settings string for this level. - pub fn as_cranelift_str(self) -> &'static str { - match self { - CraneliftOptLevel::None => "none", - CraneliftOptLevel::Speed => "speed", - CraneliftOptLevel::SpeedAndSize => "speed_and_size", - } - } -} - -/// Register allocator algorithm for the Cranelift backend. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum RegallocAlgorithm { - /// Backtracking allocator with range splitting. - /// Slower compilation but generates better code with fewer spills. - #[default] - Backtracking, - /// Single-pass allocator. - /// Much faster compilation but generates code with more register spills and moves. - SinglePass, -} - -impl RegallocAlgorithm { - /// Returns the Cranelift settings string for this algorithm. - pub fn as_cranelift_str(self) -> &'static str { - match self { - RegallocAlgorithm::Backtracking => "backtracking", - RegallocAlgorithm::SinglePass => "single_pass", - } - } -} - -/// Fine-grained Cranelift backend options beyond the optimization level. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CraneliftDiagnostics { - pub pass_timing: bool, -} - -/// Fine-grained Cranelift backend options beyond the optimization level. -#[derive(Debug, Clone, Copy)] -pub struct CraneliftOptions { - /// Optimization level (default: Speed). - pub opt_level: CraneliftOptLevel, - /// Register allocator algorithm (default: Backtracking). - pub regalloc_algorithm: RegallocAlgorithm, - /// Enable alias analysis during egraph optimization (default: true). - /// Only effective when `opt_level` is not `None`. - pub enable_alias_analysis: bool, - /// Enable the Cranelift IR verifier (default: true). - /// Disabling saves compile time at the cost of less validation. - pub enable_verifier: bool, - /// Enable backend-owned splitting for oversized functions. - pub tail_call_split: bool, - pub diagnostics: CraneliftDiagnostics, -} - -impl Default for CraneliftOptions { - fn default() -> Self { - Self { - opt_level: CraneliftOptLevel::default(), - regalloc_algorithm: RegallocAlgorithm::default(), - enable_alias_analysis: true, - enable_verifier: true, - tail_call_split: true, - diagnostics: CraneliftDiagnostics::default(), - } - } -} - -impl CraneliftOptions { - /// Fast compilation preset: no optimizations, single-pass regalloc, no verifier. - pub fn fast_compile() -> Self { - Self { - opt_level: CraneliftOptLevel::None, - regalloc_algorithm: RegallocAlgorithm::SinglePass, - enable_alias_analysis: false, - enable_verifier: false, - tail_call_split: true, - diagnostics: CraneliftDiagnostics::default(), - } - } - - /// Select backend defaults without importing the facade's optimization policy. - pub fn for_speed_optimization(enabled: bool) -> Self { - if enabled { - Self::default() - } else { - Self::fast_compile() - } - } -} +pub use celox_backend_common::cranelift_options::*; diff --git a/crates/celox-bench/Cargo.toml b/crates/celox-bench/Cargo.toml index f60dc650a26..ffa140da835 100644 --- a/crates/celox-bench/Cargo.toml +++ b/crates/celox-bench/Cargo.toml @@ -9,6 +9,7 @@ description = "Macro-benchmark runners for Celox" edition.workspace = true [features] +cranelift = ["celox/cranelift"] default = [] arm64-codegen = ["celox/arm64-codegen"] x86_64-codegen = ["celox/x86_64-codegen"] @@ -36,3 +37,7 @@ celox-design = { workspace = true } [lints] workspace = true + +[[bin]] +name = "parallel-report" +required-features = ["cranelift"] diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f53a2af7176..c42896d21be 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -936,85 +936,126 @@ pub fn schedule_symbolic_rtl_reporting_loops( // working state is seeded with the stable value first, so a store // compares with the value its update replaces. let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); - for (source, counter) in probes { - let width = source.access.msb - source.access.lsb + 1; - let four_state = four_state && variables[&source.id].1; - let offset = match unpacked_element_widths.get(&source.id) { - Some(&element_width) - if width > element_width - && source.access.lsb.is_multiple_of(element_width) - && width.is_multiple_of(element_width) => - { - celox_sir::SIROffset::PackedElements { - bit_offset: source.access.lsb, - element_width, + // Each unit is instrumented once for all probes. Probe `p` is pass + // `2p` over the stable state and pass `2p + 1` over a flip-flop + // evaluation's working state, the order of instrumenting probe by + // probe. + let probe_codes: Vec<_> = probes + .iter() + .map(|&(source, counter)| { + let width = source.access.msb - source.access.lsb + 1; + let four_state = four_state && variables[&source.id].1; + let offset = match unpacked_element_widths.get(&source.id) { + Some(&element_width) + if width > element_width + && source.access.lsb.is_multiple_of(element_width) + && width.is_multiple_of(element_width) => + { + celox_sir::SIROffset::PackedElements { + bit_offset: source.access.lsb, + element_width, + } } - } - _ => celox_sir::SIROffset::Static(source.access.lsb), - }; - let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == STABLE_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: stable(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for process in &mut processes { - crate::watch::instrument_unit(&mut process.kernel, code); + _ => celox_sir::SIROffset::Static(source.access.lsb), + }; + (counter, width, four_state, offset) + }) + .collect(); + let mut probes_of: HashMap> = HashMap::default(); + for (index, (source, _)) in probes.iter().enumerate() { + probes_of.entry(source.id).or_default().push(index); + } + // The first probe of `signal` whose `pass` is `after` or later. + let first_probe = |signal: AbsoluteAddr, pass: fn(usize) -> usize, after: usize| { + let indices = probes_of.get(&signal)?; + indices + .get(indices.partition_point(|&index| pass(index) < after)) + .copied() + }; + fn probe_code( + probe: &(AbsoluteAddr, usize, bool, celox_sir::SIROffset), + signal: A, + counter: A, + ) -> crate::watch::WatchCode { + let &(_, width, four_state, ref offset) = probe; + crate::watch::WatchCode { + signal, + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, counter)], } - for units in eval_apply_ffs - .values_mut() - .chain(eval_only_ffs.values_mut()) - .chain(apply_ffs.values_mut()) + } + let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); + let working = |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let stable_code = |instruction: &SIRInstruction, after: usize| { + let address = crate::watch::write_destination(instruction)?; + if address.region != STABLE_REGION { + return None; + } + let index = first_probe(address.absolute_addr(), |index| 2 * index, after)?; + Some(( + 2 * index, + probe_code( + &probe_codes[index], + stable(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )) + }; + // A flip-flop evaluation's stores to a signal of `ff_multi_stored`; + // the commits that seed its working state are not writes of the + // process. + let evaluation_code = |instruction: &SIRInstruction, after: usize| { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && ff_multi_stored.contains(&address.absolute_addr()) + && let Some(index) = + first_probe(address.absolute_addr(), |index| 2 * index + 1, after) { - for unit in units { - crate::watch::instrument_unit(unit, code); - } + return Some(( + 2 * index + 1, + probe_code( + &probe_codes[index], + working(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )); } - for parts in parallel_ff_units.values_mut() { - for (_, part) in parts { - crate::watch::instrument_unit(&mut part.evaluate, code); - crate::watch::instrument_unit(&mut part.apply, code); - } + stable_code(instruction, after) + }; + for process in &mut processes { + crate::watch::instrument_writes_in_passes(&mut process.kernel, stable_code); + } + for units in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, evaluation_code); } - if ff_multi_stored.contains(&source.id) { - let working = - |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: working(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for_each_ff_evaluation( - &mut eval_apply_ffs, - &mut eval_only_ffs, - &mut parallel_ff_units, - |unit| instrument_stores(unit, code), - ); + } + for units in apply_ffs.values_mut() { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, stable_code); } - for path in &mut comb_blocks { - if let LogicPathTarget::Process { unit, .. } = &mut path.target { - crate::watch::instrument_unit(unit, |address| { - (*address == source.id).then(|| crate::watch::WatchCode { - signal: source.id, - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, counter)], - }) - }); - } + } + for parts in parallel_ff_units.values_mut() { + for (_, part) in parts { + crate::watch::instrument_writes_in_passes(&mut part.evaluate, evaluation_code); + crate::watch::instrument_writes_in_passes(&mut part.apply, stable_code); + } + } + for path in &mut comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let &address = crate::watch::write_destination(instruction)?; + let index = first_probe(address, |index| index, after)?; + Some(( + index, + probe_code(&probe_codes[index], address, probe_codes[index].0), + )) + }); } } let ff_units = eval_apply_ffs @@ -1052,31 +1093,45 @@ pub fn schedule_symbolic_rtl_reporting_loops( .iter() .map(|slots| slots.signal) .collect(); - for (signal, slots) in &counted { - if !ff_multi_stored.contains(signal) || pending.contains(signal) { - continue; - } - let (width, is_4state) = variables[signal]; - let regioned = RegionedAbsoluteAddr::from_absolute_addr; - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( - || crate::watch::WatchCode { - signal: regioned(WORKING_REGION, *signal), - offset: celox_sir::SIROffset::Static(0), - width, - four_state: four_state && is_4state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) - .collect(), - }, - ) - }; + // One pass per signal, in signal order; each pass watches only its + // own signal. + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let multi_stored: HashMap)> = counted + .iter() + .filter(|(signal, _)| ff_multi_stored.contains(signal) && !pending.contains(signal)) + .enumerate() + .map(|(pass, (&signal, slots))| { + let (width, is_4state) = variables[&signal]; + let code = crate::watch::WatchCode { + signal: regioned(WORKING_REGION, signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }; + (signal, (pass, code)) + }) + .collect(); + if !multi_stored.is_empty() { for_each_ff_evaluation( &mut eval_apply_ffs, &mut eval_only_ffs, &mut parallel_ff_units, - |unit| instrument_stores(unit, code), + |unit| { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let SIRInstruction::Store(address, ..) = instruction else { + return None; + }; + if address.region != WORKING_REGION { + return None; + } + let (pass, code) = multi_stored.get(&address.absolute_addr())?; + (*pass >= after).then(|| (*pass, code.clone())) + }) + }, ); } counted @@ -4012,19 +4067,6 @@ fn ff_multi_stored( .collect() } -/// [`crate::watch::instrument_unit`] for the stores alone: the commits that -/// seed a flip-flop evaluation's working state are not writes of the -/// process. -fn instrument_stores( - unit: &mut ExecutionUnit, - watch_for: impl Fn(&RegionedAbsoluteAddr) -> Option>, -) { - crate::watch::instrument_writes(unit, |instruction| match instruction { - SIRInstruction::Store(address, ..) => watch_for(address), - _ => None, - }); -} - /// Run `f` on every flip-flop evaluation. fn for_each_ff_evaluation( eval_apply_ffs: &mut FfUnits, diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 40a2bdbbc5c..b29ce3188b5 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -641,6 +641,113 @@ pub fn instrument_writes( } } +/// The result of [`instrument_writes`] once per pass, in pass order, in one +/// walk over `unit`. `watch_for(instruction, after)` gives the first pass +/// from `after` on that watches `instruction`, and its code. +/// +/// A later pass also sees the code an earlier one added, and wraps the write +/// inside it, so a write watched by several passes is surrounded by their +/// code from the first pass outward in. The new registers are numbered as +/// the passes one after another would number them. +pub fn instrument_writes_in_passes( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&SIRInstruction, usize) -> Option<(usize, WatchCode)>, +) { + let ExecutionUnit { + blocks, + register_map, + .. + } = unit; + let first_new = register_map.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let mut next_register = first_new; + // The pass, block and first register of every piece of code added, in + // the order the walk adds them. + let mut added: Vec<(usize, usize, usize)> = Vec::new(); + let mut instrumented = Vec::new(); + for (order, block) in blocks.values_mut().enumerate() { + if !block + .instructions + .iter() + .any(|instruction| watch_for(instruction, 0).is_some()) + { + continue; + } + let mut instructions = Vec::with_capacity(block.instructions.len()); + let mut work: Vec<(SIRInstruction, usize)> = Vec::new(); + for instruction in std::mem::take(&mut block.instructions) { + work.push((instruction, 0)); + while let Some((instruction, after)) = work.pop() { + let Some((pass, watch)) = watch_for(&instruction, after) else { + instructions.push(instruction); + continue; + }; + let value_type = match &instruction { + SIRInstruction::Store(_, _, _, value, ..) => register_map.get(value).cloned(), + _ => None, + }; + let mut b = SIRBuilder::new_with(next_register); + emit_watched(&mut b, &watch, instruction, value_type.as_ref()); + b.seal_block(SIRTerminator::Return); + let (mut emitted, registers, next) = b.drain(); + added.push((pass, order, next_register)); + next_register = next; + register_map.extend(registers); + let emitted = emitted + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions; + work.extend(emitted.into_iter().rev().map(|emitted| (emitted, pass + 1))); + } + } + block.instructions = instructions; + instrumented.push(block.id); + } + if added.is_empty() { + return; + } + + // Renumber the new registers pass by pass, then block by block in the + // order a pass visits them; within a block the walk already added each + // pass's code in order. + let mut ends: Vec = added.iter().skip(1).map(|&(.., first)| first).collect(); + ends.push(next_register); + let mut pieces: Vec<(usize, usize, usize, usize)> = added + .iter() + .zip(ends) + .map(|(&(pass, order, first), end)| (pass, order, first, end)) + .collect(); + pieces.sort_by_key(|&(pass, order, ..)| (pass, order)); + let mut renumbered = vec![0; next_register - first_new]; + let mut next = first_new; + for (.., first, end) in pieces { + for register in first..end { + renumbered[register - first_new] = next; + next += 1; + } + } + let renumber = |register: &mut RegisterId| { + if register.0 >= first_new { + register.0 = renumbered[register.0 - first_new]; + } + }; + for id in instrumented { + let block = blocks.get_mut(&id).expect("an instrumented block"); + for instruction in &mut block.instructions { + if let Some(register) = instruction.defined_register_mut() { + renumber(register); + } + instruction.for_each_use_mut(renumber); + } + } + let new_registers: Vec<_> = (first_new..next_register) + .filter_map(|id| register_map.remove_entry(&RegisterId(id))) + .collect(); + register_map.extend(new_registers.into_iter().map(|(mut id, ty)| { + renumber(&mut id); + (id, ty) + })); +} + /// Objects that hold back the occurrences of one flip-flop evaluation's /// writes to a signal until the commit that publishes them. /// @@ -1281,7 +1388,10 @@ pub fn declare_pending_slots( mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; - use super::{multi_store_candidates, multi_write_candidates, successors, write_destination}; + use super::{ + WatchCode, instrument_writes, instrument_writes_in_passes, multi_store_candidates, + multi_write_candidates, successors, write_destination, + }; /// Store a constant to `address` at the open block. fn store(b: &mut SIRBuilder, address: u32) { @@ -1556,4 +1666,118 @@ mod tests { let found = multi_store_candidates(&unit, |address| Some(*address)); assert_eq!(found, (0..10000).step_by(2).collect::>()); } + + /// One pass of the equivalence test: the writes it watches and the + /// code it adds. + struct Pass { + address: u32, + stores_only: bool, + code: WatchCode, + } + + impl Pass { + fn watches(&self, instruction: &SIRInstruction) -> bool { + match instruction { + SIRInstruction::Store(address, ..) => *address == self.address, + _ => !self.stores_only && write_destination(instruction) == Some(&self.address), + } + } + } + + /// A random unit of a few blocks writing a few addresses, and random + /// passes over the same addresses; a pass's counters may be written + /// by another pass's code. + fn random_instrumentation(seed: u64) -> (celox_sir::ExecutionUnit, Vec) { + use celox_design::CounterKind; + let state = std::cell::Cell::new(seed); + let next = |bound: u64| { + state.set( + state + .get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + (state.get() >> 33) % bound + }; + let addresses = 1 + next(6) as u32; + let widths = [1, 4, 8]; + let mut b = SIRBuilder::new(); + let blocks = 1 + next(4); + for block in 0..blocks { + for _ in 0..next(6) { + let width = widths[next(3) as usize]; + let value = if next(2) == 0 { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Imm(value, SIRValue::new(next(256) as u8))); + let address = next(addresses as u64) as u32; + b.emit(match next(3) { + 0 => SIRInstruction::Commit( + address, + address, + SIROffset::Static(0), + width, + Vec::new(), + ), + _ => SIRInstruction::Store( + address, + SIROffset::Static(next(2) as usize * 2), + width, + value, + Vec::new(), + Vec::new(), + ), + }); + } + if block + 1 < blocks { + let following = b.new_block(); + b.seal_block(SIRTerminator::Jump(following, Vec::new())); + b.switch_to_block(following); + } + } + let value = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(0u8))); + let unit = b.flush_eu().unwrap(); + let passes = (0..1 + next(8)) + .map(|_| Pass { + address: next(addresses as u64) as u32, + stores_only: next(2) == 0, + code: WatchCode { + signal: next(addresses as u64) as u32, + width: widths[next(3) as usize], + offset: SIROffset::Static(next(2) as usize * 2), + four_state: next(2) == 0, + counters: CounterKind::ALL + .into_iter() + .filter(|_| next(2) == 0) + .map(|kind| (kind, next(addresses as u64 + 2) as u32)) + .collect(), + }, + }) + .collect(); + (unit, passes) + } + + #[test] + fn instrumenting_in_passes_matches_one_pass_after_another() { + for seed in 0..3000 { + let (unit, passes) = random_instrumentation(seed); + let mut one_by_one = unit.clone(); + for pass in &passes { + instrument_writes(&mut one_by_one, |instruction| { + pass.watches(instruction).then(|| pass.code.clone()) + }); + } + let mut at_once = unit; + instrument_writes_in_passes(&mut at_once, |instruction, after| { + let found = passes[after.min(passes.len())..] + .iter() + .position(|pass| pass.watches(instruction))?; + Some((after + found, passes[after + found].code.clone())) + }); + assert_eq!(at_once, one_by_one, "seed {seed}"); + } + } } diff --git a/crates/celox-napi/Cargo.toml b/crates/celox-napi/Cargo.toml index 667b6181826..234b32ac704 100644 --- a/crates/celox-napi/Cargo.toml +++ b/crates/celox-napi/Cargo.toml @@ -9,6 +9,10 @@ description = "N-API/WASI simulator handles and frontend adapter API f readme = "README.md" edition.workspace = true +[features] +cranelift = ["celox/cranelift"] +wasm-component = ["celox/wasm-component"] + [lib] crate-type = ["rlib", "cdylib"] diff --git a/crates/celox-napi/package.json b/crates/celox-napi/package.json index 97437f964ad..fc11fd058ac 100644 --- a/crates/celox-napi/package.json +++ b/crates/celox-napi/package.json @@ -24,7 +24,7 @@ }, "scripts": { "artifacts": "napi artifacts", - "build": "napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi", + "build": "napi build --platform --release --manifest-path ../../Cargo.toml -p celox-napi --features wasm-component", "build:debug": "napi build --platform --manifest-path ../../Cargo.toml -p celox-napi", "prepublishOnly": "napi prepublish -t npm", "version": "napi version" diff --git a/crates/celox-vpi/Cargo.toml b/crates/celox-vpi/Cargo.toml index 19bba376bfb..d866e6d7603 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -9,6 +9,9 @@ description.workspace = true edition.workspace = true [features] +cranelift = ["celox/cranelift"] +wasm-runtime = ["celox/wasm-runtime"] +wasm-component = ["celox/wasm-component"] default = ["systemverilog"] arm64-codegen = ["celox/arm64-codegen"] x86_64-codegen = ["celox/x86_64-codegen"] diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index eb1e030dd2d..dce33a96a11 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -179,8 +179,10 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { } match arguments.execution.backend() { runner::Backend::Native => execute!(build), + #[cfg(feature = "cranelift")] runner::Backend::Cranelift => execute!(build_cranelift), runner::Backend::Interpreter => execute!(build_interpreter), + #[cfg(feature = "wasm-runtime")] runner::Backend::Wasm => execute!(build_wasm), runner::Backend::Tiered => execute!(build_tiered), } diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index cb25cfc3b1a..da81269186c 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -175,8 +175,10 @@ pub(super) enum RunError { #[derive(Clone, Copy, PartialEq, ValueEnum)] pub(super) enum Backend { Native, + #[cfg(feature = "cranelift")] Cranelift, Interpreter, + #[cfg(feature = "wasm-runtime")] Wasm, Tiered, } @@ -191,8 +193,10 @@ impl Backend { fn as_str(self) -> &'static str { match self { Backend::Native => "native", + #[cfg(feature = "cranelift")] Backend::Cranelift => "cranelift", Backend::Interpreter => "interpreter", + #[cfg(feature = "wasm-runtime")] Backend::Wasm => "wasm", Backend::Tiered => "tiered", } @@ -780,9 +784,11 @@ pub(super) fn run( target_arch = "aarch64" )))] Backend::Native => unreachable!("native backend availability checked above"), + #[cfg(feature = "wasm-runtime")] Backend::Wasm => { builder.build_wasm()?; } + #[cfg(feature = "cranelift")] Backend::Cranelift => { let _sim = builder.build_cranelift()?; } @@ -888,6 +894,7 @@ pub(super) fn run( all(target_arch = "aarch64", not(feature = "x86_64-codegen")) )))] Backend::Native => unreachable!("native backend availability checked above"), + #[cfg(feature = "cranelift")] Backend::Cranelift => { let mut sim = builder.build_cranelift()?; super::report_warnings(sim.warnings()) @@ -946,6 +953,7 @@ pub(super) fn run( None, ) } + #[cfg(feature = "wasm-runtime")] Backend::Wasm => { let mut sim = builder.build_wasm()?; super::report_warnings(sim.warnings()) diff --git a/crates/celox-vpi/tests/run_build_cache.rs b/crates/celox-vpi/tests/run_build_cache.rs index 0e4fc2abf3a..cc9c295ddd1 100644 --- a/crates/celox-vpi/tests/run_build_cache.rs +++ b/crates/celox-vpi/tests/run_build_cache.rs @@ -482,6 +482,7 @@ fn rebuilds_corrupt_entries_and_tolerates_unwritable_cache() { fn rejects_incompatible_modes() { let project = project(SOURCE); for args in [ + #[cfg(feature = "cranelift")] vec!["--backend", "cranelift"], vec!["--dump-ir-dir", "trace"], vec!["--native-image-input", "image"], diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 4c3a66abbf5..9947d41f80c 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -335,7 +335,15 @@ fn sv_stop_is_not_reported_as_successful_completion() { fn veryl_backends_share_cli_execution_and_opt_in_reports() { let source = "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(4); $finish(); } }"; - for backend in ["native", "tiered", "interpreter", "cranelift", "wasm"] { + for backend in [ + "native", + "tiered", + "interpreter", + #[cfg(feature = "cranelift")] + "cranelift", + #[cfg(feature = "wasm-runtime")] + "wasm", + ] { for four_state in [false, true] { let mut args = vec!["--backend", backend, "--threads", "2", "--report"]; if four_state { @@ -473,7 +481,15 @@ fn sv_backends_preserve_timed_nba_execution_and_failures() { end endmodule "#; - for backend in ["native", "cranelift", "interpreter", "wasm", "tiered"] { + for backend in [ + "native", + #[cfg(feature = "cranelift")] + "cranelift", + "interpreter", + #[cfg(feature = "wasm-runtime")] + "wasm", + "tiered", + ] { for four_state in [false, true] { let mut args = vec!["--backend", backend, "--threads", "2"]; if four_state { diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index 6ba5486a1b6..12deac9c765 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -13,26 +13,30 @@ rust-version.workspace = true [features] default = ["host-runtime"] host-runtime = [ - "dep:celox-backend-cranelift", "dep:celox-backend-x86", "dep:celox-macros", - "dep:wasmtime", "dep:veryl-component-sys", "dep:libloading", "rand/thread_rng", "celox-sir-opt/timing", ] +cranelift = ["host-runtime", "dep:celox-backend-cranelift"] +wasm-runtime = ["host-runtime", "dep:wasmtime"] +veryl-reference = ["host-runtime", "dep:veryl-simulator"] +wasm-component = ["host-runtime", "dep:wasmtime"] systemverilog = ["dep:celox-frontend-sv"] # Accept SystemVerilog DPI-C imports, linked to C functions at build time. sv-dpi = ["systemverilog", "celox-frontend-sv/dpi"] -arm64-codegen = ["host-runtime", "dep:celox-backend-arm64"] +arm64-codegen = ["cranelift", "dep:celox-backend-arm64"] x86_64-codegen = [ - "host-runtime", + "cranelift", "dep:celox-backend-x86", "celox-backend-x86/cross-codegen", ] [dependencies] +veryl-simulator = { workspace = true, optional = true } +celox-backend-common = { workspace = true } toml = { workspace = true } veryl-analyzer = { workspace = true } veryl-metadata = { workspace = true } @@ -97,11 +101,11 @@ test-case = "3" tempfile.workspace = true veryl-std = { workspace = true } veryl-emitter = { workspace = true } -veryl-simulator = { workspace = true } vcd = "0.7" [[bench]] name = "vcd" +required-features = ["cranelift"] harness = false [[bench]] @@ -115,15 +119,16 @@ harness = false [[test]] name = "systemverilog" path = "tests/systemverilog.rs" -required-features = ["systemverilog"] +required-features = ["systemverilog", "cranelift", "wasm-runtime"] [[test]] name = "sv_dpi" path = "tests/sv_dpi.rs" -required-features = ["sv-dpi"] +required-features = ["sv-dpi", "cranelift", "wasm-runtime"] [[bench]] name = "compilation" +required-features = ["cranelift"] harness = false bench = false @@ -152,3 +157,179 @@ required-features = ["host-runtime"] [lints] workspace = true + +[[test]] +name = "component_method" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "concurrent_initial_runtime" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "cross_validate" +required-features = ["cranelift"] + +[[test]] +name = "diagnostic_policy" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "divrem_state_modes" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "edge_api" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "four_state_explicit_edges" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "frontend_sdk" +required-features = ["cranelift"] + +[[test]] +name = "fuzz_cross_validate" +required-features = ["cranelift"] + +[[test]] +name = "issue3_repro" +required-features = ["cranelift"] + +[[test]] +name = "latch" +required-features = ["cranelift"] + +[[test]] +name = "multi_clock" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "native_boundary_hardening" +required-features = ["cranelift"] + +[[test]] +name = "native_concat_width" +required-features = ["wasm-runtime"] + +[[test]] +name = "nested_write_perf" +required-features = ["cranelift"] + +[[test]] +name = "param_override_width" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "scalar_write_widths" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "simulation_stop" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "state_file" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_declaration_startup" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_deferred_assertions" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_distributions" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_host_requests" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_ordinary_host_requests" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_plusargs" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_real_math" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_reports" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_scan" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_scan_real" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_scheduled_host_requests" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_scheduled_startup" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_system_actuals" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_timescale_options" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_untimed_processes" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "sv_update_events" +required-features = ["wasm-runtime"] + +[[test]] +name = "sv_vcd" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "time_precision" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "time_state_and_delays" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "unknown_shift_counts" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "vcd" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "wasm_backend" +required-features = ["wasm-runtime"] + +[[test]] +name = "wasm_regression" +required-features = ["cranelift", "wasm-runtime"] + +[[test]] +name = "veryl_reference_adapter" +required-features = ["veryl-reference"] + +[[test]] +name = "native_testbench" +required-features = ["veryl-reference", "cranelift"] diff --git a/crates/celox/README.md b/crates/celox/README.md index 07c2266085f..4bb55aec7be 100644 --- a/crates/celox/README.md +++ b/crates/celox/README.md @@ -4,6 +4,19 @@ crates use its low-level `Simulator::from_frontend` hook after lowering their own artifact through `celox-frontend-sdk`. +The default `host-runtime` feature provides native, interpreter and tiered +execution. Optional execution engines are enabled explicitly: + +| Feature | Enables | +| --- | --- | +| `cranelift` | `build_cranelift()` and the Cranelift JIT backend | +| `wasm-runtime` | `build_wasm()` using Wasmtime | +| `wasm-component` | Hosting Veryl `.wasm` component libraries | +| `veryl-reference` | Development comparisons against upstream Veryl's simulator | + +Native component libraries and WASM byte generation do not need Wasmtime. +Cross-codegen features enable Cranelift for their host execution fallback. + A frontend crate should wrap that hook with a constructor named for its own artifact: diff --git a/crates/celox/examples/vtest-exec.rs b/crates/celox/examples/vtest-exec.rs index 66e69731bc6..dc760fea8ad 100644 --- a/crates/celox/examples/vtest-exec.rs +++ b/crates/celox/examples/vtest-exec.rs @@ -4,6 +4,7 @@ use clap::{Parser, ValueEnum}; #[path = "../tests/test_utils/suite.rs"] mod suite; +#[cfg(feature = "veryl-reference")] #[path = "../tests/test_utils/veryl_sim.rs"] mod veryl_sim; #[path = "../tests/test_utils/veryl_sv.rs"] diff --git a/crates/celox/src/backend.rs b/crates/celox/src/backend.rs index 129f9a248a0..e1a72af061c 100644 --- a/crates/celox/src/backend.rs +++ b/crates/celox/src/backend.rs @@ -16,13 +16,13 @@ pub(crate) mod memory_layout; ) ))] pub(crate) mod native; -#[cfg(feature = "host-runtime")] +#[cfg(feature = "cranelift")] mod runtime; #[cfg(feature = "host-runtime")] pub(crate) mod tiered; pub use celox_backend_wasm as wasm_codegen; pub use celox_runtime::backend as traits; -#[cfg(feature = "host-runtime")] +#[cfg(feature = "wasm-runtime")] pub mod wasm_runtime; #[cfg(feature = "host-runtime")] pub(crate) use celox_runtime::RuntimeEventBuffer; @@ -33,15 +33,17 @@ pub use traits::{EventHandle, SimBackend}; #[cfg(feature = "host-runtime")] mod host { pub use super::interp::InterpBackend; + #[cfg(feature = "cranelift")] pub use super::runtime::{EventRef, JitBackend, SharedJitCode}; pub use super::tiered::{ TieredBackend, TieredExecutionStats, TieredExecutionTier, TieredExecutionTiming, TieredPromotionStatus, }; - pub(crate) use celox_backend_cranelift::JitEngine; - pub use celox_backend_cranelift::{ + pub use celox_backend_common::cranelift_options::{ CraneliftDiagnostics, CraneliftOptLevel, CraneliftOptions, RegallocAlgorithm, }; + #[cfg(feature = "cranelift")] + pub(crate) use celox_backend_cranelift::JitEngine; #[cfg(any( target_arch = "x86_64", diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index d3651da5bc6..14dc97903e9 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -3,7 +3,7 @@ //! [`InterpBackend`] implements [`SimBackend`] by executing the laid-out SIR //! directly on the Tier-0 interpreter ([`crate::interpreter::execute_unit`]) //! instead of generated machine code. It shares the exact memory image ABI -//! with [`super::JitBackend`] — little-endian byte packing, four-state value +//! with `JitBackend` — little-endian byte packing, four-state value //! and mask regions stored adjacently per object, the runtime-event-buffer //! and comb-capture-enable pointers installed into the state header, and the //! triggered-bits bitset region — so a simulation can migrate individual @@ -1089,6 +1089,69 @@ fn collect_trigger_addrs( addrs } +/// The trigger-bearing addresses of a schedule group: the union of two +/// sorted lists, so a clock's group shares the combinational list instead of +/// holding a copy of it. +#[derive(Clone, Copy, Default)] +struct TriggerAddrs<'a> { + first: &'a [(AbsoluteAddr, u32)], + second: &'a [(AbsoluteAddr, u32)], +} + +impl<'a> TriggerAddrs<'a> { + fn len(&self) -> usize { + self.first.len() + self.second.len() + } + + /// The addresses of both lists in order, each once. + fn iter(self) -> impl Iterator + 'a { + let (mut first, mut second) = ( + self.first.iter().copied().peekable(), + self.second.iter().copied().peekable(), + ); + std::iter::from_fn(move || match (first.peek(), second.peek()) { + (Some(a), Some(b)) if a < b => first.next(), + (Some(a), Some(b)) if b < a => second.next(), + (Some(_), Some(_)) => { + second.next(); + first.next() + } + (Some(_), None) => first.next(), + (None, _) => second.next(), + }) + } +} + +/// The trigger-bearing addresses of one clock's FF units, from every group +/// it is scheduled in. +#[derive(Default)] +struct ClockTriggerAddrs { + /// Whether the clock's groups also snapshot the combinational units' + /// addresses: an eval/apply clock may run them in a combined tick. + with_comb: bool, + ff: Vec<(AbsoluteAddr, u32)>, +} + +/// The trigger-bearing addresses snapshot at the entry of a group of +/// `clock`. +fn clock_trigger_addrs<'a>( + event_trigger_addrs: &'a HashMap, + comb_trigger_addrs: &'a [(AbsoluteAddr, u32)], + clock: AbsoluteAddr, +) -> TriggerAddrs<'a> { + let Some(addrs) = event_trigger_addrs.get(&clock) else { + return TriggerAddrs::default(); + }; + TriggerAddrs { + first: if addrs.with_comb { + comb_trigger_addrs + } else { + &[] + }, + second: &addrs.ff, + } +} + /// One scheduled SIR unit with register metadata prepared once at backend /// construction. Keeping register storage with the unit removes per-tick /// HashMap walks and slot clearing from the interpreter dispatch path. @@ -1117,15 +1180,15 @@ fn prepare_units( /// Execute every unit in `units` against the split backend storage. #[allow(clippy::too_many_arguments)] -fn run_units( +fn run_units<'u>( memory: &mut [u64], layout: &MemoryLayout, extern_functions: &ExternFunctionTable, four_state: bool, comb_capture_enabled: &mut [u8], heap: &mut celox_heap::Heap, - units: &mut [PreparedUnit], - trigger_addrs: &[(AbsoluteAddr, u32)], + units: impl IntoIterator, + trigger_addrs: TriggerAddrs<'_>, trigger_snapshots: &mut Vec<((AbsoluteAddr, u32), u64)>, emit_triggers: bool, ) -> Result<(), SimulatorErrorCode> { @@ -1136,7 +1199,7 @@ fn run_units( trigger_snapshots.clear(); if emit_triggers { trigger_snapshots.reserve(trigger_addrs.len()); - for &(absolute, region) in trigger_addrs { + for (absolute, region) in trigger_addrs.iter() { let addr = RegionedAbsoluteAddrBase::from_absolute_addr(region, absolute); let machine = Machine { memory: &mut *memory, @@ -1224,14 +1287,15 @@ pub struct InterpBackend { id_to_addr: Vec, id_to_event: Vec, four_state_inits: Vec<(usize, usize)>, - /// Units for the fused comb+FF tick of each event, mirroring the - /// compiled `comb_apply_func`: fused schedules when present, otherwise - /// comb units followed by the clock's FF units. - comb_apply_units: HashMap>, + /// Units for the fused comb+FF tick of an eval/apply clock with a fused + /// schedule, mirroring the compiled `comb_apply_func`. The other + /// eval/apply clocks run `eval_comb_units` followed by their + /// `eval_apply_units` in one group, without a copy of either. + fused_comb_apply_units: HashMap>, /// Trigger-bearing addresses per schedule group, precomputed so a group /// invocation only performs snapshot reads. comb_trigger_addrs: Vec<(AbsoluteAddr, u32)>, - event_trigger_addrs: HashMap>, + event_trigger_addrs: HashMap, /// Reused group-entry trigger snapshots; sorted by address and region. trigger_snapshots: Vec<((AbsoluteAddr, u32), u64)>, /// The extern functions the units call. @@ -1359,17 +1423,15 @@ impl InterpBackend { // program; executing independently scheduled comb and FF units can // observe a different pre-edge snapshot around reset and NBA regions, // exactly as with the compiled backends. - let mut comb_apply_units: HashMap> = HashMap::default(); - for (clock, ff_units) in &laid_out.sir.eval_apply_ffs { - let units = if let Some(fused) = laid_out.sir.eval_comb_apply_ffs.get(clock) { - prepare_units(fused, four_state) - } else { - let mut combined = prepare_units(&laid_out.sir.eval_comb, four_state); - combined.extend(prepare_units(ff_units, four_state)); - combined - }; - comb_apply_units.insert(*clock, units); - } + let fused_comb_apply_units: HashMap> = laid_out + .sir + .eval_apply_ffs + .keys() + .filter_map(|clock| { + let fused = laid_out.sir.eval_comb_apply_ffs.get(clock)?; + Some((*clock, prepare_units(fused, four_state))) + }) + .collect(); let eval_comb_units = prepare_units(&laid_out.sir.eval_comb, four_state); let eval_apply_units = laid_out .sir @@ -1393,29 +1455,23 @@ impl InterpBackend { // Only eval/apply clocks receive combined ticks; eval-only and // apply-only groups fall back to the default two-phase evaluation. let comb_trigger_addrs = collect_trigger_addrs(&laid_out.sir.eval_comb); - let mut event_trigger_addrs: HashMap> = - HashMap::default(); - for (clock, ff_units) in &laid_out.sir.eval_apply_ffs { - let mut addrs = comb_trigger_addrs.clone(); - addrs.extend(collect_trigger_addrs(ff_units)); - addrs.sort_unstable(); - addrs.dedup(); - event_trigger_addrs.insert(*clock, addrs); + let mut event_trigger_addrs: HashMap = HashMap::default(); + for clock in laid_out.sir.eval_apply_ffs.keys() { + event_trigger_addrs.entry(*clock).or_default().with_comb = true; } // Split scheduling can register the same canonical clock under both // maps; merge the address sets so neither phase loses snapshots. for (clock, units) in laid_out .sir - .eval_only_ffs + .eval_apply_ffs .iter() + .chain(&laid_out.sir.eval_only_ffs) .chain(&laid_out.sir.apply_ffs) { let entry = event_trigger_addrs.entry(*clock).or_default(); - let mut addrs = collect_trigger_addrs(units); - addrs.extend(entry.iter().copied()); - addrs.sort_unstable(); - addrs.dedup(); - *entry = addrs; + entry.ff.extend(collect_trigger_addrs(units)); + entry.ff.sort_unstable(); + entry.ff.dedup(); } let mut backend = Self { @@ -1436,7 +1492,7 @@ impl InterpBackend { id_to_addr, id_to_event, four_state_inits, - comb_apply_units, + fused_comb_apply_units, comb_trigger_addrs, event_trigger_addrs, trigger_snapshots: Vec::new(), @@ -1536,7 +1592,10 @@ impl SimBackend for InterpBackend { &mut self.comb_capture_enabled, &mut self.heap, &mut self.eval_comb_units, - &self.comb_trigger_addrs, + TriggerAddrs { + first: &self.comb_trigger_addrs, + second: &[], + }, &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1553,20 +1612,32 @@ impl SimBackend for InterpBackend { self.eval_apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) } fn eval_comb_apply_ff_at(&mut self, event: InterpEventRef) -> Result<(), SimulatorErrorCode> { - let Some(units) = self.comb_apply_units.get_mut(&event.addr()) else { - // Events outside the eval/apply map keep the default ordering. - self.eval_comb()?; - return self.eval_apply_ff_at(event); - }; + let trigger_addrs = clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ); + let (first, second): (&mut [PreparedUnit], &mut [PreparedUnit]) = + if let Some(fused) = self.fused_comb_apply_units.get_mut(&event.addr()) { + (fused, &mut []) + } else if let Some(ff_units) = self.eval_apply_units.get_mut(&event.addr()) { + (&mut self.eval_comb_units, ff_units) + } else { + // Events outside the eval/apply map keep the default ordering. + self.eval_comb()?; + return self.eval_apply_ff_at(event); + }; run_units( self.memory.as_mut_slice(), &self.layout, @@ -1574,8 +1645,8 @@ impl SimBackend for InterpBackend { self.four_state, &mut self.comb_capture_enabled, &mut self.heap, - units, - &self.event_trigger_addrs[&event.addr()], + first.iter_mut().chain(second), + trigger_addrs, &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1592,9 +1663,11 @@ impl SimBackend for InterpBackend { self.eval_only_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1611,9 +1684,11 @@ impl SimBackend for InterpBackend { self.apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), - self.event_trigger_addrs - .get(&event.addr()) - .map_or(&[] as &[(AbsoluteAddr, u32)], Vec::as_slice), + clock_trigger_addrs( + &self.event_trigger_addrs, + &self.comb_trigger_addrs, + event.addr(), + ), &mut self.trigger_snapshots, self.emit_triggers, ) @@ -1633,8 +1708,8 @@ impl SimBackend for InterpBackend { self.four_state, &mut self.comb_capture_enabled, &mut self.heap, - std::slice::from_mut(unit), - &[], + std::iter::once(unit), + TriggerAddrs::default(), &mut self.trigger_snapshots, false, ) @@ -2085,4 +2160,86 @@ mod tests { } } } + + #[test] + fn trigger_addrs_iterate_the_union_in_order() { + let addr = |id: u32| AbsoluteAddr { + instance_id: celox_design::InstanceId(0), + var_id: celox_design::StateObjectId(id), + }; + let lists: [&[u32]; 5] = [&[], &[1], &[1, 4, 9], &[2, 4, 7, 9, 11], &[0, 3, 11]]; + for first in lists { + for second in lists { + for region in [0, 1] { + let entries = |ids: &[u32]| -> Vec<(AbsoluteAddr, u32)> { + ids.iter().map(|&id| (addr(id), region)).collect() + }; + let (first, second) = (entries(first), entries(second)); + let mut expected: Vec<_> = first.iter().chain(&second).copied().collect(); + expected.sort_unstable(); + expected.dedup(); + let addrs = TriggerAddrs { + first: &first, + second: &second, + }; + assert_eq!(addrs.iter().collect::>(), expected); + } + } + } + } + + /// Clocks sharing one combinational program each run it before their + /// flip-flops in a combined tick, as the compiled backends do. + #[test] + fn combined_ticks_of_several_clocks_match_the_compiled_backend() { + const CODE: &str = r#" +module Top ( + clk_a: input 'a clock, + clk_b: input 'b clock, + clk_c: input 'c clock, + din: input 'a logic<8>, + qa: output 'a logic<8>, + qb: output 'b logic<8>, + qc: output 'c logic<8>, +) { + var x: 'a logic<8>; + assign x = din ^ qa; + always_ff (clk_a) { + qa = x + 1; + } + unsafe (cdc) { + always_ff (clk_b) { + qb = qa + x; + } + always_ff (clk_c) { + qc = qb ^ x; + } + } +} +"#; + fn run(mut sim: crate::Simulator) -> Vec { + let clocks = [sim.event("clk_a"), sim.event("clk_b"), sim.event("clk_c")]; + let din = sim.signal("din"); + let outputs = [sim.signal("qa"), sim.signal("qb"), sim.signal("qc")]; + let mut seen = Vec::new(); + for step in 0..60u64 { + let value = (step * 37 + 11) as u8; + sim.modify(|io| io.set(din, value)).unwrap(); + sim.tick_deferred_comb(clocks[(step * 7 % 3) as usize]) + .unwrap(); + if step % 4 == 0 { + sim.tick_deferred_comb(clocks[((step + 1) % 3) as usize]) + .unwrap(); + } + for output in outputs { + seen.push(sim.get(output)); + } + } + seen + } + let builder = || crate::Simulator::builder(CODE, "Top"); + let interpreted = builder().build_interpreter().unwrap(); + assert_eq!(interpreted.backend.eval_apply_units.len(), 3); + assert_eq!(run(interpreted), run(builder().build_cranelift().unwrap())); + } } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 269dbefb940..488c9fc9c90 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -1320,42 +1320,101 @@ struct NativeCompileTask<'a> { type NativeTaskBindings = HashMap<(&'static str, AbsoluteAddr), usize>; +type NativeUnit = crate::ir::ExecutionUnit; + +/// Classes of structurally equal execution units. Each distinct unit is +/// hashed once and compared only against the units of its hash, so tasks +/// whose unit lists share whole programs, such as every unfused comb-apply +/// task starting with all of `eval_comb`, are told apart by their class +/// lists instead of by comparing the programs again for each trigger. +#[derive(Default)] +struct NativeUnitClasses<'a> { + by_unit: HashMap<*const NativeUnit, usize>, + by_hash: HashMap>, + count: usize, +} + +impl<'a> NativeUnitClasses<'a> { + fn class(&mut self, unit: &'a NativeUnit) -> usize { + if let Some(class) = self.by_unit.get(&std::ptr::from_ref(unit)) { + return *class; + } + let bucket = self.by_hash.entry(native_unit_hash(unit)).or_default(); + let class = match bucket.iter().find(|(other, _)| *other == unit) { + Some((_, class)) => *class, + None => { + let class = self.count; + self.count += 1; + bucket.push((unit, class)); + class + } + }; + self.by_unit.insert(std::ptr::from_ref(unit), class); + class + } + + fn classes(&mut self, units: &[&'a NativeUnit]) -> Vec { + units.iter().map(|unit| self.class(unit)).collect() + } +} + +/// A hash of `unit` that equal units share, independent of the iteration +/// order of its maps. +fn native_unit_hash(unit: &NativeUnit) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = fxhash::FxHasher::default(); + unit.entry_block_id.hash(&mut hasher); + let mut blocks = unit.blocks.iter().collect::>(); + blocks.sort_unstable_by_key(|(id, _)| **id); + for (id, block) in blocks { + id.hash(&mut hasher); + block.id.hash(&mut hasher); + block.params.hash(&mut hasher); + block.instructions.hash(&mut hasher); + block.terminator.hash(&mut hasher); + } + let mut registers = unit.register_map.iter().collect::>(); + registers.sort_unstable_by_key(|(id, _)| **id); + registers.hash(&mut hasher); + hasher.finish() +} + fn collect_ff_compile_tasks( sir: &LaidOutProgram, ) -> (Vec>, NativeTaskBindings) { let mut tasks = Vec::new(); let mut task_bindings = HashMap::default(); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_apply_ffs, - "eval_apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_only_ffs, - "eval_only_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.apply_ffs, - "apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_comb_apply_compile_tasks(sir, &mut tasks, &mut task_bindings); + let mut classes = NativeUnitClasses::default(); + // Edge tasks of every label share one index: a task is reused for any + // edge trigger with equal units. + let mut ff_tasks = HashMap::default(); + for (ff_map, label) in [ + (&sir.sir.eval_apply_ffs, "eval_apply_ff"), + (&sir.sir.eval_only_ffs, "eval_only_ff"), + (&sir.sir.apply_ffs, "apply_ff"), + ] { + collect_ff_compile_tasks_from( + sir, + ff_map, + label, + &mut classes, + &mut ff_tasks, + &mut tasks, + &mut task_bindings, + ); + } + collect_comb_apply_compile_tasks(sir, &mut classes, &mut tasks, &mut task_bindings); (tasks, task_bindings) } fn collect_comb_apply_compile_tasks<'a>( sir: &'a LaidOutProgram, + classes: &mut NativeUnitClasses<'a>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { const LABEL: &str = "eval_comb_apply_ff"; + let mut comb_tasks = HashMap::<(Option, Vec), usize>::default(); for (addr, ff_units) in &sir.sir.eval_apply_ffs { let fused_units = sir.sir.eval_comb_apply_ffs.get(addr); let (unit_refs, first_ff_unit) = if let Some(fused_units) = fused_units { @@ -1368,11 +1427,8 @@ fn collect_comb_apply_compile_tasks<'a>( (unit_refs, first_ff_unit) }; let binding = format!("{LABEL} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| { - task.merge_kind == NativeMergeKind::FusedCombAndFf - && task.first_ff_unit == first_ff_unit - && task.units == unit_refs - }) { + let key = (first_ff_unit, classes.classes(&unit_refs)); + let index = if let Some(&index) = comb_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1384,6 +1440,7 @@ fn collect_comb_apply_compile_tasks<'a>( first_ff_unit, bindings: vec![binding], }); + comb_tasks.insert(key, index); index }; task_bindings.insert((LABEL, *addr), index); @@ -1397,13 +1454,16 @@ fn collect_ff_compile_tasks_from<'a>( Vec>, >, label: &'static str, + classes: &mut NativeUnitClasses<'a>, + ff_tasks: &mut HashMap, usize>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { for (addr, units) in ff_map { let unit_refs = units.iter().collect::>(); let binding = format!("{label} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| task.units == unit_refs) { + let key = classes.classes(&unit_refs); + let index = if let Some(&index) = ff_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1415,6 +1475,7 @@ fn collect_ff_compile_tasks_from<'a>( first_ff_unit: None, bindings: vec![binding], }); + ff_tasks.insert(key, index); index }; task_bindings.insert((label, *addr), index); @@ -3522,3 +3583,84 @@ impl super::super::SimBackend for NativeBackend { celox_runtime::backend::triggered_bits_from_bytes(&self.mem_bytes()[offset..offset + size]) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir::{ + BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, + }; + + /// A unit of `blocks` blocks loading `value`, with its maps filled in + /// forward or reverse order. + fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit { + let mut ids = (0..blocks).collect::>(); + if reverse { + ids.reverse(); + } + NativeUnit { + entry_block_id: BlockId(0), + blocks: ids + .iter() + .map(|&id| { + let terminator = if id + 1 < blocks { + SIRTerminator::Jump(BlockId(id + 1), vec![]) + } else { + SIRTerminator::Return + }; + let block = BasicBlock { + id: BlockId(id), + params: vec![], + instructions: vec![SIRInstruction::Imm( + RegisterId(id), + SIRValue::new(value), + )], + terminator, + }; + (BlockId(id), block) + }) + .collect(), + register_map: ids + .iter() + .map(|&id| (RegisterId(id), RegisterType::Logic { width })) + .collect(), + } + } + + #[test] + fn unit_classes_match_deep_comparison() { + let mut pool = Vec::new(); + for blocks in 1..4 { + for value in 0..2 { + for width in [1, 8] { + for reverse in [false, true] { + pool.push(unit(blocks, value, width, reverse)); + } + } + } + } + let units = pool.iter().collect::>(); + // Lists of up to two units, repeating the same references as the + // shared prefix of comb-apply tasks does. + let lists = std::iter::once(Vec::new()) + .chain(units.iter().map(|unit| vec![*unit])) + .chain( + units + .iter() + .flat_map(|a| units.iter().map(move |b| vec![*a, *b])), + ) + .collect::>(); + let mut classes = NativeUnitClasses::default(); + let keys = lists + .iter() + .map(|list| classes.classes(list)) + .collect::>(); + for (a, key_a) in lists.iter().zip(&keys) { + for (b, key_b) in lists.iter().zip(&keys) { + assert_eq!(a == b, key_a == key_b, "{a:?} {b:?}"); + } + } + // The pool has equal units with differently ordered maps. + assert!(classes.count < pool.len()); + } +} diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index ef541fac47e..cf70f8db73b 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -45,16 +45,18 @@ use num_bigint::BigUint; use super::compile_cancel::CompileCancel; use super::{ - EventHandle, MemoryLayout, RuntimeEventBuffer, SharedJitCode, SimBackend, SimulatorErrorCode, + EventHandle, MemoryLayout, RuntimeEventBuffer, SimBackend, SimulatorErrorCode, memory_image::MemoryImage, }; +use crate::backend::InterpBackend; #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", target_arch = "aarch64" ))] use crate::backend::native::SharedNativeCode; -use crate::backend::{InterpBackend, JitBackend}; +#[cfg(feature = "cranelift")] +use crate::backend::{JitBackend, SharedJitCode}; use crate::{ SimulatorError, SimulatorOptions, ir::{AbsoluteAddr, LaidOutProgram, SignalRef}, @@ -109,6 +111,7 @@ pub(crate) fn tiered_layout_mode( /// The adopted compiled tier. enum CompiledTier { + #[cfg(feature = "cranelift")] Jit(Box), #[cfg(any( target_arch = "x86_64", @@ -127,6 +130,7 @@ impl CompiledCode { // scratch beyond the semantic state, and adoption resizes the // transferred image to the compiled layout's total size; report // that requirement so promotion stays inside the reservation. + #[cfg(feature = "cranelift")] CompiledCode::Cranelift(shared) => shared.layout.merged_total_size.div_ceil(8), #[cfg(any( target_arch = "x86_64", @@ -158,6 +162,7 @@ impl CompiledTier { memory.resize_zeroed_within_capacity(code.required_image_words()); } match code { + #[cfg(feature = "cranelift")] CompiledCode::Cranelift(shared) => { Self::Jit(Box::new(JitBackend::adopt_shared_with_state( shared, @@ -186,6 +191,7 @@ impl CompiledTier { fn layout(&self) -> &MemoryLayout { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => jit.layout(), #[cfg(any( target_arch = "x86_64", @@ -198,6 +204,7 @@ impl CompiledTier { fn memory_base_mut(&mut self) -> *mut u8 { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => jit.memory_as_ptr().0.cast_mut(), #[cfg(any( target_arch = "x86_64", @@ -211,6 +218,7 @@ impl CompiledTier { /// Logical capacity of the live image in `u64` words. fn memory_word_capacity(&self) -> usize { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => { let (_, size_bytes) = jit.memory_as_ptr(); size_bytes.div_ceil(8) @@ -233,12 +241,14 @@ impl CompiledTier { feature = "arm64-codegen", target_arch = "aarch64" ))] + #[allow(irrefutable_let_patterns)] if let CompiledCode::Native(shared) = code { return match self { Self::Native(native) => { native.replace_shared_code(shared); true } + #[cfg(feature = "cranelift")] Self::Jit(_) => false, }; } @@ -255,6 +265,7 @@ impl CompiledTier { fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => jit.eval_comb(), #[cfg(any( target_arch = "x86_64", @@ -270,6 +281,7 @@ impl CompiledTier { /// so translation is an array lookup. fn eval_apply_ff_at(&mut self, id: usize) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => { let event = jit.id_to_event_slice()[id]; jit.eval_apply_ff_at(event) @@ -288,6 +300,7 @@ impl CompiledTier { fn eval_comb_apply_ff_at(&mut self, id: usize) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => { let event = jit.id_to_event_slice()[id]; jit.eval_comb_apply_ff_at(event) @@ -314,6 +327,7 @@ impl CompiledTier { count: u64, ) -> (u64, Result<(), SimulatorErrorCode>) { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => (1, { let event = jit.id_to_event_slice()[id]; jit.eval_comb_apply_ff_at(event) @@ -337,6 +351,7 @@ impl CompiledTier { /// here; the address resolves through each tier's phase-specific map. fn eval_only_ff_at_addr(&mut self, addr: &AbsoluteAddr) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => { let event = jit .resolve_eval_only_event(addr) @@ -359,6 +374,7 @@ impl CompiledTier { fn run_process(&mut self, index: usize) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => jit.run_process(index), #[cfg(any( target_arch = "x86_64", @@ -373,6 +389,7 @@ impl CompiledTier { /// and execute it. fn apply_ff_at_addr(&mut self, addr: &AbsoluteAddr) -> Result<(), SimulatorErrorCode> { match self { + #[cfg(feature = "cranelift")] Self::Jit(jit) => { let event = jit .resolve_apply_event(addr) @@ -397,6 +414,7 @@ impl CompiledTier { /// Compiled code produced by the background worker, before it is bound to a /// live simulation state at promotion time. pub(crate) enum CompiledCode { + #[cfg(feature = "cranelift")] Cranelift(Arc), #[cfg(any( target_arch = "x86_64", @@ -661,6 +679,16 @@ impl TieredBackend { unreachable!("native tier selected on a host without native support") } } else { + #[cfg(not(feature = "cranelift"))] + { + Self::with_compiler(laid_out, options, |_, _, _| { + Err( + crate::CodegenError::message("Cranelift requires the cranelift feature") + .into(), + ) + }) + } + #[cfg(feature = "cranelift")] Self::with_compiler(laid_out, options, |laid_out, options, _cancel| { let mut trace = crate::debug::CompilationTrace::default(); let wants_codegen_trace = options.trace.pre_optimized_clif @@ -1354,6 +1382,7 @@ impl SimBackend for TieredBackend { fn resolve_signal(&self, addr: &AbsoluteAddr) -> SignalRef { match &self.phase { Phase::Interpreting(Some(interp)) => interp.resolve_signal(addr), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.resolve_signal(addr), #[cfg(any( target_arch = "x86_64", @@ -1374,6 +1403,7 @@ impl SimBackend for TieredBackend { id: ev.id(), } } + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => { let ev = jit.resolve_event(addr); TieredEventRef { @@ -1405,6 +1435,7 @@ impl SimBackend for TieredBackend { id: ev.id(), }) } + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => { jit.resolve_event_opt(addr).map(|ev| TieredEventRef { addr: ev.addr(), @@ -1436,6 +1467,7 @@ impl SimBackend for TieredBackend { id: ev.id(), }) } + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => { jit.resolve_eval_only_event(addr).map(|ev| TieredEventRef { addr: ev.addr(), @@ -1465,6 +1497,7 @@ impl SimBackend for TieredBackend { id: ev.id(), }) } + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => { jit.resolve_apply_event(addr).map(|ev| TieredEventRef { addr: ev.addr(), @@ -1489,6 +1522,7 @@ impl SimBackend for TieredBackend { fn set(&mut self, signal: SignalRef, value: T) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.set(signal, value), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.set(signal, value), #[cfg(any( target_arch = "x86_64", @@ -1503,6 +1537,7 @@ impl SimBackend for TieredBackend { fn set_wide(&mut self, signal: SignalRef, value: BigUint) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.set_wide(signal, value), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.set_wide(signal, value), #[cfg(any( target_arch = "x86_64", @@ -1517,6 +1552,7 @@ impl SimBackend for TieredBackend { fn set_four_state(&mut self, signal: SignalRef, value: BigUint, mask: BigUint) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.set_four_state(signal, value, mask), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.set_four_state(signal, value, mask), #[cfg(any( target_arch = "x86_64", @@ -1533,6 +1569,7 @@ impl SimBackend for TieredBackend { fn get(&self, signal: SignalRef) -> BigUint { match &self.phase { Phase::Interpreting(Some(interp)) => interp.get(signal), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.get(signal), #[cfg(any( target_arch = "x86_64", @@ -1547,6 +1584,7 @@ impl SimBackend for TieredBackend { fn get_as(&self, signal: SignalRef) -> T { match &self.phase { Phase::Interpreting(Some(interp)) => interp.get_as(signal), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.get_as(signal), #[cfg(any( target_arch = "x86_64", @@ -1561,6 +1599,7 @@ impl SimBackend for TieredBackend { fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint) { match &self.phase { Phase::Interpreting(Some(interp)) => interp.get_four_state(signal), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.get_four_state(signal), #[cfg(any( target_arch = "x86_64", @@ -1575,6 +1614,7 @@ impl SimBackend for TieredBackend { fn memory_as_ptr(&self) -> (*const u8, usize) { match &self.phase { Phase::Interpreting(Some(interp)) => interp.memory_as_ptr(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.memory_as_ptr(), #[cfg(any( target_arch = "x86_64", @@ -1589,6 +1629,7 @@ impl SimBackend for TieredBackend { fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.memory_as_mut_ptr(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.memory_as_mut_ptr(), #[cfg(any( target_arch = "x86_64", @@ -1603,6 +1644,7 @@ impl SimBackend for TieredBackend { fn memory_owner(&self) -> Option> { match &self.phase { Phase::Interpreting(Some(interp)) => interp.memory_owner(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.memory_owner(), #[cfg(any( target_arch = "x86_64", @@ -1617,6 +1659,7 @@ impl SimBackend for TieredBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.write_memory(offset, bytes), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.write_memory(offset, bytes), #[cfg(any( target_arch = "x86_64", @@ -1631,6 +1674,7 @@ impl SimBackend for TieredBackend { fn vcd_tracking_enabled(&self) -> bool { match &self.phase { Phase::Interpreting(Some(interp)) => interp.vcd_tracking_enabled(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.vcd_tracking_enabled(), #[cfg(any( target_arch = "x86_64", @@ -1645,6 +1689,7 @@ impl SimBackend for TieredBackend { fn runtime_event_buffer_as_ptr(&self) -> (*const u8, usize) { match &self.phase { Phase::Interpreting(Some(interp)) => interp.runtime_event_buffer_as_ptr(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.runtime_event_buffer_as_ptr(), #[cfg(any( target_arch = "x86_64", @@ -1659,6 +1704,7 @@ impl SimBackend for TieredBackend { fn runtime_event_buffer(&self) -> Option> { match &self.phase { Phase::Interpreting(Some(interp)) => interp.runtime_event_buffer(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => Some(jit.runtime_event_buffer().clone()), #[cfg(any( target_arch = "x86_64", @@ -1675,6 +1721,7 @@ impl SimBackend for TieredBackend { Phase::Interpreting(Some(interp)) => { interp.set_comb_capture_event_enabled(active_sites) } + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => { jit.set_comb_capture_event_enabled(active_sites) } @@ -1693,6 +1740,7 @@ impl SimBackend for TieredBackend { fn comb_capture_event_enabled(&self) -> Vec { match &self.phase { Phase::Interpreting(Some(interp)) => interp.comb_capture_event_enabled(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.comb_capture_event_enabled(), #[cfg(any( target_arch = "x86_64", @@ -1707,6 +1755,7 @@ impl SimBackend for TieredBackend { fn stable_region_size(&self) -> usize { match &self.phase { Phase::Interpreting(Some(interp)) => interp.stable_region_size(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.stable_region_size(), #[cfg(any( target_arch = "x86_64", @@ -1721,6 +1770,7 @@ impl SimBackend for TieredBackend { fn layout(&self) -> &MemoryLayout { match &self.phase { Phase::Interpreting(Some(interp)) => interp.layout(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.layout(), #[cfg(any( target_arch = "x86_64", @@ -1735,6 +1785,7 @@ impl SimBackend for TieredBackend { fn heap(&self) -> &celox_heap::Heap { match &self.phase { Phase::Interpreting(Some(interp)) => interp.heap(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.heap(), #[cfg(any( target_arch = "x86_64", @@ -1749,6 +1800,7 @@ impl SimBackend for TieredBackend { fn heap_mut(&mut self) -> &mut celox_heap::Heap { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.heap_mut(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.heap_mut(), #[cfg(any( target_arch = "x86_64", @@ -1763,6 +1815,7 @@ impl SimBackend for TieredBackend { fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { match &self.phase { Phase::Interpreting(Some(interp)) => interp.id_to_addr_slice(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.id_to_addr_slice(), #[cfg(any( target_arch = "x86_64", @@ -1781,6 +1834,7 @@ impl SimBackend for TieredBackend { fn num_events(&self) -> usize { match &self.phase { Phase::Interpreting(Some(interp)) => interp.num_events(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.num_events(), #[cfg(any( target_arch = "x86_64", @@ -1795,6 +1849,7 @@ impl SimBackend for TieredBackend { fn clear_triggered_bits(&mut self) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.clear_triggered_bits(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.clear_triggered_bits(), #[cfg(any( target_arch = "x86_64", @@ -1809,6 +1864,7 @@ impl SimBackend for TieredBackend { fn mark_triggered_bit(&mut self, id: usize) { match &mut self.phase { Phase::Interpreting(Some(interp)) => interp.mark_triggered_bit(id), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.mark_triggered_bit(id), #[cfg(any( target_arch = "x86_64", @@ -1823,6 +1879,7 @@ impl SimBackend for TieredBackend { fn get_triggered_bits(&self) -> bit_set::BitSet { match &self.phase { Phase::Interpreting(Some(interp)) => interp.get_triggered_bits(), + #[cfg(feature = "cranelift")] Phase::Compiled(CompiledTier::Jit(jit)) => jit.get_triggered_bits(), #[cfg(any( target_arch = "x86_64", @@ -2631,6 +2688,7 @@ module Top ( /// beyond the interpreter's semantic state), and the growth must stay /// within the reserved arena so the live image never moves. #[test] + #[cfg(feature = "cranelift")] fn cranelift_promotion_covers_its_image_requirement_without_moving_the_image() { use std::sync::Mutex; diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 26e5c70b1a2..45cbdac4913 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -2,7 +2,7 @@ //! //! Compiles SIRT → WASM bytecode via [`wasm_codegen`], then instantiates and //! executes the generated modules with Wasmtime. Provides the same interface -//! as [`JitBackend`] so that [`Simulator`] can use either backend. +//! as `JitBackend` so that [`crate::Simulator`] can use either backend. use num_bigint::BigUint; use wasmtime::{Engine, Linker, Memory, Module, Store, TypedFunc}; diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 9091f8e1f52..71356d5fc44 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -9,7 +9,7 @@ use veryl_metadata::component_manifest::{ConnectionFacts, ConnectionTarget, Conn mod host; mod injected; mod loader; -#[cfg(not(target_family = "wasm"))] +#[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] mod wasm; use host::{ExternalInstance, HostContext, HostValue, PortDir, PortRole}; diff --git a/crates/celox/src/component/host.rs b/crates/celox/src/component/host.rs index 61335a5a20b..0abcd07d528 100644 --- a/crates/celox/src/component/host.rs +++ b/crates/celox/src/component/host.rs @@ -805,7 +805,7 @@ enum InstanceInner { state: *mut c_void, vtable: &'static sys::VrlComponentVTable, }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] Wasm(Box), Injected { instance: String, @@ -886,7 +886,7 @@ impl ExternalInstance { inner: InstanceInner::Native { state, vtable }, }) } - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] crate::component::loader::ComponentBackend::Wasm { library, type_name, @@ -912,7 +912,7 @@ impl ExternalInstance { pub fn kind(&self) -> u32 { match &self.inner { InstanceInner::Native { vtable, .. } => vtable.kind, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.kind(), InstanceInner::Injected { definition, .. } => definition.kind, } @@ -923,7 +923,7 @@ impl ExternalInstance { InstanceInner::Native { state, vtable } => unsafe { (vtable.on_init)(*state, host.as_ctx()) }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.on_init(host), InstanceInner::Injected { instance, @@ -939,7 +939,7 @@ impl ExternalInstance { InstanceInner::Native { state, vtable } => unsafe { (vtable.on_reset)(*state, host.as_ctx()) }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.on_reset(host), InstanceInner::Injected { instance, @@ -955,7 +955,7 @@ impl ExternalInstance { InstanceInner::Native { state, vtable } => unsafe { (vtable.on_clock)(*state, host.as_ctx()) }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.on_clock(host), InstanceInner::Injected { instance, @@ -971,7 +971,7 @@ impl ExternalInstance { InstanceInner::Native { state, vtable } => unsafe { (vtable.on_finish)(*state, host.as_ctx()) }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.on_finish(host), InstanceInner::Injected { instance, @@ -1029,7 +1029,7 @@ impl ExternalInstance { _ => HostValue::Unit, }) } - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(instance) => instance.call_method(host, name, args), InstanceInner::Injected { instance, @@ -1052,7 +1052,7 @@ impl Drop for ExternalInstance { match &mut self.inner { InstanceInner::Native { state, vtable } => unsafe { (vtable.destroy)(*state) }, // The wasm instance's own Drop calls the guest destructor. - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(_) => {} InstanceInner::Injected { .. } => {} } @@ -1063,7 +1063,7 @@ impl std::fmt::Debug for ExternalInstance { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let transport = match &self.inner { InstanceInner::Native { .. } => "native", - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] InstanceInner::Wasm(_) => "wasm", InstanceInner::Injected { .. } => "injected", }; diff --git a/crates/celox/src/component/loader.rs b/crates/celox/src/component/loader.rs index 601c72a59b6..eb38e37239c 100644 --- a/crates/celox/src/component/loader.rs +++ b/crates/celox/src/component/loader.rs @@ -38,12 +38,12 @@ pub enum ComponentError { #[cfg(target_family = "wasm")] #[error("dynamic component libraries are not supported on this platform")] Unsupported, - #[cfg(target_family = "wasm")] + #[cfg(not(all(feature = "wasm-component", not(target_family = "wasm"))))] #[error( - "component library {path} is a wasm binary, but this veryl build targets a wasm platform and cannot host wasm components; use a native veryl build instead" + "component library {path} is a wasm binary, but WASM component hosting is unavailable; enable the wasm-component feature on a native host" )] WasmHostUnsupported { path: PathBuf }, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] #[error( "component `{name}` declares `requires(native)` and cannot run as a prebuilt wasm binary; build it from source instead" )] @@ -53,7 +53,7 @@ pub enum ComponentError { /// A resolved component implementation behind one of the transports. pub enum ComponentBackend { Native(&'static sys::VrlComponentVTable), - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] Wasm { library: std::sync::Arc, type_name: String, @@ -67,7 +67,7 @@ impl ComponentBackend { pub fn kind(&self) -> u32 { match self { ComponentBackend::Native(vtable) => vtable.kind, - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] ComponentBackend::Wasm { kind, .. } => *kind, } } @@ -77,7 +77,7 @@ impl std::fmt::Debug for ComponentBackend { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ComponentBackend::Native(_) => write!(f, "ComponentBackend::Native"), - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] ComponentBackend::Wasm { type_name, kind, .. } => f @@ -107,11 +107,11 @@ pub fn lookup_component_backend( ) -> Result { match library { Some(path) if is_wasm_library(path) => { - #[cfg(not(target_family = "wasm"))] + #[cfg(all(feature = "wasm-component", not(target_family = "wasm")))] { crate::component::wasm::lookup_wasm_component(path, type_name) } - #[cfg(target_family = "wasm")] + #[cfg(not(all(feature = "wasm-component", not(target_family = "wasm"))))] { let _ = type_name; Err(ComponentError::WasmHostUnsupported { @@ -332,6 +332,19 @@ fn lookup_in_library( mod tests { use super::parse_library_manifest_json; + #[cfg(not(feature = "wasm-component"))] + #[test] + fn disabled_wasm_host_reports_required_feature() { + let error = + super::lookup_component_backend(Some(std::path::Path::new("missing.wasm")), "Counter") + .unwrap_err(); + assert!(matches!( + error, + super::ComponentError::WasmHostUnsupported { .. } + )); + assert!(error.to_string().contains("wasm-component")); + } + #[test] fn strict_library_manifest_parser_rejects_malformed_documents() { assert!(parse_library_manifest_json("not json", "component").is_err()); diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 32c2c0ae4f9..55f2ba8b88b 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -717,7 +717,10 @@ impl Emitter<'_> { /// settle before the domains evaluate. #[derive(Clone, Copy, Debug)] enum Settle { - #[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] + #[cfg_attr( + not(all(test, feature = "systemverilog", feature = "cranelift")), + allow(dead_code) + )] Fixed(bool), /// A flag object, not zero when it must. Flag(AbsoluteAddr), @@ -851,7 +854,7 @@ pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { } /// A generated edge unit and the edge it runs, for the tests. -#[cfg(all(test, feature = "systemverilog"))] +#[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] #[derive(Clone, Copy, Debug)] pub(crate) struct TestEdgeUnit { pub(crate) event: AbsoluteAddr, @@ -861,12 +864,12 @@ pub(crate) struct TestEdgeUnit { pub(crate) index: usize, } -#[cfg(all(test, feature = "systemverilog"))] +#[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] pub(crate) type TestEdgeUnits = std::sync::Arc>>; /// Append an edge unit of every event with a plan this module emits, for /// each edge, settle and own-edge case, and record them in `sink`. -#[cfg(all(test, feature = "systemverilog"))] +#[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUnits) { let model = ScheduleModel::derive(&program.design, &program.runtime.runtime_schema); for event in crate::edge_plans::event_addresses(program) { @@ -893,7 +896,7 @@ pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUni } } -#[cfg(all(test, feature = "systemverilog"))] +#[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] mod tests { use std::path::Path; diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 0ff34139732..474221fabfc 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -103,11 +103,16 @@ pub const MAX_SIMULATION_THREADS: u32 = 64; mod host_api { use crate::SimBackend; pub use crate::backend::tiered::TieredEventRef; + #[cfg(feature = "wasm-runtime")] pub use crate::backend::wasm_runtime::WasmBackend; pub use crate::backend::{ - CraneliftDiagnostics, CraneliftOptLevel, CraneliftOptions, EventRef, InterpBackend, - JitBackend, RegallocAlgorithm, SharedJitCode, TieredBackend, TieredExecutionStats, - TieredExecutionTier, TieredExecutionTiming, TieredPromotionStatus, + CraneliftDiagnostics, CraneliftOptLevel, CraneliftOptions, RegallocAlgorithm, + }; + #[cfg(feature = "cranelift")] + pub use crate::backend::{EventRef, JitBackend, SharedJitCode}; + pub use crate::backend::{ + InterpBackend, TieredBackend, TieredExecutionStats, TieredExecutionTier, + TieredExecutionTiming, TieredPromotionStatus, }; pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 9ff42deb8cc..2bcd39299f2 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1272,8 +1272,11 @@ mod process_tests { fn check_all_backends(four_state: bool, steps: usize) { let timed = || Simulation::from_frontend(design(four_state, steps)).four_state(four_state); check(timed().build_interpreter().unwrap(), steps as u64); + #[cfg(feature = "cranelift")] check(timed().build_cranelift().unwrap(), steps as u64); + #[cfg(feature = "wasm-runtime")] check(timed().build_wasm().unwrap(), steps as u64); + #[cfg(feature = "cranelift")] check( timed() .threads(4) @@ -1425,7 +1428,9 @@ mod process_tests { .emit_triggers() }; check(build().build_interpreter().unwrap()); + #[cfg(feature = "cranelift")] check(build().build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] check(build().build_wasm().unwrap()); check(build().build_tiered().unwrap()); #[cfg(any( @@ -1482,7 +1487,9 @@ mod process_tests { .emit_triggers() }; check(build().build_interpreter().unwrap(), step, bit); + #[cfg(feature = "cranelift")] check(build().build_cranelift().unwrap(), step, bit); + #[cfg(feature = "wasm-runtime")] check(build().build_wasm().unwrap(), step, bit); check(build().build_tiered().unwrap(), step, bit); #[cfg(any( @@ -1610,24 +1617,28 @@ mod process_tests { "{}", context("interp tick") ); + #[cfg(feature = "cranelift")] assert_eq!( timed(build().build_cranelift().unwrap()), want, "{}", context("cranelift timed") ); + #[cfg(feature = "cranelift")] assert_eq!( ticked(build().build_cranelift().unwrap()), want, "{}", context("cranelift tick") ); + #[cfg(feature = "wasm-runtime")] assert_eq!( timed(build().build_wasm().unwrap()), want, "{}", context("wasm timed") ); + #[cfg(feature = "wasm-runtime")] assert_eq!( ticked(build().build_wasm().unwrap()), want, @@ -1728,7 +1739,9 @@ endmodule .emit_triggers() }; check(build().build_interpreter().unwrap()); + #[cfg(feature = "cranelift")] check(build().build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] check(build().build_wasm().unwrap()); check(build().build_tiered().unwrap()); #[cfg(any( @@ -1845,7 +1858,9 @@ mod four_state_edge_tests { ($builder:expr, $check:ident) => {{ let builder = || $builder.four_state(true).emit_triggers(); $check(builder().build_interpreter().unwrap()); + #[cfg(feature = "cranelift")] $check(builder().build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] $check(builder().build_wasm().unwrap()); $check(builder().build_tiered().unwrap()); #[cfg(any( diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 44896cfbc7f..ceb3ba86f99 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -802,10 +802,12 @@ mod tests { &expected, &format!("{mode:?}"), ); + #[cfg(feature = "cranelift")] let cranelift = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") .scheduler_mode(mode) .build_cranelift() .unwrap(); + #[cfg(feature = "cranelift")] check(cranelift, runs, &expected, &format!("cranelift {mode:?}")); } } diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 0eff469ac73..2b497812fd2 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -18,7 +18,9 @@ macro_rules! on_every_backend { ($builder:expr, |$sim:ident| $body:block) => {{ fn run(mut $sim: Simulation) $body run($builder.build_interpreter().unwrap()); + #[cfg(feature = "cranelift")] run($builder.build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] run($builder.build_wasm().unwrap()); run($builder.build_tiered().unwrap()); #[cfg(any( diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index abae66ea6c2..3ac1eeebf08 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -55,7 +55,7 @@ mod host { use crate::backend::native::{NativeBackend, SharedNativeCode}; use crate::{ IOContext, RuntimeErrorCode, - backend::{JitBackend, MemoryLayout, SharedJitCode, SimBackend}, + backend::{MemoryLayout, SimBackend}, ir::{ DisplaySizing, InitialMemoryData, InitialMemoryWriteRun, InstancePath, RuntimeEventKind, RuntimeEventSite, RuntimeProgram, SignalRef, VariableInfo, @@ -2561,7 +2561,7 @@ mod host { } /// The edge facts of `event`. - #[cfg(all(test, feature = "systemverilog"))] + #[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] pub(crate) fn event_edge(&self, event: B::Event) -> celox_runtime::EventEdge { self.event_edges[event.id()] } @@ -2707,7 +2707,7 @@ mod host { /// Build VCD signal descriptors for all instances. /// /// The returned descriptors are self-contained (no IR references) and can - /// be cached alongside [`SharedJitCode`] so that VCD works on cache-hit + /// be cached alongside `SharedJitCode` so that VCD works on cache-hit /// paths without the original [`RuntimeProgram`]. pub fn build_vcd_descs(&self, four_state_mode: bool) -> Vec { let mut descs = Vec::new(); @@ -3024,6 +3024,8 @@ mod host { } } + #[cfg(feature = "cranelift")] + use crate::backend::{JitBackend, SharedJitCode}; // ── JitBackend-specific methods ────────────────────────────────────── impl Simulator { pub fn builder<'a>(code: &'a str, top: &'a str) -> SimulatorBuilder<'a, Simulator> { @@ -3077,6 +3079,7 @@ mod host { } } + #[cfg(feature = "cranelift")] impl Simulator { /// Returns the shared compiled JIT code, allowing it to be reused /// for creating additional simulator instances without recompilation. @@ -3090,6 +3093,7 @@ mod host { } } + #[cfg(feature = "wasm-runtime")] impl Simulator { /// Consume the simulator and return the inner Wasmtime backend. pub fn into_backend(self) -> crate::backend::wasm_runtime::WasmBackend { diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index c732c12f32f..75e1a4f61a5 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1636,6 +1636,7 @@ fn compile_hdl_to_sir_with_layout_mode( mod host { use super::super::Simulator; use super::*; + #[cfg(feature = "cranelift")] use crate::backend::JitBackend; use crate::ir::LaidOutProgram; @@ -1680,7 +1681,7 @@ mod host { /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, /// Generated derived-edge units the tests run, recorded here. - #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] pub(crate) derived_edge_units: Option, /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. @@ -1988,7 +1989,7 @@ mod host { diagnostic_policy: Default::default(), sv_timescale: None, emit_triggers: false, - #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] derived_edge_units: None, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), @@ -2148,7 +2149,7 @@ mod host { /// Append the generated derived-edge units of every event and record /// them in `sink`. - #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] pub(crate) fn derived_edge_units( mut self, sink: crate::derived_edge::TestEdgeUnits, @@ -2917,7 +2918,7 @@ mod host { { crate::derived_edge::attach(&mut laid_out); } - #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); } @@ -2963,6 +2964,7 @@ mod host { } /// Compiles using the Cranelift JIT backend. + #[cfg(feature = "cranelift")] pub fn build_cranelift(self) -> Result, SimulatorError> { let phase_timing = self.options.diagnostics.phase_timing; let phase_start = phase_timing.then(crate::timing::now); @@ -3383,6 +3385,7 @@ mod host { } /// Compiles using the Wasmtime WASM backend. + #[cfg(feature = "wasm-runtime")] pub fn build_wasm( self, ) -> Result, SimulatorError> { @@ -3422,6 +3425,7 @@ mod host { } /// Compiles and runs a testbench using the Cranelift JIT backend. + #[cfg(feature = "cranelift")] pub fn run_test_cranelift(self) -> Result { run_test_with_sim(self.build_cranelift()?) } @@ -3746,6 +3750,7 @@ mod host { } /// Compiles a timed simulation using the Cranelift JIT backend. + #[cfg(feature = "cranelift")] pub fn build_cranelift(self) -> Result, SimulatorError> { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, @@ -3842,6 +3847,7 @@ mod host { } /// Compiles a timed simulation using the Wasmtime WASM backend. + #[cfg(feature = "wasm-runtime")] pub fn build_wasm( self, ) -> Result, SimulatorError> diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index de6d0097ec0..a633fbf92b6 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -168,7 +168,7 @@ pub enum SimulatorErrorKind { #[derive(Debug, Error)] #[non_exhaustive] pub enum CodegenError { - #[cfg(feature = "host-runtime")] + #[cfg(feature = "cranelift")] #[error("{0}")] Cranelift( #[from] @@ -232,7 +232,7 @@ pub enum CodegenError { source: std::io::Error, }, - #[cfg(feature = "host-runtime")] + #[cfg(feature = "wasm-runtime")] #[error("WASM {stage} failed: {source}")] Wasm { stage: &'static str, @@ -398,7 +398,7 @@ impl From for SimulatorError { } } -#[cfg(feature = "host-runtime")] +#[cfg(feature = "cranelift")] impl From for SimulatorError { fn from(error: celox_backend_cranelift::CraneliftError) -> Self { CodegenError::from(error).into() @@ -426,6 +426,7 @@ mod tests { ); } + #[cfg(feature = "cranelift")] #[test] fn simulator_error_keeps_the_backend_source_chain() { let backend = celox_backend_cranelift::CraneliftError::NativeTarget { diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 55d2078f84c..1420c5d1975 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -494,7 +494,9 @@ mod queue_tests { }; } regressions!(interpreter, build_interpreter); + #[cfg(feature = "cranelift")] regressions!(cranelift, build_cranelift); + #[cfg(feature = "wasm-runtime")] regressions!(wasm, build_wasm); #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] regressions!(native, build_native); diff --git a/crates/celox/tests/flip_flop.rs b/crates/celox/tests/flip_flop.rs index f845393ee10..7f64d2c7c13 100644 --- a/crates/celox/tests/flip_flop.rs +++ b/crates/celox/tests/flip_flop.rs @@ -3837,8 +3837,7 @@ fn test_ff_runtime_for_dynamic_zero_start_mul_reports_true_loop(sim) { .unwrap(); let error = sim.tick(clk).unwrap_err(); // Only the Veryl reference adapter lacks Celox's detailed loop diagnostic. - let expected = if (&sim as &dyn std::any::Any) - .is::() + let expected = if test_utils::is_veryl_reference(&sim) { celox::RuntimeErrorCode::DetectedTrueLoop } else { @@ -3876,8 +3875,7 @@ fn test_ff_runtime_for_terminal_inclusive_mul_loop_reports_true_loop(sim) { sim.modify(|io| io.set(count, 0u8)).unwrap(); let error = sim.tick(clk).unwrap_err(); // Only the Veryl reference adapter lacks Celox's detailed loop diagnostic. - let expected = if (&sim as &dyn std::any::Any) - .is::() + let expected = if test_utils::is_veryl_reference(&sim) { celox::RuntimeErrorCode::DetectedTrueLoop } else { diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 6ad262ad875..8c1e8c02fdd 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -312,6 +312,7 @@ fn build(design: &Design, backend: &str) -> Result> { .build_native_from_image(image)?, )) } + #[cfg(feature = "cranelift")] "cranelift" => Box::new(TimedBackend::new(builder.build_cranelift()?)), "native-parallel" => Box::new(TimedBackend::new( builder @@ -319,12 +320,14 @@ fn build(design: &Design, backend: &str) -> Result> { .parallel_partition(celox::ParallelPartition::Always) .build_native()?, )), + #[cfg(feature = "cranelift")] "cranelift-parallel" => Box::new(TimedBackend::new( builder .threads(4) .parallel_partition(celox::ParallelPartition::Always) .build_cranelift()?, )), + #[cfg(feature = "wasm-runtime")] "wasm" => Box::new(TimedBackend::new(builder.build_wasm()?)), _ => return Err(format!("unknown backend: {backend}").into()), }); @@ -365,6 +368,7 @@ fn build(design: &Design, backend: &str) -> Result> { .map_err(rejected)?, )) } + #[cfg(feature = "cranelift")] "cranelift" => Box::new(CeloxBackend(builder.build_cranelift().map_err(rejected)?)), "native-parallel" => Box::new(CeloxBackend( builder @@ -373,6 +377,7 @@ fn build(design: &Design, backend: &str) -> Result> { .build_native() .map_err(rejected)?, )), + #[cfg(feature = "cranelift")] "cranelift-parallel" => Box::new(CeloxBackend( builder .threads(4) @@ -380,6 +385,7 @@ fn build(design: &Design, backend: &str) -> Result> { .build_cranelift() .map_err(rejected)?, )), + #[cfg(feature = "wasm-runtime")] "wasm" => Box::new(CeloxBackend(builder.build_wasm().map_err(rejected)?)), _ => return Err(format!("unknown backend: {backend}").into()), }) diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 6d45dc72af6..bc04df46378 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -420,6 +420,7 @@ fn process_writes_reach_the_waveform() { ); } +#[cfg(feature = "cranelift")] #[test] fn veryl_testbenches_reject_artifacts_with_processes() { let source = r#" diff --git a/crates/celox/tests/test_utils/mod.rs b/crates/celox/tests/test_utils/mod.rs index 141a34687f5..6aa4a723577 100644 --- a/crates/celox/tests/test_utils/mod.rs +++ b/crates/celox/tests/test_utils/mod.rs @@ -1,4 +1,5 @@ pub mod suite; +#[cfg(feature = "veryl-reference")] pub mod veryl_sim; pub mod veryl_sv; pub mod vtest_exec; @@ -153,6 +154,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* #[allow(unused_mut, unused_variables)] + #[cfg(feature = "veryl-reference")] fn veryl() { #[allow(dead_code)] const FRONTEND: test_utils::Frontend = test_utils::Frontend::Veryl; @@ -235,6 +237,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* #[allow(unused_mut, unused_variables)] + #[cfg(feature = "cranelift")] fn cranelift() { #[allow(dead_code)] const FRONTEND: test_utils::Frontend = test_utils::Frontend::Veryl; @@ -251,6 +254,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* #[allow(unused_mut, unused_variables)] + #[cfg(feature = "cranelift")] fn cranelift_parallel() { #[allow(dead_code)] const FRONTEND: test_utils::Frontend = test_utils::Frontend::Veryl; @@ -269,6 +273,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* #[allow(unused_mut, unused_variables)] + #[cfg(feature = "wasm-runtime")] fn wasm() { #[allow(dead_code)] const FRONTEND: test_utils::Frontend = test_utils::Frontend::Veryl; @@ -395,6 +400,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* + #[cfg(feature = "cranelift")] fn cranelift() { test_utils::suite::run_case($case, "cranelift"); } @@ -403,6 +409,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* + #[cfg(feature = "cranelift")] fn cranelift_parallel() { test_utils::suite::run_case($case, "cranelift-parallel"); } @@ -411,6 +418,7 @@ macro_rules! all_backends { #[test] $(#[$meta])* + #[cfg(feature = "wasm-runtime")] fn wasm() { test_utils::suite::run_case($case, "wasm"); } @@ -431,6 +439,7 @@ macro_rules! all_backends { all_backends!(@with_ignore veryl; $ignore_list; { #[test] $(#[$meta])* + #[cfg(feature = "veryl-reference")] fn veryl() { test_utils::suite::run_case($case, "veryl"); } @@ -459,3 +468,16 @@ macro_rules! all_backends { ); )*}; } + +#[allow(dead_code)] +pub fn is_veryl_reference(value: &dyn std::any::Any) -> bool { + #[cfg(feature = "veryl-reference")] + { + value.is::() + } + #[cfg(not(feature = "veryl-reference"))] + { + let _ = value; + false + } +} diff --git a/crates/celox/tests/test_utils/suite.rs b/crates/celox/tests/test_utils/suite.rs index a152d50d399..2dcbfc9c803 100644 --- a/crates/celox/tests/test_utils/suite.rs +++ b/crates/celox/tests/test_utils/suite.rs @@ -81,8 +81,10 @@ impl Backend for CeloxBackend { } } +#[cfg(feature = "veryl-reference")] struct VerylBackend(super::veryl_sim::VerylSimAdapter); +#[cfg(feature = "veryl-reference")] impl VerylBackend { fn signal(&mut self, path: &SignalPath) -> super::veryl_sim::VerylSignalRef { let instances: Vec<_> = path @@ -94,6 +96,7 @@ impl VerylBackend { } } +#[cfg(feature = "veryl-reference")] impl Backend for VerylBackend { fn write(&mut self, path: &SignalPath, payload: BigUint, mask: BigUint) -> Result<()> { let signal = self.signal(path); @@ -126,6 +129,7 @@ pub fn build(design: &Design, backend: &str) -> Result> { .iter() .map(|source| (source.text.as_str(), source.path.as_path())) .collect::>(); + #[cfg(feature = "veryl-reference")] if backend == "veryl" { if !design.parameters.is_empty() { return Err("the veryl-simulator adapter cannot set top parameters".into()); @@ -158,9 +162,11 @@ pub fn build(design: &Design, backend: &str) -> Result> { .build_native() .map_err(classify_build_error)?, )), + #[cfg(feature = "cranelift")] "cranelift" => Box::new(CeloxBackend( builder.build_cranelift().map_err(classify_build_error)?, )), + #[cfg(feature = "cranelift")] "cranelift-parallel" => Box::new(CeloxBackend( builder .threads(4) @@ -168,6 +174,7 @@ pub fn build(design: &Design, backend: &str) -> Result> { .build_cranelift() .map_err(classify_build_error)?, )), + #[cfg(feature = "wasm-runtime")] "wasm" => Box::new(CeloxBackend( builder.build_wasm().map_err(classify_build_error)?, )), diff --git a/scripts/ci-rust-scope.mjs b/scripts/ci-rust-scope.mjs index d7d1e2a18a0..96faf33d99a 100644 --- a/scripts/ci-rust-scope.mjs +++ b/scripts/ci-rust-scope.mjs @@ -8,6 +8,13 @@ import { classifyFiles } from "./ci-changes.mjs"; // package can see the feature's package, as Cargo requires. export const CI_FEATURES = Object.freeze([ "celox/systemverilog", + "celox/cranelift", + "celox/wasm-runtime", + "celox/wasm-component", + "celox/veryl-reference", + "celox-vpi/cranelift", + "celox-vpi/wasm-runtime", + "celox-bench/cranelift", "celox-test-suite/verilator", "celox-test-suite/icarus", "celox-test-suite/xezim", @@ -34,7 +41,6 @@ const SV = Object.freeze({ variants: ["sv"], binaries: ["systemverilog"] }); // are not generated per variant. Any other crate celox depends on needs all // of them. export const VARIANT_CRATES = new Map([ - ["celox-backend-common", NATIVE], ["celox-backend-x86", NATIVE], ["celox-backend-arm64", NATIVE], [ diff --git a/scripts/ci-rust-scope.test.mjs b/scripts/ci-rust-scope.test.mjs index 48e1fb03d2d..8f315adf2db 100644 --- a/scripts/ci-rust-scope.test.mjs +++ b/scripts/ci-rust-scope.test.mjs @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import test from "node:test"; import { fileURLToPath } from "node:url"; @@ -92,10 +93,10 @@ test("a test file change runs only that binary and nothing downstream", () => { assert.deepEqual(rustTestScope(["crates/celox/tests/flip_flop.rs"], workspace), { full: false, packages: ["celox"], - features: ["celox/systemverilog"], + features: ["celox/systemverilog", "celox/cranelift", "celox/wasm-runtime", "celox/wasm-component", "celox/veryl-reference"], filter: "binary_id(celox::flip_flop)", targets: ["flip_flop"], - builds: [{ packages: ["celox"], targets: ["flip_flop"], features: ["celox/systemverilog"] }], + builds: [{ packages: ["celox"], targets: ["flip_flop"], features: ["celox/systemverilog", "celox/cranelift", "celox/wasm-runtime", "celox/wasm-component", "celox/veryl-reference"] }], libraries: [], libraryFeatures: [], }); @@ -282,7 +283,7 @@ test("multiple packages keep their own Cargo test targets and omit unused adapte [["celox"], ["flip_flop"]], [["consumer"], ["e2e"]], ]); const real = rustTestScope(["crates/celox/tests/param_override.rs"], readWorkspace(root)); - assert.deepEqual(real.features, ["celox/systemverilog"]); + assert.deepEqual(real.features, ["celox/systemverilog", "celox/cranelift", "celox/wasm-runtime", "celox/wasm-component", "celox/veryl-reference"]); }); test("a shared case does not turn a simultaneous SV fix into every backend", () => { @@ -296,3 +297,11 @@ test("a shared case does not turn a simultaneous SV fix into every backend", () assert.ok(scope.filter.includes("binary_id(celox::param_override)"), scope.filter); assert.ok(scope.filter.includes("binary_id(celox::systemverilog)"), scope.filter); }); + +test("default application builds and tests do not pull optional compilers", () => { + const tree = execFileSync("cargo", [ + "tree", "--locked", "-e", "normal,build,dev", "--prefix", "none", + ], { cwd: root, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }); + assert.doesNotMatch(tree, /^(?:wasmtime|cranelift)(?:-| )/m); + assert.doesNotMatch(tree, /^(?:celox-backend-cranelift|veryl-simulator) /m); +}); diff --git a/scripts/run-ci-cocotb.mjs b/scripts/run-ci-cocotb.mjs index f3356338cc9..da06182b54f 100644 --- a/scripts/run-ci-cocotb.mjs +++ b/scripts/run-ci-cocotb.mjs @@ -11,7 +11,7 @@ export function cocotbCommands(full, builds) { if (full !== "false") return [[ "nextest", "run", "--locked", "--workspace", "--exclude", "lydite*", "--profile", "ci", - "--features", "celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases", + "--features", "celox/systemverilog,celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference,celox-vpi/cranelift,celox-vpi/wasm-runtime,celox-bench/cranelift,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/xezim,celox-test-suite/runtime-cases", "--run-ignored", "only", "-E", cocotbFilter, ]]; // Validate all plans first, including ones we do not need to execute. diff --git a/scripts/run-vtest.mjs b/scripts/run-vtest.mjs index c16a4ae606c..eb46b0813b5 100644 --- a/scripts/run-vtest.mjs +++ b/scripts/run-vtest.mjs @@ -5,7 +5,11 @@ import { appendFileSync } from "node:fs"; const root = fileURLToPath(new URL("../", import.meta.url)); export const runtimeCasesFeature = "celox-test-suite/runtime-cases"; -const features = `celox/systemverilog,${runtimeCasesFeature}`; +const baseFeatures = `celox/systemverilog,${runtimeCasesFeature}`; +const comparisonFeatures = "celox/cranelift,celox/wasm-runtime,celox/wasm-component,celox/veryl-reference"; +function features(env) { + return env.CELOX_TEST_FEATURES ? `${baseFeatures},${env.CELOX_TEST_FEATURES}` : baseFeatures; +} export function executorPath(output) { const paths = output.split("\n").filter(Boolean).map((line) => JSON.parse(line)) @@ -20,7 +24,7 @@ export function executorPath(output) { export function buildExecutor(spawn = spawnSync, env = process.env) { const build = spawn("cargo", [ "build", "--locked", "-p", "celox", "--example", "vtest-exec", - "--profile", "vtest", "--features", features, "--message-format=json-render-diagnostics", + "--profile", "vtest", "--features", features(env), "--message-format=json-render-diagnostics", ], { cwd: root, env, encoding: "utf8", stdio: ["inherit", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 }); if (build.error) throw build.error; if (build.status !== 0) return { status: build.status ?? 1 }; @@ -34,7 +38,7 @@ export function buildExecutor(spawn = spawnSync, env = process.env) { // Prepare once per CI job, even when scoped tests need several Cargo invocations. export function prepareCi(spawn = spawnSync, env = process.env, append = appendFileSync) { if (!env.GITHUB_ENV) throw new Error("--prepare-ci requires GITHUB_ENV"); - const result = buildExecutor(spawn, env); + const result = buildExecutor(spawn, { ...env, CELOX_TEST_FEATURES: comparisonFeatures }); if (result.status !== 0) return result.status; const lines = Object.entries(result.environment).map(([name, value]) => { if (/[\r\n]/.test(value)) throw new Error("Invalid executor environment path"); @@ -50,7 +54,7 @@ export function run(args, spawn = spawnSync, env = process.env) { const result = buildExecutor(spawn, env); if (result.status !== 0) return result.status; const tests = spawn("cargo", [ - "nextest", "run", "--locked", "-p", "celox", "--features", features, ...args, + "nextest", "run", "--locked", "-p", "celox", "--features", features(env), ...args, ], { cwd: root, env: { ...env, ...result.environment }, @@ -69,9 +73,10 @@ nextest. Case bodies are read from disk; Rust API tests run in their test binary Examples: node scripts/run-vtest.mjs --test counter node scripts/run-vtest.mjs --test operators -E 'test(::native$)' - node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' + CELOX_TEST_FEATURES=cranelift,wasm-runtime node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' The runner and registrations both enable systemverilog and runtime-cases. +Set CELOX_TEST_FEATURES=cranelift,wasm-runtime to include optional backends. Use ordinary cargo nextest run for the existing in-process test path.`); } else if (process.argv[2] === "--prepare-ci") { if (process.argv.length !== 3) throw new Error("--prepare-ci accepts no test arguments"); diff --git a/scripts/run-vtest.test.mjs b/scripts/run-vtest.test.mjs index 1bec1f1a200..e4b295e3345 100644 --- a/scripts/run-vtest.test.mjs +++ b/scripts/run-vtest.test.mjs @@ -68,3 +68,17 @@ test("failed CI preparation cannot export a stale executor or silently skip setu assert.throws(() => prepareCi(() => ({ status: 0, stdout: JSON.stringify(message) }), { GITHUB_ENV: "/job/env" }, unexpected), /Invalid executor environment/); }); + +test("local tests leave heavy backends off unless explicitly requested", () => { + for (const extra of [undefined, "cranelift,wasm-runtime,veryl-reference"]) { + const calls = []; + run([], (...args) => { + calls.push(args); + return calls.length === 1 ? { status: 0, stdout: artifact } : { status: 0 }; + }, { CELOX_TEST_FEATURES: extra }); + const features = calls.map(([, args]) => args[args.indexOf("--features") + 1]); + assert.equal(features[0], features[1]); + assert.equal(features[0], "celox/systemverilog,celox-test-suite/runtime-cases" + + (extra ? `,${extra}` : "")); + } +});