From 1b4b94acb2d1fd3707026695d05e89bd55478300 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:36:28 +0900 Subject: [PATCH 1/3] feat(simulator): support scalar floating-point arithmetic and formatting Add Veryl f32/f64 and SystemVerilog shortreal/real/realtime scalar execution across the interpreter, native, Cranelift, and Wasm backends. Preserve IEEE storage while applying numeric arithmetic, comparisons, precision changes, integer conversions through 64 bits, and SV conversion functions at assignments, ports, and subroutine boundaries. Carry floating-point type metadata through runtime events and testbench arguments so display/write, assertion messages, and file output format numeric values with f/e/g, width, and precision. Include NAPI and browser helper integration and invalidate older native images with container version 22. The stale-load optimization exposed by combinational display capture was fixed in #1665, now included in master. Validation: - Pinned official sv-tests, full release-driver runs before/after: 20 fail-to-pass rows across 10 cases, no regressions (2state 462 -> 472 passes; 4state 464 -> 474). Update only those reviewed expectations. - Full Celox common suite before the master update: 12,458 passed, no failures; known exclusions retained. - After integrating current master: 776 SV analyzer tests and 3,450 integration tests passed, covering SystemVerilog, FP display/assertions, native image roundtrip in a fresh process, shared JIT cache. - Affected Rust unit tests and clippy, formatting, Wasm target checks, NAPI rebuild, JS tests and TypeScript checks. Two JS tests timed out under concurrent build load and passed on focused reruns. - New portable cases exercised through Icarus and Verilator. Known external shortreal/port/format differences are documented in crates/celox-test-suite/LIMITATIONS.md; expected results and retained verification baselines are unchanged. Veryl analyzer 0.22 mis-evaluates some FP constant expressions before lowering. Those reproductions retain their assertions with targeted ignores; default analyzer folding is preserved to avoid integer generate regressions. Runtime FP display/assertion tests remain enabled. Follow-up: #1657. Reject real-valued select indices, including parameters and expressions, while preserving integral indices and explicit real-to-integer conversions. A driven-input regression covers the legality check masked by an unrelated undriven-net error in the pinned upstream negative case. The symbolic bitvector bridge explicitly rejects FP operations rather than treating their payloads as integer arithmetic. The Python proof bridge also reports a typed unsupported result before proof execution. Six FP cases receive explicit reviewed proof-model exceptions, with zero reads and no proof artifacts; malformed IR and transport failures remain hard errors. The integer-folded FP case retains its assertions and receives a targeted known-failure entry for the existing Veryl bug #1657. Existing 771 coverage records were checked against the successful CI proof artifacts and preserved exactly; only the nine newly catalogued cases are added (including two aggregate cases from master). Targeted protocol and gate regressions are run locally; the full proof suite is not rerun locally. Deferred: wide integer and aggregate numeric conversions (#1653), and direct native FP instruction emission in place of helper calls (#1654). Refs #1401 Change-Id: Ie4380b73114505db30ac122288d528b078d28a62 --- conformance/sv-tests/README.md | 11 + conformance/sv-tests/expected.tsv | 40 +- .../src/isel/extern_call.rs | 53 +- .../src/isel/four_state.rs | 6 + .../src/isel/instruction.rs | 28 + crates/celox-backend-arm64/src/isel/wide.rs | 3 + .../src/isel/wide_unary.rs | 3 + .../src/scalar/extern_call.rs | 7 +- .../src/translator/arith.rs | 23 + .../src/translator/core.rs | 64 ++- .../celox-backend-cranelift/src/wide_ops.rs | 2 + crates/celox-backend-wasm/src/lib.rs | 500 +++++++++++++++++- .../src/backend/native/emit/extern_call.rs | 10 +- .../src/backend/native/isel/extern_call.rs | 59 ++- .../src/backend/native/isel/four_state.rs | 6 + .../src/backend/native/isel/instruction.rs | 28 + .../src/backend/native/isel/tests.rs | 1 + .../src/backend/native/isel/tests/floating.rs | 169 ++++++ .../src/backend/native/isel/wide.rs | 3 + .../src/backend/native/isel/wide_unary.rs | 3 + crates/celox-design/src/float.rs | 167 ++++++ crates/celox-design/src/lib.rs | 67 +++ crates/celox-frontend-sv/src/lowering.rs | 153 +++++- crates/celox-frontend-sv/src/lowering/comb.rs | 160 +++++- crates/celox-frontend-sv/src/lowering/ff.rs | 105 +++- .../src/lowering/ff/file_io.rs | 21 +- .../src/lowering/floating.rs | 411 ++++++++++++++ .../src/lowering/procedural.rs | 75 ++- crates/celox-frontend-veryl/src/float.rs | 206 ++++++++ crates/celox-frontend-veryl/src/lib.rs | 1 + .../celox-frontend-veryl/src/lowering/ff.rs | 4 + .../src/lowering/ff/expression.rs | 107 +++- .../src/lowering/ff/function_call.rs | 16 + .../src/lowering/ff/inline_call.rs | 3 +- .../src/lowering/logic_tree.rs | 24 +- .../src/lowering/logic_tree/effect.rs | 4 + .../src/lowering/logic_tree/expr.rs | 84 ++- .../lowering/logic_tree/recover_unrolled.rs | 17 + crates/celox-frontend-veryl/src/module.rs | 30 +- crates/celox-frontend-veryl/src/testbench.rs | 103 +++- .../src/value_type_check.rs | 144 ++--- crates/celox-napi/src/lib.rs | 19 +- crates/celox-runtime/src/file_io.rs | 1 + crates/celox-runtime/src/testbench.rs | 1 + .../pass_branchify_mux/profitability.rs | 1 + .../pass_control_flow_simplify.rs | 65 +++ .../control_flow/pass_sparse_case_dispatch.rs | 1 + crates/celox-sir/src/float.rs | 133 +++++ crates/celox-sir/src/lib.rs | 5 +- crates/celox-sir/src/verify.rs | 42 ++ crates/celox-slt/src/const_inline.rs | 101 ++++ crates/celox-slt/src/lower.rs | 12 +- crates/celox-slt/src/lower/concat.rs | 2 + crates/celox-slt/src/lower/cost.rs | 1 + crates/celox-slt/src/node.rs | 2 + crates/celox-slt/src/node_rules.rs | 15 + crates/celox-sv-analyzer/src/ast.rs | 12 + .../src/ast/array_compatibility.rs | 1 + .../src/ast/bound_patterns.rs | 4 + crates/celox-sv-analyzer/src/ast/casts.rs | 79 +++ .../src/ast/constant_binding.rs | 18 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 13 +- .../src/ast/dimensions/discovery.rs | 9 +- .../src/ast/dimensions/query_binding.rs | 2 +- .../src/ast/expression_binding.rs | 3 +- .../src/ast/expression_binding/direct.rs | 179 ++++++- .../celox-sv-analyzer/src/ast/expressions.rs | 8 +- crates/celox-sv-analyzer/src/ast/functions.rs | 31 +- crates/celox-sv-analyzer/src/ast/generate.rs | 2 +- crates/celox-sv-analyzer/src/ast/inlining.rs | 10 +- .../src/ast/packed_structs/layout.rs | 2 +- .../src/ast/packed_structs/selects.rs | 1 + .../celox-sv-analyzer/src/ast/parameters.rs | 101 +++- .../src/ast/parameters/declaration_types.rs | 7 + .../src/ast/parameters/skipped.rs | 6 + crates/celox-sv-analyzer/src/ast/patterns.rs | 1 + .../src/ast/patterns/binding.rs | 4 + .../celox-sv-analyzer/src/ast/procedural.rs | 6 +- crates/celox-sv-analyzer/src/ast/selects.rs | 7 + .../celox-sv-analyzer/src/ast/statements.rs | 25 +- .../celox-sv-analyzer/src/ast/type_binding.rs | 2 + crates/celox-sv-analyzer/src/ir.rs | 4 + .../celox-sv-analyzer/src/system_functions.rs | 27 +- crates/celox-sv-analyzer/src/tests.rs | 208 ++++++++ crates/celox-test-suite/LIMITATIONS.md | 69 +++ .../src/sv/cases/floating_point.vtest | 265 ++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../src/veryl/cases/floating_point.vtest | 134 +++++ .../celox-test-suite/src/veryl/cases/mod.rs | 4 + crates/celox-testbench/src/format.rs | 365 ++++++++++++- crates/celox-testbench/src/lib.rs | 17 + crates/celox-testbench/src/vm.rs | 60 +++ crates/celox-wasm/src/lib.rs | 6 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/backend/wasm_runtime.rs | 6 +- crates/celox/src/dpi.rs | 30 +- crates/celox/src/interpreter.rs | 15 + crates/celox/src/simulator.rs | 18 +- crates/celox/src/simulator/host/file_io.rs | 3 + crates/celox/src/testbench.rs | 16 +- crates/celox/tests/floating_point.rs | 40 ++ crates/celox/tests/floating_point_display.rs | 350 ++++++++++++ .../frontends/systemverilog/floating_point.rs | 42 ++ .../systemverilog/review_regressions.rs | 12 +- crates/celox/tests/native_float_image.rs | 87 +++ crates/celox/tests/shared_jit_cache.rs | 19 + crates/celox/tests/systemverilog.rs | 3 + crates/celox/tests/test_utils/suite.rs | 18 + crates/celox/tests/unsupported_value_types.rs | 169 +++--- .../src/bin/lydite-celox-suite.rs | 16 + crates/lydite-celox/src/lib.rs | 2 +- crates/lydite-celox/src/tests.rs | 34 ++ docs/guide/type-conversion.md | 12 +- docs/ja/guide/type-conversion.md | 11 +- lydite/conformance/veryl-proof/README.md | 17 +- .../veryl-proof/case-exceptions.json | 35 ++ .../veryl-proof/coverage-manifest.json | 198 +++++++ lydite/conformance/veryl-proof/coverage.py | 12 +- .../conformance/veryl-proof/proof_backend.py | 27 + lydite/conformance/veryl-proof/server.py | 11 +- .../veryl-proof/tests/test_float_boundary.py | 63 +++ .../celox/src/floating-point-addon.test.ts | 53 ++ packages/celox/src/types.ts | 2 + packages/celox/src/wasm-bridge.test.ts | 62 ++- packages/celox/src/wasm-bridge.ts | 37 +- .../playground/src/playground-simulator.ts | 7 +- packages/playground/src/wasm-float.ts | 35 ++ packages/playground/test/wasm-float.test.ts | 50 ++ 128 files changed, 6163 insertions(+), 369 deletions(-) create mode 100644 crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs create mode 100644 crates/celox-design/src/float.rs create mode 100644 crates/celox-frontend-sv/src/lowering/floating.rs create mode 100644 crates/celox-frontend-veryl/src/float.rs create mode 100644 crates/celox-sir/src/float.rs create mode 100644 crates/celox-test-suite/src/sv/cases/floating_point.vtest create mode 100644 crates/celox-test-suite/src/veryl/cases/floating_point.vtest create mode 100644 crates/celox/tests/floating_point.rs create mode 100644 crates/celox/tests/floating_point_display.rs create mode 100644 crates/celox/tests/frontends/systemverilog/floating_point.rs create mode 100644 crates/celox/tests/native_float_image.rs create mode 100644 lydite/conformance/veryl-proof/tests/test_float_boundary.py create mode 100644 packages/celox/src/floating-point-addon.test.ts create mode 100644 packages/playground/src/wasm-float.ts create mode 100644 packages/playground/test/wasm-float.test.ts diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 86e969e56df..ec53f24ef68 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -92,6 +92,17 @@ assigning a specparam to a value parameter is rejected, as required by 6.20.5; an unreferenced specparam declaration remains accepted. No other expectation rows are changed for these repairs. +The scalar floating-point implementation updates twenty reviewed expectation +rows: both state modes for `5.7.2-real-constants`, `5.7.2-real-token`, +`6.12--real`, `6.12--realtime`, `6.12--shortreal`, `6.24.1--cast_op`, +`20.5--itor`, `20.5--rtoi`, `20.5--real-bits-conv`, and +`20.5--shortreal-bits-conv` change from fail to pass. Full official runs at the +pinned revision report 472 passing cases in 2state and 474 in 4state, ten more +in each mode. No passing case regresses. The negative real-select and real-edge +cases retain their verdicts. The pinned `real_bit_select_idx` input is rejected +earlier for its undriven net, so a separate analyzer regression uses a driven +input to check that real-valued indices themselves are rejected. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 4e44a96be83..8681451cce9 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -715,14 +715,14 @@ chapter-20/20.4--printtimescale.sv 2state pass chapter-20/20.4--printtimescale.sv 4state pass chapter-20/20.4--timeformat.sv 2state fail chapter-20/20.4--timeformat.sv 4state fail -chapter-20/20.5--itor.sv 2state fail -chapter-20/20.5--itor.sv 4state fail -chapter-20/20.5--real-bits-conv.sv 2state fail -chapter-20/20.5--real-bits-conv.sv 4state fail -chapter-20/20.5--rtoi.sv 2state fail -chapter-20/20.5--rtoi.sv 4state fail -chapter-20/20.5--shortreal-bits-conv.sv 2state fail -chapter-20/20.5--shortreal-bits-conv.sv 4state fail +chapter-20/20.5--itor.sv 2state pass +chapter-20/20.5--itor.sv 4state pass +chapter-20/20.5--real-bits-conv.sv 2state pass +chapter-20/20.5--real-bits-conv.sv 4state pass +chapter-20/20.5--rtoi.sv 2state pass +chapter-20/20.5--rtoi.sv 4state pass +chapter-20/20.5--shortreal-bits-conv.sv 2state pass +chapter-20/20.5--shortreal-bits-conv.sv 4state pass chapter-20/20.6--bits.sv 2state pass chapter-20/20.6--bits.sv 4state pass chapter-20/20.6--bits_type.sv 2state pass @@ -1071,10 +1071,10 @@ chapter-5/5.7.1--integers-unsized.sv 2state pass chapter-5/5.7.1--integers-unsized.sv 4state pass chapter-5/5.7.2-real-constants-illegal.sv 2state pass chapter-5/5.7.2-real-constants-illegal.sv 4state pass -chapter-5/5.7.2-real-constants.sv 2state fail -chapter-5/5.7.2-real-constants.sv 4state fail -chapter-5/5.7.2-real-token.sv 2state fail -chapter-5/5.7.2-real-token.sv 4state fail +chapter-5/5.7.2-real-constants.sv 2state pass +chapter-5/5.7.2-real-constants.sv 4state pass +chapter-5/5.7.2-real-token.sv 2state pass +chapter-5/5.7.2-real-token.sv 4state pass chapter-5/5.8-time-literals.sv 2state fail chapter-5/5.8-time-literals.sv 4state fail chapter-5/5.9-string-assignment.sv 2state pass @@ -1093,18 +1093,18 @@ chapter-6/6.10--implicit_port.sv 2state pass chapter-6/6.10--implicit_port.sv 4state pass chapter-6/6.10--implicit_port_connection.sv 2state pass chapter-6/6.10--implicit_port_connection.sv 4state pass -chapter-6/6.12--real.sv 2state fail -chapter-6/6.12--real.sv 4state fail +chapter-6/6.12--real.sv 2state pass +chapter-6/6.12--real.sv 4state pass chapter-6/6.12--real_bit_select.sv 2state pass chapter-6/6.12--real_bit_select.sv 4state pass chapter-6/6.12--real_bit_select_idx.sv 2state pass chapter-6/6.12--real_bit_select_idx.sv 4state pass chapter-6/6.12--real_edge.sv 2state pass chapter-6/6.12--real_edge.sv 4state pass -chapter-6/6.12--realtime.sv 2state fail -chapter-6/6.12--realtime.sv 4state fail -chapter-6/6.12--shortreal.sv 2state fail -chapter-6/6.12--shortreal.sv 4state fail +chapter-6/6.12--realtime.sv 2state pass +chapter-6/6.12--realtime.sv 4state pass +chapter-6/6.12--shortreal.sv 2state pass +chapter-6/6.12--shortreal.sv 4state pass chapter-6/6.13--void.sv 2state pass chapter-6/6.13--void.sv 4state pass chapter-6/6.14--chandle.sv 2state fail @@ -1225,8 +1225,8 @@ chapter-6/6.23--type_op.sv 2state fail chapter-6/6.23--type_op.sv 4state fail chapter-6/6.23--type_op_compare.sv 2state fail chapter-6/6.23--type_op_compare.sv 4state fail -chapter-6/6.24.1--cast_op.sv 2state fail -chapter-6/6.24.1--cast_op.sv 4state fail +chapter-6/6.24.1--cast_op.sv 2state pass +chapter-6/6.24.1--cast_op.sv 4state pass chapter-6/6.24.2--cast_fn.sv 2state fail chapter-6/6.24.2--cast_fn.sv 4state fail chapter-6/6.24.2--cast_task.sv 2state fail diff --git a/crates/celox-backend-arm64/src/isel/extern_call.rs b/crates/celox-backend-arm64/src/isel/extern_call.rs index f297e420ba1..0762769bb20 100644 --- a/crates/celox-backend-arm64/src/isel/extern_call.rs +++ b/crates/celox-backend-arm64/src/isel/extern_call.rs @@ -74,7 +74,10 @@ fn extern_argument(ctx: &mut ISelContext, block: &mut MBlock, arg: RegisterId) - /// Define `dst` from the C integer `result` of an extern call. fn define_extern_result(ctx: &mut ISelContext, block: &mut MBlock, dst: RegisterId, result: VReg) { let value = ctx.reg_map.get(dst); - let ty = ExternValue::of_verified(&ctx.register_types[&dst]); + let ty = ExternValue::of(&ctx.register_types[&dst]).unwrap_or(ExternValue::Integer { + width: ctx.sir_width(&dst), + signed: false, + }); match ty.result_value_mask() { u64::MAX => block.push(MInst::Mov { dst: value, @@ -116,3 +119,51 @@ fn define_extern_result(ctx: &mut ISelContext, block: &mut MBlock, dst: Register }; ctx.set_mask(dst, mask); } + +pub(super) fn lower_float( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + lhs: RegisterId, + rhs: Option, + code: u64, +) { + let a = ctx.reg_map.get(lhs); + let a = if ctx.four_state && matches!(code & 255, 34 | 35) { + let mask = ctx.get_mask(lhs, block); + let known = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::BitNot { + dst: known, + src: mask, + }); + let value = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::And { + dst: value, + lhs: a, + rhs: known, + }); + value + } else { + a + }; + + let b = if let Some(rhs) = rhs { + ctx.reg_map.get(rhs) + } else { + let v = ctx.alloc_vreg(SpillDesc::remat(0)); + block.push(MInst::LoadImm { dst: v, value: 0 }); + v + }; + let c = ctx.alloc_vreg(SpillDesc::remat(code)); + block.push(MInst::LoadImm { + dst: c, + value: code, + }); + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::CallExtern { + dst: Some(result), + func: celox_sir::float::FLOAT_HELPER_ID, + args: vec![a, b, c], + }); + define_extern_result(ctx, block, dst, result); +} diff --git a/crates/celox-backend-arm64/src/isel/four_state.rs b/crates/celox-backend-arm64/src/isel/four_state.rs index b6760a8f1a2..f80f8c47979 100644 --- a/crates/celox-backend-arm64/src/isel/four_state.rs +++ b/crates/celox-backend-arm64/src/isel/four_state.rs @@ -685,6 +685,9 @@ pub(super) fn lower_unary_mask( src_width: usize, ) -> VReg { match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::ToTwoState => { let zero = ctx.alloc_vreg(SpillDesc::remat(0)); block.push(MInst::LoadImm { @@ -1677,6 +1680,9 @@ pub(super) fn lower_wide_unary_mask( let sm_chunks = get_wide_mask_chunks(ctx, block, &src, n_src); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::ToTwoState => { let n_dst = ISelContext::num_chunks(d_width); let mut dst_m_chunks = Vec::with_capacity(n_dst); diff --git a/crates/celox-backend-arm64/src/isel/instruction.rs b/crates/celox-backend-arm64/src/isel/instruction.rs index b1769d333b5..fc826bb6ca3 100644 --- a/crates/celox-backend-arm64/src/isel/instruction.rs +++ b/crates/celox-backend-arm64/src/isel/instruction.rs @@ -1992,6 +1992,17 @@ pub(super) fn lower_instruction( } SIRInstruction::Binary(dst, lhs, op, rhs) => { + if let BinaryOp::Float { op, precision } = op { + extern_call::lower_float( + ctx, + block, + *dst, + *lhs, + Some(*rhs), + celox_sir::float::binary_code(*op, *precision), + ); + return; + } let d_width = ctx.sir_width(dst); let lhs_width = ctx.sir_width(lhs); let rhs_width = ctx.sir_width(rhs); @@ -2070,6 +2081,9 @@ pub(super) fn lower_instruction( let rhs_vreg = ctx.reg_map.get(*rhs); match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul => { // 64-bit arithmetic may produce upper bits; mask to output width. let raw = if d_width < 64 { @@ -2778,6 +2792,17 @@ pub(super) fn lower_instruction( } SIRInstruction::Unary(dst, op, src) => { + if let UnaryOp::Float { op, precision } = op { + extern_call::lower_float( + ctx, + block, + *dst, + *src, + None, + celox_sir::float::unary_code(*op, *precision), + ); + return; + } let d_width = ctx.sir_width(dst); let src_width = ctx.sir_width(src); debug_assert!(src_width > 64 || !ctx.wide_regs.contains_key(src)); @@ -2798,6 +2823,9 @@ pub(super) fn lower_instruction( let src_vreg = ctx.reg_map.get(*src); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::Ident | UnaryOp::ToTwoState => { ctx.emit_mov(block, dst_vreg, src_vreg); } diff --git a/crates/celox-backend-arm64/src/isel/wide.rs b/crates/celox-backend-arm64/src/isel/wide.rs index e5e848747d3..4e8a4017c0f 100644 --- a/crates/celox-backend-arm64/src/isel/wide.rs +++ b/crates/celox-backend-arm64/src/isel/wide.rs @@ -163,6 +163,9 @@ pub(super) fn lower_wide_binary( } match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } // Chunk-wise operations: apply to each 64-bit chunk independently BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { let lhs_chunks = ctx.get_wide_chunks(&lhs, block); diff --git a/crates/celox-backend-arm64/src/isel/wide_unary.rs b/crates/celox-backend-arm64/src/isel/wide_unary.rs index 91cb349f357..83d8433f865 100644 --- a/crates/celox-backend-arm64/src/isel/wide_unary.rs +++ b/crates/celox-backend-arm64/src/isel/wide_unary.rs @@ -15,6 +15,9 @@ pub(super) fn lower_wide_unary( let n_chunks = ISelContext::num_chunks(d_width.max(src_width)); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::BitNot => { let src_chunks = ctx.get_wide_chunks(&src, block); let mut dst_chunks = Vec::with_capacity(n_chunks); diff --git a/crates/celox-backend-arm64/src/scalar/extern_call.rs b/crates/celox-backend-arm64/src/scalar/extern_call.rs index 5b154cb6e01..0ecf279451f 100644 --- a/crates/celox-backend-arm64/src/scalar/extern_call.rs +++ b/crates/celox-backend-arm64/src/scalar/extern_call.rs @@ -112,7 +112,12 @@ pub(super) fn emit_call_extern( celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET as i64, OpSize::S64, ); - emit_load_at(ops, SCRATCH1, SCRATCH1, i64::from(func) * 8, OpSize::S64); + let offset = if func == celox_sir::float::FLOAT_HELPER_ID { + -8 + } else { + i64::from(func) * 8 + }; + emit_load_at(ops, SCRATCH1, SCRATCH1, offset, OpSize::S64); dynasm!(ops ; .arch aarch64 ; blr x17); // The result interferes with every value live across the call, so the diff --git a/crates/celox-backend-cranelift/src/translator/arith.rs b/crates/celox-backend-cranelift/src/translator/arith.rs index a935dbc5005..e887df70db5 100644 --- a/crates/celox-backend-cranelift/src/translator/arith.rs +++ b/crates/celox-backend-cranelift/src/translator/arith.rs @@ -298,6 +298,16 @@ impl SIRTranslator { op: &BinaryOp, rhs: &RegisterId, ) { + if let BinaryOp::Float { op, precision } = op { + self.translate_float( + state, + *dst, + *lhs, + Some(*rhs), + celox_sir::float::binary_code(*op, *precision), + ); + return; + } let l_width = state.register_map[lhs].width(); let r_width = state.register_map[rhs].width(); let d_width = state.register_map[dst].width(); @@ -396,6 +406,7 @@ impl SIRTranslator { }; let mut res_v = match op { + BinaryOp::Float { .. } => unreachable!("lowered separately"), BinaryOp::Add => state.builder.ins().iadd(l, r), BinaryOp::Sub => state.builder.ins().isub(l, r), BinaryOp::Mul => state.builder.ins().imul(l, r), @@ -1390,6 +1401,16 @@ impl SIRTranslator { op: &UnaryOp, rhs: &RegisterId, ) { + if let UnaryOp::Float { op, precision } = op { + self.translate_float( + state, + *dst, + *rhs, + None, + celox_sir::float::unary_code(*op, *precision), + ); + return; + } if matches!( op, UnaryOp::PopCount | UnaryOp::CountLeadingZeros | UnaryOp::CountTrailingZeros @@ -1414,6 +1435,7 @@ impl SIRTranslator { let r = promote_to_physical(state, r_val, r_width, r_is_signed, common_ty); let res_v = match op { + UnaryOp::Float { .. } => unreachable!("lowered separately"), UnaryOp::Minus => state.builder.ins().ineg(r), UnaryOp::Ident | UnaryOp::ToTwoState => r, UnaryOp::BitNot => { @@ -1475,6 +1497,7 @@ impl SIRTranslator { let r_m = promote_to_physical(state, r_m_val, r_width, r_is_signed, common_ty); let res_m = match op { + UnaryOp::Float { .. } => unreachable!("lowered separately"), UnaryOp::Ident | UnaryOp::BitNot => r_m, UnaryOp::ToTwoState => state.builder.ins().iconst(common_ty, 0), UnaryOp::LogicNot | UnaryOp::Or => { diff --git a/crates/celox-backend-cranelift/src/translator/core.rs b/crates/celox-backend-cranelift/src/translator/core.rs index 7d7801a5a91..3c2803aeeee 100644 --- a/crates/celox-backend-cranelift/src/translator/core.rs +++ b/crates/celox-backend-cranelift/src/translator/core.rs @@ -512,6 +512,61 @@ impl SIRTranslator { } } + pub(super) fn translate_float( + &self, + state: &mut TranslationState, + dst: RegisterId, + lhs: RegisterId, + rhs: Option, + code: u64, + ) { + let a = state.regs[&lhs].first_value(state.builder); + let a = if matches!(code & 255, 34 | 35) { + if let Some(mask) = state.regs[&lhs].first_mask(state.builder) { + let known = state.builder.ins().bnot(mask); + state.builder.ins().band(a, known) + } else { + a + } + } else { + a + }; + + let a = if state.builder.func.dfg.value_type(a) == types::I64 { + a + } else { + state.builder.ins().uextend(types::I64, a) + }; + let b = if let Some(rhs) = rhs { + let b = state.regs[&rhs].first_value(state.builder); + if state.builder.func.dfg.value_type(b) == types::I64 { + b + } else { + state.builder.ins().uextend(types::I64, b) + } + } else { + state.builder.ins().iconst(types::I64, 0) + }; + let c = state.builder.ins().iconst(types::I64, code as i64); + let address = state.builder.ins().iconst( + types::I64, + celox_sir::float::evaluate as *const () as usize as i64, + ); + let mut signature = Signature::new(self.target_config.default_call_conv); + signature + .params + .extend((0..3).map(|_| AbiParam::new(types::I64))); + signature.returns.push(AbiParam::new(types::I64)); + let signature = state.builder.import_signature(signature); + let call = state + .builder + .ins() + .call_indirect(signature, address, &[a, b, c]); + let result = state.builder.inst_results(call)[0]; + let value = self.extern_call_result(state, dst, result); + state.regs.insert(dst, value); + } + /// The 64-bit C integer passed for an extern call argument. fn extern_call_argument(&self, state: &mut TranslationState, arg: RegisterId) -> Value { let ty = ExternValue::of_verified(&state.register_map[&arg]); @@ -555,12 +610,15 @@ impl SIRTranslator { builder.ins().ireduce(cl_type, raw) } }; - let ty = ExternValue::of_verified(&state.register_map[&dst]); + let ty = ExternValue::of(&state.register_map[&dst]).unwrap_or(ExternValue::Integer { + width: state.register_map[&dst].width(), + signed: false, + }); // Narrowing truncates a result to the register's type, which is wider // than a one-bit register. let value = match ty.result_value_mask() { - 1 => state.builder.ins().band_imm_u(result, 1), - _ => result, + u64::MAX => result, + mask => state.builder.ins().band_imm_u(result, mask as i64), }; let value = narrow(state.builder, value); let mask = match ty { diff --git a/crates/celox-backend-cranelift/src/wide_ops.rs b/crates/celox-backend-cranelift/src/wide_ops.rs index 7469db15dba..738252d01ab 100644 --- a/crates/celox-backend-cranelift/src/wide_ops.rs +++ b/crates/celox-backend-cranelift/src/wide_ops.rs @@ -33,6 +33,7 @@ pub fn emit_wide_binary( operation_width: usize, ) -> Vec { match op { + BinaryOp::Float { .. } => unreachable!("float operations are lowered separately"), // 1. Bitwise operations ───────────────────────────── BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { emit_wide_bitwise(builder, op, l_chunks, r_chunks, num_chunks) @@ -152,6 +153,7 @@ pub fn emit_wide_unary( common_logical_width: usize, ) -> Vec { match op { + UnaryOp::Float { .. } => unreachable!("float operations are lowered separately"), UnaryOp::Minus => emit_wide_negate(builder, r_chunks, num_chunks), UnaryOp::Ident | UnaryOp::ToTwoState => emit_wide_ident(builder, r_chunks, num_chunks), UnaryOp::BitNot => emit_wide_bitnot(builder, r_chunks, num_chunks), diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index 7a454a365ac..aee519a5087 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -7,6 +7,8 @@ //! RegisterId → WASM local (i64 for ≤64-bit; multiple i64 locals for wide values). //! Block control flow is implemented via `loop` + `block` + `br_table`. +pub use celox_sir::float::evaluate as evaluate_float; + use wasm_encoder::{ CodeSection, EntityType, ExportKind, ExportSection, Function, FunctionSection, ImportSection, Instruction, MemoryType, Module, TypeSection, ValType, @@ -227,6 +229,18 @@ impl ExternImports { .flat_map(|unit| unit.blocks.values()) .flat_map(|block| &block.instructions) { + let helper = match instruction { + SIRInstruction::Binary(_, _, BinaryOp::Float { op, precision }, _) => { + float_needs_helper(celox_sir::float::binary_code(*op, *precision)) + } + SIRInstruction::Unary(_, UnaryOp::Float { op, precision }, _) => { + float_needs_helper(celox_sir::float::unary_code(*op, *precision)) + } + _ => false, + }; + if helper { + arities.insert(celox_sir::float::FLOAT_HELPER_ID, 3); + } if let SIRInstruction::ExternCall { func, args, .. } = instruction { let arity = *arities.entry(*func).or_insert(args.len()); assert_eq!( @@ -526,10 +540,34 @@ fn compile_instruction( compile_imm(dst, val, unit, four_state, &*locals, instrs); } SIRInstruction::Binary(dst, lhs, op, rhs) => { - compile_binary(dst, lhs, op, rhs, unit, four_state, &mut *locals, instrs); + if let BinaryOp::Float { op, precision } = op { + compile_float( + *dst, + *lhs, + Some(*rhs), + celox_sir::float::binary_code(*op, *precision), + externs, + locals, + instrs, + ); + } else { + compile_binary(dst, lhs, op, rhs, unit, four_state, &mut *locals, instrs); + } } SIRInstruction::Unary(dst, op, src) => { - compile_unary(dst, op, src, unit, four_state, locals, instrs); + if let UnaryOp::Float { op, precision } = op { + compile_float( + *dst, + *src, + None, + celox_sir::float::unary_code(*op, *precision), + externs, + locals, + instrs, + ); + } else { + compile_unary(dst, op, src, unit, four_state, locals, instrs); + } } SIRInstruction::Load(dst, addr, offset, op_width) => { compile_load( @@ -1582,6 +1620,9 @@ fn compile_binary_narrow( instrs.push(Instruction::LocalGet(r.value_idx)); match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } BinaryOp::Add => instrs.push(Instruction::I64Add), BinaryOp::Sub => instrs.push(Instruction::I64Sub), BinaryOp::Mul => instrs.push(Instruction::I64Mul), @@ -1902,6 +1943,9 @@ fn compile_binary_wide( } match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } // 1. Chunk-wise bitwise ops BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { for c in 0..d_chunks { @@ -3478,6 +3522,9 @@ fn compile_unary( let s_width = unit.register_map[src].width(); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::Ident | UnaryOp::ToTwoState => { for c in 0..d.num_chunks { emit_wide_get_chunk(instrs, &s, c); @@ -3693,6 +3740,9 @@ fn compile_unary_mask( }; match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::Ident | UnaryOp::BitNot => { for c in 0..dst.num_chunks { if c < src.num_chunks { @@ -6174,6 +6224,224 @@ fn emit_trigger_detection( instrs.push(Instruction::End); // end if } +fn float_needs_helper(code: u64) -> bool { + matches!(code & 255, 4 | 5) +} +fn compile_float( + dst: RegisterId, + lhs: RegisterId, + rhs: Option, + code: u64, + externs: &ExternImports, + locals: &mut LocalAllocator, + instrs: &mut Vec>, +) { + let op = code & 255; + let f64 = code & 256 != 0; + let d = locals.reg_map[&dst].clone(); + instrs.push(Instruction::LocalGet(locals.reg_map[&lhs].value_idx)); + if matches!(code & 255, 34 | 35) { + if let Some(mask) = locals.reg_map[&lhs].mask_idx { + instrs.extend([ + Instruction::LocalGet(mask), + Instruction::I64Const(-1), + Instruction::I64Xor, + Instruction::I64And, + ]); + } + } + + if float_needs_helper(code) { + if let Some(rhs) = rhs { + instrs.push(Instruction::LocalGet(locals.reg_map[&rhs].value_idx)); + } else { + instrs.push(Instruction::I64Const(0)); + } + instrs.push(Instruction::I64Const(code as i64)); + instrs.push(Instruction::Call( + externs.function_index(celox_sir::float::FLOAT_HELPER_ID), + )); + } else if matches!(op, 34 | 35) { + let width = (code >> 16) as usize; + if width < 64 { + if op == 34 { + instrs.extend([ + Instruction::I64Const((64 - width) as i64), + Instruction::I64Shl, + Instruction::I64Const((64 - width) as i64), + Instruction::I64ShrS, + ]); + } else { + instrs.extend([ + Instruction::I64Const(((1u64 << width) - 1) as i64), + Instruction::I64And, + ]); + } + } + instrs.push(match (f64, op == 34) { + (false, true) => Instruction::F32ConvertI64S, + (false, false) => Instruction::F32ConvertI64U, + (true, true) => Instruction::F64ConvertI64S, + (true, false) => Instruction::F64ConvertI64U, + }); + if f64 { + instrs.push(Instruction::I64ReinterpretF64); + } else { + instrs.extend([Instruction::I32ReinterpretF32, Instruction::I64ExtendI32U]); + } + } else if matches!(op, 36 | 37) { + compile_float_to_integer(lhs, code, locals, instrs); + } else { + if f64 { + instrs.push(Instruction::F64ReinterpretI64); + } else { + instrs.extend([Instruction::I32WrapI64, Instruction::F32ReinterpretI32]); + } + if let Some(rhs) = rhs { + instrs.push(Instruction::LocalGet(locals.reg_map[&rhs].value_idx)); + if f64 { + instrs.push(Instruction::F64ReinterpretI64); + } else { + instrs.extend([Instruction::I32WrapI64, Instruction::F32ReinterpretI32]); + } + } + let instruction = match (f64, op) { + (false, 0) => Some(Instruction::F32Add), + (false, 1) => Some(Instruction::F32Sub), + (false, 2) => Some(Instruction::F32Mul), + (false, 3) => Some(Instruction::F32Div), + (true, 0) => Some(Instruction::F64Add), + (true, 1) => Some(Instruction::F64Sub), + (true, 2) => Some(Instruction::F64Mul), + (true, 3) => Some(Instruction::F64Div), + (false, 6) => Some(Instruction::F32Eq), + (false, 7) => Some(Instruction::F32Ne), + (false, 8) => Some(Instruction::F32Lt), + (false, 9) => Some(Instruction::F32Le), + (false, 10) => Some(Instruction::F32Gt), + (false, 11) => Some(Instruction::F32Ge), + (true, 6) => Some(Instruction::F64Eq), + (true, 7) => Some(Instruction::F64Ne), + (true, 8) => Some(Instruction::F64Lt), + (true, 9) => Some(Instruction::F64Le), + (true, 10) => Some(Instruction::F64Gt), + (true, 11) => Some(Instruction::F64Ge), + (false, 32) => Some(Instruction::F32Neg), + (true, 32) => Some(Instruction::F64Neg), + (false, 33) => { + instrs.push(Instruction::F32Const(0.0.into())); + Some(Instruction::F32Ne) + } + (true, 33) => { + instrs.push(Instruction::F64Const(0.0.into())); + Some(Instruction::F64Ne) + } + (true, 38) => Some(Instruction::F32DemoteF64), + (false, 39) => Some(Instruction::F64PromoteF32), + (false, 38) | (true, 39) => None, + _ => unreachable!("known floating operation"), + }; + if let Some(instruction) = instruction { + instrs.push(instruction); + } + if matches!(op, 6..=11 | 33) { + instrs.push(Instruction::I64ExtendI32U); + } else if op == 38 || (!f64 && op != 39) { + instrs.extend([Instruction::I32ReinterpretF32, Instruction::I64ExtendI32U]); + } else { + instrs.push(Instruction::I64ReinterpretF64); + } + } + instrs.push(Instruction::LocalSet(d.value_idx)); + if let Some(mask) = d.mask_idx { + instrs.push(Instruction::I64Const(0)); + instrs.push(Instruction::LocalSet(mask)); + } +} + +/// Reduce a rounded floating value modulo 2^64 before converting it. Scaling +/// by a power of two keeps the remainder exact for representable IEEE values; +/// saturating conversion maps the NaN remainder of infinity/NaN to known zero. +fn compile_float_to_integer( + lhs: RegisterId, + code: u64, + locals: &mut LocalAllocator, + instrs: &mut Vec>, +) { + let abs = locals.alloc(1); + let truncated = locals.alloc(1); + let rounded = locals.alloc(1); + let magnitude = locals.alloc(1); + let f64 = code & 256 != 0; + if f64 { + instrs.push(Instruction::F64ReinterpretI64); + } else { + instrs.extend([ + Instruction::I32WrapI64, + Instruction::F32ReinterpretI32, + Instruction::F64PromoteF32, + ]); + } + instrs.extend([ + Instruction::F64Abs, + Instruction::I64ReinterpretF64, + Instruction::LocalSet(abs), + Instruction::LocalGet(abs), + Instruction::F64ReinterpretI64, + Instruction::F64Trunc, + Instruction::I64ReinterpretF64, + Instruction::LocalSet(truncated), + Instruction::LocalGet(truncated), + Instruction::F64ReinterpretI64, + ]); + if code & 512 != 0 { + instrs.extend([ + Instruction::LocalGet(abs), + Instruction::F64ReinterpretI64, + Instruction::LocalGet(truncated), + Instruction::F64ReinterpretI64, + Instruction::F64Sub, + Instruction::F64Const(0.5.into()), + Instruction::F64Ge, + Instruction::F64ConvertI32U, + Instruction::F64Add, + ]); + } + instrs.extend([ + Instruction::I64ReinterpretF64, + Instruction::LocalSet(rounded), + Instruction::LocalGet(rounded), + Instruction::F64ReinterpretI64, + Instruction::LocalGet(rounded), + Instruction::F64ReinterpretI64, + Instruction::F64Const(18_446_744_073_709_551_616.0.into()), + Instruction::F64Div, + Instruction::F64Floor, + Instruction::F64Const(18_446_744_073_709_551_616.0.into()), + Instruction::F64Mul, + Instruction::F64Sub, + Instruction::I64TruncSatF64U, + Instruction::LocalSet(magnitude), + Instruction::I64Const(0), + Instruction::LocalGet(magnitude), + Instruction::I64Sub, + Instruction::LocalGet(magnitude), + Instruction::LocalGet(locals.reg_map[&lhs].value_idx), + Instruction::I64Const((1u64 << if f64 { 63 } else { 31 }) as i64), + Instruction::I64And, + Instruction::I64Const(0), + Instruction::I64Ne, + Instruction::Select, + ]); + let width = (code >> 16) as usize; + if width < 64 { + instrs.extend([ + Instruction::I64Const(((1u64 << width) - 1) as i64), + Instruction::I64And, + ]); + } +} + #[cfg(test)] mod bit_count_tests { mod slice_tests; @@ -6351,6 +6619,234 @@ mod bit_count_tests { memory.data(&store).to_vec() } + #[test] + fn float_integer_conversions_are_portable_without_host_imports() { + use celox_sir::{FloatPrecision as P, FloatUnaryOp as U}; + let double_round = (1u64 << 63) + (1u64 << 39) + 1; + assert_ne!( + (double_round as f32).to_bits(), + ((double_round as f64) as f32).to_bits() + ); + for four_state in [false, true] { + let mut cases = Vec::new(); + for p in [P::F32, P::F64] { + for width in [1, 3, 8, 32, 64] { + for value in [0, 1, u64::MAX, double_round, 1u64 << 63] { + for op in [U::FromSigned { width }, U::FromUnsigned { width }] { + let mask = if four_state { value & 0x24 } else { 0 }; + cases.push((op, p, width, value, mask)); + } + } + } + let encode = |x: f64| { + if p == P::F32 { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } + }; + let half = encode(0.5); + let mut inputs = [ + 0.0, + -0.0, + 0.5, + -0.5, + 1.5, + -1.5, + 1.75, + -1.75, + f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + f64::MAX, + -f64::MAX, + 9_223_372_036_854_775_808.0, + 18_446_744_073_709_551_616.0, + 18_446_744_073_709_555_712.0, + -18_446_744_073_709_555_712.0, + ] + .into_iter() + .map(encode) + .collect::>(); + inputs.extend([ + half - 1, + half + 1, + if p == P::F32 { + f32::MAX.to_bits() as u64 + } else { + f64::MAX.to_bits() + }, + ]); + for width in [1, 3, 8, 32, 64] { + for round in [false, true] { + for &value in &inputs { + for op in [U::ToSigned { width, round }, U::ToUnsigned { width, round }] + { + cases.push((op, p, p.width(), value, 0)); + } + } + } + } + } + let mut register_map = HashMap::default(); + let mut instructions = Vec::new(); + let mut expected = Vec::new(); + for (index, (op, p, width, value, mask)) in cases.into_iter().enumerate() { + let source = RegisterId(index * 2); + let dst = RegisterId(index * 2 + 1); + let float_op = UnaryOp::Float { op, precision: p }; + let result_width = float_op.result_width(width); + let integer_input = matches!(op, U::FromSigned { .. } | U::FromUnsigned { .. }); + let width_mask = if width == 64 { + u64::MAX + } else { + (1u64 << width) - 1 + }; + let value = value & width_mask; + let mask = mask & width_mask; + register_map.insert( + source, + if four_state && integer_input { + RegisterType::Logic { width } + } else { + RegisterType::Bit { + width, + signed: false, + } + }, + ); + register_map.insert( + dst, + RegisterType::Bit { + width: result_width, + signed: false, + }, + ); + instructions.push(SIRInstruction::Imm( + source, + if four_state && integer_input { + SIRValue::new_four_state(value, mask) + } else { + SIRValue::new(value) + }, + )); + instructions.push(SIRInstruction::Unary(dst, float_op, source)); + instructions.push(SIRInstruction::Store( + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address()), + SIROffset::Static(index * 64), + result_width, + dst, + vec![], + vec![], + )); + expected.push(( + result_width, + celox_design::eval_float_unary(op, p, value & !mask), + )); + } + let block = BasicBlock { + id: BlockId(0), + params: vec![], + instructions, + terminator: SIRTerminator::Return, + }; + let unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks: std::iter::once((BlockId(0), block)).collect(), + register_map, + }; + unit.verify(); + let layout = layout(expected.len() * 64, four_state); + // run_wasm binds only memory, so this also rejects accidental helper imports. + let output = run_wasm(&unit, &layout, four_state); + for (index, (width, value)) in expected.into_iter().enumerate() { + assert_eq!( + read_bits_at(&output, OUTPUT_OFFSET, index * 64, width), + BigUint::from(value), + "case {index}, four_state={four_state}" + ); + } + } + } + + #[test] + fn float_native_arithmetic_preserves_ieee_bits() { + use celox_sir::{FloatBinaryOp as F, FloatPrecision as P}; + for precision in [P::F32, P::F64] { + for four_state in [false, true] { + for (op, a, b, expected) in [ + (F::Add, 1.25, 2.5, 3.75), + (F::Div, 1.0, 0.0, f64::INFINITY), + (F::Mul, -0.0, 2.0, -0.0), + ] { + let bits = |x: f64| { + if precision == P::F32 { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } + }; + let width = precision.width(); + let register_map = (0..3) + .map(|i| { + ( + RegisterId(i), + RegisterType::Bit { + width, + signed: false, + }, + ) + }) + .collect(); + let block = BasicBlock { + id: BlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Imm( + RegisterId(0), + SIRValue::new(BigUint::from(bits(a))), + ), + SIRInstruction::Imm( + RegisterId(1), + SIRValue::new(BigUint::from(bits(b))), + ), + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Float { op, precision }, + RegisterId(1), + ), + SIRInstruction::Store( + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address()), + SIROffset::Static(0), + width, + RegisterId(2), + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }; + let unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks: std::iter::once((BlockId(0), block)).collect(), + register_map, + }; + let layout = layout(width, four_state); + for output in [ + run_cranelift(&unit, &layout, four_state), + run_wasm(&unit, &layout, four_state), + ] { + assert_eq!( + read_bits_at(&output, OUTPUT_OFFSET, 0, width), + BigUint::from(bits(expected)) + ); + } + } + } + } + } + fn read_bits_at(memory: &[u8], base_offset: usize, bit_offset: usize, width: usize) -> BigUint { assert!(bit_offset.is_multiple_of(8)); let byte_offset = base_offset + bit_offset / 8; diff --git a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs index e1ef6936f30..a35ed57289a 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs @@ -144,10 +144,12 @@ pub(super) fn emit_call_extern( rax, qword_ptr(rbx + celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET as i32), )?; - asm.mov( - rax, - qword_ptr(rax + i32::try_from(u64::from(func) * 8).expect("extern function index")), - )?; + let offset = if func == celox_sir::float::FLOAT_HELPER_ID { + -8 + } else { + i32::try_from(u64::from(func) * 8).expect("extern function index") + }; + asm.mov(rax, qword_ptr(rax + offset))?; asm.call(rax)?; asm.add(rsp, frame)?; asm.mov(qword_ptr(rbx + (area + CALL_AREA_RESULT)), rax)?; diff --git a/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs b/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs index 899cc80ea81..259e46e30cb 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs @@ -78,7 +78,10 @@ fn extern_argument(ctx: &mut ISelContext, block: &mut MBlock, arg: RegisterId) - /// Define `dst` from the C integer `result` of an extern call. fn define_extern_result(ctx: &mut ISelContext, block: &mut MBlock, dst: RegisterId, result: VReg) { let value = ctx.reg_map.get(dst); - let ty = ExternValue::of_verified(&ctx.register_types[&dst]); + let ty = ExternValue::of(&ctx.register_types[&dst]).unwrap_or(ExternValue::Integer { + width: ctx.sir_width(&dst), + signed: false, + }); match ty.result_value_mask() { u64::MAX => block.push(MInst::Mov { dst: value, @@ -120,3 +123,57 @@ fn define_extern_result(ctx: &mut ISelContext, block: &mut MBlock, dst: Register }; ctx.set_mask(dst, mask); } + +pub(super) fn lower_float( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + lhs: RegisterId, + rhs: Option, + code: u64, +) { + let a = ctx.reg_map.get(lhs); + let a = if ctx.four_state && matches!(code & 255, 34 | 35) { + let mask = ctx.get_mask(lhs, block); + let known = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::BitNot { + dst: known, + src: mask, + }); + let value = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::And { + dst: value, + lhs: a, + rhs: known, + }); + value + } else { + a + }; + + let b = if let Some(rhs) = rhs { + ctx.reg_map.get(rhs) + } else { + let v = ctx.alloc_vreg(SpillDesc::remat(0)); + block.push(MInst::LoadImm { dst: v, value: 0 }); + v + }; + let c = ctx.alloc_vreg(SpillDesc::remat(code)); + block.push(MInst::LoadImm { + dst: c, + value: code, + }); + for (index, src) in [a, b, c].into_iter().enumerate() { + block.push(MInst::ExternArg { + index: index as u8, + src, + }); + } + block.push(MInst::CallExtern { + func: celox_sir::float::FLOAT_HELPER_ID, + arg_count: 3, + }); + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::ExternResult { dst: result }); + define_extern_result(ctx, block, dst, result); +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/four_state.rs b/crates/celox-backend-x86/src/backend/native/isel/four_state.rs index f90d1ad8e6d..806afb8ac68 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/four_state.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/four_state.rs @@ -478,6 +478,9 @@ pub(super) fn lower_unary_mask( src_width: usize, ) -> VReg { match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::ToTwoState => { let zero = ctx.alloc_vreg(SpillDesc::remat(0)); block.push(MInst::LoadImm { @@ -1490,6 +1493,9 @@ pub(super) fn lower_wide_unary_mask( let sm_chunks = get_wide_mask_chunks(ctx, block, &src, n_src); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::ToTwoState => { let n_dst = ISelContext::num_chunks(d_width); let mut dst_m_chunks = Vec::with_capacity(n_dst); diff --git a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs index beace7d4ff6..cd507041791 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs @@ -1995,6 +1995,17 @@ pub(super) fn lower_instruction( } SIRInstruction::Binary(dst, lhs, op, rhs) => { + if let BinaryOp::Float { op, precision } = op { + extern_call::lower_float( + ctx, + block, + *dst, + *lhs, + Some(*rhs), + celox_sir::float::binary_code(*op, *precision), + ); + return; + } let d_width = ctx.sir_width(dst); let lhs_width = ctx.sir_width(lhs); let rhs_width = ctx.sir_width(rhs); @@ -2075,6 +2086,9 @@ pub(super) fn lower_instruction( let rhs_vreg = ctx.reg_map.get(*rhs); match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul => { // 64-bit arithmetic may produce upper bits; mask to output width. let raw = if d_width < 64 { @@ -2777,6 +2791,17 @@ pub(super) fn lower_instruction( } SIRInstruction::Unary(dst, op, src) => { + if let UnaryOp::Float { op, precision } = op { + extern_call::lower_float( + ctx, + block, + *dst, + *src, + None, + celox_sir::float::unary_code(*op, *precision), + ); + return; + } let d_width = ctx.sir_width(dst); let src_width = ctx.sir_width(src); debug_assert!(src_width > 64 || !ctx.wide_regs.contains_key(src)); @@ -2797,6 +2822,9 @@ pub(super) fn lower_instruction( let src_vreg = ctx.reg_map.get(*src); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::Ident | UnaryOp::ToTwoState => { ctx.emit_mov(block, dst_vreg, src_vreg); } diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests.rs b/crates/celox-backend-x86/src/backend/native/isel/tests.rs index d4ea0d57003..19b3c5d844b 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests.rs @@ -1,4 +1,5 @@ mod bit_count; +mod floating; mod memory; mod packed; mod selection; diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs new file mode 100644 index 00000000000..2b17451218e --- /dev/null +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs @@ -0,0 +1,169 @@ +use super::*; +use crate::native::features::{StateBaseStrategy, X86Features}; +use celox_sir::{FloatBinaryOp as F, FloatPrecision as P, FloatUnaryOp as U}; + +#[test] +fn float_helpers_preserve_live_registers_and_narrow_mux_results() { + const LIVE: usize = 24; + const BASE: usize = 64; + for four_state in [false, true] { + for strategy in [StateBaseStrategy::R15, StateBaseStrategy::Gs] { + if strategy == StateBaseStrategy::Gs && X86Features::detect().state_base() != strategy { + continue; + } + let abs = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId::default(), + }; + let addr = RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, abs); + let mut layout = empty_layout(); + layout.four_state = four_state; + layout.offsets.insert(abs, BASE); + layout.widths.insert(abs, (LIVE * 2 + 1) * 64); + layout.is_4states.insert(abs, false); + layout.total_size = BASE + (LIVE * 2 + 1) * 8; + layout.merged_total_size = layout.total_size; + layout.scratch_base_offset = layout.total_size; + let bit = |width| RegisterType::Bit { + width, + signed: false, + }; + let mut types = (0..LIVE) + .map(|i| (RegisterId(i), bit(64))) + .collect::>(); + let mut insts = (0..LIVE) + .map(|i| SIRInstruction::Load(RegisterId(i), addr, SIROffset::Static(i * 64), 64)) + .collect::>(); + let sum = RegisterId(LIVE); + let narrow = RegisterId(LIVE + 1); + let condition = RegisterId(LIVE + 2); + let fallback = RegisterId(LIVE + 3); + let result = RegisterId(LIVE + 4); + types.extend([ + (sum, bit(64)), + (narrow, bit(3)), + (condition, bit(1)), + (fallback, bit(3)), + (result, bit(3)), + ]); + insts.extend([ + SIRInstruction::Binary( + sum, + RegisterId(0), + BinaryOp::Float { + op: F::Add, + precision: P::F64, + }, + RegisterId(1), + ), + SIRInstruction::Unary( + narrow, + UnaryOp::Float { + op: U::ToUnsigned { + width: 3, + round: true, + }, + precision: P::F64, + }, + sum, + ), + SIRInstruction::Unary( + condition, + UnaryOp::Float { + op: U::ToBool, + precision: P::F64, + }, + RegisterId(0), + ), + SIRInstruction::Imm(fallback, SIRValue::new(7u8)), + SIRInstruction::Mux(result, condition, narrow, fallback), + ]); + for i in 0..LIVE { + insts.push(SIRInstruction::Store( + addr, + SIROffset::Static((LIVE + i) * 64), + 64, + RegisterId(i), + vec![], + vec![], + )); + } + insts.push(SIRInstruction::Store( + addr, + SIROffset::Static(LIVE * 2 * 64), + 3, + result, + vec![], + vec![], + )); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: insts, + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: types, + }; + unit.verify(); + let mut function = lower_execution_unit(&unit, &layout, four_state); + function.target_features = X86Features::for_test_with_state_base(false, strategy); + mir_legalize::legalize(&mut function); + mir_opt::optimize(&mut function); + assert_eq!( + function + .blocks + .iter() + .flat_map(|block| &block.insts) + .filter(|inst| matches!(inst, MInst::CallExtern { .. })) + .count(), + 3 + ); + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "fixture must exercise spill preservation" + ); + mir_opt::post_regalloc_peephole(&mut function, &allocation.assignment); + let emitted = emit::emit( + &function, + &allocation.assignment, + allocation.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let mut memory = vec![0u8; emitted.required_state_size as usize]; + let table = [celox_sir::float::evaluate as *const () as usize]; + let pointer = table.as_ptr().wrapping_add(1) as u64; + let header = celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET; + memory[header..header + 8].copy_from_slice(&pointer.to_le_bytes()); + let mut values = (0..LIVE) + .map(|i| 0x0101_0101_0000_0000u64.wrapping_mul(i as u64 + 1) + i as u64) + .collect::>(); + values[0] = 1.5f64.to_bits(); + values[1] = 2.25f64.to_bits(); + for (i, value) in values.iter().enumerate() { + memory[BASE + i * 8..BASE + i * 8 + 8].copy_from_slice(&value.to_le_bytes()); + } + assert_eq!(unsafe { jit.call(&mut memory) }, 0); + for (i, value) in values.iter().enumerate() { + assert_eq!( + &memory[BASE + (LIVE + i) * 8..BASE + (LIVE + i) * 8 + 8], + &value.to_le_bytes(), + "{strategy:?} {four_state} live r{i}" + ); + } + assert_eq!( + memory[BASE + LIVE * 2 * 8] & 7, + 4, + "{strategy:?} {four_state} narrow rounded mux" + ); + } + } +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/wide.rs index fb87b246654..2e5861376d2 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/wide.rs @@ -163,6 +163,9 @@ pub(super) fn lower_wide_binary( } match op { + BinaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } // Chunk-wise operations: apply to each 64-bit chunk independently BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { let lhs_chunks = ctx.get_wide_chunks(&lhs, block); diff --git a/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs b/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs index 91cb349f357..83d8433f865 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/wide_unary.rs @@ -15,6 +15,9 @@ pub(super) fn lower_wide_unary( let n_chunks = ISelContext::num_chunks(d_width.max(src_width)); match op { + UnaryOp::Float { .. } => { + unreachable!("float operations are lowered before integer operations") + } UnaryOp::BitNot => { let src_chunks = ctx.get_wide_chunks(&src, block); let mut dst_chunks = Vec::with_capacity(n_chunks); diff --git a/crates/celox-design/src/float.rs b/crates/celox-design/src/float.rs new file mode 100644 index 00000000000..e4c5f458572 --- /dev/null +++ b/crates/celox-design/src/float.rs @@ -0,0 +1,167 @@ +//! IEEE floating point operations on raw two-state register payloads. +use crate::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; + +pub fn eval_float_binary(op: B, precision: P, lhs: u64, rhs: u64) -> u64 { + macro_rules! eval { + ($ty:ty, $lhs:expr, $rhs:expr) => {{ + let a = $lhs; + let b = $rhs; + match op { + B::Add => (a + b).to_bits() as u64, + B::Sub => (a - b).to_bits() as u64, + B::Mul => (a * b).to_bits() as u64, + B::Div => (a / b).to_bits() as u64, + B::Rem => (a % b).to_bits() as u64, + B::Pow => a.powf(b).to_bits() as u64, + B::Eq => (a == b) as u64, + B::Ne => (a != b) as u64, + B::Lt => (a < b) as u64, + B::Le => (a <= b) as u64, + B::Gt => (a > b) as u64, + B::Ge => (a >= b) as u64, + } + }}; + } + match precision { + P::F32 => eval!(f32, f32::from_bits(lhs as u32), f32::from_bits(rhs as u32)), + P::F64 => eval!(f64, f64::from_bits(lhs), f64::from_bits(rhs)), + } +} + +pub fn eval_float_unary(op: U, precision: P, value: u64) -> u64 { + let x = match precision { + P::F32 => f32::from_bits(value as u32) as f64, + P::F64 => f64::from_bits(value), + }; + let mask = |width: usize| { + if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + } + }; + match op { + U::Neg => value ^ (1u64 << (precision.width() - 1)), + U::ToBool => (x != 0.0) as u64, + U::FromSigned { width } => { + let signed = if width == 0 { + 0 + } else if width >= 64 { + value as i64 + } else { + ((value << (64 - width)) as i64) >> (64 - width) + }; + // Convert directly to f32 to avoid double rounding through f64. + match precision { + P::F32 => (signed as f32).to_bits() as u64, + P::F64 => (signed as f64).to_bits(), + } + } + U::FromUnsigned { width } => { + let v = value & mask(width); + match precision { + P::F32 => (v as f32).to_bits() as u64, + P::F64 => (v as f64).to_bits(), + } + } + U::ToSigned { width, round } | U::ToUnsigned { width, round } => { + // Integer destinations keep the low bits, independently of signedness. + // Non-finite values have no integer representation; use known zero. + let rounded = if round { x.round() } else { x.trunc() }; + let magnitude = (rounded.abs() % 18_446_744_073_709_551_616.0) as u64; + let bits = if rounded.is_sign_negative() { + magnitude.wrapping_neg() + } else { + magnitude + }; + bits & mask(width) + } + U::Convert { to: P::F32 } => (x as f32).to_bits() as u64, + U::Convert { to: P::F64 } => x.to_bits(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ieee_arithmetic_and_comparisons() { + for p in [P::F32, P::F64] { + let bits = |x: f64| { + if p == P::F32 { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } + }; + assert_eq!( + eval_float_binary(B::Add, p, bits(1.25), bits(2.5)), + bits(3.75) + ); + assert_eq!( + eval_float_binary(B::Div, p, bits(1.0), bits(0.0)), + bits(f64::INFINITY) + ); + assert_eq!(eval_float_binary(B::Eq, p, bits(0.0), bits(-0.0)), 1); + assert_eq!( + eval_float_binary(B::Eq, p, bits(f64::NAN), bits(f64::NAN)), + 0 + ); + assert_eq!(eval_float_binary(B::Ne, p, bits(f64::NAN), bits(1.0)), 1); + assert_eq!(eval_float_binary(B::Lt, p, bits(f64::NAN), bits(1.0)), 0); + assert_eq!(eval_float_unary(U::Neg, p, bits(0.0)), bits(-0.0)); + assert_eq!(eval_float_unary(U::ToBool, p, bits(-0.0)), 0); + } + } + #[test] + fn real_integer_rounding_and_bit_truncation() { + for (x, expected) in [ + (1.5f64, 2u64), + (-1.5, 0xffff_fffe), + (35.2, 35), + (35.7, 36), + (-0.5, 0xffff_ffff), + ] { + for signed in [true, false] { + let op = if signed { + U::ToSigned { + width: 32, + round: true, + } + } else { + U::ToUnsigned { + width: 32, + round: true, + } + }; + assert_eq!(eval_float_unary(op, P::F64, x.to_bits()), expected); + } + } + assert_eq!( + eval_float_unary( + U::ToUnsigned { + width: 64, + round: true + }, + P::F64, + 9_223_372_036_854_775_808f64.to_bits() + ), + 1u64 << 63 + ); + assert_eq!( + eval_float_unary( + U::ToSigned { + width: 8, + round: false + }, + P::F64, + (-1.75f64).to_bits() + ), + 255 + ); + assert_eq!( + eval_float_unary(U::FromSigned { width: 8 }, P::F32, 255), + (-1f32).to_bits() as u64 + ); + } +} diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 553e510abbf..7fcb09250fb 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1,5 +1,8 @@ //! Source-language-independent design identities and semantic vocabulary. +mod float; +pub use float::{eval_float_binary, eval_float_unary}; + use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use num_bigint::BigUint; use serde::{Deserialize, Serialize}; @@ -94,6 +97,8 @@ pub struct RuntimeEventSite { pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, + #[serde(default)] + pub arg_float_precision: Vec>, } /// A function in the host's C ABI that the design calls, such as a @@ -329,6 +334,8 @@ pub struct HostRequestValue { pub width: usize, pub signed: bool, pub is_string: bool, + #[serde(default)] + pub float_precision: Option, } impl HostRequestValue { @@ -338,6 +345,7 @@ impl HostRequestValue { width: self.width, signed: self.signed, is_string: self.is_string, + float_precision: self.float_precision, } } } @@ -994,6 +1002,45 @@ impl ElaboratedDesign { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum FloatPrecision { + F32, + F64, +} +impl FloatPrecision { + pub fn width(self) -> usize { + match self { + Self::F32 => 32, + Self::F64 => 64, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum FloatBinaryOp { + Add, + Sub, + Mul, + Div, + Rem, + Pow, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum FloatUnaryOp { + Neg, + ToBool, + FromSigned { width: usize }, + FromUnsigned { width: usize }, + ToSigned { width: usize, round: bool }, + ToUnsigned { width: usize, round: bool }, + Convert { to: FloatPrecision }, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum BinaryOp { Add, @@ -1025,6 +1072,10 @@ pub enum BinaryOp { LogicOr, EqWildcard, NeWildcard, + Float { + op: FloatBinaryOp, + precision: FloatPrecision, + }, } impl BinaryOp { @@ -1050,6 +1101,7 @@ impl BinaryOp { impl fmt::Display for BinaryOp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let op_str = match self { + BinaryOp::Float { op, precision } => return write!(f, "Float{precision:?}{op:?}"), BinaryOp::Add => "Add", BinaryOp::Sub => "Sub", BinaryOp::Mul => "Mul", @@ -1099,6 +1151,10 @@ pub enum UnaryOp { PopCount, CountLeadingZeros, CountTrailingZeros, + Float { + op: FloatUnaryOp, + precision: FloatPrecision, + }, } impl UnaryOp { @@ -1110,6 +1166,14 @@ impl UnaryOp { /// `usize::MAX`. pub fn result_width(self, operand_width: usize) -> usize { match self { + UnaryOp::Float { op, precision } => match op { + FloatUnaryOp::ToBool => 1, + FloatUnaryOp::ToSigned { width, .. } | FloatUnaryOp::ToUnsigned { width, .. } => { + width + } + FloatUnaryOp::Convert { to } => to.width(), + _ => precision.width(), + }, UnaryOp::LogicNot | UnaryOp::And | UnaryOp::Or | UnaryOp::Xor => 1, UnaryOp::Ident | UnaryOp::ToTwoState | UnaryOp::Minus | UnaryOp::BitNot => { operand_width @@ -1124,6 +1188,7 @@ impl UnaryOp { impl fmt::Display for UnaryOp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let op_str = match self { + UnaryOp::Float { op, precision } => return write!(f, "Float{precision:?}{op:?}"), UnaryOp::Ident => "Ident", UnaryOp::ToTwoState => "ToTwoState", UnaryOp::Minus => "Minus", @@ -1349,6 +1414,7 @@ mod tests { width: 17, signed: true, is_string: false, + float_precision: None, }; let site = HostRequestSite { process: 2, @@ -1439,6 +1505,7 @@ mod tests { arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), + arg_float_precision: Vec::new(), }); runtime.comb_observers.push(RuntimeCombObserver { site_id: 0, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 1c576a4a14d..0bc6ac9085b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -39,6 +39,7 @@ use num_bigint::BigUint; mod comb; mod ff; +mod floating; mod procedural; type RegionedVarAddr = RegionedVarAddrBase; @@ -62,6 +63,7 @@ const FORCE_VALUE: &str = "@force-value:"; #[derive(Clone)] struct SvVariable { + float: Option, path: Vec, width: usize, signed: bool, @@ -1435,6 +1437,7 @@ fn prepare_external_hierarchy_collecting( ( id, SvVariable { + float: None, path: vec![variable.path.join("$")], width: variable.metadata.width, signed: variable.signed, @@ -2417,6 +2420,7 @@ fn lower_module_with_overrides( let path = vec![port.name().to_string()]; let kind = signal_kind_from_port_direction(port.direction())?; let variable = SvVariable { + float: type_info.float, path, width: type_info.width, signed: type_info.signed, @@ -2498,6 +2502,7 @@ fn lower_module_with_overrides( package_variables.push((id, package.to_string(), variable.to_string())); } let variable = SvVariable { + float: type_info.float, path, width: type_info.width, signed: type_info.signed, @@ -2571,6 +2576,7 @@ fn lower_module_with_overrides( variables.insert( id, SvVariable { + float: None, path: vec![parameter.name().to_string()], width, signed, @@ -3607,6 +3613,7 @@ fn lower_initial_processes( variables.insert( id, SvVariable { + float: None, path: vec![format!("$initial[{index}]"), slot.to_string()], width, signed: false, @@ -3957,6 +3964,7 @@ fn ensure_parent_output_signals( parent_signal_names.insert(actual.to_string(), next_id); implicit_output_signals.insert(actual.to_string()); let variable = SvVariable { + float: None, path: vec![actual.to_string()], width: 1, signed: false, @@ -4091,6 +4099,9 @@ fn build_instance_glue( { let actual_expr = expr_for_state_mode(actual_expr, four_state); let actual = connection.map_or("", |item| item.actual.as_str()); + let from = + floating::precision(&actual_expr, parent_variables, parent_signal_names); + let to = child_var.float; let (expr, sources, source_ids) = lower_glue_parent_expr( &actual_expr, parent_variables, @@ -4098,7 +4109,11 @@ fn build_instance_glue( parent_constants, parent_parameter_types, &mut arena, - Some(width), + if from.is_some() || to.is_some() { + None + } else { + Some(width) + }, Some(sv_glue_expr_is_signed( &actual_expr, parent_variables, @@ -4115,6 +4130,34 @@ fn build_instance_glue( None, ) })?; + let source_signed = sv_glue_expr_is_signed( + &actual_expr, + parent_variables, + parent_signal_names, + parent_parameter_types, + ); + let expr = floating::convert( + &mut arena, + expr, + from, + to, + width, + if from.is_none() { + source_signed + } else { + child_var.signed + }, + true, + ) + .ok_or_else(|| { + ParserError::unsupported( + sv::SV_FRONTEND_TRACKING_ISSUE, + LoweringPhase::SimulatorParser, + "real input port conversion", + formal.clone(), + None, + ) + })?; let expr = coerce_node_width( &mut arena, expr, @@ -4239,6 +4282,47 @@ fn build_instance_glue( index: Vec::new(), access: BitAccess::new(0, width - 1), })?; + let target_float = if let [target] = accesses.as_slice() { + parent_variables[&target.signal].float + } else { + None + }; + if child_var.float.is_some() && accesses.len() != 1 { + return Err(ParserError::unsupported( + sv::SV_FRONTEND_TRACKING_ISSUE, + LoweringPhase::SimulatorParser, + "real output port concatenation", + formal.clone(), + None, + )); + } + let target_signed = if let [target] = accesses.as_slice() { + parent_variables[&target.signal].signed + } else { + child_var.signed + }; + let child_input = floating::convert( + &mut arena, + child_input, + child_var.float, + target_float, + target_width, + if child_var.float.is_none() { + child_var.signed + } else { + target_signed + }, + true, + ) + .ok_or_else(|| { + ParserError::unsupported( + sv::SV_FRONTEND_TRACKING_ISSUE, + LoweringPhase::SimulatorParser, + "real output port conversion", + formal.clone(), + None, + ) + })?; let child_node = coerce_node_width( &mut arena, child_input, @@ -4419,6 +4503,36 @@ fn lower_glue_parent_expr( HashSet>, Vec, )> { + if floating::handles(expr, variables, name_to_id) { + let mut native_arena = SLTNodeArena::new(); + let (node, sources) = floating::lower( + expr, + variables, + name_to_id, + constants, + parameter_types, + &mut native_arena, + )?; + let mut cache = HashMap::default(); + let mapped = native_arena + .get(node) + .map_addr(node, &native_arena, arena, &mut cache, &|id| { + GlueAddr::Parent(*id) + }) + .ok()?; + let source_ids = sources.iter().map(|source| source.id).collect(); + let sources = sources + .into_iter() + .map(|source| { + VarAtomBase::new( + GlueAddr::Parent(source.id), + source.access.lsb, + source.access.msb, + ) + }) + .collect(); + return Some((mapped, sources, source_ids)); + } match expr { sv::ir::Expr::Ident(name) => { let Some(id) = name_to_id.get(name).copied() else { @@ -4989,8 +5103,9 @@ fn lower_glue_parent_expr( context_width.map_or(natural_width, |width| width.max(natural_width)) }) .or(context_width); + let float_condition = floating::condition(condition, variables, name_to_id); let (condition, mut sources, mut source_ids) = lower_glue_parent_expr( - condition, + &float_condition, variables, name_to_id, constants, @@ -5154,6 +5269,7 @@ fn signal_kind_from_port_direction( } struct SvSignalType { + float: Option, width: usize, signed: bool, is_4state: bool, @@ -5237,7 +5353,12 @@ fn signal_type_from_sv( .checked_mul(element_count) .ok_or_else(|| sv::AnalyzerError::Unsupported("signal width overflow".to_string()))?; let signed = typ.is_signed(); - let is_4state = !matches!(typ.kind(), sv::ir::TypeKind::Bit); + let float = match typ.kind() { + sv::ir::TypeKind::Real => Some(celox_sir::FloatPrecision::F64), + sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), + _ => None, + }; + let is_4state = float.is_none() && !matches!(typ.kind(), sv::ir::TypeKind::Bit); let packed_ranges = typ .packed_ranges() .iter() @@ -5256,12 +5377,15 @@ fn signal_type_from_sv( }) .collect(); let type_kind = match typ.kind() { - sv::ir::TypeKind::Bit => PortTypeKind::Bit, + sv::ir::TypeKind::Bit | sv::ir::TypeKind::Real | sv::ir::TypeKind::Shortreal => { + PortTypeKind::Bit + } sv::ir::TypeKind::Logic | sv::ir::TypeKind::Reg | sv::ir::TypeKind::Implicit => { PortTypeKind::Logic } }; Ok(SvSignalType { + float, width, signed, is_4state, @@ -5571,7 +5695,13 @@ fn lower_bit_vector_function_slt( } // The random number and time functions need process state, and the // analyzer folds the other functions to constants. - SystemFunction::Time + SystemFunction::Rtoi + | SystemFunction::Itor + | SystemFunction::Realtobits + | SystemFunction::Bitstoreal + | SystemFunction::Shortrealtobits + | SystemFunction::Bitstoshortreal + | SystemFunction::Time | SystemFunction::Stime | SystemFunction::Random | SystemFunction::DistUniform @@ -5631,6 +5761,16 @@ fn lower_expr_with_context( context_width: Option, context_signed: Option, ) -> Option<(celox_slt::NodeId, HashSet>)> { + if floating::handles(expr, variables, name_to_id) { + return floating::lower( + expr, + variables, + name_to_id, + constants, + parameter_types, + arena, + ); + } match expr { sv::ir::Expr::Ident(name) => { let Some(id) = name_to_id.get(name).copied() else { @@ -6216,8 +6356,9 @@ fn lower_expr_with_context( context_width.map_or(natural_width, |width| width.max(natural_width)) }) .or(context_width); + let float_condition = floating::condition(condition, variables, name_to_id); let (condition, mut sources) = lower_expr( - condition, + &float_condition, variables, name_to_id, constants, diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9b9e3489141..b872e0b9461 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -507,6 +507,9 @@ impl<'p, 'a> Comb<'p, 'a> { continue; }; let var = self.m.var(id); + if var.float.is_some() { + continue; + } let (width, signed) = (var.width, var.signed); let Ok(parts) = range.get_parts(full(width)) else { continue; @@ -946,7 +949,12 @@ impl<'p, 'a> Comb<'p, 'a> { op: sv::ir::BinaryOp, left: &sv::ir::Expr, ) -> Result { - let left_value = self.eval(store, frames, left, None)?; + let left_value = self.eval( + store, + frames, + &floating::condition(left, self.m.variables, self.m.name_to_id), + None, + )?; let guard = if op == sv::ir::BinaryOp::LogicAnd { slt_not_false(self.arena, left_value.0)? } else { @@ -965,7 +973,12 @@ impl<'p, 'a> Comb<'p, 'a> { frames: &[Frame], condition: &sv::ir::Expr, ) -> Result<(Value, Value), sv::AnalyzerError> { - let condition_value = self.eval(store, frames, condition, None)?; + let condition_value = self.eval( + store, + frames, + &floating::condition(condition, self.m.variables, self.m.name_to_id), + None, + )?; let truth = slt_truth(self.arena, condition_value.0)?; let unknown = if self.m.four_state { Some(slt_truth_unknown( @@ -1368,6 +1381,14 @@ impl<'p, 'a> Comb<'p, 'a> { None => (1, false, false), }; let (temp, temp_name) = self.m.temp("call", width, signed, is_4state); + self.m.variables.get_mut(&temp).unwrap().float = subroutine + .return_type + .as_ref() + .and_then(|ty| match ty.kind() { + sv::ir::TypeKind::Real => Some(celox_sir::FloatPrecision::F64), + sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), + _ => None, + }); let node = coerce_node_width(self.arena, node, Some(width), signed).map_err(slt_error)?; self.write(store, temp, full(width), (node, sources))?; @@ -1608,6 +1629,12 @@ impl<'p, 'a> Comb<'p, 'a> { lhs: &sv::ir::LValue, rhs: &sv::ir::Expr, ) -> Result<(), sv::AnalyzerError> { + let owned_rhs = if self.m.calls(rhs) { + self.hoist(store, frames, rhs)? + } else { + rhs.clone() + }; + let rhs = &owned_rhs; let lhs = &self.hoist_lvalue(store, frames, lhs)?; let target = self.lvalue_target(store, lhs)?; let width = match &target { @@ -1623,8 +1650,21 @@ impl<'p, 'a> Comb<'p, 'a> { ))); } let signed = self.expr_signed(rhs); - let value = self - .eval(store, frames, rhs, Some((width, signed))) + let from = floating::precision(rhs, self.m.variables, self.m.name_to_id); + let target_var = self.m.id(lhs.name()).map(|id| self.m.var(id)); + let to = target_var.and_then(|v| v.float); + let target_signed = target_var.is_some_and(|v| v.signed); + let (mut node, sources) = self + .eval( + store, + frames, + rhs, + if from.is_some() || to.is_some() { + None + } else { + Some((width, signed)) + }, + ) .map_err(|error| match error { sv::AnalyzerError::Unsupported(construct) if construct == "combinational expression" => @@ -1636,7 +1676,21 @@ impl<'p, 'a> Comb<'p, 'a> { } error => error, })?; - self.store_value(store, frames, target, value, signed, rhs) + node = floating::convert( + self.arena, + node, + from, + to, + width, + if from.is_none() { + signed + } else { + target_signed + }, + true, + ) + .ok_or_else(|| unsupported("real assignment conversion"))?; + self.store_value(store, frames, target, (node, sources), signed, rhs) } fn store_value( @@ -2001,7 +2055,12 @@ impl<'p, 'a> Comb<'p, 'a> { then_body, else_body, } => { - let (node, sources) = self.eval(&mut store, frames, condition, None)?; + let (node, sources) = self.eval( + &mut store, + frames, + &floating::condition(condition, self.m.variables, self.m.name_to_id), + None, + )?; let truth = slt_truth(self.arena, node)?; match slt_bool(self.arena, &mut self.consts, truth).or_else(|| self.known(truth)) { Some(true) => self.exec_block(store, frames, then_body), @@ -2642,7 +2701,12 @@ impl<'p, 'a> Comb<'p, 'a> { } (sv::ir::LoopKind::Forever, _) => None, (_, Some(condition)) => { - let (node, sources) = self.eval(&mut store, frames, condition, None)?; + let (node, sources) = self.eval( + &mut store, + frames, + &floating::condition(condition, self.m.variables, self.m.name_to_id), + None, + )?; let truth = slt_truth(self.arena, node)?; match slt_bool(self.arena, &mut self.consts, truth) { Some(false) => break, @@ -3153,8 +3217,38 @@ impl<'p, 'a> Comb<'p, 'a> { param.source_name )) })?; + let actual = if self.m.calls(&actual) { + self.hoist(store, frames, &actual)? + } else { + actual + }; let signed = self.expr_signed(&actual); - let (node, sources) = self.eval(store, frames, &actual, Some((width, signed)))?; + let from = floating::precision(&actual, self.m.variables, self.m.name_to_id); + let to = self.m.var(id).float; + let (node, sources) = self.eval( + store, + frames, + &actual, + if from.is_some() || to.is_some() { + None + } else { + Some((width, signed)) + }, + )?; + let node = floating::convert( + self.arena, + node, + from, + to, + width, + if from.is_none() { + signed + } else { + self.m.var(id).signed + }, + true, + ) + .ok_or_else(|| unsupported("real argument conversion"))?; let node = coerce_node_width(self.arena, node, Some(width), signed).map_err(slt_error)?; let node = if self.m.var(id).is_4state { @@ -3200,8 +3294,28 @@ impl<'p, 'a> Comb<'p, 'a> { for (id, lvalues) in outputs { let width = self.m.var(id).width; let signed = self.m.var(id).signed; - let value = self.read(store, id, full(width))?; - self.write_back(store, frames, &lvalues, value, signed)?; + let (mut node, sources) = self.read(store, id, full(width))?; + let from = self.m.var(id).float; + if let [target] = lvalues.as_slice() { + let target_id = self + .m + .id(target.name()) + .ok_or_else(|| unsupported("output argument target"))?; + let target_var = self.m.var(target_id); + node = floating::convert( + self.arena, + node, + from, + target_var.float, + target_var.width, + target_var.signed, + true, + ) + .ok_or_else(|| unsupported("real output argument conversion"))?; + } else if from.is_some() { + return Err(unsupported("real output argument concatenation")); + } + self.write_back(store, frames, &lvalues, (node, sources), signed)?; } match return_var { Some(id) => { @@ -3314,23 +3428,39 @@ impl<'p, 'a> Comb<'p, 'a> { let Some(sv::ir::SystemTaskArg::Expr(condition)) = args.first() else { return Err(unsupported(format!("condition of `{task}`"))); }; - let (node, sources) = self.eval(store, frames, condition, None)?; + let (node, sources) = self.eval( + store, + frames, + &floating::condition(condition, self.m.variables, self.m.name_to_id), + None, + )?; observed.extend(sources); let truth = slt_truth(self.arena, node)?; Some(self.capture(truth)?) } else { None }; - let (template, values) = system_task_template(&kind, args); + let (template, values) = system_task_template(self.m, &kind, args); let mut captured = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); let mut arg_is_string = Vec::with_capacity(values.len()); + let mut arg_float_precision = Vec::with_capacity(values.len()); for value in &values { let node = match value { sv::ir::SystemTaskArg::Expr(expr) => { - let signed = self.expr_signed(expr); - let (node, sources) = self.eval(store, frames, expr, None)?; + let expr = if self.m.calls(expr) { + self.hoist(store, frames, expr)? + } else { + expr.clone() + }; + let signed = self.expr_signed(&expr); + arg_float_precision.push(floating::precision( + &expr, + self.m.variables, + self.m.name_to_id, + )); + let (node, sources) = self.eval(store, frames, &expr, None)?; arg_signed.push(signed); arg_is_string.push(false); observed.extend(sources); @@ -3344,6 +3474,7 @@ impl<'p, 'a> Comb<'p, 'a> { }); arg_signed.push(false); arg_is_string.push(true); + arg_float_precision.push(None); slt_constant(self.arena, value, width, false)? } sv::ir::SystemTaskArg::Empty => { @@ -3421,6 +3552,7 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths, arg_signed, arg_is_string, + arg_float_precision, }); let mut preceding_writes = Vec::new(); for (id, range) in store.iter() { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 0a7a5fd1a6b..12055ad741a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -397,7 +397,11 @@ impl<'p, 'a> Ff<'p, 'a> { expr: &sv::ir::Expr, ) -> Result<(RegisterId, Option), sv::AnalyzerError> { let mut arena = SLTNodeArena::new(); - let node = self.expr_slt(expr, None, &mut arena)?; + let node = self.expr_slt( + &floating::condition(expr, self.m.variables, self.m.name_to_id), + None, + &mut arena, + )?; let truth = slt_truth(&mut arena, node)?; let constant = slt_bool(&arena, &mut ConstCache::default(), truth); Ok((self.lower_slt(&arena, truth)?, constant)) @@ -406,7 +410,11 @@ impl<'p, 'a> Ff<'p, 'a> { /// Whether an expression is not logically false, as a one-bit register. fn eval_not_false(&mut self, expr: &sv::ir::Expr) -> Result { let mut arena = SLTNodeArena::new(); - let node = self.expr_slt(expr, None, &mut arena)?; + let node = self.expr_slt( + &floating::condition(expr, self.m.variables, self.m.name_to_id), + None, + &mut arena, + )?; let not_false = slt_not_false(&mut arena, node)?; self.lower_slt(&arena, not_false) } @@ -942,6 +950,11 @@ impl<'p, 'a> Ff<'p, 'a> { let (width, signed, is_4state) = self.m.type_shape(&r#type)?; let result = self.call(name, &args, arg_order)?; let (temp, temp_name) = self.m.temp("call", width, signed, is_4state); + self.m.variables.get_mut(&temp).unwrap().float = match r#type.kind() { + sv::ir::TypeKind::Real => Some(celox_sir::FloatPrecision::F64), + sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), + _ => None, + }; let Some(result) = result else { return Err(unsupported(format!( "void function `{name}` used as a value" @@ -1214,6 +1227,7 @@ impl<'p, 'a> Ff<'p, 'a> { let (id, _) = self.m.temp("vcd_argument", width, signed, is_4state); self.store(id, SIROffset::Static(0), width, reg); values.push(HostRequestValue { + float_precision: None, id, width, signed, @@ -1806,6 +1820,7 @@ impl<'p, 'a> Ff<'p, 'a> { let mut results = Vec::new(); let (ret_id, ret_name) = self.m.temp("plusargs_result", 32, true, false); results.push(HostRequestValue { + float_precision: None, id: ret_id, width: 32, signed: true, @@ -1823,6 +1838,7 @@ impl<'p, 'a> Ff<'p, 'a> { .ok_or_else(|| unsupported("integral plusargs destination"))?; let (id, result) = self.host_hidden("plusargs_value", &captured, width, false, true)?; results.push(HostRequestValue { + float_precision: None, id, width, signed: false, @@ -1843,6 +1859,7 @@ impl<'p, 'a> Ff<'p, 'a> { requires_timed_simulation: false, operation: u32::from(value_query), args: vec![HostRequestValue { + float_precision: None, id: query_id, width, signed: false, @@ -1938,10 +1955,42 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result<(), sv::AnalyzerError> { let lhs = self.propagate_lvalue(lhs); let lhs = self.hoist_lvalue(&lhs)?; + let owned_rhs = if self.m.calls(rhs) { + self.hoist(rhs)? + } else { + rhs.clone() + }; + let rhs = &owned_rhs; let width = self.lvalue_width(&lhs)?; let signed = self.expr_signed(rhs); let mut arena = SLTNodeArena::new(); - let node = self.expr_slt(rhs, Some((width, signed)), &mut arena)?; + let from = floating::precision(rhs, self.m.variables, self.m.name_to_id); + let target_var = self.m.id(lhs.name()).map(|id| self.m.var(id)); + let to = target_var.and_then(|v| v.float); + let target_signed = target_var.is_some_and(|v| v.signed); + let node = self.expr_slt( + rhs, + if from.is_some() || to.is_some() { + None + } else { + Some((width, signed)) + }, + &mut arena, + )?; + let node = floating::convert( + &mut arena, + node, + from, + to, + width, + if from.is_none() { + signed + } else { + target_signed + }, + true, + ) + .ok_or_else(|| unsupported("real assignment conversion"))?; self.write(&lhs, &mut arena, node, signed, rhs) } @@ -2661,16 +2710,27 @@ impl<'p, 'a> Ff<'p, 'a> { } else { None }; - let (template, values) = system_task_template(&kind, args); + let (template, values) = system_task_template(self.m, &kind, args); let mut regs = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); let mut arg_is_string = Vec::with_capacity(values.len()); + let mut arg_float_precision = Vec::with_capacity(values.len()); for value in &values { match value { sv::ir::SystemTaskArg::Expr(expr) => { - let signed = self.expr_signed(expr); - let reg = self.eval(expr, None)?; + let expr = if self.m.calls(expr) { + self.hoist(expr)? + } else { + expr.clone() + }; + let signed = self.expr_signed(&expr); + arg_float_precision.push(floating::precision( + &expr, + self.m.variables, + self.m.name_to_id, + )); + let reg = self.eval(&expr, None)?; arg_widths.push(self.b.register(®).width()); arg_signed.push(signed); arg_is_string.push(false); @@ -2687,6 +2747,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_widths.push(width); arg_signed.push(false); arg_is_string.push(true); + arg_float_precision.push(None); regs.push(reg); } sv::ir::SystemTaskArg::Empty => { @@ -2726,6 +2787,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_widths, arg_signed, arg_is_string, + arg_float_precision, }); self.b.emit(SIRInstruction::RuntimeEvent { site_id, @@ -3257,10 +3319,39 @@ impl<'p, 'a> Ff<'p, 'a> { param.source_name )) })?; + let actual = if self.m.calls(&actual) { + self.hoist(&actual)? + } else { + actual + }; let width = self.m.var(id).width; let signed = self.expr_signed(&actual); + let from = floating::precision(&actual, self.m.variables, self.m.name_to_id); + let to = self.m.var(id).float; let mut arena = SLTNodeArena::new(); - let node = self.expr_slt(&actual, Some((width, signed)), &mut arena)?; + let node = self.expr_slt( + &actual, + if from.is_some() || to.is_some() { + None + } else { + Some((width, signed)) + }, + &mut arena, + )?; + let node = floating::convert( + &mut arena, + node, + from, + to, + width, + if from.is_none() { + signed + } else { + self.m.var(id).signed + }, + true, + ) + .ok_or_else(|| unsupported("real argument conversion"))?; let mut node = coerce_node_width(&mut arena, node, Some(width), signed).map_err(slt_error)?; if !self.m.var(id).is_4state { diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs index 4b9dfed5aa4..81852f26cc2 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -6,9 +6,20 @@ impl Ff<'_, '_> { &mut self, arg: &sv::ir::SystemTaskArg, ) -> Result, sv::AnalyzerError> { - let (reg, signed, is_string) = match arg { + let (reg, signed, is_string, float_precision) = match arg { sv::ir::SystemTaskArg::Expr(expr) => { - (self.eval(expr, None)?, self.expr_signed(expr), false) + let expr = if self.m.calls(expr) { + self.hoist(expr)? + } else { + expr.clone() + }; + let precision = floating::precision(&expr, self.m.variables, self.m.name_to_id); + ( + self.eval(&expr, None)?, + self.expr_signed(&expr), + false, + precision, + ) } sv::ir::SystemTaskArg::Str(text) => { let bytes = unescape(text).into_bytes(); @@ -17,7 +28,7 @@ impl Ff<'_, '_> { reg, SIRValue::new(BigUint::from_bytes_be(&bytes)), )); - (reg, false, true) + (reg, false, true, None) } _ => return Err(unsupported("empty file I/O argument")), }; @@ -30,6 +41,7 @@ impl Ff<'_, '_> { width, signed, is_string, + float_precision, }) } @@ -81,6 +93,7 @@ impl Ff<'_, '_> { width: 32, signed: false, is_string: false, + float_precision: None, }], Vec::new(), )?; @@ -104,7 +117,7 @@ impl Ff<'_, '_> { SystemTask::Fdisplay(radix) | SystemTask::Fwrite(radix) => { let descriptor = self.file_io_arg(&args[0])?; let kind = SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()); - let (template, args) = system_task_template(&kind, &args[1..]); + let (template, args) = system_task_template(self.m, &kind, &args[1..]); let mut values = vec![descriptor]; for arg in &args { values.push(self.file_io_arg(arg)?); diff --git a/crates/celox-frontend-sv/src/lowering/floating.rs b/crates/celox-frontend-sv/src/lowering/floating.rs new file mode 100644 index 00000000000..be8306c664d --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/floating.rs @@ -0,0 +1,411 @@ +//! Real values use IEEE payload bits in storage and explicit floating operations. +use super::*; +use celox_sir::{FloatBinaryOp as FB, FloatPrecision as FP, FloatUnaryOp as FU}; + +type Value = (NodeId, HashSet>); + +pub(super) fn precision( + expr: &sv::ir::Expr, + variables: &HashMap, + names: &HashMap, +) -> Option { + use sv::ir::{Expr as E, SystemFunction as F}; + match expr { + E::Ident(name) => variables.get(names.get(name)?).and_then(|v| v.float), + E::Literal(text) + if text.contains(['.', 'e', 'E']) && text.replace('_', "").parse::().is_ok() => + { + Some(FP::F64) + } + E::Call { + callee: sv::ir::Callee::System(F::Bitstoreal | F::Itor), + .. + } => Some(FP::F64), + E::Call { + callee: sv::ir::Callee::System(F::Bitstoshortreal), + .. + } => Some(FP::F32), + E::Unary { + op: sv::ir::UnaryOp::Plus | sv::ir::UnaryOp::Minus | sv::ir::UnaryOp::ToTwoState, + expr, + } => precision(expr, variables, names), + E::Mux { + then_expr, + else_expr, + .. + } => match ( + precision(then_expr, variables, names), + precision(else_expr, variables, names), + ) { + (Some(FP::F64), _) | (_, Some(FP::F64)) => Some(FP::F64), + (Some(FP::F32), _) | (_, Some(FP::F32)) => Some(FP::F32), + _ => None, + }, + E::Binary { left, op, right } if binary(*op).is_some_and(|(_, comparison)| !comparison) => { + match ( + precision(left, variables, names), + precision(right, variables, names), + ) { + (Some(FP::F64), _) | (_, Some(FP::F64)) => Some(FP::F64), + (Some(FP::F32), _) | (_, Some(FP::F32)) => Some(FP::F32), + _ => None, + } + } + _ => None, + } +} + +fn binary(op: sv::ir::BinaryOp) -> Option<(FB, bool)> { + use sv::ir::BinaryOp as B; + Some(match op { + B::Add => (FB::Add, false), + B::Sub => (FB::Sub, false), + B::Mul => (FB::Mul, false), + B::Div => (FB::Div, false), + B::Pow => (FB::Pow, false), + B::Eq => (FB::Eq, true), + B::Ne => (FB::Ne, true), + B::Lt => (FB::Lt, true), + B::Le => (FB::Le, true), + B::Gt => (FB::Gt, true), + B::Ge => (FB::Ge, true), + _ => return None, + }) +} + +pub(super) fn handles( + expr: &sv::ir::Expr, + variables: &HashMap, + names: &HashMap, +) -> bool { + use sv::ir::{Expr as E, SystemFunction as F}; + precision(expr, variables, names).is_some() + || match expr { + E::Binary { left, right, .. } => { + precision(left, variables, names).is_some() + || precision(right, variables, names).is_some() + } + E::Unary { expr, .. } | E::Resize { expr, .. } => { + precision(expr, variables, names).is_some() + } + E::Call { + callee: sv::ir::Callee::System(F::Rtoi | F::Realtobits | F::Shortrealtobits), + .. + } => true, + _ => false, + } +} + +pub(super) fn convert( + arena: &mut SLTNodeArena, + node: NodeId, + from: Option, + to: Option, + width: usize, + signed: bool, + round: bool, +) -> Option { + let node = if from.is_none() && to.is_some() { + arena + .alloc(SLTNode::Unary(UnaryOp::ToTwoState, node)) + .ok()? + } else { + node + }; + let (precision, op) = match (from, to) { + (Some(a), Some(b)) if a == b => return Some(node), + (Some(a), Some(b)) => (a, FU::Convert { to: b }), + (None, Some(p)) => { + let width = celox_slt::get_width(node, arena); + ( + p, + if signed { + FU::FromSigned { width } + } else { + FU::FromUnsigned { width } + }, + ) + } + (Some(p), None) => ( + p, + if signed { + FU::ToSigned { width, round } + } else { + FU::ToUnsigned { width, round } + }, + ), + (None, None) => return Some(node), + }; + arena + .alloc(SLTNode::Unary(UnaryOp::Float { op, precision }, node)) + .ok() +} + +pub(super) fn lower( + expr: &sv::ir::Expr, + variables: &HashMap, + names: &HashMap, + constants: &HashMap, + types: &HashMap, + arena: &mut SLTNodeArena, +) -> Option { + use sv::ir::{Expr as E, SystemFunction as F}; + let recur = |expr: &E, arena: &mut SLTNodeArena| { + lower_expr_with_context(expr, variables, names, constants, types, arena, None, None) + }; + let operand = |expr: &E, to: FP, arena: &mut SLTNodeArena| -> Option { + let (node, sources) = recur(expr, arena)?; + let signed = sv_expr_is_signed_with_parameters(expr, variables, names, types); + Some(( + convert( + arena, + node, + precision(expr, variables, names), + Some(to), + 0, + signed, + true, + )?, + sources, + )) + }; + match expr { + E::Ident(name) => { + let id = *names.get(name)?; + let var = variables.get(&id)?; + let node = arena + .alloc(SLTNode::Input { + variable: id, + signed: false, + index: Vec::new(), + access: BitAccess::new(0, var.width - 1), + }) + .ok()?; + Some(( + node, + [VarAtomBase::new(id, 0, var.width - 1)] + .into_iter() + .collect(), + )) + } + E::Literal(text) => { + let bits = text.replace('_', "").parse::().ok()?.to_bits(); + Some(( + arena + .alloc(SLTNode::Constant( + BigUint::from(bits), + BigUint::default(), + 64, + false, + )) + .ok()?, + HashSet::default(), + )) + } + E::Binary { left, op, right } => { + if matches!(op, sv::ir::BinaryOp::LogicAnd | sv::ir::BinaryOp::LogicOr) { + let (mut a, mut sources) = recur(left, arena)?; + let (mut b, other) = recur(right, arena)?; + sources.extend(other); + if let Some(p) = precision(left, variables, names) { + a = arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FU::ToBool, + precision: p, + }, + a, + )) + .ok()?; + } + if let Some(p) = precision(right, variables, names) { + b = arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FU::ToBool, + precision: p, + }, + b, + )) + .ok()?; + } + let op = if *op == sv::ir::BinaryOp::LogicAnd { + BinaryOp::LogicAnd + } else { + BinaryOp::LogicOr + }; + return Some((arena.alloc(SLTNode::Binary(a, op, b)).ok()?, sources)); + } + let (op, _) = binary(*op)?; + let p = match ( + precision(left, variables, names), + precision(right, variables, names), + ) { + (Some(FP::F64), _) | (_, Some(FP::F64)) => FP::F64, + _ => FP::F32, + }; + let (left, mut sources) = operand(left, p, arena)?; + let (right, other) = operand(right, p, arena)?; + sources.extend(other); + Some(( + arena + .alloc(SLTNode::Binary( + left, + BinaryOp::Float { op, precision: p }, + right, + )) + .ok()?, + sources, + )) + } + E::Mux { + condition, + then_expr, + else_expr, + } => { + let p = precision(expr, variables, names)?; + let (condition_node, mut sources) = recur(condition, arena)?; + let condition_node = if let Some(p) = precision(condition, variables, names) { + arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FU::ToBool, + precision: p, + }, + condition_node, + )) + .ok()? + } else { + condition_node + }; + let (then_expr, other) = operand(then_expr, p, arena)?; + sources.extend(other); + let (else_expr, other) = operand(else_expr, p, arena)?; + sources.extend(other); + Some(( + arena + .alloc(SLTNode::Mux { + cond: condition_node, + then_expr, + else_expr, + }) + .ok()?, + sources, + )) + } + E::Resize { + expr, + width, + signed, + } => { + let p = precision(expr, variables, names)?; + let (node, sources) = recur(expr, arena)?; + Some(( + convert(arena, node, Some(p), None, *width, *signed, true)?, + sources, + )) + } + E::Unary { op, expr } => { + let p = precision(expr, variables, names)?; + let (node, sources) = recur(expr, arena)?; + let node = match op { + sv::ir::UnaryOp::Plus | sv::ir::UnaryOp::ToTwoState => node, + sv::ir::UnaryOp::Minus => arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FU::Neg, + precision: p, + }, + node, + )) + .ok()?, + sv::ir::UnaryOp::LogicNot => { + let truth = arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FU::ToBool, + precision: p, + }, + node, + )) + .ok()?; + arena.alloc(SLTNode::Unary(UnaryOp::LogicNot, truth)).ok()? + } + _ => return None, + }; + Some((node, sources)) + } + E::Call { + callee: sv::ir::Callee::System(function), + args, + .. + } => { + let arg = args.first()?.as_ref()?; + match function { + F::Bitstoreal | F::Bitstoshortreal => { + let (node, sources) = recur(arg, arena)?; + let width = if *function == F::Bitstoreal { 64 } else { 32 }; + Some(( + coerce_node_width(arena, node, Some(width), false).ok()?, + sources, + )) + } + F::Realtobits | F::Shortrealtobits => operand( + arg, + if *function == F::Realtobits { + FP::F64 + } else { + FP::F32 + }, + arena, + ), + F::Itor => { + let (node, sources) = recur(arg, arena)?; + let node = if let Some(p) = precision(arg, variables, names) { + convert(arena, node, Some(p), None, 32, true, true)? + } else { + coerce_node_width( + arena, + node, + Some(32), + sv_expr_is_signed_with_parameters(arg, variables, names, types), + ) + .ok()? + }; + Some(( + convert(arena, node, None, Some(FP::F64), 32, true, true)?, + sources, + )) + } + F::Rtoi => { + let p = precision(arg, variables, names).unwrap_or(FP::F64); + let (node, sources) = operand(arg, p, arena)?; + Some(( + convert(arena, node, Some(p), None, 32, true, false)?, + sources, + )) + } + _ => None, + } + } + _ => None, + } +} + +/// Preserve floating zero semantics in conditions, including negative zero. +pub(super) fn condition( + expr: &sv::ir::Expr, + variables: &HashMap, + names: &HashMap, +) -> sv::ir::Expr { + if precision(expr, variables, names).is_none() { + return expr.clone(); + } + sv::ir::Expr::Unary { + op: sv::ir::UnaryOp::LogicNot, + expr: Box::new(sv::ir::Expr::Unary { + op: sv::ir::UnaryOp::LogicNot, + expr: Box::new(expr.clone()), + }), + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 8960d107d1a..3f87467ce95 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -59,6 +59,52 @@ pub(super) struct MemoryWord { } impl<'a> ProcModule<'a> { + pub fn expr_float_precision(&self, expr: &sv::ir::Expr) -> Option { + use celox_sir::FloatPrecision as P; + use sv::ir::{BinaryOp, Expr}; + let combine = |left, right| match (left, right) { + (Some(P::F64), _) | (_, Some(P::F64)) => Some(P::F64), + (Some(P::F32), _) | (_, Some(P::F32)) => Some(P::F32), + _ => None, + }; + match expr { + Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } => self + .subroutines + .get(name)? + .return_type + .as_ref() + .and_then(|ty| match ty.kind() { + sv::ir::TypeKind::Real => Some(P::F64), + sv::ir::TypeKind::Shortreal => Some(P::F32), + _ => None, + }), + Expr::Binary { + left, + op: BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow, + right, + } => combine( + self.expr_float_precision(left), + self.expr_float_precision(right), + ), + Expr::Unary { + op: sv::ir::UnaryOp::Plus | sv::ir::UnaryOp::Minus | sv::ir::UnaryOp::ToTwoState, + expr, + } => self.expr_float_precision(expr), + Expr::Mux { + then_expr, + else_expr, + .. + } => combine( + self.expr_float_precision(then_expr), + self.expr_float_precision(else_expr), + ), + _ => floating::precision(expr, self.variables, self.name_to_id), + } + } + pub fn new( module: &sv::ir::Module, variables: &'a mut HashMap, @@ -559,6 +605,7 @@ impl<'a> ProcModule<'a> { self.variables.insert( id, SvVariable { + float: None, path: vec![name.clone()], width: width.max(1), signed, @@ -626,6 +673,7 @@ impl<'a> ProcModule<'a> { last.push_str(suffix); } let variable = SvVariable { + float: None, path, width: 1, signed: false, @@ -934,10 +982,16 @@ fn template_arguments(template: &str) -> usize { if ch != '%' { continue; } - chars.next_if_eq(&'-'); + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } if let Some(spec) = chars.next() - && "bBoOhHxXdDiIcCsStT".contains(spec) + && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { count += 1; } @@ -951,6 +1005,7 @@ fn template_arguments(template: &str) -> usize { /// displayed in the task's radix, directly after the previous one (IEEE /// 1800-2023 21.2.1.1). pub(super) fn system_task_template( + module: &ProcModule<'_>, kind: &SystemTaskKind, args: &[sv::ir::SystemTaskArg], ) -> (Option, Vec>) { @@ -978,11 +1033,17 @@ pub(super) fn system_task_template( let mut text = template.unwrap_or_default(); for value in &values[converted..] { text.push('%'); - text.push(if matches!(value, sv::ir::SystemTaskArg::Str(_)) { - 's' + if let sv::ir::SystemTaskArg::Expr(expr) = value + && module.expr_float_precision(expr).is_some() + { + text.push_str("#g"); } else { - *radix - }); + text.push(if matches!(value, sv::ir::SystemTaskArg::Str(_)) { + 's' + } else { + *radix + }); + } } template = Some(text); } @@ -1029,6 +1090,7 @@ pub(super) fn register_locals( variables.insert( id, SvVariable { + float: type_info.float, path: vec![local.source_name.clone()], width: type_info.width, signed: type_info.signed, @@ -1158,6 +1220,7 @@ fn slt_const4_node( let (value, mask, inner_width) = child(*inner)?; let inner_all = mask_of(inner_width); match op { + UnaryOp::Float { .. } => return None, UnaryOp::Ident => (value, mask, width), UnaryOp::ToTwoState => ( (&value & (&inner_all ^ &mask)) & &all, diff --git a/crates/celox-frontend-veryl/src/float.rs b/crates/celox-frontend-veryl/src/float.rs new file mode 100644 index 00000000000..ffc46dd697d --- /dev/null +++ b/crates/celox-frontend-veryl/src/float.rs @@ -0,0 +1,206 @@ +//! Floating-point semantics shared by RTL and testbench lowering. +use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp, UnaryOp}; +use veryl_analyzer::ir::{Expression, Factor, Op, Type, TypeKind, ValueVariant}; + +pub(crate) fn precision(ty: &Type) -> Option { + match ty.kind { + TypeKind::F32 => Some(FloatPrecision::F32), + TypeKind::F64 => Some(FloatPrecision::F64), + _ => None, + } +} + +/// Veryl 0.22 reports unary and ternary float results as bit types. +/// Recover their numeric type before choosing operations or conversions. +pub(crate) fn type_of(expr: &Expression) -> &Type { + // A reported f64 is already the widest numeric type. Other results may + // hide a float behind the analyzer's unary/conditional bit-type result. + if matches!( + precision(&expr.comptime().r#type), + Some(FloatPrecision::F64) + ) { + return &expr.comptime().r#type; + } + if !matches!( + expr, + Expression::Unary(Op::Add | Op::Sub, _, _) | Expression::Ternary(..) + ) && !matches!( + expr, + Expression::Binary( + _, + Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Rem | Op::Pow, + _, + _ + ) + ) { + return &expr.comptime().r#type; + } + let mut pending = vec![expr]; + let mut float = None; + while let Some(node) = pending.pop() { + let reported = &node.comptime().r#type; + match precision(reported) { + Some(FloatPrecision::F64) => return reported, + Some(FloatPrecision::F32) => float = Some(reported), + None => (), + } + match node { + Expression::Unary(Op::Add | Op::Sub, inner, _) => pending.push(inner), + Expression::Binary( + left, + Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Rem | Op::Pow, + right, + _, + ) => { + pending.push(right); + pending.push(left); + } + Expression::Ternary(_, left, right, _) => { + pending.push(right); + pending.push(left); + } + // Comparisons and explicit casts are numeric type boundaries. + _ => (), + } + } + float.unwrap_or(&expr.comptime().r#type) +} + +/// Cached analyzer values involving floats can contain integer evaluation of +/// a unary operand. Keep the original expression's numeric operations instead. +pub(crate) fn needs_numeric_lowering(expr: &Expression) -> bool { + if precision(type_of(expr)).is_some() { + return !matches!(expr, Expression::Term(_)); + } + match expr { + Expression::Unary(_, inner, _) => precision(type_of(inner)).is_some(), + Expression::Binary(left, _, right, _) => { + precision(type_of(left)).is_some() || precision(type_of(right)).is_some() + } + _ => false, + } +} + +pub(crate) fn binary(op: Op) -> Option { + Some(match op { + Op::Add => FloatBinaryOp::Add, + Op::Sub => FloatBinaryOp::Sub, + Op::Mul => FloatBinaryOp::Mul, + Op::Div => FloatBinaryOp::Div, + Op::Rem => FloatBinaryOp::Rem, + Op::Pow => FloatBinaryOp::Pow, + Op::Eq => FloatBinaryOp::Eq, + Op::Ne => FloatBinaryOp::Ne, + Op::Less => FloatBinaryOp::Lt, + Op::LessEq => FloatBinaryOp::Le, + Op::Greater => FloatBinaryOp::Gt, + Op::GreaterEq => FloatBinaryOp::Ge, + _ => return None, + }) +} + +pub(crate) fn conversion(source: &Type, target: &Type) -> Option { + let source_precision = precision(source); + let target_precision = precision(target); + let (precision, op) = match (source_precision, target_precision) { + (Some(from), Some(to)) if from != to => (from, FloatUnaryOp::Convert { to }), + (Some(from), None) => ( + from, + if target.signed { + FloatUnaryOp::ToSigned { + width: target.total_width()?, + round: true, + } + } else { + FloatUnaryOp::ToUnsigned { + width: target.total_width()?, + round: true, + } + }, + ), + (None, Some(to)) => ( + to, + if source.signed { + FloatUnaryOp::FromSigned { + width: source.total_width()?, + } + } else { + FloatUnaryOp::FromUnsigned { + width: source.total_width()?, + } + }, + ), + _ => return None, + }; + Some(UnaryOp::Float { op, precision }) +} + +/// Insert a numeric conversion without asking the analyzer to reinterpret the +/// source's IEEE payload as an integer or to fold a synthetic expression. +pub(crate) fn converted<'a>( + expr: &'a Expression, + target: &Type, +) -> std::borrow::Cow<'a, Expression> { + if conversion(type_of(expr), target).is_none() { + return std::borrow::Cow::Borrowed(expr); + } + let mut ct = expr.comptime().clone(); + ct.r#type = target.clone(); + ct.is_const = false; + let mut target_ct = ct.clone(); + target_ct.value = ValueVariant::Type(target.clone()); + std::borrow::Cow::Owned(Expression::Binary( + Box::new(expr.clone()), + Op::As, + Box::new(Expression::Term(Box::new(Factor::Value(target_ct)))), + Box::new(ct), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use veryl_analyzer::ir::{Comptime, Shape}; + + #[test] + fn recovers_float_types_in_deep_arithmetic_without_recursion() { + let mut float_type = Type::new(TypeKind::F32); + float_type.set_concrete_width(Shape::new(vec![Some(32)])); + let mut integer = Type::new(TypeKind::Bit); + integer.set_concrete_width(Shape::new(vec![Some(32)])); + let ct = Comptime { + r#type: integer, + ..Default::default() + }; + let float_ct = Comptime { + r#type: float_type, + ..Default::default() + }; + let mut expression = Expression::Unary( + Op::Sub, + Box::new(Expression::Term(Box::new(Factor::Value(float_ct)))), + Box::new(ct.clone()), + ); + for _ in 0..10_000 { + expression = Expression::Binary( + Box::new(expression), + Op::Add, + Box::new(Expression::Term(Box::new(Factor::Value(ct.clone())))), + Box::new(ct.clone()), + ); + } + assert_eq!(precision(type_of(&expression)), Some(FloatPrecision::F32)); + // The test also destroys the recursive AST iteratively. + let mut pending = vec![expression]; + while let Some(expression) = pending.pop() { + match expression { + Expression::Unary(_, inner, _) => pending.push(*inner), + Expression::Binary(left, _, right, _) => { + pending.push(*left); + pending.push(*right); + } + _ => (), + } + } + } +} diff --git a/crates/celox-frontend-veryl/src/lib.rs b/crates/celox-frontend-veryl/src/lib.rs index 8b7b441bbf8..dcc37f38b5d 100644 --- a/crates/celox-frontend-veryl/src/lib.rs +++ b/crates/celox-frontend-veryl/src/lib.rs @@ -9,6 +9,7 @@ mod config; mod dynamic_for_check; mod error; mod file_dependencies; +mod float; pub mod hierarchy; mod interface_captures; pub mod loop_provenance; diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 1535b67afe9..490449601cb 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -560,6 +560,10 @@ impl<'a> FfParser<'a> { .iter() .map(|arg| arg.0.comptime().expr_context.signed) .collect(), + arg_float_precision: value_args + .iter() + .map(|arg| crate::float::precision(crate::float::type_of(&arg.0))) + .collect(), arg_is_string: value_args .iter() .map(|arg| arg.0.comptime().r#type.is_string()) diff --git a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs index a8f2d731c83..3cacbe59e11 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs @@ -3752,8 +3752,13 @@ impl<'a> FfParser<'a> { .map(|dst| get_access_width(self.module, dst.id, &dst.index, &dst.select)) .sum::>()?; + let expression = assign_statement + .dst + .first() + .map(|dst| crate::float::converted(&assign_statement.expr, &dst.comptime.r#type)) + .unwrap_or(std::borrow::Cow::Borrowed(&assign_statement.expr)); self.parse_expression( - &assign_statement.expr, + &expression, targets, domain, convert, @@ -5222,6 +5227,11 @@ impl<'a> FfParser<'a> { ir_builder: &mut SIRBuilder, context: Option, ) -> Result<(), ParserError> { + let context = if crate::float::precision(crate::float::type_of(expr)).is_some() { + None + } else { + context + }; let context_width = context.map(|context| context.width); if let Some(bound_reg) = self .get_bound_function_expression_value(expr.token_range()) @@ -5240,7 +5250,10 @@ impl<'a> FfParser<'a> { // match context_width because emit_multi_dst_assign assumes rhs_width >= part_width. if !matches!(expr, Expression::Term(_)) { let ct = expr.comptime(); - if ct.is_const { + if ct.is_const + && !crate::float::needs_numeric_lowering(expr) + && crate::float::type_of(expr).kind == ct.r#type.kind + { if let Some((celox_value, mask_xz, width, _)) = celox_value_from_comptime_in_context(ct, context_width) { @@ -5267,18 +5280,106 @@ impl<'a> FfParser<'a> { )?; } Expression::Binary(left, op, right, _) => { + if *op == Op::As { + if let Some(op) = crate::float::conversion( + crate::float::type_of(left), + crate::float::type_of(expr), + ) { + self.parse_expression_in_context( + left, targets, domain, convert, sources, ir_builder, None, + )?; + let source = self.stack.pop_back().unwrap(); + let result = ir_builder.alloc_bit( + crate::float::type_of(expr).total_width().unwrap(), + expr.comptime().r#type.signed, + ); + ir_builder.emit(SIRInstruction::Unary(result, op, source)); + self.stack.push_back(result); + return Ok(()); + } + } else if crate::float::precision(crate::float::type_of(left)).is_some() + || crate::float::precision(crate::float::type_of(right)).is_some() + { + let target = if matches!( + crate::float::precision(crate::float::type_of(left)), + Some(celox_design::FloatPrecision::F64) + ) { + crate::float::type_of(left) + } else if crate::float::precision(crate::float::type_of(right)).is_some() { + crate::float::type_of(right) + } else { + crate::float::type_of(left) + }; + let precision = crate::float::precision(target).unwrap(); + self.parse_expression_in_context( + &crate::float::converted(left, target), + targets, + domain, + convert, + sources, + ir_builder, + None, + )?; + let left = self.stack.pop_back().unwrap(); + self.parse_expression_in_context( + &crate::float::converted(right, target), + targets, + domain, + convert, + sources, + ir_builder, + None, + )?; + let right = self.stack.pop_back().unwrap(); + let result = ir_builder + .alloc_bit(crate::float::type_of(expr).total_width().unwrap(), false); + ir_builder.emit(SIRInstruction::Binary( + result, + left, + BinaryOp::Float { + op: crate::float::binary(*op).expect("validated float operator"), + precision, + }, + right, + )); + self.stack.push_back(result); + return Ok(()); + } self.parse_binary( op, left, right, targets, domain, convert, sources, ir_builder, context, )?; } Expression::Unary(op, expr, _) => { + if let Some(precision) = crate::float::precision(crate::float::type_of(expr)) { + self.parse_expression_in_context( + expr, targets, domain, convert, sources, ir_builder, None, + )?; + if *op == Op::Sub { + let source = self.stack.pop_back().unwrap(); + let result = ir_builder + .alloc_bit(crate::float::type_of(expr).total_width().unwrap(), false); + ir_builder.emit(SIRInstruction::Unary( + result, + UnaryOp::Float { + op: celox_design::FloatUnaryOp::Neg, + precision, + }, + source, + )); + self.stack.push_back(result); + } + return Ok(()); + } self.parse_unary( op, expr, targets, domain, convert, sources, ir_builder, context, )?; } Expression::Ternary(cond, then, els, _) => { + let target_type = crate::float::type_of(expr); + let then = crate::float::converted(then, target_type); + let els = crate::float::converted(els, target_type); self.parse_ternary( - cond, then, els, targets, domain, convert, sources, ir_builder, context, + cond, &then, &els, targets, domain, convert, sources, ir_builder, context, )?; } Expression::Concatenation(exprs, _) => { diff --git a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs index a7c82db7d33..b57af9a439d 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs @@ -694,6 +694,9 @@ impl<'a> FfParser<'a> { } fn coerce_function_expression_to_type(expr: Expression, target_type: &Type) -> Expression { + if crate::float::conversion(&expr.comptime().r#type, target_type).is_some() { + return crate::float::converted(&expr, target_type).into_owned(); + } let source_type = &expr.comptime().r#type; if source_type.total_width() == target_type.total_width() && source_type.signed == target_type.signed @@ -1786,6 +1789,19 @@ impl<'a> FfParser<'a> { dsts: &[AssignDestination], ir_builder: &mut SIRBuilder, ) -> Result { + if let [destination] = dsts { + if let Some(op) = crate::float::conversion( + &self.module.variables[&formal_id].r#type, + &destination.comptime.r#type, + ) { + let result = ir_builder.alloc_bit( + destination.comptime.r#type.total_width().unwrap(), + destination.comptime.r#type.signed, + ); + ir_builder.emit(SIRInstruction::Unary(result, op, reg)); + return Ok(result); + } + } let width = dsts .iter() .map(|dst| get_access_width(self.module, dst.id, &dst.index, &dst.select)) diff --git a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs index a08dbca3271..19ddd058a81 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs @@ -406,8 +406,9 @@ impl<'a> FfParser<'a> { .collect(); let element_count: usize = formal_shape.iter().product(); if formal_shape.is_empty() || element_count == 0 || !width.is_multiple_of(element_count) { + let actual = crate::float::converted(actual, &self.module.variables[&formal_id].r#type); self.parse_expression( - actual, + &actual, targets, domain, convert, diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree.rs index 2712c028fe3..dc45a20bf5a 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree.rs @@ -2530,7 +2530,17 @@ fn eval_assignment_rhs_effectful( bounds, )) } else { - eval_assignment_expression_effectful(module, store, &stmt.expr, arena, rhs_expected_width) + eval_assignment_expression_effectful( + module, + store, + &stmt + .dst + .first() + .map(|dst| crate::float::converted(&stmt.expr, &dst.comptime.r#type)) + .unwrap_or(std::borrow::Cow::Borrowed(&stmt.expr)), + arena, + rhs_expected_width, + ) } } @@ -2936,6 +2946,18 @@ pub(super) fn apply_function_output( ) -> Result<(SymbolicStore, BoundaryMap), ParserError> { let (output_expr, output_sources, output_is_2state) = function_output_value(module, arg_id, call, final_local_store, arena)?; + let output_expr = if let [destination] = dsts { + if let Some(op) = crate::float::conversion( + &module.variables[&arg_id].r#type, + &destination.comptime.r#type, + ) { + arena.alloc(SLTNode::Unary(op, output_expr))? + } else { + output_expr + } + } else { + output_expr + }; // Copy-out reads the formal variable. Its declared signedness can differ // from the expression stored by the last assignment in the callee. let output_signed = module.variables[&arg_id].r#type.signed; diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index a1b90d67f40..56227bf5699 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -108,6 +108,10 @@ fn register_comb_runtime_event_site<'a>( .iter() .map(|arg| arg.0.comptime().expr_context.signed) .collect(), + arg_float_precision: value_args + .iter() + .map(|arg| crate::float::precision(crate::float::type_of(&arg.0))) + .collect(), arg_is_string: value_args .iter() .map(|arg| arg.0.comptime().r#type.is_string()) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/expr.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/expr.rs index d626cc46082..c38372773d0 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/expr.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/expr.rs @@ -70,7 +70,13 @@ fn eval_function_input_assignment_in_store( arena: &mut SLTNodeArena, ) -> Result<((NodeId, HashSet>), BoundaryMap), ParserError> { if target_type.array.is_empty() { - return eval_assignment_expression_in_store(module, store, expr, arena, target_width); + return eval_assignment_expression_in_store( + module, + store, + &crate::float::converted(expr, target_type), + arena, + target_width, + ); } let element_width = target_type.total_width().ok_or_else(|| { @@ -177,7 +183,7 @@ fn eval_array_literal_item_in_store( return finish_assignment_expression(expr, arena, target_width, value); } - let source_type = &expr.comptime().r#type; + let source_type = crate::float::type_of(expr); // A scalar leaf is assigned to one formal element, not concatenated at // its natural width and widened after the aggregate has been assembled. @@ -2704,6 +2710,11 @@ pub(super) fn eval_expression_in_context( arena: &mut SLTNodeArena, context: Option, ) -> Result<((NodeId, HashSet>), BoundaryMap), ParserError> { + let context = if crate::float::precision(crate::float::type_of(expr)).is_some() { + None + } else { + context + }; let context_width = context.map(|context| context.width); // Short-circuit: compile-time constant compound expression → emit Constant node. // The folded value still participates in its enclosing width context. Skipping @@ -2711,7 +2722,10 @@ pub(super) fn eval_expression_in_context( // can also lose carry bits when a folded operand is widened by its parent. if !matches!(expr, Expression::Term(_)) { let ct = expr.comptime(); - if ct.is_const { + if ct.is_const + && !crate::float::needs_numeric_lowering(expr) + && crate::float::type_of(expr).kind == ct.r#type.kind + { if let Some((celox_value, mask_xz, width, signed)) = celox_value_from_comptime_in_context(ct, context_width) { @@ -2731,6 +2745,15 @@ pub(super) fn eval_expression_in_context( Expression::Term(factor) => eval_factor(module, store, factor, arena, context), Expression::Binary(lhs, op, rhs, _) => { if matches!(op, Op::As) { + if let Some(conversion) = crate::float::conversion( + crate::float::type_of(lhs), + crate::float::type_of(expr), + ) { + let ((node, sources), bounds) = + eval_expression_in_context(module, store, lhs, arena, None)?; + let node = arena.alloc(SLTNode::Unary(conversion, node))?; + return Ok(((node, sources), bounds)); + } let Some(cast) = cast_semantics(lhs, rhs) else { return Err(ParserError::internal( "as cast target", @@ -2787,6 +2810,36 @@ pub(super) fn eval_expression_in_context( )); } + if crate::float::precision(crate::float::type_of(lhs)).is_some() + || crate::float::precision(crate::float::type_of(rhs)).is_some() + { + let target = if matches!( + crate::float::precision(crate::float::type_of(lhs)), + Some(celox_design::FloatPrecision::F64) + ) { + crate::float::type_of(lhs) + } else if crate::float::precision(crate::float::type_of(rhs)).is_some() { + crate::float::type_of(rhs) + } else { + crate::float::type_of(lhs) + }; + let precision = crate::float::precision(target).unwrap(); + let left = crate::float::converted(lhs, target); + let right = crate::float::converted(rhs, target); + let ((left, mut sources), lb) = + eval_expression_in_context(module, store, &left, arena, None)?; + let ((right, rs), rb) = + eval_expression_in_context(module, store, &right, arena, None)?; + sources.extend(rs); + let op = crate::float::binary(*op).expect("validated floating-point operator"); + let node = arena.alloc(SLTNode::Binary( + left, + BinaryOp::Float { op, precision }, + right, + ))?; + return Ok(((node, sources), merge_boundaries(lb, rb))); + } + let lhs_width = get_expr_width(lhs) .or_else(|| lhs.comptime().r#type.total_width()) .unwrap_or(1); @@ -2961,6 +3014,22 @@ pub(super) fn eval_expression_in_context( Ok(((result, total_sources), all_bounds)) } Expression::Unary(op, expr, _) => { + if let Some(precision) = crate::float::precision(crate::float::type_of(expr)) { + let ((node, sources), bounds) = + eval_expression_in_context(module, store, expr, arena, None)?; + let node = if *op == Op::Sub { + arena.alloc(SLTNode::Unary( + UnaryOp::Float { + op: celox_design::FloatUnaryOp::Neg, + precision, + }, + node, + ))? + } else { + node + }; + return Ok(((node, sources), bounds)); + } let result_signed = expression_signed(expr); let operand_context = if matches!( op, @@ -3005,6 +3074,11 @@ pub(super) fn eval_expression_in_context( Ok(((result_node, sources), bounds)) } Expression::Ternary(cond, then_expr, else_expr, _) => { + let target_type = crate::float::type_of(expr); + let then_value = crate::float::converted(then_expr, target_type); + let else_value = crate::float::converted(else_expr, target_type); + let then_expr = &then_value; + let else_expr = &else_value; let branch_width = get_expr_width(then_expr) .or_else(|| then_expr.comptime().r#type.total_width()) .unwrap_or(1) @@ -3806,6 +3880,7 @@ pub(super) fn is_signed(module: &Module, expr: NodeId, arena: &SLTNodeArena module.variables[id].r#type.signed, SLTNode::Constant(_, _, _, signed) => *signed, SLTNode::Binary(lhs, op, rhs) => match op { + BinaryOp::Float { .. } => false, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase @@ -3833,6 +3908,9 @@ pub(super) fn is_signed(module: &Module, expr: NodeId, arena: &SLTNodeArena is_signed(module, *lhs, arena) && is_signed(module, *rhs, arena), }, + SLTNode::Unary(UnaryOp::Float { op, .. }, _) => { + matches!(op, celox_design::FloatUnaryOp::ToSigned { .. }) + } SLTNode::Unary( UnaryOp::LogicNot | UnaryOp::And diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/recover_unrolled.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/recover_unrolled.rs index c9a38f2905f..396860d0126 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/recover_unrolled.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/recover_unrolled.rs @@ -3347,6 +3347,7 @@ fn proof_node_signed( Rule::Known(*signed) } SLTNode::Binary(lhs, op, rhs) => match op { + BinaryOp::Float { .. } => Rule::Known(false), BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase @@ -3374,6 +3375,9 @@ fn proof_node_signed( | BinaryOp::Or | BinaryOp::Xor => Rule::Both(*lhs, *rhs), }, + SLTNode::Unary(UnaryOp::Float { op, .. }, _) => { + Rule::Known(matches!(op, celox_design::FloatUnaryOp::ToSigned { .. })) + } SLTNode::Unary( UnaryOp::LogicNot | UnaryOp::And @@ -3516,6 +3520,7 @@ fn specialized_binary_result_signed( rhs: &SpecializedConstant, ) -> bool { match op { + BinaryOp::Float { .. } => false, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase @@ -3547,6 +3552,7 @@ fn specialized_binary_result_signed( fn specialized_unary_result_signed(op: UnaryOp, inner: &SpecializedConstant) -> bool { match op { + UnaryOp::Float { op, .. } => matches!(op, celox_design::FloatUnaryOp::ToSigned { .. }), UnaryOp::Ident | UnaryOp::ToTwoState | UnaryOp::Minus | UnaryOp::BitNot => inner.signed, UnaryOp::LogicNot | UnaryOp::And @@ -3670,6 +3676,12 @@ fn specialize_binary_constant( let comparison_lhs = extend_comparison(lhs)?; let comparison_rhs = extend_comparison(rhs)?; let value = match op { + BinaryOp::Float { op, precision } => BigUint::from(celox_design::eval_float_binary( + op, + precision, + lhs.value.to_u64()?, + rhs.value.to_u64()?, + )), BinaryOp::Add => (&lhs.value + &rhs.value) & &mask, BinaryOp::Sub => { let modulus = BigUint::from(1u8) << result_width; @@ -3825,6 +3837,11 @@ fn specialize_unary_constant( return None; } let value = match op { + UnaryOp::Float { op, precision } => BigUint::from(celox_design::eval_float_unary( + op, + precision, + inner.value.to_u64()?, + )), UnaryOp::Ident | UnaryOp::ToTwoState => inner.value.clone(), UnaryOp::Minus => { let modulus = BigUint::from(1u8) << result_width; diff --git a/crates/celox-frontend-veryl/src/module.rs b/crates/celox-frontend-veryl/src/module.rs index 6d2c45b1e48..947c07fa5a7 100644 --- a/crates/celox-frontend-veryl/src/module.rs +++ b/crates/celox-frontend-veryl/src/module.rs @@ -1095,7 +1095,14 @@ impl<'a> ModuleParser<'a> { let ((node, sources), _bounds) = eval_assignment_expression_effectful( self.module, &mut connection_store, - expression, + &crate::float::converted( + expression, + &child_module + .variables + .get(&child_port_id) + .expect("resolved child input") + .r#type, + ), &mut self.arena, expression_width, )?; @@ -1302,7 +1309,16 @@ impl<'a> ModuleParser<'a> { let geometry = select_geometry(self.module, dst.id, &dst.index, &dst.select)?; let prefix_access = eval_var_select_with_geometry(&dst.index, &dst.select, &geometry)?; - let part_width = geometry.selected_width; + let conversion = if output.dst.len() == 1 && child_elements == 1 { + crate::float::conversion(&child_port.r#type, &dst.comptime.r#type) + } else { + None + }; + let part_width = if conversion.is_some() { + width + } else { + geometry.selected_width + }; // Extract this part from rhs_node let slice_end = current_offset.checked_add(part_width).ok_or_else(|| { @@ -1343,6 +1359,16 @@ impl<'a> ModuleParser<'a> { access: slice_access, })? }; + let rhs_part = if let Some(op) = conversion { + glue_arena.alloc(SLTNode::Unary(op, rhs_part))? + } else { + rhs_part + }; + let preview_rhs_part = if let Some(op) = conversion { + destination_arena.alloc(SLTNode::Unary(op, preview_rhs_part))? + } else { + preview_rhs_part + }; let preview_rhs_sources: HashSet<_> = std::iter::once(VarAtomBase::new( child_port_id, slice_access.lsb, diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 097a8059a4a..b427e7f8268 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -53,6 +53,7 @@ fn compile_assert_arg( width: ec.natural_width(expr), signed: expression_signed(expr), is_string: expr.comptime().r#type.is_string(), + float_precision: crate::float::precision(crate::float::type_of(expr)), } } @@ -66,6 +67,7 @@ fn compile_component_arg( width: assert_arg_width(input), signed: expression_signed(expr), is_string: expr.comptime().r#type.is_string(), + float_precision: crate::float::precision(crate::float::type_of(expr)), } } @@ -112,6 +114,10 @@ fn runtime_event_site_for_assert( .iter() .map(|arg| expression_signed(&arg.0)) .collect(), + arg_float_precision: value_args + .iter() + .map(|arg| crate::float::precision(crate::float::type_of(&arg.0))) + .collect(), arg_is_string: value_args .iter() .map(|arg| arg.0.comptime().r#type.is_string()) @@ -1170,7 +1176,9 @@ impl ExprCompiler<'_> { ) -> ValueContext { // A string's declared width is nominal; its runtime length must never // pass through integer context sizing or assignment truncation. - let context = if expr.comptime().r#type.is_string() { + let context = if expr.comptime().r#type.is_string() + || crate::float::precision(crate::float::type_of(expr)).is_some() + { None } else { context @@ -1185,6 +1193,16 @@ impl ExprCompiler<'_> { self.resize_result(ops, source, context) } Expression::Unary(op, inner, _) => { + if let Some(precision) = crate::float::precision(crate::float::type_of(inner)) { + let operand = self.emit_in_context(inner, ops, None); + if *op == VerylOp::Sub { + ops.push(TbOpcode::FloatUnary { + op: celox_design::FloatUnaryOp::Neg, + precision, + }); + } + return operand; + } let reduction = matches!( op, VerylOp::BitAnd @@ -1233,6 +1251,23 @@ impl ExprCompiler<'_> { } Expression::Binary(lhs, op, rhs, _) => { if matches!(op, VerylOp::As) { + if let Some(celox_design::UnaryOp::Float { op, precision }) = + crate::float::conversion( + crate::float::type_of(lhs), + crate::float::type_of(expr), + ) + { + self.emit_in_context(lhs, ops, None); + ops.push(TbOpcode::FloatUnary { op, precision }); + return self.resize_result( + ops, + ValueContext { + width: self.natural_width(expr), + signed: expression_signed(expr), + }, + context, + ); + } let cast = cast_semantics(lhs, rhs) .expect("analyzed testbench cast must have a concrete target"); let source = self.emit_in_context( @@ -1250,6 +1285,34 @@ impl ExprCompiler<'_> { return self.resize_result(ops, casted, context); } + if crate::float::precision(crate::float::type_of(lhs)).is_some() + || crate::float::precision(crate::float::type_of(rhs)).is_some() + { + let target = if matches!( + crate::float::precision(crate::float::type_of(lhs)), + Some(celox_design::FloatPrecision::F64) + ) { + crate::float::type_of(lhs) + } else if crate::float::precision(crate::float::type_of(rhs)).is_some() { + crate::float::type_of(rhs) + } else { + crate::float::type_of(lhs) + }; + self.emit_in_context(&crate::float::converted(lhs, target), ops, None); + self.emit_in_context(&crate::float::converted(rhs, target), ops, None); + ops.push(TbOpcode::FloatBinary { + op: crate::float::binary(*op).expect("validated float operator"), + precision: crate::float::precision(target).unwrap(), + }); + return self.resize_result( + ops, + ValueContext { + width: self.natural_width(expr), + signed: expression_signed(expr), + }, + context, + ); + } if lhs.comptime().r#type.is_string() && rhs.comptime().r#type.is_string() { self.emit_in_context(lhs, ops, None); self.emit_in_context(rhs, ops, None); @@ -1316,6 +1379,11 @@ impl ExprCompiler<'_> { self.resize_result(ops, result, context) } Expression::Ternary(cond, then_expr, else_expr, _) => { + let target_type = crate::float::type_of(expr); + let then_value = crate::float::converted(then_expr, target_type); + let else_value = crate::float::converted(else_expr, target_type); + let then_expr = &then_value; + let else_expr = &else_value; self.emit_in_context(cond, ops, None); let branch_context = ValueContext { width: self @@ -1534,8 +1602,15 @@ impl ExprCompiler<'_> { for (arg_path, arg_expr) in &fc.inputs { if let Some(&arg_var_id) = func_body.arg_map.get(arg_path) { if let Some(sig) = self.resolve_var(&arg_var_id) { + let converted = func + .args + .iter() + .flat_map(|arg| &arg.members) + .find(|(path, _, _)| path == arg_path) + .map(|(_, ct, _)| crate::float::converted(arg_expr, &ct.r#type)) + .unwrap_or(std::borrow::Cow::Borrowed(arg_expr)); self.emit_in_context( - arg_expr, + &converted, ops, Some(ValueContext { width: sig.width, @@ -1562,7 +1637,7 @@ impl ExprCompiler<'_> { if let Some(first_dst) = a.dst.first() { if let Some(dst_sig) = self.resolve_var(&first_dst.id) { self.emit_in_context( - &a.expr, + &crate::float::converted(&a.expr, &first_dst.comptime.r#type), ops, Some(ValueContext { width: dst_sig.width, @@ -2893,7 +2968,16 @@ impl<'a> SemanticTestbenchBuilder<'a> { let dst_width = dst.width; Some(GenericTestbenchStatement::Assign { dst, - expr: ec.compile_with_width(&a.expr, dst_width), + expr: ec.compile_with_width( + &crate::float::converted( + &a.expr, + a.hier_dst + .as_ref() + .map(|dst| &dst.comptime.r#type) + .unwrap_or_else(|| &a.dst.first().unwrap().comptime.r#type), + ), + dst_width, + ), }) } Statement::Break => Some(GenericTestbenchStatement::Break), @@ -2930,7 +3014,16 @@ impl<'a> SemanticTestbenchBuilder<'a> { selection: None, width: sig.width, }, - expr: ec.compile_with_width(arg_expr, sig.width), + expr: ec.compile_with_width( + &func + .args + .iter() + .flat_map(|arg| &arg.members) + .find(|(path, _, _)| path == arg_path) + .map(|(_, ct, _)| crate::float::converted(arg_expr, &ct.r#type)) + .unwrap_or(std::borrow::Cow::Borrowed(arg_expr)), + sig.width, + ), }); } } diff --git a/crates/celox-frontend-veryl/src/value_type_check.rs b/crates/celox-frontend-veryl/src/value_type_check.rs index a2631eeb7cb..495a0ec728b 100644 --- a/crates/celox-frontend-veryl/src/value_type_check.rs +++ b/crates/celox-frontend-veryl/src/value_type_check.rs @@ -1,11 +1,4 @@ -//! Rejects uses of `string` and floating-point values that Celox cannot -//! represent yet. -//! -//! Runtime strings exist only in the testbench VM: in RTL a non-constant -//! string occupies a one-bit slot. Floating-point values are stored as their -//! IEEE 754 bit patterns, so copies are exact, but every operation on them -//! would run as integer arithmetic. Constant expressions are folded by the -//! analyzer and stay accepted. +//! Validates unsupported string and floating-point contexts. use veryl_analyzer::ir::{ ArrayLiteralItem, AssignDestination, CasePattern, Component, Declaration, Expression, Factor, ForBound, ForRange, FunctionCall, Module, Op, Statement, SystemFunctionCall, @@ -65,6 +58,12 @@ pub(crate) fn check_module(module: &Module) -> Result<(), ParserError> { let port = child.and_then(|child| child.variables.get(&output.id)); for destination in &output.dst { if let Some(port) = port { + if output.dst.len() != 1 + && float_kind(&port.r#type) + != float_kind(&destination.comptime.r#type) + { + return Err(float_operation("floating-point conversion", "concatenated floating-point output conversions are not supported".to_string(), &destination.token)); + } checker.port_output(&port.r#type, destination)?; } } @@ -107,14 +106,13 @@ impl Checker<'_> { } match expression { Expression::Term(factor) => self.factor(factor), - Expression::Unary(_, inner, comptime) => { - if float_kind(&inner.comptime().r#type).is_some() - || float_kind(&comptime.r#type).is_some() + Expression::Unary(op, inner, comptime) => { + if float_kind(crate::float::type_of(inner)).is_some() + && !matches!(op, Op::Add | Op::Sub) { return Err(float_operation( "floating-point operation", - "operations on non-constant f32/f64 values run as integer arithmetic" - .to_string(), + format!("operator `{op}` is not supported on floating-point values"), &comptime.token, )); } @@ -122,43 +120,31 @@ impl Checker<'_> { } Expression::Binary(left, op, right, comptime) => { if *op == Op::As { - let source = float_kind(&left.comptime().r#type); - let target = float_kind(&comptime.r#type); - if source != target { - return Err(float_operation( - "floating-point conversion", - "casts between f32, f64 and integer types do not convert non-constant values" - .to_string(), - &comptime.token, - )); - } + self.conversion(&comptime.r#type, left)?; return self.expression(left); } - if float_kind(&left.comptime().r#type).is_some() - || float_kind(&right.comptime().r#type).is_some() - || float_kind(&comptime.r#type).is_some() + if (float_kind(crate::float::type_of(left)).is_some() + || float_kind(crate::float::type_of(right)).is_some()) + && crate::float::binary(*op).is_none() { return Err(float_operation( "floating-point operation", - format!( - "operator `{op}` on non-constant f32/f64 values runs as integer arithmetic" - ), + format!("operator `{op}` is not supported on floating-point values"), &comptime.token, )); } + if float_kind(crate::float::type_of(left)).is_some() { + self.conversion(crate::float::type_of(left), right)?; + } else if float_kind(crate::float::type_of(right)).is_some() { + self.conversion(crate::float::type_of(right), left)?; + } self.expression(left)?; self.expression(right) } - Expression::Ternary(cond, left, right, comptime) => { + Expression::Ternary(cond, left, right, _) => { self.condition(cond)?; - if float_kind(&left.comptime().r#type) != float_kind(&right.comptime().r#type) { - return Err(float_operation( - "floating-point conversion", - "conditional arms of different f32/f64/integer types are not converted" - .to_string(), - &comptime.token, - )); - } + self.conversion(crate::float::type_of(expression), left)?; + self.conversion(crate::float::type_of(expression), right)?; self.expression(cond)?; self.expression(left)?; self.expression(right) @@ -221,7 +207,7 @@ impl Checker<'_> { /// Rejects a non-constant float where an integral value is required. fn integral(&self, expression: &Expression, role: &str) -> Result<(), ParserError> { let comptime = expression.comptime(); - if !comptime.is_const && float_kind(&comptime.r#type).is_some() { + if !comptime.is_const && float_kind(crate::float::type_of(expression)).is_some() { return Err(float_operation( "floating-point operation", format!("non-constant f32/f64 values cannot be used as a {role}"), @@ -235,33 +221,53 @@ impl Checker<'_> { self.integral(expression, "condition") } - /// Rejects an implicit conversion between float and integer types. - /// Even constant values are stored without conversion. fn conversion(&self, target: &Type, expression: &Expression) -> Result<(), ParserError> { - let comptime = expression.comptime(); - if float_kind(target) != float_kind(&comptime.r#type) { - return Err(float_operation( - "floating-point conversion", - format!( - "assigning a {} value to a {} target is not converted", - comptime.r#type.kind, target.kind - ), - &comptime.token, - )); + let source = crate::float::type_of(expression); + if float_kind(target) != float_kind(source) + && (float_kind(target).is_some() || float_kind(source).is_some()) + { + if !target.array.is_empty() || !source.array.is_empty() { + return Err(float_operation( + "floating-point conversion", + "array floating-point conversions are not supported".to_string(), + &expression.comptime().token, + )); + } + let integer = if float_kind(target).is_none() { + target + } else { + source + }; + if float_kind(integer).is_none() && integer.total_width().unwrap_or(0) > 64 { + return Err(float_operation( + "floating-point conversion", + "integer conversions wider than 64 bits are not supported".to_string(), + &expression.comptime().token, + )); + } } Ok(()) } fn port_output(&self, port: &Type, destination: &AssignDestination) -> Result<(), ParserError> { - if float_kind(port) != float_kind(&destination.comptime.r#type) { - return Err(float_operation( - "floating-point conversion", - format!( - "connecting a {} port to a {} destination is not converted", - port.kind, destination.comptime.r#type.kind - ), - &destination.token, - )); + let target = &destination.comptime.r#type; + if float_kind(port) != float_kind(target) { + let integer = if float_kind(port).is_none() { + port + } else { + target + }; + if !port.array.is_empty() + || !target.array.is_empty() + || (float_kind(integer).is_none() && integer.total_width().unwrap_or(0) > 64) + { + return Err(float_operation( + "floating-point conversion", + "output conversions require scalar float or integer types up to 64 bits" + .to_string(), + &destination.token, + )); + } } Ok(()) } @@ -271,14 +277,6 @@ impl Checker<'_> { args: impl IntoIterator, ) -> Result<(), ParserError> { for arg in args { - let comptime = arg.comptime(); - if float_kind(&comptime.r#type).is_some() { - return Err(float_operation( - "floating-point formatting", - "f32/f64 values cannot be formatted yet".to_string(), - &comptime.token, - )); - } self.expression(arg)?; } Ok(()) @@ -305,6 +303,16 @@ impl Checker<'_> { for (path, destinations) in &call.outputs { for destination in destinations { if let Some(formal) = formal(path) { + if destinations.len() != 1 + && float_kind(formal) != float_kind(&destination.comptime.r#type) + { + return Err(float_operation( + "floating-point conversion", + "concatenated floating-point function outputs are not supported" + .to_string(), + &destination.token, + )); + } self.port_output(formal, destination)?; } } diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index aa4b99a5079..46fb8068877 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -2558,6 +2558,24 @@ impl NativeSimulatorHandle { self.total_size } + /// Evaluate an internal floating-point operation for generated WASM modules. + #[napi] + pub fn evaluate_float(&self, lhs: BigInt, rhs: BigInt, code: BigInt) -> BigInt { + fn bits(value: BigInt) -> u64 { + let word = value.words.first().copied().unwrap_or(0); + if value.sign_bit { + word.wrapping_neg() + } else { + word + } + } + napi_bigint(celox::wasm_codegen::evaluate_float( + bits(lhs), + bits(rhs), + bits(code), + )) + } + /// Returns the WASM module bytes for eval_comb (combinational logic evaluation). #[napi] pub fn comb_wasm_bytes(&self) -> Vec { @@ -3136,7 +3154,6 @@ unsafe impl Send for NapiInjectedHandler {} #[cfg(not(target_arch = "wasm32"))] unsafe impl Sync for NapiInjectedHandler {} -#[cfg(not(target_arch = "wasm32"))] fn napi_bigint(value: u64) -> BigInt { BigInt { sign_bit: false, diff --git a/crates/celox-runtime/src/file_io.rs b/crates/celox-runtime/src/file_io.rs index ef8c307cd70..805e2b4ac66 100644 --- a/crates/celox-runtime/src/file_io.rs +++ b/crates/celox-runtime/src/file_io.rs @@ -331,6 +331,7 @@ mod tests { width: 8, signed: false, is_string: false, + float_precision: None, }; FileIo::write_memory(&path, true, [word()]).unwrap(); assert_eq!(std::fs::read_to_string(&path).unwrap(), "xzxz0101\n"); diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 1ab00ffb273..92a8753bc0e 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -89,6 +89,7 @@ fn bind_assert_arg( width: arg.width, signed: arg.signed, is_string: arg.is_string, + float_precision: arg.float_precision, }) } diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/profitability.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/profitability.rs index 7b5dfb1cb42..26534ab5d6e 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/profitability.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/profitability.rs @@ -202,6 +202,7 @@ pub(super) fn branchified_instruction_cost( .max(register_width(*rhs)), ); match op { + crate::ir::BinaryOp::Float { .. } => 32, crate::ir::BinaryOp::And | crate::ir::BinaryOp::Or | crate::ir::BinaryOp::Xor diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_control_flow_simplify.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_control_flow_simplify.rs index a5b292ecc94..bae65f9a530 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_control_flow_simplify.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_control_flow_simplify.rs @@ -1930,6 +1930,7 @@ fn evaluate_instruction( match instruction { SIRInstruction::Imm(_, value) => LatticeValue::Constant(value.clone()), SIRInstruction::Unary(dst, op, source) => match op { + UnaryOp::Float { .. } => LatticeValue::Overdefined, UnaryOp::Ident => state(*source), UnaryOp::ToTwoState => unary(*source, |value, ty| { let width_mask = width_mask(ty.width()); @@ -2277,6 +2278,70 @@ mod tests { use crate::ir::InstanceId; use celox_design::StateObjectId as VarId; + #[test] + fn float_operations_do_not_inherit_integer_algebraic_identities() { + use celox_design::{FloatBinaryOp as F, FloatPrecision as P}; + let source = RegisterId(0); + let zero = RegisterId(1); + let dst = RegisterId(2); + let mut values = LatticeValues::default(); + values.insert( + source, + LatticeValue::Constant(SIRValue::new((-0.0f64).to_bits())), + ); + values.insert(zero, LatticeValue::Constant(SIRValue::new(0u8))); + let analysis = Analysis { + executable: HashSet::default(), + values, + }; + for four_state in [false, true] { + for (op, rhs, width) in [ + (F::Add, zero, 64), + (F::Sub, source, 64), + (F::Eq, source, 1), + (F::Ne, source, 1), + ] { + let types = [ + ( + source, + RegisterType::Bit { + width: 64, + signed: false, + }, + ), + ( + zero, + RegisterType::Bit { + width: 64, + signed: false, + }, + ), + ( + dst, + RegisterType::Bit { + width, + signed: false, + }, + ), + ] + .into_iter() + .collect(); + let instruction = SIRInstruction::Binary( + dst, + source, + BinaryOp::Float { + op, + precision: P::F64, + }, + rhs, + ); + assert!( + algebraic_replacement(&instruction, &analysis, &types, four_state).is_none() + ); + } + } + } + #[test] fn sccp_tracks_backedge_parameters_without_retaining_local_use_sets() { let entry = BasicBlock { diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_sparse_case_dispatch.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_sparse_case_dispatch.rs index b11692d5eab..1a14312f773 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_sparse_case_dispatch.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_sparse_case_dispatch.rs @@ -1669,6 +1669,7 @@ fn runtime_instruction_cost( SIRInstruction::Binary(dst, lhs, op, rhs) => { let n = chunks(width(*dst).max(width(*lhs)).max(width(*rhs))); match op { + BinaryOp::Float { .. } => 32, BinaryOp::And | BinaryOp::Or | BinaryOp::Xor diff --git a/crates/celox-sir/src/float.rs b/crates/celox-sir/src/float.rs new file mode 100644 index 00000000000..45d7568dec2 --- /dev/null +++ b/crates/celox-sir/src/float.rs @@ -0,0 +1,133 @@ +//! Native helper ABI for floating point register operations. +use crate::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; +/// Private backend call target, outside the user extern function table. +pub const FLOAT_HELPER_ID: u32 = u32::MAX; +pub fn binary_code(op: B, p: P) -> u64 { + let code = match op { + B::Add => 0, + B::Sub => 1, + B::Mul => 2, + B::Div => 3, + B::Rem => 4, + B::Pow => 5, + B::Eq => 6, + B::Ne => 7, + B::Lt => 8, + B::Le => 9, + B::Gt => 10, + B::Ge => 11, + }; + code | if p == P::F64 { 256 } else { 0 } +} +pub fn unary_code(op: U, p: P) -> u64 { + let (code, width, round) = match op { + U::Neg => (32, 0, false), + U::ToBool => (33, 0, false), + U::FromSigned { width } => (34, width, false), + U::FromUnsigned { width } => (35, width, false), + U::ToSigned { width, round } => (36, width, round), + U::ToUnsigned { width, round } => (37, width, round), + U::Convert { to: P::F32 } => (38, 0, false), + U::Convert { to: P::F64 } => (39, 0, false), + }; + code | if p == P::F64 { 256 } else { 0 } | ((width as u64) << 16) | ((round as u64) << 9) +} +pub extern "C" fn evaluate(lhs: u64, rhs: u64, code: u64) -> u64 { + let p = if code & 256 != 0 { P::F64 } else { P::F32 }; + let encoded_width = code >> 16; + if encoded_width > 64 { + return 0; + } + let width = encoded_width as usize; + let round = code & 512 != 0; + let opcode = code & 255; + let conversion = matches!(opcode, 34..=37); + if (conversion && !(1..=64).contains(&width)) + || (!conversion && width != 0) + || (round && !matches!(opcode, 36 | 37)) + || code & 0xfc00 != 0 + { + return 0; + } + let op = match opcode { + 0 => B::Add, + 1 => B::Sub, + 2 => B::Mul, + 3 => B::Div, + 4 => B::Rem, + 5 => B::Pow, + 6 => B::Eq, + 7 => B::Ne, + 8 => B::Lt, + 9 => B::Le, + 10 => B::Gt, + 11 => B::Ge, + n => { + let op = match n { + 32 => U::Neg, + 33 => U::ToBool, + 34 => U::FromSigned { width }, + 35 => U::FromUnsigned { width }, + 36 => U::ToSigned { width, round }, + 37 => U::ToUnsigned { width, round }, + 38 => U::Convert { to: P::F32 }, + 39 => U::Convert { to: P::F64 }, + _ => return 0, + }; + return celox_design::eval_float_unary(op, p, lhs); + } + }; + celox_design::eval_float_binary(op, p, lhs, rhs) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn helper_encoding_preserves_precision_rounding_and_width() { + for p in [P::F32, P::F64] { + let bits = if p == P::F32 { + (-1.5f32).to_bits() as u64 + } else { + (-1.5f64).to_bits() + }; + for width in [8, 32, 64] { + let op = U::ToUnsigned { width, round: true }; + assert_eq!( + evaluate(bits, 0, unary_code(op, p)), + celox_design::eval_float_unary(op, p, bits) + ); + } + } + assert_eq!( + evaluate(1f64.to_bits(), 2f64.to_bits(), binary_code(B::Add, P::F64)), + 3f64.to_bits() + ); + } + #[test] + fn malformed_helper_encodings_return_zero() { + for width in [0, 65, usize::MAX] { + for op in [ + U::FromSigned { width }, + U::FromUnsigned { width }, + U::ToSigned { width, round: true }, + U::ToUnsigned { + width, + round: false, + }, + ] { + assert_eq!(evaluate(u64::MAX, u64::MAX, unary_code(op, P::F64)), 0); + } + } + for code in [ + u64::MAX, + 255, + 0x400, + 32 | (1 << 16), + 32 | 512, + ((1u64 << 32 | 1) << 16) | 34, + ] { + assert_eq!(evaluate(u64::MAX, u64::MAX, code), 0); + } + } +} diff --git a/crates/celox-sir/src/lib.rs b/crates/celox-sir/src/lib.rs index 830830aaedc..c3efdb07d9c 100644 --- a/crates/celox-sir/src/lib.rs +++ b/crates/celox-sir/src/lib.rs @@ -6,13 +6,16 @@ use num_traits::Zero; use serde::{Deserialize, Serialize}; use std::{fmt, fmt::Display}; -pub use celox_design::{BinaryOp, DomainKind, TriggerIdWithKind, UnaryOp}; +pub use celox_design::{ + BinaryOp, DomainKind, FloatBinaryOp, FloatPrecision, FloatUnaryOp, TriggerIdWithKind, UnaryOp, +}; pub mod analysis; pub mod builder; pub mod cfg; pub mod effects; pub mod extern_abi; +pub mod float; mod serde_helpers; pub mod transform; pub mod two_state; diff --git a/crates/celox-sir/src/verify.rs b/crates/celox-sir/src/verify.rs index 9e235776c01..8e2515d2b23 100644 --- a/crates/celox-sir/src/verify.rs +++ b/crates/celox-sir/src/verify.rs @@ -382,6 +382,24 @@ fn verify_instruction_types( } } SIRInstruction::Binary(dst, lhs, op, rhs) => match op { + BinaryOp::Float { op, precision } => { + exact_width(*lhs, precision.width(), "TYPE.FLOAT_OPERAND_WIDTH")?; + exact_width(*rhs, precision.width(), "TYPE.FLOAT_OPERAND_WIDTH")?; + let comparison = matches!( + op, + crate::FloatBinaryOp::Eq + | crate::FloatBinaryOp::Ne + | crate::FloatBinaryOp::Lt + | crate::FloatBinaryOp::Le + | crate::FloatBinaryOp::Gt + | crate::FloatBinaryOp::Ge + ); + exact_width( + *dst, + if comparison { 1 } else { precision.width() }, + "TYPE.FLOAT_RESULT_WIDTH", + )?; + } BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase @@ -422,6 +440,30 @@ fn verify_instruction_types( } }, SIRInstruction::Unary(dst, op, src) => match op { + UnaryOp::Float { + op: float_op, + precision, + } => { + let input_width = match float_op { + crate::FloatUnaryOp::FromSigned { width } + | crate::FloatUnaryOp::FromUnsigned { width } => *width, + _ => precision.width(), + }; + exact_width(*src, input_width, "TYPE.FLOAT_OPERAND_WIDTH")?; + exact_width( + *dst, + op.result_width(input_width), + "TYPE.FLOAT_RESULT_WIDTH", + )?; + if input_width == 0 || input_width > 64 || ty(*dst)?.width() > 64 { + return Err(SirVerifyError::instruction( + "TYPE.FLOAT_CONVERSION_WIDTH", + block, + index, + "floating conversions require integer widths in 1..=64", + )); + } + } UnaryOp::LogicNot | UnaryOp::And | UnaryOp::Or | UnaryOp::Xor => { exact_width(*dst, 1, "TYPE.REDUCTION_RESULT_WIDTH")?; unsigned_if_bit(*dst, "TYPE.BOOLEAN_RESULT_UNSIGNED")?; diff --git a/crates/celox-slt/src/const_inline.rs b/crates/celox-slt/src/const_inline.rs index 46ead00f36e..8ad1eaa3981 100644 --- a/crates/celox-slt/src/const_inline.rs +++ b/crates/celox-slt/src/const_inline.rs @@ -81,6 +81,14 @@ fn eval_const_expr( return (BigUint::from(0u32), width_mask.clone(), width); // unknown } let result = match op { + BinaryOp::Float { op, precision } => { + BigUint::from(celox_design::eval_float_binary( + *op, + *precision, + lv.iter_u64_digits().next().unwrap_or(0), + rv.iter_u64_digits().next().unwrap_or(0), + )) + } BinaryOp::And => &lv & &rv, BinaryOp::Or => &lv | &rv, BinaryOp::Xor => &lv ^ &rv, @@ -110,6 +118,28 @@ fn eval_const_expr( } SLTNode::Unary(op, inner) => { let (v, m, inner_width) = eval_const_expr(*inner, arena); + if let UnaryOp::Float { + op: float_op, + precision, + } = op + { + if matches!( + float_op, + celox_design::FloatUnaryOp::FromSigned { .. } + | celox_design::FloatUnaryOp::FromUnsigned { .. } + ) { + let known = &v & (((BigUint::from(1u8) << inner_width) - 1u8) ^ &m); + return ( + BigUint::from(celox_design::eval_float_unary( + *float_op, + *precision, + known.iter_u64_digits().next().unwrap_or(0), + )), + BigUint::from(0u8), + width, + ); + } + } if matches!(op, UnaryOp::ToTwoState) { return ( v & (&width_mask ^ (&m & &width_mask)), @@ -154,6 +184,11 @@ fn eval_const_expr( return (BigUint::from(0u32), width_mask.clone(), width); } let result = match op { + UnaryOp::Float { op, precision } => BigUint::from(celox_design::eval_float_unary( + *op, + *precision, + v.iter_u64_digits().next().unwrap_or(0), + )), UnaryOp::BitNot => (&width_mask) ^ &v, UnaryOp::PopCount => BigUint::from( v.iter_u64_digits() @@ -518,6 +553,72 @@ mod tests { use super::eval_const_expr; + #[test] + fn floating_operations_fold_ieee_payloads_and_result_widths() { + use celox_design::{BinaryOp, FloatBinaryOp, FloatPrecision, FloatUnaryOp}; + let mut arena = SLTNodeArena::::new(); + let left = arena + .alloc(SLTNode::Constant( + 1.5f32.to_bits().into(), + 0u8.into(), + 32, + false, + )) + .unwrap(); + let right = arena + .alloc(SLTNode::Constant( + 2.0f32.to_bits().into(), + 0u8.into(), + 32, + false, + )) + .unwrap(); + let sum = arena + .alloc(SLTNode::Binary( + left, + BinaryOp::Float { + op: FloatBinaryOp::Add, + precision: FloatPrecision::F32, + }, + right, + )) + .unwrap(); + assert_eq!( + eval_const_expr(sum, &arena), + (BigUint::from(3.5f32.to_bits()), 0u8.into(), 32) + ); + let comparison = arena + .alloc(SLTNode::Binary( + left, + BinaryOp::Float { + op: FloatBinaryOp::Lt, + precision: FloatPrecision::F32, + }, + right, + )) + .unwrap(); + assert_eq!( + eval_const_expr(comparison, &arena), + (1u8.into(), 0u8.into(), 1) + ); + let integer = arena + .alloc(SLTNode::Unary( + UnaryOp::Float { + op: FloatUnaryOp::ToSigned { + width: 8, + round: true, + }, + precision: FloatPrecision::F32, + }, + sum, + )) + .unwrap(); + assert_eq!( + eval_const_expr(integer, &arena), + (4u8.into(), 0u8.into(), 8) + ); + } + #[test] fn evaluates_constant_concat_payload_and_mask_at_declared_widths() { let mut arena = SLTNodeArena::::new(); diff --git a/crates/celox-slt/src/lower.rs b/crates/celox-slt/src/lower.rs index 001fa149fe5..7c367258206 100644 --- a/crates/celox-slt/src/lower.rs +++ b/crates/celox-slt/src/lower.rs @@ -647,14 +647,18 @@ impl SLTToSIRLowerer { l = self.cast_reg_width_ext(builder, l, width, signed); r = self.cast_reg_width_ext(builder, r, width, signed); } - let dest = builder.alloc_logic(width); + let dest = if matches!(op, BinaryOp::Float { .. }) { + builder.alloc_bit(width, false) + } else { + builder.alloc_logic(width) + }; builder.emit(SIRInstruction::Binary(dest, l, *op, r)); dest } SLTNode::Unary(op, inner) => { let i = self.lower_inner(builder, *inner, arena, cache, env, allow_cache); let width = self.get_width(node, arena); - let dest = if matches!(op, UnaryOp::ToTwoState) { + let dest = if matches!(op, UnaryOp::ToTwoState | UnaryOp::Float { .. }) { builder.alloc_bit(width, self.get_bound_signed(node, arena)) } else { builder.alloc_logic(width) @@ -760,6 +764,7 @@ impl SLTToSIRLowerer { SLTNode::Input { signed, .. } => *signed, SLTNode::Constant(_, _, _, signed) => *signed, SLTNode::Binary(lhs, op, rhs) => match op { + BinaryOp::Float { .. } => false, BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase @@ -789,6 +794,9 @@ impl SLTToSIRLowerer { self.get_bound_signed(*lhs, arena) && self.get_bound_signed(*rhs, arena) } }, + SLTNode::Unary(UnaryOp::Float { op, .. }, _) => { + matches!(op, celox_design::FloatUnaryOp::ToSigned { .. }) + } SLTNode::Unary( UnaryOp::LogicNot | UnaryOp::And diff --git a/crates/celox-slt/src/lower/concat.rs b/crates/celox-slt/src/lower/concat.rs index da70da3d444..f178eff165e 100644 --- a/crates/celox-slt/src/lower/concat.rs +++ b/crates/celox-slt/src/lower/concat.rs @@ -95,6 +95,7 @@ impl SLTToSIRLowerer { let lhs = child(*lhs); let rhs = child(*rhs); match op { + BinaryOp::Float { .. } => ZeroControllerFacts::default(), BinaryOp::And | BinaryOp::LogicAnd | BinaryOp::Mul => { Self::zero_from_either(&lhs, &rhs) } @@ -125,6 +126,7 @@ impl SLTToSIRLowerer { } } SLTNode::Unary(op, inner) => match op { + UnaryOp::Float { .. } => ZeroControllerFacts::default(), UnaryOp::Ident | UnaryOp::ToTwoState | UnaryOp::Minus diff --git a/crates/celox-slt/src/lower/cost.rs b/crates/celox-slt/src/lower/cost.rs index 60c5fbb8b74..d3b1cfa608b 100644 --- a/crates/celox-slt/src/lower/cost.rs +++ b/crates/celox-slt/src/lower/cost.rs @@ -185,6 +185,7 @@ impl SLTToSIRLowerer { fn binary_operation_cost(op: BinaryOp, width: usize) -> u128 { let chunks = Self::chunks(width); match op { + BinaryOp::Float { .. } => 12 * chunks, BinaryOp::And | BinaryOp::Or | BinaryOp::Xor diff --git a/crates/celox-slt/src/node.rs b/crates/celox-slt/src/node.rs index 35f57eba031..b55b4bc2a4a 100644 --- a/crates/celox-slt/src/node.rs +++ b/crates/celox-slt/src/node.rs @@ -374,6 +374,7 @@ impl SLTNode { write!(f, "n{}:", lhs.0)?; arena.get(*lhs).fmt_expression(f, arena)?; let op_str = match op { + celox_design::BinaryOp::Float { .. } => "float", celox_design::BinaryOp::Add => "+", celox_design::BinaryOp::Sub => "-", celox_design::BinaryOp::Mul => "*", @@ -405,6 +406,7 @@ impl SLTNode { } SLTNode::Unary(op, inner) => { let op_str = match op { + celox_design::UnaryOp::Float { .. } => "float", celox_design::UnaryOp::Ident => "", celox_design::UnaryOp::ToTwoState => "2state", celox_design::UnaryOp::Minus => "-", diff --git a/crates/celox-slt/src/node_rules.rs b/crates/celox-slt/src/node_rules.rs index 08b0a6834a9..eebb9ffa330 100644 --- a/crates/celox-slt/src/node_rules.rs +++ b/crates/celox-slt/src/node_rules.rs @@ -91,6 +91,21 @@ pub(super) fn binary_width( /// full verifier. pub(super) fn binary_result_width(op: BinaryOp, lhs_width: usize, rhs_width: usize) -> usize { match op { + BinaryOp::Float { op, precision } => { + if matches!( + op, + celox_design::FloatBinaryOp::Eq + | celox_design::FloatBinaryOp::Ne + | celox_design::FloatBinaryOp::Lt + | celox_design::FloatBinaryOp::Le + | celox_design::FloatBinaryOp::Gt + | celox_design::FloatBinaryOp::Ge + ) { + 1 + } else { + precision.width() + } + } BinaryOp::EqWildcard | BinaryOp::NeWildcard | BinaryOp::Eq diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 23794d3418f..71150c14ea3 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1435,6 +1435,7 @@ const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Parameter { + floating: Option, name: String, value: Option, declared_width: Option, @@ -1462,6 +1463,7 @@ impl Parameter { name, value, declared_width, + floating: None, packed_ranges: Vec::new(), members: Vec::new(), declared_signed, @@ -1486,6 +1488,9 @@ impl Parameter { constants: &HashMap, parameter_types: &HashMap, ) -> Option { + if self.floating.is_some() { + return None; + } let mut value = substitute_typed_parameter_literals(self.value()?.clone(), constants, parameter_types); if self.declared_is_2state { @@ -1539,6 +1544,9 @@ impl Parameter { parameter_types: &HashMap, literals: &HashMap, ) -> Option { + if let Some(kind) = self.floating { + return parameters::real_literal(self.value()?, kind, constants, literals); + } #[cfg(test)] parameters::LITERAL_RESOLUTIONS.with(|calls| calls.set(calls.get() + 1)); if self @@ -1924,6 +1932,8 @@ impl Type { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum TypeKind { + Real, + Shortreal, Bit, Logic, Reg, @@ -2343,6 +2353,7 @@ impl ConditionalAssignment { #[derive(Debug, Clone, PartialEq, Eq)] struct Function { + return_real: bool, name: String, params: Vec, /// The function's value as one expression of its arguments, or `None` @@ -2582,6 +2593,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { randomizable: bool, + real: bool, packed: Vec, unpacked: Vec, signed: bool, diff --git a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs index 31bcdfa81da..97333bf8978 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -51,6 +51,7 @@ pub(super) fn selected_unpacked_shape( .get(indices..) .filter(|rest| !rest.is_empty())?; Some(VariableDimensions { + real: false, unpacked: unpacked.to_vec(), ..shape.clone() }) diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index 5d1cd457b68..c2bfcb3f450 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -140,6 +140,7 @@ impl Value { .and_then(|n| usize::try_from(n).ok()) .ok_or_else(|| unsupported("pattern target array size"))?; let shape = VariableDimensions { + real: false, unpacked: rest.to_vec(), ..shape.clone() }; @@ -189,6 +190,7 @@ impl BoundPattern { .map_err(|_| unsupported("assignment pattern target size"))?; shapes = vec![ VariableDimensions { + real: false, unpacked: rest.to_vec(), ..shape.clone() }; @@ -227,6 +229,7 @@ impl BoundPattern { .map_err(|_| unsupported("assignment pattern target size"))?; shapes = vec![ VariableDimensions { + real: false, packed: rest.to_vec(), signed: shape.signed_element_depth == Some(1), signed_element_depth: shape @@ -251,6 +254,7 @@ impl BoundPattern { .ok_or_else(|| unsupported("pattern target width"))?; shapes = vec![ VariableDimensions { + real: false, packed: Vec::new(), signed: false, signed_element_depth: None, diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index 940dd8a3d0c..5158f7e926a 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -26,6 +26,9 @@ pub(super) fn expr_type_from_type( #[derive(Clone, Copy)] pub(super) enum RuntimeCastTarget { + Real { + short: bool, + }, Zero(ExprType), Signing(bool), Integral { @@ -50,6 +53,24 @@ pub(super) fn runtime_cast_target_expr( ) -> Converted { let const_env = &packed_dimensions.const_env; let (target, numeric_size, two_state) = match target { + RuntimeCastTarget::Real { short } => { + let call = |function, value| Expr::Call { + callee: Callee::System(function), + args: vec![Some(value)], + arg_order: Vec::new(), + }; + return Ok(if short { + call( + SystemFunction::Bitstoshortreal, + call(SystemFunction::Shortrealtobits, expr), + ) + } else { + call( + SystemFunction::Bitstoreal, + call(SystemFunction::Realtobits, expr), + ) + }); + } RuntimeCastTarget::Zero(target) => { return Ok(Expr::Resize { expr: Box::new(expr), @@ -107,6 +128,63 @@ pub(super) fn cast_constant_target( target: RuntimeCastTarget, const_env: &HashMap, ) -> Option { + if let RuntimeCastTarget::Real { short } = target { + let kind = if short { + TypeKind::Shortreal + } else { + TypeKind::Real + }; + return expr_to_const( + state, + parameters::real_literal(&operand, kind, const_env, &HashMap::default())?, + ); + } + fn contains_real(expr: &ConstExpr) -> bool { + match expr { + ConstExpr::Literal(text) => { + text.contains(['.', 'e', 'E']) && text.replace('_', "").parse::().is_ok() + } + ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => contains_real(expr), + ConstExpr::Binary { left, right, .. } => contains_real(left) || contains_real(right), + _ => false, + } + } + if contains_real(&operand) { + let Expr::Literal(text) = + parameters::real_literal(&operand, TypeKind::Real, const_env, &HashMap::default())? + else { + return None; + }; + let value = text.parse::().ok()?.round(); + let (width, signed) = match target { + RuntimeCastTarget::Integral { + target, + numeric_size, + .. + } => (target.width, numeric_size || target.signed), + RuntimeCastTarget::Zero(target) => (target.width, target.signed), + RuntimeCastTarget::Signing(_) | RuntimeCastTarget::Real { .. } => return None, + }; + if width == 0 || width > 128 { + return None; + } + let magnitude = (value.abs() % 2.0f64.powi(width as i32)) as u128; + let bits = if value.is_sign_negative() { + 0u128.wrapping_sub(magnitude) + } else { + magnitude + }; + let bits = if width == 128 { + bits + } else { + bits & ((1u128 << width) - 1) + }; + return Some(ConstExpr::Literal(format_typed_parameter_literal( + bits as i128, + width, + signed, + ))); + } let parameter_types = parameter_types_from_const_env(const_env); let operand_type = infer_const_expr_type(&operand, ¶meter_types)?; let literal = if let ConstExpr::Literal(literal) = &operand { @@ -133,6 +211,7 @@ pub(super) fn cast_constant_target( })? }; let (target_type, numeric_size, two_state) = match target { + RuntimeCastTarget::Real { .. } => return None, RuntimeCastTarget::Signing(signed) => ( ExprType { width: literal.width, diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 31c1698cce2..125bcc4a2ca 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -89,16 +89,26 @@ fn bind_in_context( Job::Enter(id) => match &native.expression(id).kind { ExprKind::Group(inner) => jobs.push(Job::Enter(*inner)), ExprKind::Literal(text) - if typecheck::integral_literal_type_metadata(text).is_some() => + if typecheck::integral_literal_type_metadata(text).is_some() + || (text.contains(['.', 'e', 'E']) + && text.replace('_', "").parse::().is_ok()) => { values.push(ConstExpr::Literal(text.clone())) } ExprKind::Name(name) if name.spelling == "$" => { values.push(ConstExpr::Literal("$".into())) } - ExprKind::Name(name) if !name.spelling.starts_with('$') => values.push( - ConstExpr::Ident(instances::normalize_identifier(&name.spelling)), - ), + ExprKind::Name(name) if !name.spelling.starts_with('$') => { + let name = instances::normalize_identifier(&name.spelling); + let literal = dimensions.parameter_values.get(&name).and_then(|value| { + let Expr::Literal(text) = value else { + return None; + }; + (text.contains(['.', 'e', 'E']) && text.parse::().is_ok()) + .then(|| ConstExpr::Literal(text.clone())) + }); + values.push(literal.unwrap_or(ConstExpr::Ident(name))); + } ExprKind::Unary { operator, expression, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index e9ac9ddfb74..4427db6f394 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -132,10 +132,14 @@ pub(super) fn packed_dimensions_from_ports_and_signals( port.name().to_string(), VariableDimensions { randomizable: !port.r#type().is_enum && port.randomizable, + real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), packed: signal_packed_dimension_widths(port.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()), signed: port.r#type().is_signed(), - is_2state: port.r#type().kind() == TypeKind::Bit, + is_2state: matches!( + port.r#type().kind(), + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + ), members: port.r#type().members.clone(), signed_element_depth: port.r#type().signed_element_depth, }, @@ -146,10 +150,14 @@ pub(super) fn packed_dimensions_from_ports_and_signals( signal.name().to_string(), VariableDimensions { randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, + real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()), signed: signal.r#type().is_signed(), - is_2state: signal.r#type().kind() == TypeKind::Bit, + is_2state: matches!( + signal.r#type().kind(), + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + ), members: signal.r#type().members.clone(), signed_element_depth: signal.r#type().signed_element_depth, }, @@ -510,6 +518,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP parameter.name.clone(), VariableDimensions { randomizable: true, + real: false, packed: function_packed_dimension_widths(¶meter.packed_ranges), unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 236a65024ce..d32057707b9 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -358,7 +358,14 @@ fn return_metadata( .and_then(|widths| widths.as_ref()) .and_then(|widths| widths.first().copied()) .or(width), - dimensions: ty.map(|ty| ty.packed_ranges().len() + ty.unpacked_ranges().len()), + dimensions: ty.map(|ty| { + ty.unpacked_ranges().len() + + if matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { + 0 + } else { + ty.packed_ranges().len() + } + }), signed: ty.is_some_and(Type::is_signed), is_2state: ty.is_some_and(|ty| ty.kind() == TypeKind::Bit), } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index a4d3fcbee87..3ba3408febd 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -132,7 +132,7 @@ pub(in crate::ast) fn query_value( Some(count) } else if let Some(shape) = &shape { Some(if function == SystemFunction::Dimensions { - shape.unpacked.len() + shape.packed.len() + shape.unpacked.len() + if shape.real { 0 } else { shape.packed.len() } } else { shape.unpacked.len() }) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 6a78623d400..87a9c131b7b 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -8,7 +8,8 @@ mod lvalues; mod selected; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; pub(super) use direct::{ - arguments, bind_value, call_name as native_name, callable_name, cast_target_native, ungroup, + arguments, bind_value, call_name as native_name, callable_name, cast_target_native, real_value, + remove_real_division_guards, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; fn disagreement() -> AnalyzerError { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index f3c11aabc6c..e4c0f6cd94f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -135,6 +135,14 @@ pub(in crate::ast) fn cast_target_native( dimensions: &PackedDimensions, ) -> Converted { let target = ungroup(target, native); + if let ExprKind::Type(id) = native.expression(target).kind + && let Some(ty) = type_binding::binding::bind_in(id, native, tree, dimensions)? + && matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) + { + return Ok(casts::RuntimeCastTarget::Real { + short: ty.kind() == TypeKind::Shortreal, + }); + } if let ExprKind::Name(name) = &native.expression(target).kind && matches!(name.spelling.as_str(), "signed" | "unsigned") { @@ -299,7 +307,10 @@ pub(in crate::ast) fn bind_value( if let Some(packed) = packed_string_literal(text) { values.push(Expr::Literal(packed)); } else { - if typecheck::integral_literal_type_metadata(text).is_none() { + if typecheck::integral_literal_type_metadata(text).is_none() + && !(text.contains(['.', 'e', 'E']) + && text.replace('_', "").parse::().is_ok()) + { return Err(unsupported("primary literal")); } values.push(Expr::Literal(text.clone())); @@ -665,14 +676,38 @@ pub(in crate::ast) fn bind_value( let start = values.len().checked_sub(count).ok_or_else(disagreement)?; let mut operands = values.split_off(start); let value = match finish { - Finish::Unary(op) => constants::unary_expr_from_text( - &op, - operands.pop().ok_or_else(disagreement)?, - ) - .ok_or_else(|| unsupported(format!("unary operator `{op}`")))?, + Finish::Unary(op) => { + let operand = operands.pop().ok_or_else(disagreement)?; + if real_value(&operand, dimensions) + && !matches!(op.as_str(), "+" | "-" | "!") + { + return Err(unsupported("operator on a real operand")); + } + constants::unary_expr_from_text(&op, operand) + .ok_or_else(|| unsupported(format!("unary operator `{op}`")))? + } Finish::Binary(op) => { let right = operands.pop().ok_or_else(disagreement)?; let left = operands.pop().ok_or_else(disagreement)?; + if (real_value(&left, dimensions) || real_value(&right, dimensions)) + && !matches!( + op.as_str(), + "+" | "-" + | "*" + | "/" + | "**" + | "==" + | "!=" + | "<" + | "<=" + | ">" + | ">=" + | "&&" + | "||" + ) + { + return Err(unsupported("operator on a real operand")); + } let xnor = matches!(op.as_str(), "~^" | "^~"); let value = Expr::Binary { left: Box::new(left), @@ -711,9 +746,12 @@ pub(in crate::ast) fn bind_value( } Finish::Concat => Expr::Concat(operands), Finish::Cast(target) => { - let operand = guard_zero_divisions( - &tree.state, - operands.pop().ok_or_else(disagreement)?, + let operand = remove_real_division_guards( + guard_zero_divisions( + &tree.state, + operands.pop().ok_or_else(disagreement)?, + ), + dimensions, ); if dimensions.constant_indexed_base { let operand = @@ -857,7 +895,10 @@ pub(in crate::ast) fn bind_value( if values.len() != 1 { return Err(disagreement()); } - Ok(guard_zero_divisions(&tree.state, values.pop().unwrap())) + Ok(remove_real_division_guards( + guard_zero_divisions(&tree.state, values.pop().unwrap()), + dimensions, + )) } fn index_value( @@ -867,6 +908,9 @@ fn index_value( dimensions: &PackedDimensions, ) -> Converted { let value = bind_value(id, native, tree, dimensions, None)?; + if real_value(&value, dimensions) { + return Err(unsupported("real-valued select index")); + } let value = expand_expr_calls( value, &dimensions.functions, @@ -878,6 +922,10 @@ fn index_value( && (matches!(folded, ConstExpr::Literal(_)) || eval_ast_const_expr(&tree.state, &folded, &dimensions.const_env).is_some()) { + if matches!(&folded, ConstExpr::Literal(text) if real_value(&Expr::Literal(text.clone()), dimensions)) + { + return Err(unsupported("real-valued select index")); + } return Ok(folded); } (if dimensions.constant_indexed_base { @@ -985,6 +1033,13 @@ fn selected_value( base = *expression; } suffix.reverse(); + if let ExprKind::Name(name) = &native.expression(base).kind + && dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some_and(|ty| ty.real && suffix.len() > ty.unpacked.len()) + { + return Err(unsupported("bit-select or part-select of a real variable")); + } if let ExprKind::Concatenation(_) | ExprKind::Replication { .. } = native.expression(base).kind { let expr = bind_value(base, native, tree, dimensions, None)?; @@ -1095,6 +1150,12 @@ pub(in crate::ast) fn selected_lvalue( return packed_structs::whole_member(&tree.state, parts, qualified, dimensions); } let finish = |name: String, context: &PackedDimensions, strict: bool| -> Converted { + if context + .get(&name) + .is_some_and(|ty| ty.real && suffix.len() > ty.unpacked.len()) + { + return Err(unsupported("bit-select or part-select of a real variable")); + } let mut indices = Vec::new(); let mut range = None; let mut ranged = false; @@ -1251,6 +1312,104 @@ fn packed_string_literal(text: &str) -> Option { )) } +pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> bool { + match expr { + Expr::Ident(name) => { + dimensions.get(name).is_some_and(|ty| ty.real) + || dimensions.parameter_values.get(name).is_some_and(|value| { + matches!(value, Expr::Literal(text) if text.contains(['.', 'e', 'E']) && text.replace('_', "").parse::().is_ok()) + }) + } + Expr::Literal(text) => { + text.contains(['.', 'e', 'E']) && text.replace('_', "").parse::().is_ok() + } + Expr::Call { + callee: + Callee::System( + SystemFunction::Bitstoreal + | SystemFunction::Bitstoshortreal + | SystemFunction::Itor, + ), + .. + } => true, + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => dimensions + .functions + .get(name) + .is_some_and(|function| function.return_real), + Expr::Unary { + op: UnaryOp::Plus | UnaryOp::Minus | UnaryOp::ToTwoState, + expr, + } => real_value(expr, dimensions), + Expr::Binary { + left, + op: BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow, + right, + } => real_value(left, dimensions) || real_value(right, dimensions), + Expr::Mux { + then_expr, + else_expr, + .. + } => real_value(then_expr, dimensions) || real_value(else_expr, dimensions), + _ => false, + } +} + +// Integer zero-divisor guards must not change real arithmetic or its type. +pub(in crate::ast) fn remove_real_division_guards(expr: Expr, dims: &PackedDimensions) -> Expr { + match expr { + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + if matches!(&*then_expr, Expr::Literal(text) if text == crate::DIV_ZERO_UNKNOWN_LITERAL) + && matches!(&*else_expr, Expr::Binary { left, op: BinaryOp::Div, right } if real_value(left, dims) || real_value(right, dims)) + { + return remove_real_division_guards(*else_expr, dims); + } + Expr::Mux { + condition: Box::new(remove_real_division_guards(*condition, dims)), + then_expr: Box::new(remove_real_division_guards(*then_expr, dims)), + else_expr: Box::new(remove_real_division_guards(*else_expr, dims)), + } + } + Expr::Unary { op, expr } => Expr::Unary { + op, + expr: Box::new(remove_real_division_guards(*expr, dims)), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: Box::new(remove_real_division_guards(*left, dims)), + op, + right: Box::new(remove_real_division_guards(*right, dims)), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: Box::new(remove_real_division_guards(*expr, dims)), + width, + signed, + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee, + args: args + .into_iter() + .map(|arg| arg.map(|arg| remove_real_division_guards(arg, dims))) + .collect(), + arg_order, + }, + expr => expr, + } +} + #[cfg(test)] mod string_literal_tests { use super::packed_string_literal; diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index cd1d18e6e19..957e16d9593 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -131,7 +131,13 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } - SystemFunction::Clog2 + SystemFunction::Rtoi + | SystemFunction::Itor + | SystemFunction::Realtobits + | SystemFunction::Bitstoreal + | SystemFunction::Shortrealtobits + | SystemFunction::Bitstoshortreal + | SystemFunction::Clog2 | SystemFunction::Countones | SystemFunction::Onehot | SystemFunction::Onehot0 diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 4605b8b49e5..ba3ca88c3c2 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -99,7 +99,22 @@ pub(super) fn native_functions( item, ) { Ok(subroutine) => { - let body = symbolic::body(&subroutine, &locals); + let has_real = subroutine.return_type.as_ref().is_some_and(|ty| { + matches!( + ty.kind(), + crate::ir::TypeKind::Real | crate::ir::TypeKind::Shortreal + ) + }) || subroutine.params.iter().any(|param| { + matches!( + param.r#type.kind(), + crate::ir::TypeKind::Real | crate::ir::TypeKind::Shortreal + ) + }); + let body = if has_real { + None + } else { + symbolic::body(&subroutine, &locals) + }; if let Some((value, outputs)) = body { function.body = Some(value); function.outputs = outputs; @@ -229,15 +244,23 @@ fn native_signature( None => result.map(|ty| ty.width), }; Ok(Function { + return_real: ty + .as_ref() + .is_some_and(|ty| matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal)), name: instances::normalize_identifier(&native.name.spelling), params, body: None, outputs: Vec::new(), return_width: result.map(|ty| ty.width), return_first_packed_dimension_width: first, - return_dimensions: ty - .as_ref() - .map(|ty| ty.packed_ranges().len() + ty.unpacked_ranges().len()), + return_dimensions: ty.as_ref().map(|ty| { + ty.unpacked_ranges().len() + + if matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { + 0 + } else { + ty.packed_ranges().len() + } + }), return_signed: result.is_some_and(|ty| ty.signed), return_is_2state: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Bit), }) diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index d2ebefd8a09..3fc3547d771 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -1836,7 +1836,7 @@ mod tests { module Top(); if (1) begin : g localparam A=B, B=A; - localparam real R=1.0; + localparam chandle R=null; end endmodule "#, diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index 6933629c7c8..a3ffacb93da 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -18,9 +18,13 @@ pub(super) fn expr_signedness_with_return_types( ) -> Option { match expr { Expr::Ident(name) => identifiers.signedness(name), - Expr::Literal(literal) => { - typecheck::integral_literal_type_metadata(literal).map(|(_, signed)| signed) - } + Expr::Literal(literal) => typecheck::integral_literal_type_metadata(literal) + .map(|(_, signed)| signed) + .or_else(|| { + (literal.contains(['.', 'e', 'E']) + && literal.replace('_', "").parse::().is_ok()) + .then_some(true) + }), Expr::Select { signed, .. } => Some(*signed), Expr::Concat(_) | Expr::RepeatConcat { .. } => Some(false), Expr::Resize { signed, .. } => Some(*signed), diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index 600559d179c..0bc33f33312 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -9,7 +9,7 @@ pub(in crate::ast) fn capture_member_type( mut ty: Type, env: &HashMap, ) -> Option { - if !ty.unpacked_ranges.is_empty() { + if !ty.unpacked_ranges.is_empty() || matches!(ty.kind, TypeKind::Real | TypeKind::Shortreal) { return None; } for range in &mut ty.packed_ranges { diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index f778f37a118..cb08b492dc7 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - name.to_string(), VariableDimensions { randomizable: true, + real: false, packed: function_packed_dimension_widths(&r#type.packed_ranges), unpacked: Vec::new(), signed: r#type.is_signed, diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 8bd0afb46cf..4fac6db5f78 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -229,7 +229,9 @@ impl<'a> ParameterEnvironment<'a> { // rank for following declarations even when an imported alias's // value is deferred; do not publish an inherited numeric value. if let Some(ty) = parameter.resolved_type(&self.types) { - let rank = if parameter.packed_ranges.is_empty() { + let rank = if parameter.floating.is_some() { + 0 + } else if parameter.packed_ranges.is_empty() { usize::from(!parameter.has_declared_type || ty.width > 1) } else { parameter.packed_ranges.len() @@ -381,12 +383,14 @@ pub(super) fn parameters_from_native_with_environment( &proof_context, )? { Some(value) - } else if skipped::needs_selected( - &syntax_tree.state, - ownership::default(native) - .ok_or_else(|| unsupported("native parameter default is missing"))?, - syntax_tree.declarations(), - ) { + } else if native_prefix.floating().is_none() + && skipped::needs_selected( + &syntax_tree.state, + ownership::default(native) + .ok_or_else(|| unsupported("native parameter default is missing"))?, + syntax_tree.declarations(), + ) + { let mut dimensions = PackedDimensions::new( parameter_packed_dimensions_with_imported(parameters, &imported), const_env, @@ -418,14 +422,12 @@ pub(super) fn parameters_from_native_with_environment( Err(_) => None, } } else { - constant_binding::expression( + constant_binding::bind( ownership::default(native).ok_or_else(|| { AnalyzerError::Parse("native parameter default is missing".into()) })?, - syntax_tree.declarations(), syntax_tree, - const_env, - type_aliases, + &proof_context, )? } } else { @@ -480,6 +482,7 @@ pub(super) fn parameters_from_native_with_environment( has_declared_type, is_local, ); + parameter.floating = native_prefix.floating(); parameter.packed_ranges = parameter_ranges.clone(); parameter.members = parameter_members.clone(); parameter.signed_element_depth = parameter_signed_element_depth; @@ -695,7 +698,9 @@ pub(super) fn bind_parameter( if let Some(ty) = parameter.resolved_type(types) { types.insert(parameter.name().to_string(), ty); insert_parameter_type_markers(env, parameter.name(), ty); - let rank = if parameter.packed_ranges.is_empty() { + let rank = if parameter.floating.is_some() { + 0 + } else if parameter.packed_ranges.is_empty() { usize::from(!parameter.has_declared_type || ty.width > 1) } else { parameter.packed_ranges.len() @@ -713,7 +718,9 @@ pub(super) fn bind_parameter( if let Some(ty) = parameter.resolved_type(types) { types.insert(parameter.name().to_string(), ty); insert_parameter_type_markers(env, parameter.name(), ty); - let rank = if parameter.packed_ranges.is_empty() { + let rank = if parameter.floating.is_some() { + 0 + } else if parameter.packed_ranges.is_empty() { usize::from(!parameter.has_declared_type || ty.width > 1) } else { parameter.packed_ranges.len() @@ -1137,6 +1144,15 @@ fn parameter_value_env_filtered( let mut values = HashMap::default(); let mut parameter_types = HashMap::default(); for parameter in parameters { + if let Some(kind) = parameter.floating { + if let Some(value) = parameter + .value() + .and_then(|value| real_literal(value, kind, const_env, &values)) + { + values.insert(parameter.name.clone(), value); + } + continue; + } if parameter.value().is_none() { continue; } @@ -1736,3 +1752,62 @@ thread_local! { #[cfg(test)] mod tests; + +/// Resolve real parameter expressions without passing IEEE payloads through integer arithmetic. +pub(super) fn real_literal( + expr: &ConstExpr, + kind: TypeKind, + constants: &HashMap, + literals: &HashMap, +) -> Option { + fn evaluate( + expr: &ConstExpr, + constants: &HashMap, + literals: &HashMap, + ) -> Option { + match expr { + ConstExpr::Literal(text) => text.replace('_', "").parse::().ok().or_else(|| { + typecheck::parse_integral_literal(text) + .and_then(|_| eval_ast_const_expr(&AnalysisState::default(), expr, constants)) + .map(|value| value as f64) + }), + ConstExpr::Ident(name) => { + if let Some(Expr::Literal(text)) = literals.get(name) { + text.parse::().ok() + } else { + constants.get(name).map(|value| *value as f64) + } + } + ConstExpr::Unary { + op: UnaryOp::Plus, + expr, + } => evaluate(expr, constants, literals), + ConstExpr::Unary { + op: UnaryOp::Minus, + expr, + } => Some(-evaluate(expr, constants, literals)?), + ConstExpr::Binary { left, op, right } => { + let a = evaluate(left, constants, literals)?; + let b = evaluate(right, constants, literals)?; + Some(match op { + BinaryOp::Add => a + b, + BinaryOp::Sub => a - b, + BinaryOp::Mul => a * b, + BinaryOp::Div => a / b, + BinaryOp::Pow => a.powf(b), + _ => return None, + }) + } + _ => None, + } + } + let value = evaluate(expr, constants, literals)?; + let value = if kind == TypeKind::Shortreal { + f64::from(value as f32) + } else { + value + }; + value + .is_finite() + .then(|| Expr::Literal(format!("{value:?}"))) +} diff --git a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs index c73e00cfb0d..c52377b5ca4 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs @@ -50,6 +50,13 @@ impl Prefix<'_> { pub fn has_declared_type(&self) -> bool { !matches!(self.data.kind, DataTypeKind::Implicit) } + pub fn floating(&self) -> Option { + self.alias + .as_ref() + .or(self.primitive.as_ref()) + .map(|ty| ty.kind) + .filter(|kind| matches!(kind, TypeKind::Real | TypeKind::Shortreal)) + } pub fn signed(&self) -> bool { self.primitive .as_ref() diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index a5097bab957..eabfe9df54a 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -280,6 +280,9 @@ pub(in crate::ast) fn validate( casts::RuntimeCastTarget::Integral { target, .. } | casts::RuntimeCastTarget::Zero(target) => Some(target.width), casts::RuntimeCastTarget::Signing(_) => None, + casts::RuntimeCastTarget::Real { short } => { + Some(if short { 32 } else { 64 }) + } }; width.map(|width| { let mut ty = Type::new(TypeKind::Logic); @@ -459,6 +462,7 @@ fn pattern_items( left.min(right), left.max(right), VariableDimensions { + real: false, unpacked: rest.to_vec(), ..shape.clone() }, @@ -479,6 +483,7 @@ fn pattern_items( left.min(right), left.max(right), VariableDimensions { + real: false, packed: rest.to_vec(), ..shape.clone() }, @@ -491,6 +496,7 @@ fn pattern_items( count as i128 - 1, VariableDimensions { randomizable: true, + real: false, packed: Vec::new(), unpacked: Vec::new(), members: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index dc9d441efef..a6fe8ab168f 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -64,6 +64,7 @@ fn pattern_value( if let Some((dimension, rest)) = shape.unpacked.split_first() { let (_, _, count) = dimension_bounds(state, &dimension.left, &dimension.right, dims)?; let element = VariableDimensions { + real: false, unpacked: rest.to_vec(), ..shape.clone() }; diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 4348cc7ed20..4dd43345df1 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -105,6 +105,7 @@ fn select<'a>( if let Some((dim, rest)) = shape.unpacked.split_first() { let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + real: false, unpacked: rest.to_vec(), ..(*shape).clone() })); @@ -204,6 +205,7 @@ fn select<'a>( let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + real: false, packed: rest.to_vec(), unpacked: Vec::new(), signed: shape.signed_element_depth == Some(1), @@ -238,6 +240,7 @@ fn select<'a>( .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + real: false, packed: Vec::new(), unpacked: Vec::new(), signed: false, @@ -378,6 +381,7 @@ pub(in crate::ast) fn bind_native( { let (_, _, count) = dimension_bounds(&tree.state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { + real: false, unpacked: rest.to_vec(), ..(*shape).clone() })); diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index ba171258fd8..d7143eee62b 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -69,10 +69,14 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { randomizable: !r#type.is_enum, + real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), packed: dimensions::signal_packed_dimension_widths(r#type.packed_ranges()), unpacked: unpacked_dimension_widths(r#type.unpacked_ranges()), signed: r#type.is_signed(), - is_2state: r#type.kind() == TypeKind::Bit, + is_2state: matches!( + r#type.kind(), + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + ), members: r#type.members.clone(), signed_element_depth: r#type.signed_element_depth, } diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 09b1184363f..941ef781958 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -1103,6 +1103,13 @@ fn fold_parameter_selection( assignment_width: Option, ) -> Converted { let expression = substitute_indexed_parameter_values(state, expression, dimensions); + if let Expr::Literal(text) = &expression + && text.contains(['.', 'e', 'E']) + && text.parse::().is_ok() + { + return Ok(ConstExpr::Literal(text.clone())); + } + let types = parameter_types_from_const_env(&dimensions.const_env); let integral_types = types .iter() diff --git a/crates/celox-sv-analyzer/src/ast/statements.rs b/crates/celox-sv-analyzer/src/ast/statements.rs index f0ebf76ebdc..9ff4406572a 100644 --- a/crates/celox-sv-analyzer/src/ast/statements.rs +++ b/crates/celox-sv-analyzer/src/ast/statements.rs @@ -135,13 +135,26 @@ pub(super) fn assignment_op_expr( "^" => BinaryOp::BitXor, _ => return Err(operator()), }; - Ok(guard_zero_divisions( - state, - Expr::Binary { - left: Box::new(expr_from_lvalue(state, lhs, packed_dimensions)), + let left = expr_from_lvalue(state, lhs, packed_dimensions); + if (expression_binding::real_value(&left, packed_dimensions) + || expression_binding::real_value(&rhs, packed_dimensions)) + && !matches!( op, - right: Box::new(rhs), - }, + BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div + ) + { + return Err(unsupported("assignment operator on a real operand")); + } + Ok(expression_binding::remove_real_division_guards( + guard_zero_divisions( + state, + Expr::Binary { + left: Box::new(left), + op, + right: Box::new(rhs), + }, + ), + packed_dimensions, )) } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 7d58a46ff99..e61f1390b46 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -229,6 +229,8 @@ pub(super) fn alias_base_type( /// Builtin integral identity/width without syntax or aggregate layout. pub(super) fn builtin_type(name: &str, signing: Option) -> Option { let (kind, width, signed) = match name { + "real" | "realtime" => (TypeKind::Real, Some(64), true), + "shortreal" => (TypeKind::Shortreal, Some(32), true), "bit" => (TypeKind::Bit, None, false), "logic" => (TypeKind::Logic, None, false), "reg" => (TypeKind::Reg, None, false), diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index fcc19b24952..900c9261652 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -650,6 +650,8 @@ impl Type { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TypeKind { + Real, + Shortreal, Bit, Logic, Reg, @@ -711,6 +713,8 @@ fn convert_type( impl From for TypeKind { fn from(kind: ast::TypeKind) -> Self { match kind { + ast::TypeKind::Real => TypeKind::Real, + ast::TypeKind::Shortreal => TypeKind::Shortreal, ast::TypeKind::Bit => TypeKind::Bit, ast::TypeKind::Logic => TypeKind::Logic, ast::TypeKind::Reg => TypeKind::Reg, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 684f08aad24..83956d1a7d0 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -18,6 +18,12 @@ use crate::AnalyzerError; /// A system function the frontend supports. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum SystemFunction { + Rtoi, + Itor, + Realtobits, + Bitstoreal, + Shortrealtobits, + Bitstoshortreal, /// `$time` (20.3.1). Time, /// `$stime` (20.3.2). @@ -91,6 +97,12 @@ impl SystemFunction { /// The built-in name (`$` functions or `std::randomize`). pub const fn name(self) -> &'static str { match self { + Self::Rtoi => "$rtoi", + Self::Itor => "$itor", + Self::Realtobits => "$realtobits", + Self::Bitstoreal => "$bitstoreal", + Self::Shortrealtobits => "$shortrealtobits", + Self::Bitstoshortreal => "$bitstoshortreal", Self::Time => "$time", Self::Stime => "$stime", Self::Timeunit => "$timeunit", @@ -193,6 +205,9 @@ impl SystemFunction { Some((32, true)) } Self::Urandom | Self::UrandomRange | Self::Stime | Self::Fopen => Some((32, false)), + Self::Rtoi => Some((32, true)), + Self::Itor | Self::Bitstoreal | Self::Realtobits => Some((64, false)), + Self::Shortrealtobits | Self::Bitstoshortreal => Some((32, false)), Self::Time => Some((64, false)), Self::Signed | Self::Unsigned @@ -550,12 +565,12 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ function(SystemFunction::Timeunit, 0, Some(1)), function(SystemFunction::Timeprecision, 0, Some(1)), // 20.5 Conversion functions - unsupported("$rtoi", Function), - unsupported("$itor", Function), - unsupported("$realtobits", Function), - unsupported("$bitstoreal", Function), - unsupported("$shortrealtobits", Function), - unsupported("$bitstoshortreal", Function), + function(SystemFunction::Rtoi, 1, Some(1)), + function(SystemFunction::Itor, 1, Some(1)), + function(SystemFunction::Realtobits, 1, Some(1)), + function(SystemFunction::Bitstoreal, 1, Some(1)), + function(SystemFunction::Shortrealtobits, 1, Some(1)), + function(SystemFunction::Bitstoshortreal, 1, Some(1)), // 11.7 Signed expressions function(SystemFunction::Signed, 1, Some(1)), function(SystemFunction::Unsigned, 1, Some(1)), diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index f32421c9afb..89f8ff9b98c 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6313,3 +6313,211 @@ fn scope_randomize_respects_port_variable_kinds() { ); } } + +#[test] +fn analyzes_real_storage_literals_and_runtime_conversions() { + let ir = analyze_source( + r#"module Top(input logic [63:0] bits, output logic [63:0] result); + real value; + shortreal narrow_value; + realtime alias_value; + always_comb begin + value = $bitstoreal(bits) + 1.5; + narrow_value = shortreal'(value); + alias_value = real'(narrow_value); + result = $realtobits(alias_value); + end + endmodule"#, + Path::new("real.sv"), + ) + .expect("real runtime expressions should analyze"); + let module = &ir.modules()[0]; + assert_eq!(module.signals()[0].r#type().kind(), ir::TypeKind::Real); + assert_eq!(module.signals()[1].r#type().kind(), ir::TypeKind::Shortreal); + assert_eq!(module.signals()[2].r#type().kind(), ir::TypeKind::Real); +} + +#[test] +fn rejects_integral_operators_and_packed_selects_on_real_values() { + for statement in [ + "assign y = x & 1;", + "assign y = ~x;", + "assign y = x[0];", + "initial x[0] = 1;", + ] { + let source = format!("module Top(output logic y); real x; {statement} endmodule"); + assert!( + analyze_source(&source, Path::new("real_invalid.sv")).is_err(), + "{statement}" + ); + } +} + +#[test] +fn analyzes_real_parameter_arithmetic() { + analyze_source( + r#"module Top(output logic [63:0] bits); + localparam real A = 1.5; + localparam real B = A * 2.0; + assign bits = $realtobits(B); + endmodule"#, + Path::new("real_parameter.sv"), + ) + .expect("real parameter arithmetic"); +} + +#[test] +fn analyzes_sized_cast_of_negated_real_local() { + analyze_source( + r#"module Top(input logic signed [31:0] a, output logic signed [31:0] result); + always_comb begin + real value; + value = a; + result = $signed(32'(-value)); + end + endmodule"#, + Path::new("real_local_cast.sv"), + ) + .expect("real local signedness remains available in sized casts"); +} + +#[test] +fn analyzes_real_type_casts_in_separate_always_comb_bodies() { + analyze_source( + r#"module Top ( + input var int a , + input var int b , + output var int sum , + output var int diff , + output var int product , + output var int quotient, + output var int negative, + output var logic lt , + output var logic eq +); + real x ; + real y ; + always_comb x = real'(a); + always_comb y = real'(b); + always_comb sum = int'((x + y)); + always_comb diff = int'((x - y)); + always_comb product = int'((x * y)); + always_comb quotient = int'((x / y)); + always_comb negative = int'((-x)); + always_comb lt = x < y; + always_comb eq = x == y; +endmodule +//# sourceMappingURL=float.sv.map +"#, + Path::new("real_emitted.sv"), + ) + .expect("real casts in module variables"); +} + +#[test] +fn real_storage_widths_do_not_create_packed_dimensions() { + let ir = analyze_source( + r#"module Top; + real value; + shortreal narrow; + real array_value [0:2]; + function automatic real real_result(); return 1.0; endfunction + localparam real REAL_PARAMETER = 1.5; + localparam DTYPE = $dimensions(real); + localparam DSHORT = $dimensions(shortreal); + localparam DVALUE = $dimensions(value); + localparam DNARROW = $dimensions(narrow); + localparam DARRAY = $dimensions(array_value); + localparam DPARAM = $dimensions(REAL_PARAMETER); + localparam DFUNC = $dimensions(real_result()); + localparam BREAL = $bits(real); + localparam BSHORT = $bits(shortreal); + endmodule"#, + Path::new("real_dimensions.sv"), + ) + .expect("real query metadata"); + for (name, expected) in [ + ("DTYPE", 0), + ("DSHORT", 0), + ("DVALUE", 0), + ("DNARROW", 0), + ("DARRAY", 1), + ("DPARAM", 0), + ("DFUNC", 0), + ("BREAL", 64), + ("BSHORT", 32), + ] { + let parameter = ir.modules()[0] + .parameters() + .iter() + .find(|p| p.name() == name) + .unwrap(); + assert_eq!(parameter.resolved_value(), Some(expected), "{name}"); + } +} + +#[test] +fn real_constant_casts_preserve_precision_and_integral_rounding() { + let ir = analyze_source( + r#"module Top; + localparam shortreal F = shortreal'(-2.25); + localparam int N = int'(F); + localparam int A = N + 5; + localparam int POS_HALF = int'(shortreal'(1.5)); + localparam int NEG_HALF = int'(real'(-1.5)); + localparam int NARROW_ROUND = int'(shortreal'(16777217.0)); + localparam int UNSIGNED_BITS = 8'(real'(-1.5)); + endmodule"#, + Path::new("real_constant_casts.sv"), + ) + .expect("real constant casts"); + for (name, expected) in [ + ("N", -2), + ("A", 3), + ("POS_HALF", 2), + ("NEG_HALF", -2), + ("NARROW_ROUND", 16777216), + ("UNSIGNED_BITS", -2), + ] { + let parameter = ir.modules()[0] + .parameters() + .iter() + .find(|p| p.name() == name) + .unwrap(); + assert_eq!(parameter.resolved_value(), Some(expected), "{name}"); + } +} + +#[test] +fn rejects_real_valued_select_indices() { + for (declaration, index) in [ + ("real a = 0.5;", "a"), + ("shortreal a = 0.5;", "a"), + ("real a = 0.5;", "a + 1"), + ("", "0.5"), + ("localparam real a = 0.5;", "a"), + ("localparam shortreal a = 0.5;", "a"), + ("localparam real a = 0.5 + 1.0;", "a"), + ("localparam real a = 0.5;", "a + 1"), + ("function real a(); return 0.5; endfunction", "a()"), + ] { + let source = format!( + "module top(input wire [3:0] b, output wire c); {declaration} assign c = b[{index}]; endmodule" + ); + let error = analyze_source(&source, Path::new("real_index.sv")).unwrap_err(); + assert!( + error.to_string().contains("real-valued select index"), + "{declaration} {index}: {error}" + ); + } +} + +#[test] +fn accepts_integral_select_indices_including_real_conversion() { + for index in ["a", "a + 1", "int'(r)", "$rtoi(r)"] { + let source = format!( + "module top(input wire [3:0] b, input int a, input real r, output wire c); assign c = b[{index}]; endmodule" + ); + analyze_source(&source, Path::new("integer_index.sv")).expect(index); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index baf27d6f58d..8e5b3ae4da7 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -474,3 +474,72 @@ Icarus 13.0 reports `Module instantiations are not allowed in interfaces` for interface. Verilator 5.052 executes the same emitted Veryl design successfully. The [retained diagnostic](verification/repros/interface_nested_icarus.json) records this compile limitation. + +## Veryl analyzer floating-point constant expressions + +Veryl analyzer 0.22 can fold negative `f32` casts and dependent floating-point +constants or parameters incorrectly before Celox lowering. The Veryl consumers +of `floating_point::integral_constants_from_float` are ignored with their +assertions preserved; the emitted SystemVerilog consumer, Icarus, and Verilator +pass. Celox's display tests retain additional ignored reproductions for inline +negative constants, named constants, and hierarchical parameter overrides. +Runtime floating-point display and assertion tests remain enabled. + +These upstream errors are deferred under +[#1657](https://github.com/celox-sim/celox/issues/1657). The analyzer's default +constant folding remains enabled: globally disabling it also breaks integer +constant selects used in generate conditions, including existing linear SEC +and LFSR regressions. + +## Veryl reference simulator floating-point values + +The Celox backend harness excludes Veryl 0.22.0's in-process reference simulator +for six `floating_point` cases while preserving their assertions. A focused +run on 2026-10-21 observed these mismatches: + +| Case | Expected | Veryl reference result | +| --- | --- | --- | +| `arithmetic_and_rounding` | integer conversion of 7.0 / 2.0 = 4 | 3 | +| `f32_precision_and_conversion` | numeric integer result | IEEE f32 payload `0x40800000` | +| `scalar_port_and_function_conversions` | implicit port conversion of 3.5 = 4 | 3 | +| `sequential_float` | clocked integer conversion of 1.5 = 2 | 0 | +| `unknown_integer_conversion` | unknown integer bits become zero, giving `0xa0` | unknown bits retained (`0xax`) | +| `formatted_display_and_write` | numeric `%0.2f` output bytes | literal `%0.2f` text; in-process adapter has no output capture API | + +These exclusions concern the in-process Veryl simulator only. The Verilator and +Icarus adapters have their own case-specific verification and tool limitations. + +### External floating-point observations + +Focused runs on 2026-10-21 with Verilator 5.052 and Icarus 13.0 observed: + +- Both tools return `16777217` where FP32 storage must round to `16777216` + in Veryl `floating_point::f32_precision_and_conversion` and SV + `floating_point::shortreal_storage_precision`. The FP64 comparisons pass. +- Verilator rejects the real-output-to-integer-port connection in Veryl + `floating_point::scalar_port_and_function_conversions` and SV + `floating_point::real_ports_and_subroutines`. Icarus passes these cases. +- Verilator reports the Veryl `unknown_integer_conversion` case unsupported + because its adapter does not execute four-state expectations; Icarus passes. + +The assertions remain enabled and the external runners continue reporting these +failures/unsupported cases; no retained JSON baseline or exclusion manifest was +changed. Other FP64 arithmetic, rounding, bit conversion, comparison and +sequential cases passed both external tools in these focused runs. + +The additional SV conversion-function and zero-divisor cases pass Icarus. +Verilator 5.052 instead interprets unsigned `32'hffffffff` passed to `$itor` +as positive `4294967295.0` rather than the signed 32-bit integer `-1.0`, and +returns false for the self-inequality check on `0.0 / 0.0`. Its positive and +negative infinity checks pass. These differences remain visible in the +external results for `real_conversion_functions` and `real_zero_divisor`. + +The SV `real_display_formats`, `real_display_negative_zero`, and +`real_file_display_formats` cases pass Icarus 13.0, including real/shortreal +arguments, numeric integer conversion, expressions, field width, precision, +scientific/general output, negative zero, and file display/write formatting. +Verilator 5.052 rejects the `+` formatting flag in `real_display_formats` as +an unknown display format code. It prints a lowercase `e` for the uppercase +`%E` conversion in `real_display_negative_zero`; the negative-zero value is +otherwise correct. Its `real_file_display_formats` case passes. The shared +assertions remain enabled, and these external differences are not exclusions. diff --git a/crates/celox-test-suite/src/sv/cases/floating_point.vtest b/crates/celox-test-suite/src/sv/cases/floating_point.vtest new file mode 100644 index 00000000000..885e6152027 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/floating_point.vtest @@ -0,0 +1,265 @@ +(group floating_point (category operators)) + +(case real_arithmetic_and_rounding + (source "float.sv" #" +module Top(input logic signed [31:0] a, b, + output logic signed [31:0] sum, difference, product, quotient, negative, + output logic lt, eq); + real x, y; + assign x = a; + assign y = b; + assign sum = x + y; + assign difference = x - y; + assign product = x * y; + assign quotient = x / y; + assign negative = -x; + assign lt = x < y; + assign eq = x == y; +endmodule +"#) + (top Top) + (modify (set a 7) (set b 2)) + (assert_eq sum 9) (assert_eq difference 5) (assert_eq product 14) + (assert_eq quotient 4) (assert_eq negative 0xfffffff9) + (assert_eq lt 0) (assert_eq eq 0) + (modify (set a 0xfffffff9) (set b 2)) + (assert_eq sum 0xfffffffb) (assert_eq difference 0xfffffff7) + (assert_eq product 0xfffffff2) (assert_eq quotient 0xfffffffc) + (assert_eq negative 7) (assert_eq lt 1) + (modify (set a 2) (set b 2)) (assert_eq eq 1)) + +(case real_bits_and_comparisons + (source "float.sv" #" +module Top(input logic [63:0] a, b, output logic [63:0] sum, negated, + output logic eq, ne, lt, le, gt, ge); + real x, y; + assign x = $bitstoreal(a); + assign y = $bitstoreal(b); + assign sum = $realtobits(x + y); + assign negated = $realtobits(-x); + assign eq = x == y; + assign ne = x != y; + assign lt = x < y; + assign le = x <= y; + assign gt = x > y; + assign ge = x >= y; +endmodule +"#) + (top Top) + ; 1.5 + 2.25 = 3.75 + (modify (set a 0x3ff8000000000000) (set b 0x4002000000000000)) + (assert_eq sum 0x400e000000000000) (assert_eq negated 0xbff8000000000000) + (assert_eq eq 0) (assert_eq ne 1) (assert_eq lt 1) (assert_eq le 1) + (assert_eq gt 0) (assert_eq ge 0) + ; Both signs of zero compare equal. + (modify (set a 0x8000000000000000) (set b 0)) + (assert_eq negated 0) (assert_eq eq 1) (assert_eq ne 0) + (assert_eq lt 0) (assert_eq le 1) (assert_eq gt 0) (assert_eq ge 1) + ; Unordered comparisons with a quiet NaN. + (modify (set a 0x7ff8000000000001) (set b 0x3ff0000000000000)) + (assert_eq eq 0) (assert_eq ne 1) (assert_eq lt 0) + (assert_eq le 0) (assert_eq gt 0) (assert_eq ge 0)) + +(case shortreal_storage_precision + (source "float.sv" #" +module Top(input logic [31:0] a, output logic [31:0] narrow, wide); + shortreal x; + real y; + assign x = a; + assign y = a; + shortreal rounded; + assign rounded = x + 1.0; + assign narrow = rounded; + assign wide = y + 1.0; +endmodule +"#) + (top Top) + (modify (set a 16777216)) + (assert_eq narrow 16777216) (assert_eq wide 16777217) + (modify (set a 7)) (assert_eq narrow 8) (assert_eq wide 8)) + +(case sequential_real + (source "float.sv" #" +module Top(input logic clk, input logic signed [31:0] a, + output logic signed [31:0] result, output logic less); + realtime q; + always @(posedge clk) begin + q <= real'(a) / 2.0; + less <= real'(a) < 0.5; + end + assign result = q; +endmodule +"#) + (top Top) + (modify (set a 3)) (tick clk) + (assert_eq result 2) (assert_eq less 0) + (modify (set a 0xfffffffd)) (tick clk) + (assert_eq result 0xfffffffe) (assert_eq less 1)) + +(case real_truth_and_unknown_integer_conversion + (source "float.sv" #" +module Top(input logic [63:0] bits, output logic truth, logical_not, logical_and, + output logic signed [31:0] converted); + real x, from_unknown; + assign x = $bitstoreal(bits); + assign from_unknown = 4'b1xz1; + assign converted = from_unknown; + assign logical_not = !x; + assign logical_and = x && 1; + always_comb begin + if (x) truth = 1; else truth = 0; + end +endmodule +"#) + (top Top) + (modify (set bits 0x8000000000000000)) + (assert_eq truth 0) (assert_eq logical_not 1) (assert_eq logical_and 0) + (assert_eq converted 9) + (modify (set bits 0x3ff0000000000000)) + (assert_eq truth 1) (assert_eq logical_not 0) (assert_eq logical_and 1)) + +(case real_parameter_and_default_storage + (source "float.sv" #" +module Top(output logic [63:0] parameter_bits, default_bits); + localparam real A = 1.5; + localparam real B = A * 2.0; + real initial_zero; + assign parameter_bits = $realtobits(B); + assign default_bits = $realtobits(initial_zero); +endmodule +"#) + (top Top) + (assert_eq parameter_bits 0x4008000000000000) + (assert_eq default_bits 0)) + +(case real_narrow_integer_conversion + (source "float.sv" #" +module Top(input logic [63:0] bits, output logic [2:0] tiny, + output logic [7:0] byte_value, output logic [31:0] unsigned_value); + real x; + assign x = $bitstoreal(bits); + assign tiny = x; + assign byte_value = x; + assign unsigned_value = x; +endmodule +"#) + (top Top) + ; -1.5 rounds away from zero to -2, then destination width keeps low bits. + (modify (set bits 0xbff8000000000000)) + (assert_eq tiny 6) (assert_eq byte_value 254) (assert_eq unsigned_value 0xfffffffe) + ; Positive values also round before their low bits are selected. + (modify (set bits 0x407015999999999a)) + (assert_eq tiny 1) (assert_eq byte_value 1) (assert_eq unsigned_value 257)) + +(case real_ports_and_subroutines + (source "float.sv" #" +module Child(input real a, output real b); + function automatic real half(input real value); + return value / 2.0; + endfunction + assign b = half(a); +endmodule +module Top(input logic signed [31:0] a, output logic signed [31:0] result, + output logic signed [31:0] task_result); + Child child(.a(a), .b(result)); + real task_value; + task automatic calculate(input real x, output real y); + y = x / 2.0; + endtask + always_comb calculate(a, task_value); + assign task_result = task_value; +endmodule +"#) + (top Top) + (modify (set a 7)) (assert_eq result 4) (assert_eq task_result 4) + (modify (set a 0xfffffff9)) (assert_eq result 0xfffffffc) (assert_eq task_result 0xfffffffc)) + +(case real_conversion_functions + (source "float.sv" #" +module Top(input logic [63:0] bits, input logic [31:0] integer_bits, short_bits, + output logic signed [31:0] truncated, rounded, + output logic [63:0] integer_real_bits, + output logic [31:0] short_roundtrip); + real x; + shortreal sx; + assign x = $bitstoreal(bits); + assign sx = $bitstoshortreal(short_bits); + assign truncated = $rtoi(x); + assign rounded = int'(x); + assign integer_real_bits = $realtobits($itor(integer_bits)); + assign short_roundtrip = $shortrealtobits(sx); +endmodule +"#) + (top Top) + (modify (set bits 0x3ff8000000000000) (set integer_bits 0xffffffff) (set short_bits 0x3fc00000)) + (assert_eq truncated 1) (assert_eq rounded 2) + (assert_eq integer_real_bits 0xbff0000000000000) (assert_eq short_roundtrip 0x3fc00000) + (modify (set bits 0xbff8000000000000) (set integer_bits 0x80000000) (set short_bits 0x80000000)) + (assert_eq truncated 0xffffffff) (assert_eq rounded 0xfffffffe) + (assert_eq integer_real_bits 0xc1e0000000000000) (assert_eq short_roundtrip 0x80000000)) + +(case real_zero_divisor + (source "float.sv" #" +module Top(input logic [63:0] a, b, output logic [63:0] quotient_bits, + output logic unordered); + real x, y, quotient; + assign x = $bitstoreal(a); + assign y = $bitstoreal(b); + assign quotient = x / y; + assign quotient_bits = $realtobits(quotient); + assign unordered = quotient != quotient; +endmodule +"#) + (top Top) + (modify (set a 0x3ff0000000000000) (set b 0)) + (assert_eq quotient_bits 0x7ff0000000000000) (assert_eq unordered 0) + (modify (set a 0xbff0000000000000)) + (assert_eq quotient_bits 0xfff0000000000000) (assert_eq unordered 0) + (modify (set a 0)) (assert_eq unordered 1)) + +(case real_display_formats + (source "float_display.sv" #" +module Top(input logic clk, input logic [63:0] bits); + real x; + shortreal sx; + function automatic real twice(input real a); return a * 2.0; endfunction + assign x = $bitstoreal(bits); + assign sx = shortreal'(x); + always @(posedge clk) begin + $display("f=[%8.2f] e=[%.3e] g=[%.3g] short=[%.1f] expr=[%.1f] signed=[%.1f] unsigned=[%.1f]", x, x, x, sx, twice(x), -32'sd2, 32'hffffffff); + $write("flags=[%+.1f][%010.2f] ", x, x); + $display(x); + end +endmodule +"#) + (top Top) + (modify (set bits 0x3ff8000000000000)) + (tick clk) + (expect_output "f=[ 1.50] e=[1.500e+00] g=[1.5] short=[1.5] expr=[3.0] signed=[-2.0] unsigned=[4294967295.0]\nflags=[+1.5][0000001.50] 1.50000\n")) + +(case real_display_negative_zero + (source "float_display.sv" #" +module Top(input logic clk, input logic [63:0] bits); + realtime x; + assign x = $bitstoreal(bits); + always @(posedge clk) $display("zero=[%.2f] scientific=[%.1E]", x, x); +endmodule +"#) + (top Top) + (modify (set bits 0x8000000000000000)) (tick clk) + (expect_output "zero=[-0.00] scientific=[-0.0E+00]\n")) + +(case real_file_display_formats + (source "float_file_display.sv" #" +module Top(output bit done); + real x; + initial begin + x = 1.5; + $fdisplay(1, "file=[%8.2f] expr=[%.1f]", x, x * 2.0); + $fwrite(32'h80000001, "write=[%.1e]\n", x); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "file=[ 1.50] expr=[3.0]\nwrite=[1.5e+00]\n")) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index fb9e4950d4a..411026486ca 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -11,6 +11,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/aggregate_regressions.vtest", text: include_str!("aggregate_regressions.vtest"), }, + Group { + file: "src/sv/cases/floating_point.vtest", + text: include_str!("floating_point.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/src/veryl/cases/floating_point.vtest b/crates/celox-test-suite/src/veryl/cases/floating_point.vtest new file mode 100644 index 00000000000..6968a5c841f --- /dev/null +++ b/crates/celox-test-suite/src/veryl/cases/floating_point.vtest @@ -0,0 +1,134 @@ +(group floating_point (category operators)) + +(case arithmetic_and_rounding + (source "float.veryl" #" +module Top(a: input i32, b: input i32, sum: output i32, diff: output i32, + product: output i32, quotient: output i32, negative: output i32, + lt: output logic, eq: output logic) { + var x: f64; var y: f64; + assign x = a as f64; + assign y = b as f64; + assign sum = (x + y) as i32; + assign diff = (x - y) as i32; + assign product = (x * y) as i32; + assign quotient = (x / y) as i32; + assign negative = (-x) as i32; + assign lt = x <: y; + assign eq = x == y; +} +"#) + (top Top) + (modify (set a 7) (set b 2)) + (assert_eq sum 9) (assert_eq diff 5) (assert_eq product 14) + (assert_eq quotient 4) (assert_eq negative 0xfffffff9) + (assert_eq lt 0) (assert_eq eq 0) + (modify (set a 0xfffffff9) (set b 2)) + (assert_eq sum 0xfffffffb) (assert_eq diff 0xfffffff7) + (assert_eq product 0xfffffff2) (assert_eq quotient 0xfffffffc) + (assert_eq negative 7) (assert_eq lt 1) + (modify (set a 2) (set b 2)) + (assert_eq eq 1)) + +(case f32_precision_and_conversion + (source "float.veryl" #" +module Top(a: input u32, narrow: output u32, wide: output u32, promoted: output u32) { + var x: f32; var y: f64; + assign x = a as f32; + assign y = a as f64; + assign narrow = (x + (1 as f32)) as u32; + assign wide = (y + 1.0) as u32; + assign promoted = ((x as f64) + 1.0) as u32; +} +"#) + (top Top) + (modify (set a 16777216)) + (assert_eq narrow 16777216) + (assert_eq wide 16777217) + (assert_eq promoted 16777217) + (modify (set a 7)) + (assert_eq narrow 8) (assert_eq wide 8) (assert_eq promoted 8)) + +(case sequential_float + (source "float.veryl" #" +module Top(clk: input clock, a: input i32, result: output i32, less: output logic) { + var q: f64; + always_ff (clk) { + q = (a as f64) / 2.0; + less = (a as f64) <: 0.5; + } + assign result = q as i32; +} +"#) + (top Top) + (modify (set a 3)) (tick clk) + (assert_eq result 2) (assert_eq less 0) + (modify (set a 0xfffffffd)) (tick clk) + (assert_eq result 0xfffffffe) (assert_eq less 1)) + +(case scalar_port_and_function_conversions + (source "float.veryl" #" +module Child(a: input f64, q: output f64) { + function increment(x: input f64) -> f64 { return x + 0.5; } + assign q = increment(a); +} +module Top(a: input i32, q: output i32, function_result: output i32) { + inst child: Child(a: a, q: q); + function promote(x: input f64) -> f64 { return x + 0.5; } + assign function_result = promote(a) as i32; +} +"#) + (top Top) + (modify (set a 3)) + (assert_eq q 4) (assert_eq function_result 4) + (modify (set a 0xfffffffd)) + (assert_eq q 0xfffffffd) (assert_eq function_result 0xfffffffd)) + +(case unknown_integer_conversion + (four_state) + (source "float.veryl" #" +module Top(a: input logic<8>, q: output u32, narrow: output u32) { + assign q = (a as f64) as u32; + assign narrow = (a as f32) as u32; +} +"#) + (top Top) + (modify (set a (fourstate 0xaf 0x0f))) + (assert_eq q 0xa0) (assert_eq narrow 0xa0) + (modify (set a (fourstate 0xa0 0x0f))) + (assert_eq q 0xa0) (assert_eq narrow 0xa0) + (modify (set a (fourstate 0xff 0xff))) + (assert_eq q 0) (assert_eq narrow 0)) + +(case formatted_display_and_write + (source "float.veryl" #" +module Top(clk: input clock, a: input i32) { + always_ff (clk) { + $display("wide=%0.2f narrow=%0.2f", (a as f64) / 2.0, a as f32); + $write("negative=%0.2f", -(a as f64)); + } +} +"#) + (top Top) + (modify (set a 3)) + (tick clk) + (expect_output "wide=1.50 narrow=3.00\nnegative=-3.00")) + +(case integral_constants_from_float + (source "float.veryl" #" +module Literal(y: output i32) { + const I: i32 = (-2.25 as f32) as i32; + assign y = I; +} +module Top(direct: output i32, named: output i32, arithmetic: output i32) { + const F: f32 = -2.25 as f32; + const N: i32 = F as i32; + const A: i32 = N + 5; + inst literal: Literal(y: direct); + assign named = N; + assign arithmetic = A; +} +"#) + (top Top) + (assert_eq direct 0xfffffffe) + (assert_eq named 0xfffffffe) + (assert_eq arithmetic 3)) diff --git a/crates/celox-test-suite/src/veryl/cases/mod.rs b/crates/celox-test-suite/src/veryl/cases/mod.rs index b84278bf228..116ca0eae11 100644 --- a/crates/celox-test-suite/src/veryl/cases/mod.rs +++ b/crates/celox-test-suite/src/veryl/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/veryl/cases/floating_point.vtest", + text: include_str!("floating_point.vtest"), + }, Group { file: "src/veryl/cases/tb_string.vtest", text: include_str!("tb_string.vtest"), diff --git a/crates/celox-testbench/src/format.rs b/crates/celox-testbench/src/format.rs index a3887dd300c..5aa0e3b0c7b 100644 --- a/crates/celox-testbench/src/format.rs +++ b/crates/celox-testbench/src/format.rs @@ -7,6 +7,143 @@ pub struct DisplayFormatArg<'a> { pub width: usize, pub signed: bool, pub is_string: bool, + /// Interpret the payload as IEEE bits rather than an integral value. + pub float_precision: Option, +} + +fn integer_float_bits(arg: &DisplayFormatArg<'_>) -> BigUint { + BigUint::from(celox_design::eval_float_unary( + celox_design::FloatUnaryOp::ToSigned { + width: 64, + round: true, + }, + arg.float_precision.unwrap(), + arg.value.to_u64().unwrap_or(0), + )) +} +fn numeric_float(arg: &DisplayFormatArg<'_>) -> f64 { + if let Some(precision) = arg.float_precision { + let bits = arg.value.to_u64().unwrap_or(0); + return match precision { + celox_design::FloatPrecision::F32 => f32::from_bits(bits as u32) as f64, + celox_design::FloatPrecision::F64 => f64::from_bits(bits), + }; + } + let mut value = masked_value(arg.value, arg.width); + if let Some(mask) = arg.mask { + value &= ((BigUint::from(1u8) << arg.width) - BigUint::from(1u8)) + ^ masked_value(mask, arg.width); + } + if arg.signed { + let value = value_to_signed_bigint(&value, arg.width); + value.to_f64().unwrap_or(if value.sign() == Sign::Minus { + f64::NEG_INFINITY + } else { + f64::INFINITY + }) + } else { + value.to_f64().unwrap_or(f64::INFINITY) + } +} + +fn normalize_exponent(text: String, upper: bool) -> String { + let Some((body, exponent)) = text.split_once('e') else { + return text; + }; + let exponent = exponent.parse::().expect("Rust float exponent"); + format!("{body}{}{exponent:+03}", if upper { 'E' } else { 'e' }) +} +fn trim_fraction(text: &str) -> String { + if text.contains('.') { + text.trim_end_matches('0').trim_end_matches('.').to_string() + } else { + text.to_string() + } +} +// IEEE 1800-2023 21.2.1.1 gives real e/f/g the C formatting semantics. +// Rust supplies decimal rounding; normalize its exponent and implement g's +// significant-digit selection and trailing-zero rules explicitly. +fn format_float(arg: &DisplayFormatArg<'_>, spec: char, field: FieldSpec) -> Vec { + let value = numeric_float(arg); + let upper = spec.is_ascii_uppercase(); + let precision = field.precision.unwrap_or(6).min(MAX_FIELD_WIDTH); + let mut text = if value.is_nan() { + format!( + "{}{}", + if value.is_sign_negative() { "-" } else { "" }, + if upper { "NAN" } else { "nan" } + ) + } else if value.is_infinite() { + format!( + "{}{}", + if value.is_sign_negative() { "-" } else { "" }, + if upper { "INF" } else { "inf" } + ) + } else { + match spec.to_ascii_lowercase() { + 'e' => { + let mut raw = format!("{value:.precision$e}"); + if field.alternate && precision == 0 { + let i = raw.find('e').unwrap(); + raw.insert(i, '.'); + } + normalize_exponent(raw, upper) + } + 'g' => { + let digits = precision.max(1); + let fractional = digits - 1; + let scientific = format!("{value:.fractional$e}"); + let (mantissa, exponent) = scientific.split_once('e').unwrap(); + let exponent = exponent.parse::().unwrap(); + if exponent < -4 || exponent >= digits as i32 { + let mut mantissa = if field.alternate { + mantissa.to_string() + } else { + trim_fraction(mantissa) + }; + if field.alternate && !mantissa.contains('.') { + mantissa.push('.'); + } + normalize_exponent(format!("{mantissa}e{exponent}"), upper) + } else { + let fractional = (digits as i32 - 1 - exponent).max(0) as usize; + let raw = format!("{value:.fractional$}"); + let mut text = if field.alternate { + raw + } else { + trim_fraction(&raw) + }; + if field.alternate && !text.contains('.') { + text.push('.'); + } + text + } + } + _ => { + let mut text = format!("{value:.precision$}"); + if field.alternate && precision == 0 { + text.push('.'); + } + text + } + } + }; + if !text.starts_with('-') { + if field.show_sign { + text.insert(0, '+'); + } else if field.space_sign { + text.insert(0, ' '); + } + } + // C does not zero-pad infinities or NaNs. + pad_veryl_field( + text.into_bytes(), + spec, + FieldSpec { + zero_pad: field.zero_pad && value.is_finite(), + ..field + }, + ) } fn bit(value: &BigUint, bit: usize) -> bool { @@ -60,6 +197,24 @@ fn packed_bytes(value: &BigUint, width: usize) -> Vec { /// Format an argument as bytes. Character conversions never decode UTF-8. pub fn format_display_arg(arg: &DisplayFormatArg<'_>, spec: Option) -> Vec { + if arg.float_precision.is_some() && spec.is_none() { + return format_float(arg, 'g', FieldSpec::default()); + } + if matches!(spec, Some('f' | 'F' | 'e' | 'E' | 'g' | 'G')) { + return format_float(arg, spec.unwrap(), FieldSpec::default()); + } + if arg.float_precision.is_some() { + let value = integer_float_bits(arg); + let integer = DisplayFormatArg { + value: &value, + mask: None, + width: 64, + signed: true, + is_string: false, + float_precision: None, + }; + return format_display_arg(&integer, spec); + } if arg.is_string { return packed_bytes(arg.value, arg.width); } @@ -209,6 +364,22 @@ pub fn format_sized_display_arg( /// by Icarus and Verilator. As in Icarus, decimal zero padding follows the sign; /// left justification takes precedence over zero padding. pub fn format_sv_display_arg(arg: &DisplayFormatArg<'_>, spec: char, field: FieldSpec) -> Vec { + if matches!(spec, 'f' | 'F' | 'e' | 'E' | 'g' | 'G') { + return format_float(arg, spec, field); + } + if arg.float_precision.is_some() { + let value = integer_float_bits(arg); + let integer = DisplayFormatArg { + value: &value, + mask: None, + width: 64, + signed: true, + is_string: false, + float_precision: None, + }; + return format_sv_display_arg(&integer, spec, field); + } + let field_width = field.width; // Table 21-1 gives each uppercase specifier the meaning of its lowercase // one, so `%H` prints lowercase digits like `%h`. @@ -220,6 +391,7 @@ pub fn format_sv_display_arg(arg: &DisplayFormatArg<'_>, spec: char, field: Fiel width: arg.width, signed: arg.signed, is_string: arg.is_string && spec == 's', + float_precision: arg.float_precision, }; if spec == 's' && !has_mask(arg) { // Integral %s is right-justified byte data; omit leading zero bytes @@ -335,7 +507,7 @@ fn radix_digits(arg: &DisplayFormatArg<'_>, bits_per_digit: usize) -> String { /// simulator caps its field widths the same way. pub const MAX_FIELD_WIDTH: usize = 1 << 16; -/// The flags and field width between `%` and a conversion character. +/// The flags, field width, and precision between `%` and a conversion character. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct FieldSpec { pub width: Option, @@ -343,6 +515,11 @@ pub struct FieldSpec { pub left_justify: bool, /// A leading `0` digit: pad numbers with zeros. pub zero_pad: bool, + /// Digits after the decimal point for f/e, significant digits for g. + pub precision: Option, + pub show_sign: bool, + pub space_sign: bool, + pub alternate: bool, } impl FieldSpec { @@ -352,9 +529,26 @@ impl FieldSpec { chars: &mut std::iter::Peekable>, c_flags: bool, ) -> Self { - let left_justify = c_flags && chars.next_if_eq(&'-').is_some(); - let zero_pad = chars.peek() == Some(&'0'); - let mut width = None; + let mut left_justify = false; + let mut zero_pad = false; + let mut show_sign = false; + let mut space_sign = false; + let mut alternate = false; + while let Some(&flag) = chars.peek() { + match flag { + '-' if c_flags => left_justify = true, + '+' if c_flags => show_sign = true, + ' ' if c_flags => space_sign = true, + '#' if c_flags => alternate = true, + '0' => zero_pad = true, + _ => break, + } + chars.next(); + if !c_flags { + break; + } + } + let mut width = if zero_pad { Some(0) } else { None }; while let Some(digit) = chars.peek().and_then(|c| c.to_digit(10)) { chars.next(); width = Some( @@ -365,10 +559,26 @@ impl FieldSpec { .min(MAX_FIELD_WIDTH), ); } + let mut precision = None; + if chars.next_if_eq(&'.').is_some() { + let mut value = 0usize; + while let Some(digit) = chars.peek().and_then(|c| c.to_digit(10)) { + chars.next(); + value = value + .saturating_mul(10) + .saturating_add(digit as usize) + .min(MAX_FIELD_WIDTH); + } + precision = Some(value); + } Self { width, left_justify, zero_pad, + precision, + show_sign, + space_sign, + alternate, } } } @@ -382,6 +592,22 @@ pub fn format_veryl_display_arg( spec: char, field: FieldSpec, ) -> Vec { + if matches!(spec, 'f' | 'F' | 'e' | 'E' | 'g' | 'G') { + return format_float(arg, spec, field); + } + if arg.float_precision.is_some() { + let value = integer_float_bits(arg); + let integer = DisplayFormatArg { + value: &value, + mask: None, + width: 64, + signed: true, + is_string: false, + float_precision: None, + }; + return format_veryl_display_arg(&integer, spec, field); + } + let spec = spec.to_ascii_lowercase(); let bits_per_digit = match spec { 'b' => Some(1), @@ -419,12 +645,15 @@ pub fn pad_veryl_field(mut body: Vec, spec: char, field: FieldSpec) -> Vec String { + let bits = BigUint::from(value.to_bits()); + let arg = DisplayFormatArg { + value: &bits, + mask: None, + width: 64, + signed: false, + is_string: false, + float_precision: Some(FloatPrecision::F64), + }; + let mut chars = format.chars().peekable(); + let field = FieldSpec::parse(&mut chars, true); + let spec = chars.next().unwrap(); + assert!(chars.next().is_none()); + String::from_utf8(format_sv_display_arg(&arg, spec, field)).unwrap() + } + #[test] + fn floating_formats_cover_precision_exponents_signs_and_padding() { + for (value, spec, expected) in [ + (1.5, "f", "1.500000"), + (1.5, "+010.2f", "+000001.50"), + (-1.5, "010.2f", "-000001.50"), + (1.5, "-10.2f", "1.50 "), + (0.0, " .0f", " 0"), + (2.0, "#.0f", "2."), + (1.5, "e", "1.500000e+00"), + (12345.0, ".2E", "1.23E+04"), + (12345.0, ".3g", "1.23e+04"), + (0.0001234, ".3g", "0.000123"), + (0.00001234, ".3g", "1.23e-05"), + (999.5, ".3g", "1e+03"), + (1.0, "#.3g", "1.00"), + (1.5, "#g", "1.50000"), + (-0.0, ".2f", "-0.00"), + (f64::INFINITY, "08f", " inf"), + (f64::NEG_INFINITY, "E", "-INF"), + (f64::NAN, "+G", "+NAN"), + (1.5, "0d", "2"), + (-1.5, "0d", "-2"), + ] { + assert_eq!(real(value, spec), expected, "{value} %{spec}"); + } + } + #[test] + fn integer_arguments_convert_numerically_and_shortreal_keeps_its_precision() { + let value = BigUint::from(0xffff_ffd6u32); + let arg = DisplayFormatArg { + value: &value, + mask: None, + width: 32, + signed: true, + is_string: false, + float_precision: None, + }; + assert_eq!( + format_sv_display_arg(&arg, 'f', FieldSpec::default()), + b"-42.000000" + ); + let masked = BigUint::from(255u8); + let unknown = BigUint::from(240u8); + let masked_arg = DisplayFormatArg { + value: &masked, + mask: Some(&unknown), + width: 8, + signed: false, + is_string: false, + float_precision: None, + }; + assert_eq!( + format_sv_display_arg(&masked_arg, 'f', FieldSpec::default()), + b"15.000000" + ); + let wide = BigUint::from(1u8) << 4095usize; + let wide_arg = DisplayFormatArg { + value: &wide, + mask: None, + width: 4096, + signed: true, + is_string: false, + float_precision: None, + }; + assert_eq!( + format_sv_display_arg(&wide_arg, 'f', FieldSpec::default()), + b"-inf" + ); + let value = BigUint::from(1.1f32.to_bits()); + let arg = DisplayFormatArg { + value: &value, + mask: None, + width: 32, + signed: false, + is_string: false, + float_precision: Some(FloatPrecision::F32), + }; + assert_eq!( + format_veryl_display_arg( + &arg, + 'f', + FieldSpec { + precision: Some(9), + ..Default::default() + } + ), + b"1.100000024" + ); + assert_eq!(format_display_arg(&arg, None), b"1.1"); + } +} diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 919d6dad3f0..5d5c95342a1 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -260,6 +260,8 @@ pub struct SemanticArgument { pub width: usize, pub signed: bool, pub is_string: bool, + #[serde(default)] + pub float_precision: Option, } pub type SemanticStatement = TestbenchStatement< @@ -469,6 +471,14 @@ pub enum ExprOpcode { width: usize, }, BinOp(TestbenchOperator), + FloatBinary { + op: celox_design::FloatBinaryOp, + precision: celox_design::FloatPrecision, + }, + FloatUnary { + op: celox_design::FloatUnaryOp, + precision: celox_design::FloatPrecision, + }, TypedBinOp { op: TestbenchOperator, lhs_width: usize, @@ -549,6 +559,7 @@ pub struct ExecutableArgument { pub width: usize, pub signed: bool, pub is_string: bool, + pub float_precision: Option, } pub type ExecutableAssertMessage = AssertMessage; @@ -708,6 +719,12 @@ impl ExprBytecode> { width, }, ExprOpcode::BinOp(op) => ExprOpcode::BinOp(op), + ExprOpcode::FloatBinary { op, precision } => { + ExprOpcode::FloatBinary { op, precision } + } + ExprOpcode::FloatUnary { op, precision } => { + ExprOpcode::FloatUnary { op, precision } + } ExprOpcode::TypedBinOp { op, lhs_width, diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs index dd965af6d64..3bba0da9720 100644 --- a/crates/celox-testbench/src/vm.rs +++ b/crates/celox-testbench/src/vm.rs @@ -210,6 +210,27 @@ impl CompiledExpr { stack.push(eval_binop(l, *op, r)); *pc += 1; } + TbOpcode::FloatBinary { op, precision } => { + let r = stack.pop().unwrap_or(TestbenchValue::U64(0)); + let l = stack.pop().unwrap_or(TestbenchValue::U64(0)); + stack.push(TestbenchValue::U64(celox_design::eval_float_binary( + *op, + *precision, + l.to_u64(), + r.to_u64(), + ))); + *pc += 1; + } + TbOpcode::FloatUnary { op, precision } => { + if let Some(top) = stack.last_mut() { + *top = TestbenchValue::U64(celox_design::eval_float_unary( + *op, + *precision, + top.to_u64(), + )); + } + *pc += 1; + } TbOpcode::TypedBinOp { op, lhs_width, @@ -976,3 +997,42 @@ fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { _ => unreachable!("operator is not testbench comparison plumbing: {op:?}"), } } + +#[cfg(test)] +mod float_tests { + use super::*; + use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; + + #[test] + fn floating_bytecode_keeps_precision_and_numeric_conversions() { + for (precision, expected) in [ + (FloatPrecision::F32, 16777216), + (FloatPrecision::F64, 16777217), + ] { + let expression = CompiledExpr::new(ExprBytecode::new(vec![ + TbOpcode::ConstU64(16777216), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::ConstU64(1), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::FloatBinary { + op: FloatBinaryOp::Add, + precision, + }, + TbOpcode::FloatUnary { + op: FloatUnaryOp::ToUnsigned { + width: 32, + round: true, + }, + precision, + }, + ])); + assert_eq!(expression.eval_u64(std::ptr::null_mut()), expected); + } + } +} diff --git a/crates/celox-wasm/src/lib.rs b/crates/celox-wasm/src/lib.rs index 473de37cec4..80bb5fe0e0a 100644 --- a/crates/celox-wasm/src/lib.rs +++ b/crates/celox-wasm/src/lib.rs @@ -64,6 +64,12 @@ impl SimHandle { }) } + /// Evaluate an internal floating-point operation for generated simulation modules. + #[wasm_bindgen(js_name = "evaluateFloat")] + pub fn evaluate_float(&self, lhs: u64, rhs: u64, code: u64) -> u64 { + wasm_codegen::evaluate_float(lhs, rhs, code) + } + /// Returns the WASM module bytes for eval_comb (combinational logic evaluation). #[wasm_bindgen(js_name = "combWasmBytes")] pub fn comb_wasm_bytes(&self) -> Vec { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 2aeba1395d7..140b7357383 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 21; +const CONTAINER_VERSION: u16 = 22; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index c2fc78eb488..14a41ed3f98 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -378,7 +378,11 @@ impl WasmBackend { } // SAFETY: the module calls each import with the // argument count of the DPI-C import it links to. - let result = unsafe { extern_functions.call(func, args) }; + let result = if func == u32::MAX { + celox_sir::float::evaluate(args[0], args[1], args[2]) + } else { + unsafe { extern_functions.call(func, args) } + }; results[0] = wasmtime::Val::I64(result as i64); Ok(()) }) diff --git a/crates/celox/src/dpi.rs b/crates/celox/src/dpi.rs index e6b1f6c674c..fc7e8cbe9da 100644 --- a/crates/celox/src/dpi.rs +++ b/crates/celox/src/dpi.rs @@ -81,10 +81,15 @@ impl DpiSymbols { { return Ok(table.clone()); } - let addresses = functions - .iter() - .map(|function| self.address(&function.name)) - .collect::, _>>()?; + // Internal helpers precede the user table so persisted machine code + // resolves them in the loading process instead of embedding addresses. + let mut addresses = vec![celox_sir::float::evaluate as *const () as usize]; + addresses.extend( + functions + .iter() + .map(|function| self.address(&function.name)) + .collect::, _>>()?, + ); Ok(ExternFunctionTable { addresses: addresses.into(), }) @@ -157,15 +162,24 @@ fn library_symbol(_path: &std::path::Path, _name: &str) -> Result, /// The addresses of a design's extern functions, indexed like its /// `ExternCall` instructions. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub(crate) struct ExternFunctionTable { addresses: Arc<[usize]>, } +impl Default for ExternFunctionTable { + fn default() -> Self { + Self { + addresses: vec![celox_sir::float::evaluate as *const () as usize].into(), + } + } +} + impl ExternFunctionTable { - /// The table's address, which the state header holds. + /// The user table's address, which the state header holds. The internal + /// floating-point helper occupies the immediately preceding slot. pub(crate) fn as_ptr(&self) -> *const usize { - self.addresses.as_ptr() + self.addresses.as_ptr().wrapping_add(1) } /// Call function `func` with C integer arguments and return its C integer @@ -177,7 +191,7 @@ impl ExternFunctionTable { /// integer or nothing, as its DPI-C import declares. pub(crate) unsafe fn call(&self, func: u32, args: &[u64]) -> u64 { // SAFETY: forwarded from the caller. - unsafe { call_c(self.addresses[func as usize], args) } + unsafe { call_c(self.addresses[func as usize + 1], args) } } } diff --git a/crates/celox/src/interpreter.rs b/crates/celox/src/interpreter.rs index d41e7b4efba..27d9f6b7a2f 100644 --- a/crates/celox/src/interpreter.rs +++ b/crates/celox/src/interpreter.rs @@ -771,6 +771,9 @@ fn alu_binary_u64( }; let promoted_rhs = rhs & mask_u64(common); let result = match op { + BinaryOp::Float { op, precision } => { + celox_design::eval_float_binary(*op, *precision, lhs, rhs) + } BinaryOp::Add => promoted_lhs.wrapping_add(promoted_rhs), BinaryOp::Sub => promoted_lhs.wrapping_sub(promoted_rhs), BinaryOp::Mul => promoted_lhs.wrapping_mul(promoted_rhs), @@ -837,6 +840,7 @@ fn alu_unary_u64( ) -> u64 { let src = src & mask_u64(src_width); let result = match op { + UnaryOp::Float { op, precision } => celox_design::eval_float_unary(*op, *precision, src), UnaryOp::Ident => { if src_signed { sign_extend_u64(src, src_width, dst_width) @@ -904,6 +908,12 @@ fn alu_binary( four_state: bool, ) -> Result { let out = match op { + BinaryOp::Float { op, precision } => SIRValue::new(celox_design::eval_float_binary( + *op, + *precision, + known_ones(lhs, lhs_width).to_u64().unwrap_or(0), + known_ones(rhs, rhs_width).to_u64().unwrap_or(0), + )), BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul => { // SEMANTICS-CHECK: any X/Z operand bit makes the whole result X. // Operands are promoted to the common width with the compiled @@ -1344,6 +1354,11 @@ fn alu_unary( dst_width: usize, ) -> Result { let out = match op { + UnaryOp::Float { op, precision } => SIRValue::new(celox_design::eval_float_unary( + *op, + *precision, + known_ones(src, src_width).to_u64().unwrap_or(0), + )), UnaryOp::Ident => { // Identity casts widen with the operand's declared signedness, // matching the compiled narrow promotion: widening a signed diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index dceaed1f6bc..d415dda73ab 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -255,6 +255,7 @@ mod host { width: usize, signed: bool, is_string: bool, + float_precision: Option, } #[derive(Clone)] @@ -422,6 +423,7 @@ mod host { width: arg.width, signed: arg.signed, is_string: arg.is_string, + float_precision: arg.float_precision, }; match sizing { DisplaySizing::Veryl => format_veryl_display_arg(&arg, spec, field), @@ -459,7 +461,16 @@ mod host { return args .iter() .map(|arg| { - runtime_event_format_arg(arg, default_spec, site.sizing, FieldSpec::default()) + runtime_event_format_arg( + arg, + if arg.float_precision.is_some() { + 'g' + } else { + default_spec + }, + site.sizing, + FieldSpec::default(), + ) }) .collect::>() .join(&b' '); @@ -488,7 +499,7 @@ mod host { out.extend_from_slice(&runtime_event_format_arg(arg, spec, site.sizing, field)); arg_idx += 1; } - 'd' | 'D' | 'i' | 'I' => { + 'd' | 'D' | 'i' | 'I' | 'f' | 'F' | 'e' | 'E' | 'g' | 'G' => { let Some(arg) = args.get(arg_idx) else { arg_idx += 1; continue; @@ -633,6 +644,9 @@ mod host { )); } args.push(RuntimeEventArgValue { + float_precision: site + .and_then(|site| site.arg_float_precision.get(idx).copied()) + .flatten(), values, masks, width: site diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 8cc9f7fc278..d6ad77dace0 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -71,6 +71,7 @@ impl Simulator { width: arg.width, signed: arg.signed, is_string: arg.is_string, + float_precision: arg.float_precision, }) .collect(); let process = &self.program.runtime_schema.processes[site.process]; @@ -99,6 +100,7 @@ impl Simulator { arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), + arg_float_precision: Vec::new(), }; let mut message = render_runtime_event_message( &format, @@ -189,6 +191,7 @@ impl Simulator { width, signed: false, is_string: false, + float_precision: None, }), ) .map_err(|err| error(format!("$writemem: {err}")))?; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 91e1a4c4daf..1c305ebff5d 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -151,6 +151,7 @@ fn format_assert_arg( width, signed: arg.signed, is_string: arg.is_string, + float_precision: arg.float_precision, }, spec, field, @@ -166,7 +167,18 @@ fn render_assert_message( None => None, Some(AssertMessage::DynamicArgs(args)) => Some( args.iter() - .map(|arg| format_assert_arg(sim, arg, 'x', FieldSpec::default())) + .map(|arg| { + format_assert_arg( + sim, + arg, + if arg.float_precision.is_some() { + 'g' + } else { + 'x' + }, + FieldSpec::default(), + ) + }) .collect::>() .join(&b' '), ), @@ -192,7 +204,7 @@ fn render_assert_message( }; match spec { 'h' | 'H' | 'x' | 'X' | 'd' | 'D' | 'i' | 'I' | 'o' | 'O' | 'b' - | 'B' | 'c' | 'C' | 's' | 'S' => { + | 'B' | 'c' | 'C' | 's' | 'S' | 'f' | 'F' | 'e' | 'E' | 'g' | 'G' => { if let Some(arg) = args.get(arg_idx) { rendered.extend_from_slice(&format_assert_arg( sim, arg, spec, field, diff --git a/crates/celox/tests/floating_point.rs b/crates/celox/tests/floating_point.rs new file mode 100644 index 00000000000..482e306f848 --- /dev/null +++ b/crates/celox/tests/floating_point.rs @@ -0,0 +1,40 @@ +#[path = "test_utils/mod.rs"] +#[macro_use] +mod test_utils; + +all_backends! { + fn integral_constants_from_float(sim) { + // Upstream Veryl 0.22 folds negative f32 constants incorrectly (#1657). + // https://github.com/celox-sim/celox/issues/1657 + @ignore_on(veryl, native, native_parallel, cranelift, cranelift_parallel, wasm, interp); + @case "floating_point::integral_constants_from_float"; + } + + fn formatted_display_and_write(sim) { + // Veryl 0.22 prints the %0.2f format text literally; its adapter also + // has no byte-output capture API. External simulators check this case. + @ignore_on(veryl); + @case "floating_point::formatted_display_and_write"; + } + + fn arithmetic_and_rounding(sim) { + // Veryl 0.22 simulator truncates 7.0 / 2.0 to 3 instead of rounding to 4. + @ignore_on(veryl); + @case "floating_point::arithmetic_and_rounding"; } + fn f32_precision_and_conversion(sim) { + // Veryl 0.22 simulator returns the f32 IEEE payload instead of a numeric integer conversion. + @ignore_on(veryl); + @case "floating_point::f32_precision_and_conversion"; } + fn scalar_port_and_function_conversions(sim) { + // Veryl 0.22 simulator truncates the implicit 3.5 port conversion to 3 instead of 4. + @ignore_on(veryl); + @case "floating_point::scalar_port_and_function_conversions"; } + fn unknown_integer_conversion(sim) { + // Veryl 0.22 simulator retains X/Z bits when converting an integer through a float. + @ignore_on(veryl); + @case "floating_point::unknown_integer_conversion"; } + fn sequential_float(sim) { + // Veryl 0.22 simulator returns zero for the clocked floating-point conversion. + @ignore_on(veryl); + @case "floating_point::sequential_float"; } +} diff --git a/crates/celox/tests/floating_point_display.rs b/crates/celox/tests/floating_point_display.rs new file mode 100644 index 00000000000..eed41c9944f --- /dev/null +++ b/crates/celox/tests/floating_point_display.rs @@ -0,0 +1,350 @@ +use celox::{RuntimeEvent, Simulator}; + +#[path = "test_utils/mod.rs"] +#[macro_use] +mod test_utils; + +all_backends! { + fn rtl_comb_float_display_and_write(sim) { + @omit_veryl; + @build Simulator::builder(r#" + module Top(a: input i32, result: output i32) { + var wide: f64; + var narrow: f32; + always_comb { + wide = (a as f64) / 2.0; + narrow = a as f32; + result = wide as i32; + $display("wide=%f narrow=%0.2f neg=%0.2f", wide, narrow, -wide); + $write("fraction=%0.2f", wide); + } + } + "#, "Top"); + sim.drain_runtime_events(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 3u32)).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![ + RuntimeEvent::Display { message: b"wide=1.500000 narrow=3.00 neg=-1.50".to_vec() }, + RuntimeEvent::Write { message: b"fraction=1.50".to_vec() }, + ]); + } + + fn rtl_implicit_float_messages(sim) { + @omit_veryl; + // Veryl separates arguments with spaces and uses %g. Emitted SV's + // implicit real formatting concatenates %#g fields instead. + @omit_sv; + @build Simulator::builder(r#" + module Top(a: input i32) { + always_comb { $display((a as f64) / 2.0, a as f32); } + } + "#, "Top"); + sim.drain_runtime_events(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 3u32)).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![RuntimeEvent::Display { message: b"1.5 3".to_vec() }]); + } + + fn rtl_negative_float_constants(sim) { + @omit_veryl; + // Upstream Veryl constant folding corrupts negative f32 payloads (#1657). + @ignore_on(native, native_parallel, cranelift, cranelift_parallel, wasm, interp); + @build Simulator::builder(r#" + module Top(clk: input clock, q: output i32) { + always_ff (clk) { + q = (-2.25 as f32) as i32; + $display("constant=%0.2f wide=%0.2f", -2.25 as f32, -1.5); + } + } + "#, "Top"); + let clk = sim.event("clk"); + sim.drain_runtime_events(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0xfffffffeu32.into()); + assert_eq!(sim.drain_runtime_events(), vec![RuntimeEvent::Display { message: b"constant=-2.25 wide=-1.50".to_vec() }]); + } + + fn rtl_ff_float_messages(sim) { + @omit_veryl; + @build Simulator::builder(r#" + module Top(clk: input clock, a: input i32) { + always_ff (clk) { + $display("ff=%0.2f f32=%0.2f", (a as f64) / 2.0, a as f32); + $assert_continue(1'b0, "value=%0.2f", (a as f64) / 2.0); + } + } + "#, "Top"); + let a = sim.signal("a"); + let clk = sim.event("clk"); + sim.modify(|io| io.set(a, 3u32)).unwrap(); + sim.drain_runtime_events(); + sim.tick(clk).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![ + RuntimeEvent::Display { message: b"ff=1.50 f32=3.00".to_vec() }, + RuntimeEvent::AssertContinue { message: b"value=1.50".to_vec() }, + ]); + } +} + +#[test] +#[ignore = "upstream Veryl negative f32 constant folding: https://github.com/celox-sim/celox/issues/1657"] +fn testbench_float_output_and_assertion_messages() { + const CHILD: &str = "CELOX_TEST_FLOAT_DISPLAY_CHILD"; + #[allow(clippy::disallowed_methods)] + let child = std::env::var_os(CHILD).is_some(); + if child { + let result = Simulator::builder( + r#" + #[test(Top)] + module Top { + var wide: f64; + var narrow: f32; + initial { + wide = 1.5; + narrow = -2.25 as f32; + $display("tb=%f narrow=%0.2f", wide, narrow); + $write("joined=%0.2f", -wide); + $display(" done=%0.2f", narrow); + $display(wide, narrow); + $display("exp=%0.2e general=%g signed=%+8.2f", wide, wide, wide); + $assert_continue(1'b0, "message=%0.2f/%0.2f", wide, narrow); + $finish(); + } + } + "#, + "Top", + ) + .run_test_detailed() + .unwrap(); + assert!(!result.passed); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"message=1.50/-2.25".as_slice()) + ); + return; + } + let current = std::thread::current(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + current.name().unwrap(), + "--nocapture", + "--test-threads=1", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("tb=1.500000 narrow=-2.25\n"), "{stderr}"); + assert!(stderr.contains("joined=-1.50 done=-2.25\n"), "{stderr}"); + assert!(stderr.contains("1.5 -2.25\n"), "{stderr}"); + assert!( + stderr.contains("exp=1.50e+00 general=1.5 signed= +1.50\n"), + "{stderr}" + ); +} + +#[test] +fn testbench_runtime_float_output_and_assertion_messages() { + const CHILD: &str = "CELOX_TEST_FLOAT_DISPLAY_CHILD"; + #[allow(clippy::disallowed_methods)] + let child = std::env::var_os(CHILD).is_some(); + if child { + let result = Simulator::builder( + r#" + #[test(Top)] + module Top { + var wide: f64; + var narrow: f32; + initial { + wide = 1.5; + narrow = -(wide + 0.75) as f32; + $display("tb=%f narrow=%0.2f", wide, narrow); + $write("joined=%0.2f", -wide); + $display(" done=%0.2f", narrow); + $display(wide, narrow); + $display("exp=%0.2e general=%g signed=%+8.2f", wide, wide, wide); + $assert_continue(1'b0, "message=%0.2f/%0.2f", wide, narrow); + $finish(); + } + } + "#, + "Top", + ) + .run_test_detailed() + .unwrap(); + assert!(!result.passed); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"message=1.50/-2.25".as_slice()) + ); + return; + } + let current = std::thread::current(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + current.name().unwrap(), + "--nocapture", + "--test-threads=1", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("tb=1.500000 narrow=-2.25\n"), "{stderr}"); + assert!(stderr.contains("joined=-1.50 done=-2.25\n"), "{stderr}"); + assert!(stderr.contains("1.5 -2.25\n"), "{stderr}"); + assert!( + stderr.contains("exp=1.50e+00 general=1.5 signed= +1.50\n"), + "{stderr}" + ); +} + +#[test] +#[ignore = "upstream Veryl FP constant folding: https://github.com/celox-sim/celox/issues/1657"] +fn named_float_constants_and_parameters_display_numeric_values() { + let source = r#" + module Top #(param P: f32 = -2.25 as f32, param Q: f32 = P + (0.5 as f32)) + (clk: input clock, mirror: output f32) { + const C: f32 = -2.25 as f32; + const POS: f32 = 1.25 as f32; + const W: f64 = -1.5; + const DEP: f32 = C + (0.5 as f32); + assign mirror = P; + always_ff (clk) { + $display("C=%0.2f P=%0.2f Q=%0.2f W=%0.2f POS=%0.2f DEP=%0.2f", C, P, Q, W, POS, DEP); + } + } + "#; + for (override_bits, expected) in [ + (None, "C=-2.25 P=-2.25 Q=-1.75 W=-1.50 POS=1.25 DEP=-1.75"), + ( + Some(1.25f32.to_bits()), + "C=-2.25 P=1.25 Q=1.75 W=-1.50 POS=1.25 DEP=-1.75", + ), + ] { + let builder = Simulator::builder(source, "Top"); + let builder = if let Some(bits) = override_bits { + builder.param("P", bits as u64) + } else { + builder + }; + let mut sim = builder.build().unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: expected.as_bytes().to_vec() + }] + ); + } + // Preserve an intentional override even when its bits equal Veryl's buggy + // default cache (unsigned f64(-2.25) bits converted numerically to f32). + let same_bits = ((-2.25f64).to_bits() as f32).to_bits(); + let mut sim = Simulator::builder(source, "Top") + .param("P", same_bits as u64) + .build() + .unwrap(); + assert_eq!(sim.get(sim.signal("mirror")), same_bits.into()); +} + +#[test] +#[ignore = "upstream Veryl FP constant folding: https://github.com/celox-sim/celox/issues/1657"] +fn hierarchical_float_parameter_overrides_keep_their_own_scope() { + let source = r#" + module Child #(param P: f32 = -2.25 as f32) (clk: input clock) { + const C: f32 = P + (0.5 as f32); + always_ff (clk) { $display("P=%0.2f C=%0.2f", P, C); } + } + module Top(clk: input clock) { + inst child: Child #(P: 1.25 as f32) (clk); + } + "#; + let mut sim = Simulator::builder(source, "Top").build().unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"P=1.25 C=1.75".to_vec() + }] + ); +} + +#[test] +#[ignore = "upstream Veryl FP constant folding: https://github.com/celox-sim/celox/issues/1657"] +fn testbench_named_float_constants_display_numeric_values() { + let result = Simulator::builder( + r#" + #[test(Top)] module Top #(param P: f32 = -2.25 as f32) { + const C: f32 = -2.25 as f32; + initial { $assert_continue(1'b0, "C=%0.2f P=%0.2f", C, P); $finish(); } + } + "#, + "Top", + ) + .run_test_detailed() + .unwrap(); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"C=-2.25 P=-2.25".as_slice()) + ); +} + +#[test] +#[ignore = "upstream Veryl FP constant folding: https://github.com/celox-sim/celox/issues/1657"] +fn package_float_constants_do_not_alias_same_named_parameter_overrides() { + let source = r#" + package Constants { const P: f32 = -2.25 as f32; } + module Top #(param P: f32 = 0.5 as f32) (clk: input clock) { + always_ff (clk) { $display("local=%0.2f package=%0.2f", P, Constants::P); } + } + "#; + let mut sim = Simulator::builder(source, "Top") + .param("P", 1.25f32.to_bits() as u64) + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"local=1.25 package=-2.25".to_vec() + }] + ); +} + +#[test] +fn integral_parameter_override_is_used_by_float_constant() { + let source = r#" + module Child #(param N: u32 = 1) (clk: input clock) { + const K: u32 = N + 1; + const F: f32 = N as f32; + const TRANSITIVE: f32 = K as f32; + const DIRECT: f32 = (N + 1) as f32; + always_ff (clk) { $display("F=%0.2f transitive=%0.2f direct=%0.2f", F, TRANSITIVE, DIRECT); } + } + module Top(clk: input clock) { inst child: Child #(N: 3) (clk); } + "#; + let mut sim = Simulator::builder(source, "Top").build().unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![RuntimeEvent::Display { + message: b"F=3.00 transitive=4.00 direct=4.00".to_vec() + }] + ); +} diff --git a/crates/celox/tests/frontends/systemverilog/floating_point.rs b/crates/celox/tests/frontends/systemverilog/floating_point.rs new file mode 100644 index 00000000000..c187238e0ac --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/floating_point.rs @@ -0,0 +1,42 @@ +use super::*; + +sv_backends! { + fn real_arithmetic_and_rounding(sim) { @case "floating_point::real_arithmetic_and_rounding"; } + fn real_bits_and_comparisons(sim) { @case "floating_point::real_bits_and_comparisons"; } + fn shortreal_storage_precision(sim) { @case "floating_point::shortreal_storage_precision"; } + fn sequential_real(sim) { @case "floating_point::sequential_real"; } + fn real_truth_and_unknown_integer_conversion(sim) { @case "floating_point::real_truth_and_unknown_integer_conversion"; } + fn real_parameter_and_default_storage(sim) { @case "floating_point::real_parameter_and_default_storage"; } + fn real_narrow_integer_conversion(sim) { @case "floating_point::real_narrow_integer_conversion"; } + fn real_ports_and_subroutines(sim) { @case "floating_point::real_ports_and_subroutines"; } + fn real_conversion_functions(sim) { @case "floating_point::real_conversion_functions"; } + fn real_zero_divisor(sim) { @case "floating_point::real_zero_divisor"; } + fn real_display_formats(sim) { @case "floating_point::real_display_formats"; } + fn real_display_negative_zero(sim) { @case "floating_point::real_display_negative_zero"; } + fn real_file_display_formats(sim) { @case "floating_point::real_file_display_formats"; } +} + +sv_backends! { + fn combinational_real_display_and_assertion_messages(sim) { + @setup { let source = r#" + module Top(input logic enabled, input logic [63:0] bits); + real x; + assign x = $bitstoreal(bits); + always_comb if (enabled) begin + $display("comb=%.2f expression=%.1f", x, x * 2.0); + assert (x < 0.0) else $error("assert=%.2f", x); + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("real_comb_display.sv"))], "Top").four_state(true); + sim.drain_runtime_events(); + let enabled = sim.signal("enabled"); + let bits = sim.signal("bits"); + sim.modify(|io| { io.set(bits, 0x3ff8000000000000u64); io.set(enabled, 1u8); }).unwrap(); + assert_eq!(sim.get(sim.signal("x")), BigUint::from(0x3ff8000000000000u64)); + let events = sim.drain_runtime_events(); + assert_eq!(events.len(), 2, "{events:?}"); + assert!(events.contains(&celox::RuntimeEvent::Display { message: b"comb=1.50 expression=3.0".to_vec() }), "{events:?}"); + assert!(events.contains(&celox::RuntimeEvent::AssertContinue { message: b"assert=1.50".to_vec() }), "{events:?}"); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index d6d4f49497c..c3b954f4429 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -239,7 +239,7 @@ fn rejects_inline_enum_ports_instead_of_scalarizing_them() { fn rejects_non_integral_ports_instead_of_scalarizing_them() { let error = cranelift_build_error( r#" - module Top(input real value, output logic y); + module Top(input string value, output logic y); assign y = 1'b0; endmodule "#, @@ -5722,7 +5722,7 @@ fn rejects_constructs_that_are_not_yet_lowered() { "#, ), ( - "unsupported function formal data type", + "operator on a real operand", r#" module Top(input logic [1:0] a, output logic [1:0] y); function automatic logic [1:0] shift(input real value); @@ -5736,8 +5736,8 @@ fn rejects_constructs_that_are_not_yet_lowered() { "void function `f` used as a value", r#" module Top(output logic y); - function automatic real f(); - return 1'b1; + function automatic void f(); + return; endfunction assign y = f(); endmodule @@ -5758,7 +5758,7 @@ fn rejects_constructs_that_are_not_yet_lowered() { ( "unsupported parameter data type", r#" - module Top #(parameter real P = 1) (output logic y); + module Top #(parameter chandle P = null) (output logic y); assign y = P; endmodule "#, @@ -6416,7 +6416,7 @@ fn rejects_unsupported_internal_data_types() { let error = cranelift_build_error( r#" module Top(output logic y); - real value; + string value; assign y = 1'b0; endmodule "#, diff --git a/crates/celox/tests/native_float_image.rs b/crates/celox/tests/native_float_image.rs new file mode 100644 index 00000000000..77231f1d2b7 --- /dev/null +++ b/crates/celox/tests/native_float_image.rs @@ -0,0 +1,87 @@ +//! Native images must resolve floating-point helpers in the loading process. +#![cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) +))] + +use celox::{NativeProgramImage, Simulator}; + +#[test] +fn floating_point_image_executes_in_a_fresh_process() { + const IMAGE_PATH: &str = "CELOX_TEST_FLOAT_NATIVE_IMAGE_PATH"; + // A subprocess recursion marker scoped to this test, not a simulator option. + #[allow(clippy::disallowed_methods)] + let image_path = std::env::var_os(IMAGE_PATH); + if let Some(image_path) = image_path { + let image = + NativeProgramImage::from_container_bytes(&std::fs::read(image_path).unwrap()).unwrap(); + // Loading requires neither the original source nor its compiler/JIT state. + let mut sim = Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + let a = sim.signal("a"); + let comb = sim.signal("comb"); + let narrow = sim.signal("narrow"); + let captured = sim.signal("captured"); + let clk = sim.event("clk"); + for (input, expected) in [(7u32, 4u32), (0xfffffff9, 0xfffffffc)] { + sim.modify(|io| io.set(a, input)).unwrap(); + assert_eq!(sim.get(comb), expected.into()); + assert_eq!(sim.get(narrow), expected.into()); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(captured), expected.into()); + let message = if input == 7 { + b"wide=3.50 narrow=3.50".as_slice() + } else { + b"wide=-3.50 narrow=-3.50".as_slice() + }; + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: message.to_vec(), + }], + ); + } + return; + } + + let source = r#" + module Top(clk: input clock, a: input i32, comb: output i32, + narrow: output i32, captured: output i32) { + assign comb = ((a as f64) / 2.0) as i32; + assign narrow = ((a as f32) / (2 as f32)) as i32; + always_ff (clk) { + captured = ((a as f64) / 2.0) as i32; + $display("wide=%.2f narrow=%.2f", (a as f64) / 2.0, + (a as f32) / (2 as f32)); + } + } + "#; + let directory = tempfile::tempdir().unwrap(); + let image_path = directory.path().join("floating.native-image"); + Simulator::builder(source, "Top") + .compile_native() + .unwrap() + .write_image(&image_path) + .unwrap(); + // Exec a new copy of the test binary so ASLR and runtime helper addresses + // are independent of the process that compiled and serialized the code. + let current = std::thread::current(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + current.name().expect("named test thread"), + "--test-threads=1", + "--nocapture", + ]) + .env(IMAGE_PATH, &image_path) + .output() + .unwrap(); + assert!( + output.status.success(), + "fresh-process native image execution failed: {}\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index b8783be3342..f8903b4d944 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -655,6 +655,25 @@ fn native_program_image_rejects_corrupt_appended_payload() { ); } +/// Version 20 requires the runtime-resolved floating-point helper table prefix. +#[test] +fn native_program_image_rejects_v19_before_loading_float_helper_abi() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&19u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(19)) + )); +} + /// Version 17 adds synchronous host requests to the runtime metadata. #[test] fn native_program_image_rejects_v16_before_decoding_host_request_schema() { diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index eae5a3c8257..087c4277673 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -217,3 +217,6 @@ fn simulates_systemverilog_always_ff() { sim.tick(clk).unwrap(); assert_eq!(sim.get(q), 1u8.into()); } + +#[path = "frontends/systemverilog/floating_point.rs"] +mod floating_point; diff --git a/crates/celox/tests/test_utils/suite.rs b/crates/celox/tests/test_utils/suite.rs index daa7d61dbc7..392cfc6e09d 100644 --- a/crates/celox/tests/test_utils/suite.rs +++ b/crates/celox/tests/test_utils/suite.rs @@ -36,6 +36,24 @@ impl Backend for CeloxBackend { self.0.eval_comb().map_err(Into::into) } + fn take_output(&mut self) -> Result> { + let mut output = Vec::new(); + for event in self.0.drain_runtime_events() { + match event { + celox::RuntimeEvent::Display { message } => { + output.extend_from_slice(&message); + output.push(b'\n'); + } + celox::RuntimeEvent::Write { message } => output.extend_from_slice(&message), + celox::RuntimeEvent::Missed { count } => { + return Err(format!("{count} runtime events were missed").into()); + } + _ => (), + } + } + Ok(output) + } + fn run_testbench(&mut self) -> Result<()> { let program = celox::testbench::compile_initial_testbench(&self.0) .ok_or("testbench program was not compiled")?; diff --git a/crates/celox/tests/unsupported_value_types.rs b/crates/celox/tests/unsupported_value_types.rs index eae0216b814..9443d02f6aa 100644 --- a/crates/celox/tests/unsupported_value_types.rs +++ b/crates/celox/tests/unsupported_value_types.rs @@ -1,6 +1,4 @@ -//! Non-constant `string` values in RTL and operations on f32/f64 values are -//! rejected until Celox represents them (#1400, #1401). Constants folded by -//! the analyzer and plain floating-point copies keep working. +//! Unsupported string/float diagnostics and regressions for supported scalar floats. use celox::{ParserError, Simulator, SimulatorErrorKind}; #[track_caller] @@ -22,7 +20,6 @@ fn assert_unsupported(code: &str, issue: u32, feature: &str) { } const STRING: u32 = 1400; -const FLOAT: u32 = 1401; #[test] fn rtl_string_variable_assignment_is_rejected() { @@ -128,107 +125,53 @@ fn testbench_strings_are_accepted() { } #[test] -fn rtl_float_arithmetic_is_rejected() { - assert_unsupported( - r#" - module Top (a: input f64, b: input f64, c: output f64) { - assign c = a + b; - } - "#, - FLOAT, - "floating-point operation", - ); -} - -#[test] -fn rtl_float_comparison_is_rejected() { - assert_unsupported( - r#" - module Top (a: input f64, o: output logic) { - assign o = a == 1.0; - } - "#, - FLOAT, - "floating-point operation", - ); -} - -#[test] -fn float_to_integer_cast_is_rejected() { - assert_unsupported( - r#" - module Top (a: input f64, o: output u32) { - assign o = a as u32; - } - "#, - FLOAT, - "floating-point conversion", - ); -} - -#[test] -fn f32_to_f64_cast_is_rejected() { - assert_unsupported( - r#" - module Top (a: input f32, o: output f64) { - assign o = a as f64; - } - "#, - FLOAT, - "floating-point conversion", - ); -} - -#[test] -fn implicit_integer_to_float_assignment_is_rejected() { - // Even a constant is stored as its integer bits, not as 3.0. - assert_unsupported( +fn scalar_float_operations_are_supported() { + let mut sim = Simulator::builder( r#" - module Top (o: output f64) { - assign o = 3; + module Top (a: input f64, b: input f32, sum: output f64, + equal: output logic, rounded: output u32, constant: output f64) { + assign sum = a + (b as f64); + assign equal = a == 1.5; + assign rounded = a as u32; + assign constant = 3; } "#, - FLOAT, - "floating-point conversion", - ); -} - -#[test] -fn float_port_connected_to_integer_is_rejected() { - assert_unsupported( - r#" - module Child (i: input f64, o: output f64) { - assign o = i; - } - module Top (a: input u32, o: output f64) { - inst u: Child (i: a, o); - } - "#, - FLOAT, - "floating-point conversion", - ); + "Top", + ) + .build() + .unwrap(); + let a = sim.signal("a"); + let b = sim.signal("b"); + sim.modify(|io| { + io.set(a, 1.5f64.to_bits()); + io.set(b, 2.25f32.to_bits()); + }) + .unwrap(); + assert_eq!(sim.get(sim.signal("sum")), 3.75f64.to_bits().into()); + assert_eq!(sim.get(sim.signal("equal")), 1u32.into()); + assert_eq!(sim.get(sim.signal("rounded")), 2u32.into()); + assert_eq!(sim.get(sim.signal("constant")), 3.0f64.to_bits().into()); } #[test] -fn ff_float_condition_is_rejected() { - assert_unsupported( +fn integer_connected_to_float_input_is_converted() { + let mut sim = Simulator::builder( r#" - module Top (clk: input clock, a: input f64, o: output logic) { - always_ff (clk) { - if a <: 0.5 { - o = 1; - } - } - } + module Child (i: input f64, o: output f64) { assign o = i; } + module Top (a: input u32, o: output f64) { inst u: Child (i: a, o); } "#, - FLOAT, - "floating-point operation", - ); + "Top", + ) + .build() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 3u32)).unwrap(); + assert_eq!(sim.get(sim.signal("o")), 3.0f64.to_bits().into()); } #[test] -fn testbench_float_arithmetic_is_rejected() { - assert_unsupported( +fn testbench_float_arithmetic_is_supported() { + let result = Simulator::builder( r#" #[test(Top)] module Top { @@ -237,31 +180,39 @@ fn testbench_float_arithmetic_is_rejected() { initial { a = 1.5; c = a * 2.0; + $assert(c == 3.0); $finish(); } } "#, - FLOAT, - "floating-point operation", - ); + "Top", + ) + .run_test_detailed() + .unwrap(); + assert!(result.passed); } #[test] -fn float_display_is_rejected() { - assert_unsupported( +fn float_display_renders_numeric_values() { + let mut sim = Simulator::builder( r#" - #[test(Top)] - module Top { - var a: f64; - initial { - a = 1.5; - $display("%f", a); - $finish(); - } + module Top(clk: input clock, a: input f64) { + always_ff (clk) { $display("%f", a); } } "#, - FLOAT, - "floating-point formatting", + "Top", + ) + .build() + .unwrap(); + let a = sim.signal("a"); + let clk = sim.event("clk"); + sim.modify(|io| io.set(a, 1.5f64.to_bits())).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"1.500000".to_vec() + }] ); } diff --git a/crates/lydite-celox/src/bin/lydite-celox-suite.rs b/crates/lydite-celox/src/bin/lydite-celox-suite.rs index 69e7ead1bec..b7543e6e3ce 100644 --- a/crates/lydite-celox/src/bin/lydite-celox-suite.rs +++ b/crates/lydite-celox/src/bin/lydite-celox-suite.rs @@ -30,6 +30,16 @@ impl std::fmt::Display for FrontendUnsupported { } } impl std::error::Error for FrontendUnsupported {} +/// An explicit proof-model boundary, never an unexpected runtime/transport error. +#[derive(Debug)] +struct ProofBackendUnsupported(String); +impl std::fmt::Display for ProofBackendUnsupported { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for ProofBackendUnsupported {} + fn path(p: &SignalPath) -> Value { json!({"name":p.name,"instances":p.instances.iter().map(|i|json!({"name":i.name,"index":i.index})).collect::>()}) } @@ -39,6 +49,7 @@ impl ProofBackend { if let Err(error) = &result { if error.downcast_ref::().is_none() && error.downcast_ref::().is_none() + && error.downcast_ref::().is_none() { self.sticky.lock().unwrap().push(error.to_string()); } @@ -69,6 +80,11 @@ impl ProofBackend { self.rejection_message = Some(error.to_string()); return Err(FrontendUnsupported(error.to_string()).into()); } + if command == "compile" && reply["proof_backend_unsupported"] == true { + self.rejected = true; + self.rejection_message = Some(error.to_string()); + return Err(ProofBackendUnsupported(error.to_string()).into()); + } self.sticky.lock().unwrap().push(error.to_string()); return Err(error.to_string().into()); } diff --git a/crates/lydite-celox/src/lib.rs b/crates/lydite-celox/src/lib.rs index 4e3573be4b9..104acc87713 100644 --- a/crates/lydite-celox/src/lib.rs +++ b/crates/lydite-celox/src/lib.rs @@ -1323,7 +1323,7 @@ fn unary(name: UnaryOp, x: Term, w: u32, signed: bool) -> Res { } boolword(v, w) } - PopCount | CountLeadingZeros | CountTrailingZeros => { + PopCount | CountLeadingZeros | CountTrailingZeros | Float { .. } => { return Err(format!("unsupported symbolic unary {name}")); } }) diff --git a/crates/lydite-celox/src/tests.rs b/crates/lydite-celox/src/tests.rs index 1e57a685cc8..92f08e7a69d 100644 --- a/crates/lydite-celox/src/tests.rs +++ b/crates/lydite-celox/src/tests.rs @@ -3,6 +3,40 @@ use celox_design::{DomainKind, PortTypeKind}; use lydite_solver::finite::{Limits, SearchHint, Verdict, solve_with_hint}; use serde::de::DeserializeOwned; +#[test] +fn floating_point_operations_are_rejected_by_symbolic_bitvector_model() { + use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; + let precision = FloatPrecision::F64; + assert!( + unary( + UnaryOp::Float { + op: FloatUnaryOp::Neg, + precision, + }, + var("value", 64), + 64, + false, + ) + .unwrap_err() + .contains("unsupported symbolic unary") + ); + assert!( + binary( + BinaryOp::Float { + op: FloatBinaryOp::Add, + precision, + }, + var("left", 64), + var("right", 64), + 64, + false, + false, + ) + .unwrap_err() + .contains("unsupported symbolic binary") + ); +} + fn var(name: &str, w: u32) -> Term { ir::var(name.into(), Sort::Bv(w)) } diff --git a/docs/guide/type-conversion.md b/docs/guide/type-conversion.md index 38e2660b968..1b6b2ccd49b 100644 --- a/docs/guide/type-conversion.md +++ b/docs/guide/type-conversion.md @@ -10,11 +10,21 @@ This page describes how Veryl types are mapped to TypeScript types when `celox-t | `reset` | `bigint` | yes | | | `logic` | `bigint` | yes | | | `bit` | `bigint` | no | 2-state only | -| `f32` / `f64` | `bigint` | no | The IEEE 754 bit pattern. Values can be copied through ports, variables and flip-flops; arithmetic, comparisons, conversions and formatting of non-constant values are not supported yet ([#1401](https://github.com/celox-sim/celox/issues/1401)) | +| `f32` / `f64` | `bigint` | no | The IEEE 754 bit pattern. Scalar arithmetic, comparisons, f32/f64 precision conversions and integer conversions up to 64 bits are supported. Numeric display supports `%f`, `%e` and `%g`, including field widths and precision. Aggregate numeric conversions and integer conversions wider than 64 bits remain unsupported ([#1653](https://github.com/celox-sim/celox/issues/1653)) | | `string` | — | no | Non-constant strings are supported only in testbench code. RTL can use string literals, constants and parameters ([#1400](https://github.com/celox-sim/celox/issues/1400)) | All signal port values use `bigint` regardless of width. This ensures a consistent type across all signals and avoids type changes when signal widths are modified. +Floating-point to integer casts round to the nearest integer, with halfway +values rounded away from zero. `$rtoi` in SystemVerilog truncates instead. +Celox converts NaN and infinity to integer zero; finite results outside the +target integer range retain their low bits. These out-of-range choices should +not be used as portable behavior across simulators. + +Veryl analyzer 0.22 can mis-evaluate some floating-point constant expressions, +including negative `f32` casts and dependent constants or parameters. These +upstream limitations are tracked in [#1657](https://github.com/celox-sim/celox/issues/1657). + ## Direction and Mutability | Direction | Read | Write | TS Modifier | diff --git a/docs/ja/guide/type-conversion.md b/docs/ja/guide/type-conversion.md index 78ea5925034..a33f619835e 100644 --- a/docs/ja/guide/type-conversion.md +++ b/docs/ja/guide/type-conversion.md @@ -10,11 +10,20 @@ | `reset` | `bigint` | yes | | | `logic` | `bigint` | yes | | | `bit` | `bigint` | no | 2 値のみ | -| `f32` / `f64` | `bigint` | no | IEEE 754 のビットパターン。ポート・変数・フリップフロップでのコピーはできるが、定数でない値の演算・比較・変換・表示は未対応([#1401](https://github.com/celox-sim/celox/issues/1401)) | +| `f32` / `f64` | `bigint` | no | IEEE 754 のビットパターン。スカラーの算術演算・比較・f32/f64 間の変換・64 ビット以下の整数との変換に対応。`%f`・`%e`・`%g` による数値表示と幅・精度指定に対応。配列などの集約型の数値変換と64ビットを超える整数との変換は未対応([#1653](https://github.com/celox-sim/celox/issues/1653)) | | `string` | — | no | 定数でない string はテストベンチのコードでのみ使える。RTL では文字列リテラル・定数・パラメータを使える([#1400](https://github.com/celox-sim/celox/issues/1400)) | すべてのシグナルポート値はビット幅に関わらず `bigint` を使用します。これにより、すべてのシグナルで一貫した型が保証され、シグナル幅の変更時に型が変わることがなくなります。 +浮動小数点から整数へのキャストは最近接整数へ丸め、ちょうど中間の場合はゼロから遠ざかる方向へ丸めます。 +SystemVerilog の `$rtoi` は切り捨てです。Celox は NaN と無限大を整数のゼロに変換し、 +有限値が変換先の整数範囲を超えた場合は下位ビットを保持します。 +この範囲外の動作にはシミュレータ間の移植性を期待しないでください。 + +Veryl analyzer 0.22 には、負の `f32` へのキャストや定数・パラメータ間の依存を含む、 +一部の浮動小数点定数式を誤評価する問題があります。 +上流の制限として [#1657](https://github.com/celox-sim/celox/issues/1657) で追跡しています。 + ## 方向とミュータビリティ | 方向 | 読み取り | 書き込み | TS 修飾子 | diff --git a/lydite/conformance/veryl-proof/README.md b/lydite/conformance/veryl-proof/README.md index 5a5e80ed7ca..d7dec4c7c86 100644 --- a/lydite/conformance/veryl-proof/README.md +++ b/lydite/conformance/veryl-proof/README.md @@ -4,12 +4,12 @@ This job executes **every case of the in-tree reusable suite** (the Veryl suite of `crates/celox-test-suite`) with reads backed by finite proofs, compiled by the in-tree Celox frontend and the workspace Veryl. Its acceptance contract is the reviewed `coverage-manifest.json` plus `case-exceptions.json`: currently -**740 actual passes / 771** and 31 recorded exceptions. The raw test executable +**742 actual passes / 780** and 38 recorded exceptions. The raw test executable still exits 1 and reports the exceptions as failed. The coverage gate accepts each exception only with its exact recorded failure and design identities; it never changes an expectation into an expected compiler rejection. -The 740 passes comprise 729 observation-checked cases, three smoke-only cases and +The 742 passes comprise 731 observation-checked cases, three smoke-only cases and eight genuine expected compilation rejections. These are test-suite results, not a claim of unbounded equivalence, complete Veryl support, or verification of all possible stimuli. The independent narrow `../veryl` job is retained. @@ -116,16 +116,25 @@ and exact failure message: unsynthesizable (veryl-lang/veryl#2604). - `unsupported_by_proof_backend`: seventeen cases drive their design from a native Veryl testbench (`Backend::run_testbench`), which this backend does not run. -- `known_celox_failure`: seven cases that Celox's own tests also ignore on its +- `known_celox_failure`: eight cases that Celox's own tests also ignore on its native backends. Five depend on interface logic or nested instances that the Veryl analyzer IR drops; the others cover instance arrays and direct function - calls on selected interface array elements. + calls on selected interface array elements. The additional floating-point + integral-constant case exposes upstream Veryl negative f32 constant folding + (#1657), already ignored by Celox on every backend. - `celox_unsupported`: one case whose design the Celox frontend refuses with a typed `Unsupported` error (generic interface ports, #1088). The bridge reports it as `frontend_unsupported`, which is neither a source rejection nor a backend fault: a `CompilationError` case cannot pass through it, and the gate accepts it only under this exception kind. +- `proof_backend_unsupported`: designs containing scalar floating-point SIR + operations are explicitly refused before proof execution. Six floating-point + cases remain catalogued as unproved limitations. + This compile-time model refusal is neither a source rejection nor a verified + result. Its typed marker, exact diagnostic, zero reads and absence of a proof + directory are required; other backend and transport errors remain fatal. + A different failure, a legal-source mutation, or an unexpected success fails the stale exception, which must then be reviewed. There is no catch-all skip or allow-failure step. Eight independent negative fixtures pass only after real diff --git a/lydite/conformance/veryl-proof/case-exceptions.json b/lydite/conformance/veryl-proof/case-exceptions.json index 2a9ef809988..53e11350939 100644 --- a/lydite/conformance/veryl-proof/case-exceptions.json +++ b/lydite/conformance/veryl-proof/case-exceptions.json @@ -54,6 +54,41 @@ "reason": "Veryl rejects a negative constant for-range bound (InvalidForRange::NegativeBound).", "panic": "compile flip_flop::test_ff_constant_signed_bounds_in_unrolled_loops: analyzer-diagnostics:{\"detail\":\"[InvalidForRange { kind: NegativeBound, help: \\\"for-loop range bounds are elaborated as unsigned; rewrite the range to start at 0 and offset inside the body\\\", input: MultiSources { sources: [Source { path: \\\"test.veryl\\\", text: \\\"\\\\n module Top (\\\\n clk: input clock,\\\\n q_fwd: output logic<32>,\\\\n q_rev_last: output logic<32>\\\\n ) {\\\\n always_ff (clk) {\\\\n q_fwd = 0;\\\\n for i in (0 - 1)..=1 {\\\\n q_fwd += i as 32;\\\\n }\\\\n\\\\n q_rev_last = 32'hdead_beef;\\\\n for i in rev (0 - 1)..=1 {\\\\n q_rev_last = (i + 1) as 32;\\\\n }\\\\n }\\\\n }\\\\n \\\\n\\\", line_offset: 0 }] }, error_location: SourceSpan { offset: SourceOffset(224), length: 11 }, token_source: File { path: PathId(0), text: TextId(1) }, instance: None }, InvalidForRange { kind: NegativeBound, help: \\\"for-loop range bounds are elaborated as unsigned; rewrite the range to start at 0 and offset inside the body\\\", input: MultiSources { sources: [Source { path: \\\"test.veryl\\\", text: \\\"\\\\n module Top (\\\\n clk: input clock,\\\\n q_fwd: output logic<32>,\\\\n q_rev_last: output logic<32>\\\\n ) {\\\\n always_ff (clk) {\\\\n q_fwd = 0;\\\\n for i in (0 - 1)..=1 {\\\\n q_fwd += i as 32;\\\\n }\\\\n\\\\n q_rev_last = 32'hdead_beef;\\\\n for i in rev (0 - 1)..=1 {\\\\n q_rev_last = (i + 1) as 32;\\\\n }\\\\n }\\\\n }\\\\n \\\\n\\\", line_offset: 0 }] }, error_location: SourceSpan { offset: SourceOffset(368), length: 11 }, token_source: File { path: PathId(0), text: TextId(1) }, instance: None }]\",\"diagnostics\":[{\"code\":\"InvalidForRange\",\"kind\":\"NegativeBound\"},{\"code\":\"InvalidForRange\",\"kind\":\"NegativeBound\"}],\"stage\":\"analyzer\"}" }, + "floating_point::arithmetic_and_rounding": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::arithmetic_and_rounding: proof backend unsupported: floating-point SIR operations" + }, + "floating_point::f32_precision_and_conversion": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::f32_precision_and_conversion: proof backend unsupported: floating-point SIR operations" + }, + "floating_point::formatted_display_and_write": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::formatted_display_and_write: proof backend unsupported: floating-point SIR operations" + }, + "floating_point::integral_constants_from_float": { + "kind": "known_celox_failure", + "reason": "Upstream Veryl 0.22 misfolds negative f32 constants (#1657), producing integer SIR values -1 and 4 instead of -2 and 3. Celox ignores this exact shared case on every backend in crates/celox/tests/floating_point.rs; the proof executor correctly exposes the incorrect frontend constant.", + "panic": "floating_point::integral_constants_from_float at 132:3: assert_eq direct: expected 0xfffffffe, got 0xffffffff" + }, + "floating_point::scalar_port_and_function_conversions": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::scalar_port_and_function_conversions: proof backend unsupported: floating-point SIR operations" + }, + "floating_point::sequential_float": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::sequential_float: proof backend unsupported: floating-point SIR operations" + }, + "floating_point::unknown_integer_conversion": { + "kind": "proof_backend_unsupported", + "reason": "The finite proof backend models integer SIR only and explicitly refuses floating-point SIR operations before proof execution. Celox scalar FP execution is covered by the shared simulator cases; this case remains an unproved proof-backend limitation.", + "panic": "compile floating_point::unknown_integer_conversion: proof backend unsupported: floating-point SIR operations" + }, "hierarchical_assignment::disjoint_loop": { "kind": "unsupported_by_proof_backend", "reason": "The proof backend has no native testbench execution (Backend::run_testbench); the case drives its design from a Veryl testbench.", diff --git a/lydite/conformance/veryl-proof/coverage-manifest.json b/lydite/conformance/veryl-proof/coverage-manifest.json index 6790193a8eb..7d94b4b85fa 100644 --- a/lydite/conformance/veryl-proof/coverage-manifest.json +++ b/lydite/conformance/veryl-proof/coverage-manifest.json @@ -5553,6 +5553,164 @@ } ] }, + { + "case": "floating_point::arithmetic_and_rounding", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "e30a79c8d730d7a362431a30be3e86144567936310566a2a99609f986bb1c5e7" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "33c0c0bb77d7b2a6398fb59b1a5702f1c6561cff74a7b1aa07534b5934379b7c", + "protocol_sha256": "29159404aa60ad8efe6a9e58e42caedad8d45b00a5c11eac081b7ed7da771a3f", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, + { + "case": "floating_point::f32_precision_and_conversion", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "05448be18fd9c4e06cc3eeba3fff69033d7c0ce678474e52ae771bea52431663" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "b7b15af710c46becb2144cddbdb228ba586e1cf71fa4c32b159dc97bee1ce765", + "protocol_sha256": "3523cd48ae1efa3e896a37f65f4af8014e5255bed008654818b3d340b90ebadb", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, + { + "case": "floating_point::formatted_display_and_write", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "8d4ba813a509aee226ac4facc204b354c36c13a64dab3df830877132da9f1722" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "0bb4d8d3537ca4d54255f182b453bd9b40e684d468e989d197f966802eb142d1", + "protocol_sha256": "d934e8715ecee6e02f3092359418804f18e9b6c51b23cde7b63f01dcaca3f2f9", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, + { + "case": "floating_point::integral_constants_from_float", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "26c75e3be7c25762abd889280379e01e5c1a2a306833b444878d3a7ccf39754b" + }, + "disposition": "known_celox_failure", + "designs": [ + { + "design_sha256": "40abae4142f25784cff500ca49af7ac1a3a49202ba286996d8fce1479eb64ace", + "protocol_sha256": "917a8975f6b9fd66ccc3c790e7d852053063fb43f09929e48cda87de48c44bdf", + "reads": 1, + "commands": 3, + "operations": 1, + "diagnostic": null + } + ] + }, + { + "case": "floating_point::scalar_port_and_function_conversions", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "f33544d3049fbec21f690d1d17bb1b2192d167da8ca07c66041f4cb81c793ccf" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "4b93b99ab5205a7f4a6127a33abbf8eebc620e5667ff21e6313cbe8fab742dbd", + "protocol_sha256": "bf0c65eb5ed5d10ef0a85561583745409cc4fe0543d5334109016bcea6dec686", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, + { + "case": "floating_point::sequential_float", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "6e94cbc66114b0c6bcb49758456f96eff3d7edf2d43b616798eb68fc4ef33e63" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "b801c96fb3788b72a88bcc18f31879a369d9209fe50c1fe5a16722e74fc1a522", + "protocol_sha256": "6dafbc606592f23cec81d519b252c223851b6dcfdcdd275d42261639026027ed", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, + { + "case": "floating_point::unknown_integer_conversion", + "expectation": "Simulation", + "category": "Operators", + "source": { + "file": "src/veryl/cases/floating_point.vtest", + "script_sha256": "0d177a5196616eb8fa67fbd2538b3ef5633db16df4752b197d566937704e290a" + }, + "disposition": "proof_backend_unsupported", + "designs": [ + { + "design_sha256": "be07903d0c33d1fad87313fcac7ad79c522b066249acad18449295dc1274a96b", + "protocol_sha256": "d496d72f77c6e010d50f1086fb02fa09e397be1f8367a7c88649cc32b7daf1d1", + "reads": 0, + "commands": 2, + "operations": 0, + "diagnostic": { + "stage": "proof_backend", + "detail_sha256": "66c30dfb7dedd7b8288bc0218b8dad496e0558154f775a9b0327f5d9ed388c83" + } + } + ] + }, { "case": "for_loop_unroll::test_for_loop_unroll_break_in_always_ff", "expectation": "Simulation", @@ -12423,6 +12581,46 @@ } ] }, + { + "case": "struct_constructor::test_single_bit_aggregate_members", + "expectation": "Simulation", + "category": "Types", + "source": { + "file": "src/veryl/cases/struct_constructor.vtest", + "script_sha256": "c848e74e8360cabf67c3383b803c30f2b3dfe71101d6e11e71762b5ea58062ff" + }, + "disposition": "observation_verified", + "designs": [ + { + "design_sha256": "b28cb6b50fb627c38d37257663238fcc7251357eba078723b0520e707ae98cc4", + "protocol_sha256": "ed849f25149487d55f2824aff43061a9265a4b66600b39c2550c03dbdd5d57ed", + "reads": 4, + "commands": 12, + "operations": 2, + "diagnostic": null + } + ] + }, + { + "case": "struct_constructor::test_single_bit_struct_ff", + "expectation": "Simulation", + "category": "Types", + "source": { + "file": "src/veryl/cases/struct_constructor.vtest", + "script_sha256": "7f6b0b1d725fd3b5b6fee21779da0b4163e6be39319bbcdabb959c51bd1b32fd" + }, + "disposition": "observation_verified", + "designs": [ + { + "design_sha256": "ed7aee8f18662ff1afa275f786c6186b66d0d6253382b1236053071c051d241b", + "protocol_sha256": "6e97d458512398e458a81dc73e618280953ac48befada3b8e37cc555967589ae", + "reads": 3, + "commands": 15, + "operations": 6, + "diagnostic": null + } + ] + }, { "case": "struct_constructor::test_struct_constructor_comb_assignment", "expectation": "Simulation", diff --git a/lydite/conformance/veryl-proof/coverage.py b/lydite/conformance/veryl-proof/coverage.py index a8323afb259..128cfa4be62 100644 --- a/lydite/conformance/veryl-proof/coverage.py +++ b/lydite/conformance/veryl-proof/coverage.py @@ -7,7 +7,7 @@ # Veryl language restrictions, suite features the proof backend lacks, and # known Celox frontend failures that Celox's own tests also ignore, and # constructs the Celox frontend reports as typed Unsupported errors. -EXCEPTION_KINDS = {'veryl_language_restriction', 'unsupported_by_proof_backend', 'known_celox_failure', 'celox_unsupported'} +EXCEPTION_KINDS = {'veryl_language_restriction', 'unsupported_by_proof_backend', 'known_celox_failure', 'celox_unsupported', 'proof_backend_unsupported'} class GateError(ValueError): pass def require(test,message): if not test: raise GateError(message) @@ -66,7 +66,7 @@ def collect(raw,listed,exceptions,raw_exit): root=raw/name.replace('::','__');dirs=sorted(root.glob('design-*')) require(len(dirs)==row['designs'],name+': missing/extra designs') require(dirs or exception,name+': no design was compiled') - designs=[];all_reads=0;unsupported_designs=0 + designs=[];all_reads=0;unsupported_designs=0;proof_unsupported_designs=0 for design in dirs: record=read(design/'backend-result.json');rejected=record['compilation_rejected'] diag=diagnostic_identity(record['diagnostic']) @@ -76,6 +76,12 @@ def collect(raw,listed,exceptions,raw_exit): require(not rejected and record['status']=='failed' and record['reads']==0 and diag is not None,name+': malformed frontend Unsupported record') require(not (design/'proof').exists(),name+': unsupported design unexpectedly reached proof execution') unsupported_designs+=1 + if record.get('proof_backend_unsupported',False): + require(exception is not None and exception['kind']=='proof_backend_unsupported',name+': proof-model refusal needs a reviewed proof_backend_unsupported exception') + require(not rejected and record['status']=='failed' and record['reads']==0 and diag is not None and diag['stage']=='proof_backend',name+': malformed proof-model refusal record') + require(record['error']=='proof backend unsupported: floating-point SIR operations',name+': unexpected proof-model refusal') + require(not (design/'proof').exists(),name+': unsupported design unexpectedly reached proof execution') + proof_unsupported_designs+=1 if exception is None: rejection_expected=meta['expectation']=='CompilationError' require(record['status']==('failed' if rejection_expected else 'passed'),name+': backend close verdict') @@ -89,6 +95,8 @@ def collect(raw,listed,exceptions,raw_exit): count,controlled=check_queries(name,design,record);queries_total+=count;totals['negative_controls']+=controlled all_reads+=record['reads'] designs.append({key:record[key] for key in ('design_sha256','protocol_sha256','reads','commands','operations')}|{'diagnostic':diag}) + if exception and exception['kind']=='proof_backend_unsupported': + require(proof_unsupported_designs>0,name+': proof_backend_unsupported exception without a typed proof-model refusal') if exception and exception['kind']=='celox_unsupported': require(unsupported_designs>0,name+': celox_unsupported exception without a frontend Unsupported design') disposition=exception['kind'] if exception else 'expected_compilation_rejection' if meta['expectation']=='CompilationError' else 'observation_verified' if all_reads else 'smoke_only' diff --git a/lydite/conformance/veryl-proof/proof_backend.py b/lydite/conformance/veryl-proof/proof_backend.py index 436f6b1c4eb..e0925a5833d 100644 --- a/lydite/conformance/veryl-proof/proof_backend.py +++ b/lydite/conformance/veryl-proof/proof_backend.py @@ -9,6 +9,33 @@ ROOT=pathlib.Path(__file__).resolve().parent class Unsupported(ValueError):pass +def is_float_operation(value,kind): + if not isinstance(value,dict) or set(value)!={'Float'}:return False + body=value['Float'] + if not isinstance(body,dict) or set(body)!={'op','precision'} or body['precision'] not in ('F32','F64'):return False + op=body['op'] + if kind=='Binary':return isinstance(op,str) and op in ('Add','Sub','Mul','Div','Rem','Pow','Eq','Ne','Lt','Le','Gt','Ge') + if isinstance(op,str):return op in ('Neg','ToBool') + if not isinstance(op,dict) or len(op)!=1:return False + name,fields=next(iter(op.items())) + if not isinstance(fields,dict):return False + if name=='Convert':return set(fields)=={'to'} and fields['to'] in ('F32','F64') + expected={'width'} if name in ('FromSigned','FromUnsigned') else {'width','round'} + return name in ('FromSigned','FromUnsigned','ToSigned','ToUnsigned') and set(fields)==expected and type(fields['width']) is int and 1<=fields['width']<=64 and ('round' not in fields or type(fields['round']) is bool) + +def has_float_operations(value): + """Recognize only serialized SIR operations; malformed IR still fails normally.""" + if isinstance(value,dict): + for kind,args in value.items(): + if kind in ('Unary','Binary') and isinstance(args,list): + index=1 if kind=='Unary' else 2 + if len(args)==(3 if kind=='Unary' else 4) and is_float_operation(args[index],kind): + return True + if has_float_operations(args):return True + elif isinstance(value,list): + return any(has_float_operations(item) for item in value) + return False + def conjunction(xs): if not xs:return True if len(xs)==1:return xs[0] diff --git a/lydite/conformance/veryl-proof/server.py b/lydite/conformance/veryl-proof/server.py index d9015a1c035..28ede82a3c1 100644 --- a/lydite/conformance/veryl-proof/server.py +++ b/lydite/conformance/veryl-proof/server.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 """JSONL bridge for the unmodified Rust test suite's proof-backed Backend.""" import json,pathlib,subprocess,sys,os,hashlib -from proof_backend import Backend,ROOT +from proof_backend import Backend,ROOT,has_float_operations from four_state import FourStateBackend out=pathlib.Path(sys.argv[1]);out.mkdir(parents=True,exist_ok=False) -backend=None;sticky=None;reads=0;commands=[];compiled_rejection=False;frontend_unsupported=False;diagnostic=None;design_hash=None +backend=None;sticky=None;reads=0;commands=[];compiled_rejection=False;frontend_unsupported=False;proof_backend_unsupported=False;diagnostic=None;design_hash=None def send(value):print(json.dumps(value),flush=True) for line in sys.stdin: @@ -19,7 +19,7 @@ def send(value):print(json.dumps(value),flush=True) if backend and not sticky:backend.proof.feasible() except Exception as error:sticky=f'{type(error).__name__}: {error}' if backend:backend.close() - result={'status':'failed' if sticky else 'passed','error':sticky,'reads':reads,'commands':len(commands),'design_sha256':design_hash,'protocol_sha256':hashlib.sha256(json.dumps(commands,sort_keys=True,separators=(',',':')).encode()).hexdigest(),'compilation_rejected':compiled_rejection,'frontend_unsupported':frontend_unsupported,'diagnostic':diagnostic,'negative_control':backend.proof.negative_control if backend else None,'operations':backend.operations if backend else 0} + result={'status':'failed' if sticky else 'passed','error':sticky,'reads':reads,'commands':len(commands),'design_sha256':design_hash,'protocol_sha256':hashlib.sha256(json.dumps(commands,sort_keys=True,separators=(',',':')).encode()).hexdigest(),'compilation_rejected':compiled_rejection,'frontend_unsupported':frontend_unsupported,'proof_backend_unsupported':proof_backend_unsupported,'diagnostic':diagnostic,'negative_control':backend.proof.negative_control if backend else None,'operations':backend.operations if backend else 0} (out/'backend-result.json').write_text(json.dumps(result,indent=2)+'\n');send(result);break if sticky:send({'error':sticky});continue try: @@ -44,6 +44,11 @@ def send(value):print(json.dumps(value),flush=True) sticky=message or 'compiler failed without diagnostics' send({'error':sticky,'compilation_rejected':rejection,'frontend_unsupported':frontend_unsupported});continue compiled=json.loads(process.stdout);(out/'scheduled-sir.json').write_text(process.stdout) + if has_float_operations(compiled): + proof_backend_unsupported=True + sticky='proof backend unsupported: floating-point SIR operations' + diagnostic={'stage':'proof_backend','detail':sticky} + send({'error':sticky,'proof_backend_unsupported':True});continue backend=(FourStateBackend if request['design']['four_state'] else Backend)(compiled,request['design']['four_state'],out/'proof') send({'status':'ready'}) elif command=='write': diff --git a/lydite/conformance/veryl-proof/tests/test_float_boundary.py b/lydite/conformance/veryl-proof/tests/test_float_boundary.py new file mode 100644 index 00000000000..a8794809e51 --- /dev/null +++ b/lydite/conformance/veryl-proof/tests/test_float_boundary.py @@ -0,0 +1,63 @@ +import json,os,pathlib,subprocess,tempfile,unittest +from proof_backend import has_float_operations +from coverage import collect,GateError +ROOT=pathlib.Path(__file__).resolve().parents[1] +BINARY=ROOT/'../../../target/debug/lydite-celox-suite' +MESSAGE='proof backend unsupported: floating-point SIR operations' +class FloatBoundaryTests(unittest.TestCase): + def test_recognizes_only_typed_float_operations(self): + op={'Float':{'op':'Add','precision':'F64'}} + instruction={'Binary':[1,2,op,3]} + self.assertTrue(has_float_operations({'blocks':[instruction]})) + self.assertTrue(has_float_operations({'Unary':[1,{'Float':{'op':{'ToSigned':{'width':32,'round':True}},'precision':'F32'}},2]})) + for bad in [None,{},'Float',{'Float':None},{'Float':{'op':'Unknown','precision':'F64'}},{'Float':{'op':'Add','precision':'invalid'}}]: + with self.subTest(bad=bad):self.assertFalse(has_float_operations({'Binary':[1,2,bad,3]})) + self.assertFalse(has_float_operations({'Binary':[1,2,'Add',3]})) + def test_coverage_requires_exact_typed_exception(self): + with tempfile.TemporaryDirectory() as temp: + raw=pathlib.Path(temp);name='floating_point::case';d=raw/'floating_point__case/design-1';d.mkdir(parents=True) + panic='compile '+name+': '+MESSAGE + row={'case':name,'status':'failed','expectation':'Simulation','errors':[],'panic':panic,'designs':1} + listed=[{'case':name,'expectation':'Simulation','category':'Test','script_identity':'fp script','source':{'file':'fp.vtest'}}] + record={'status':'failed','compilation_rejected':False,'proof_backend_unsupported':True,'error':MESSAGE,'reads':0,'operations':0,'commands':2,'design_sha256':'source','protocol_sha256':'flow','diagnostic':{'stage':'proof_backend','detail':MESSAGE}} + exception={name:{'kind':'proof_backend_unsupported','reason':'FP lacks a proof model','panic':panic}} + def save(): + (raw/'summary.json').write_text(json.dumps([row]));(d/'backend-result.json').write_text(json.dumps(record)) + save();actual,counts=collect(raw,listed,exception,1) + self.assertEqual(counts['actual_passes'],0);self.assertEqual(actual['cases'][0]['disposition'],'proof_backend_unsupported') + for label,exceptions in [('missing',{}),('wrong_kind',{name:dict(exception[name],kind='known_celox_failure')}),('wrong_message',{name:dict(exception[name],panic='other')})]: + with self.subTest(label=label),self.assertRaises(GateError):collect(raw,listed,exceptions,1) + for key,value in [('proof_backend_unsupported',False),('reads',1),('error','other failure')]: + old=record[key];record[key]=value;save() + with self.subTest(key=key),self.assertRaises(GateError):collect(raw,listed,exception,1) + record[key]=old + row['errors']=['broken pipe'];save() + with self.assertRaises(GateError):collect(raw,listed,exception,1) + row['errors']=[];save();(d/'proof').mkdir() + with self.assertRaises(GateError):collect(raw,listed,exception,1) + def test_malformed_float_is_still_a_backend_error(self): + with tempfile.TemporaryDirectory() as temp: + root=pathlib.Path(temp);compiler=root/'exporter' + compiler.write_text('#!/bin/sh\nprintf \'%s\\n\' \'{"units":[{"Binary":[1,2,{"Float":{"op":"invalid","precision":"F64"}},3]}]}\'\n') + compiler.chmod(0o700);out=root/'results' + run=subprocess.run([str(BINARY),str(out),'floating_point::arithmetic_and_rounding'],env=dict(os.environ,SIR_EXPORTER_BIN=str(compiler)),capture_output=True,text=True,timeout=30) + self.assertEqual(run.returncode,1) + row=json.loads((out/'summary.json').read_text())[0] + self.assertTrue(row['errors']) + record=json.loads((out/'floating_point__arithmetic_and_rounding/design-1/backend-result.json').read_text()) + self.assertFalse(record['proof_backend_unsupported']) + def test_compile_refusal_is_typed_and_has_no_proof(self): + with tempfile.TemporaryDirectory() as temp: + root=pathlib.Path(temp);compiler=root/'exporter' + compiler.write_text('#!/bin/sh\nprintf \'%s\\n\' \'{"units":[{"Binary":[1,2,{"Float":{"op":"Add","precision":"F64"}},3]}]}\'\n') + compiler.chmod(0o700);out=root/'results' + run=subprocess.run([str(BINARY),str(out),'floating_point::arithmetic_and_rounding'],env=dict(os.environ,SIR_EXPORTER_BIN=str(compiler)),capture_output=True,text=True,timeout=30) + self.assertEqual(run.returncode,1,run.stderr) + row=json.loads((out/'summary.json').read_text())[0] + self.assertEqual(row['errors'],[]);self.assertEqual(row['status'],'failed') + self.assertIn(MESSAGE,row['panic']) + design=out/'floating_point__arithmetic_and_rounding/design-1' + record=json.loads((design/'backend-result.json').read_text()) + self.assertTrue(record['proof_backend_unsupported']);self.assertFalse(record['compilation_rejected']) + self.assertEqual(record['reads'],0);self.assertFalse((design/'proof').exists()) +if __name__=='__main__':unittest.main() diff --git a/packages/celox/src/floating-point-addon.test.ts b/packages/celox/src/floating-point-addon.test.ts new file mode 100644 index 00000000000..20c02115685 --- /dev/null +++ b/packages/celox/src/floating-point-addon.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from "vitest"; +import { Simulation } from "./simulation.js"; +import { Simulator } from "./simulator.js"; + +test("the addon renders runtime floating-point assertion arguments numerically", () => { + const sim = Simulation.fromSource<{ + a: bigint; + b: bigint; + readonly sum: bigint; + }>( + `module Top(a: input f64, b: input f32, sum: output f64) { + always_comb { + sum = a + (b as f64); + $assert(a == 0.0, "a=%.2f b=%.1f sum=%.2f", a, b, a + (b as f64)); + } + }`, + "Top", + ); + try { + sim.dut.a = 0xbff8000000000000n; // -1.5 + sim.dut.b = 0x40100000n; // 2.25 + expect(() => sim.dut.sum).toThrow("a=-1.50 b=2.2 sum=0.75"); + } finally { + sim.dispose(); + } +}); + +test("the native addon preserves FP payloads and numeric conversions", () => { + const sim = Simulator.fromSource<{ + a: bigint; + b: bigint; + readonly sum: bigint; + readonly rounded: bigint; + }>( + `module Top(a: input f64, b: input f32, sum: output f64, rounded: output i32) { + assign sum = a + (b as f64); + assign rounded = a as i32; + }`, + "Top", + ); + try { + // Host ports retain their IEEE payload representation. + sim.dut.a = 0x3ff8000000000000n; // 1.5 + sim.dut.b = 0x40100000n; // 2.25 + expect(sim.dut.sum).toBe(0x400e000000000000n); // 3.75 + expect(sim.dut.rounded).toBe(2n); + sim.dut.a = 0xbff8000000000000n; // -1.5 + expect(sim.dut.sum).toBe(0x3fe8000000000000n); // 0.75 + expect(sim.dut.rounded).toBe(0xffff_fffen); + } finally { + sim.dispose(); + } +}); diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index e2e83c33628..aebda3d64a0 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -150,6 +150,8 @@ export interface WasmFrontendSimulatorHandle extends FrontendSimulatorHandleMetadata { initialMemoryBytes(): Uint8Array | number[]; combWasmBytes(): Uint8Array | number[]; + /** Internal floating-point helper for generated simulation modules. */ + evaluateFloat?(lhs: bigint, rhs: bigint, code: bigint): bigint; eventWasmBytes(name: string): Uint8Array | number[]; /** * Per event name, the derived domains its ticks and edges run, as JSON. diff --git a/packages/celox/src/wasm-bridge.test.ts b/packages/celox/src/wasm-bridge.test.ts index 7f6217f40eb..c9dabc20a5c 100644 --- a/packages/celox/src/wasm-bridge.test.ts +++ b/packages/celox/src/wasm-bridge.test.ts @@ -1,6 +1,10 @@ import { expect, expectTypeOf, test, vi } from "vitest"; import type { RawWasmSimulatorHandle } from "./wasm-bridge.js"; -import { isWasmHandle } from "./wasm-bridge.js"; +import { + createWasmSimulatorBridge, + createWasmSimulatorBridgeAsync, + isWasmHandle, +} from "./wasm-bridge.js"; test("narrows an unknown frontend handle to the WASM contract", () => { const handle: unknown = { @@ -23,3 +27,59 @@ test("narrows an unknown frontend handle to the WASM contract", () => { expectTypeOf(handle).toEqualTypeOf(); expect(handle.initialMemoryBytes()).toEqual(new Uint8Array()); }); + +// A real WASM module calling the generated FP helper ABI, including a signed +// i64 payload. This exercises linking and bigint preservation in both bridges. +function floatHelperModule(): Uint8Array { + const text = (s: string) => [s.length, ...new TextEncoder().encode(s)]; + const section = (id: number, bytes: number[]) => [id, bytes.length, ...bytes]; + const body = [0, 0x42, 0x7f, 0x42, 2, 0x42, 3, 0x10, 0, 0x0b]; + return new Uint8Array([ + 0, + 0x61, + 0x73, + 0x6d, + 1, + 0, + 0, + 0, + ...section(1, [2, 0x60, 3, 0x7e, 0x7e, 0x7e, 1, 0x7e, 0x60, 0, 1, 0x7e]), + ...section(2, [ + 1, + ...text("env"), + ...text("celox_extern_4294967295"), + 0, + 0, + ]), + ...section(3, [1, 1]), + ...section(7, [1, ...text("run"), 0, 1]), + ...section(10, [1, body.length, ...body]), + ]); +} + +for (const [name, create] of [ + ["sync", createWasmSimulatorBridge], + ["async", createWasmSimulatorBridgeAsync], +] as const) { + test(`${name} bridge binds the compiler FP helper for comb and event modules`, async () => { + const evaluateFloat = vi.fn(() => 0n); + const raw: RawWasmSimulatorHandle = { + layoutJson: "{}", + eventsJson: '{"clk":0}', + hierarchyJson: "{}", + warningsJson: "[]", + stableSize: 8, + totalSize: 8, + dispose: vi.fn(), + initialMemoryBytes: () => new Uint8Array(8), + combWasmBytes: floatHelperModule, + eventWasmBytes: floatHelperModule, + evaluateFloat, + }; + const { handle } = await create(raw); + handle.evalComb(); + handle.tick(0); + expect(evaluateFloat).toHaveBeenCalledWith(-1n, 2n, 3n); + expect(evaluateFloat.mock.calls.length).toBeGreaterThanOrEqual(2); + }); +} diff --git a/packages/celox/src/wasm-bridge.ts b/packages/celox/src/wasm-bridge.ts index 38dd368825b..b5810fcaca4 100644 --- a/packages/celox/src/wasm-bridge.ts +++ b/packages/celox/src/wasm-bridge.ts @@ -91,6 +91,23 @@ export function isWasmHandle(handle: unknown): boolean { // Bridge // --------------------------------------------------------------------------- +/** Supply the same FP evaluator as the compiler that generated the module. */ +function wasmImports(raw: RawWasmSimulatorHandle, memory: WebAssembly.Memory) { + return { + env: { + memory, + celox_extern_4294967295(lhs: bigint, rhs: bigint, code: bigint): bigint { + if (!raw.evaluateFloat) { + throw new Error( + "This floating-point design requires an addon with evaluateFloat support", + ); + } + return raw.evaluateFloat(lhs, rhs, code); + }, + }, + }; +} + /** Checkpoint of a bridge-driven simulator: a copy of its design state. */ interface WasmCheckpoint { readonly stateSize: number; @@ -163,7 +180,7 @@ function wasmEdgeRunner( try { const bytes = new Uint8Array(raw.eventPhaseWasmBytes(name, kind)); const module = new WebAssembly.Module(bytes); - return run(new WebAssembly.Instance(module, { env: { memory } })); + return run(new WebAssembly.Instance(module, wasmImports(raw, memory))); } catch { return undefined; } @@ -222,9 +239,10 @@ export function createWasmSimulatorBridge( // Compile and instantiate comb WASM module (synchronous) const combBytes = new Uint8Array(raw.combWasmBytes()); const combModule = new WebAssembly.Module(combBytes); - const combInstance = new WebAssembly.Instance(combModule, { - env: { memory }, - }); + const combInstance = new WebAssembly.Instance( + combModule, + wasmImports(raw, memory), + ); // Parse events and instantiate per-event WASM modules const events: Record = JSON.parse(raw.eventsJson); @@ -234,7 +252,7 @@ export function createWasmSimulatorBridge( const bytes = eventBytes(raw, name); if (!bytes) continue; const mod = new WebAssembly.Module(bytes); - const inst = new WebAssembly.Instance(mod, { env: { memory } }); + const inst = new WebAssembly.Instance(mod, wasmImports(raw, memory)); eventInstances.set(id, inst); } @@ -300,9 +318,10 @@ export async function createWasmSimulatorBridgeAsync( // Compile comb module const combBytes = new Uint8Array(raw.combWasmBytes()); const combModule = await WebAssembly.compile(combBytes); - const combInstance = await WebAssembly.instantiate(combModule, { - env: { memory }, - }); + const combInstance = await WebAssembly.instantiate( + combModule, + wasmImports(raw, memory), + ); // Parse events and compile per-event modules const events: Record = JSON.parse(raw.eventsJson); @@ -314,7 +333,7 @@ export async function createWasmSimulatorBridgeAsync( const bytes = eventBytes(raw, name); if (!bytes) return; const mod = await WebAssembly.compile(bytes); - const inst = await WebAssembly.instantiate(mod, { env: { memory } }); + const inst = await WebAssembly.instantiate(mod, wasmImports(raw, memory)); eventInstances.set(id, inst); }), ); diff --git a/packages/playground/src/playground-simulator.ts b/packages/playground/src/playground-simulator.ts index 949185bd18f..1fd89e7e534 100644 --- a/packages/playground/src/playground-simulator.ts +++ b/packages/playground/src/playground-simulator.ts @@ -22,6 +22,7 @@ import { runPlaygroundTicks, writeSignalValue, } from "./playground-runtime-helpers.js"; +import { evaluateWasmFloat } from "./wasm-float.js"; /** A clock edge, as `Simulator.edges()` of `@celox-sim/celox` names it. */ export type PlaygroundClockEdge = "posedge" | "negedge"; @@ -70,7 +71,11 @@ class PlaygroundInstance { initializeFourStateMemory(memory, compiled.fourStateInitRegions); this.view = new DataView(memory.buffer); const instantiate = (module: WebAssembly.Module) => - runExport(new WebAssembly.Instance(module, { env: { memory } })); + runExport( + new WebAssembly.Instance(module, { + env: { memory, celox_extern_4294967295: evaluateWasmFloat }, + }), + ); this.comb = instantiate(compiled.combModule); const evalApply = new Map(); for (const [name, module] of Object.entries(compiled.eventModules)) { diff --git a/packages/playground/src/wasm-float.ts b/packages/playground/src/wasm-float.ts new file mode 100644 index 00000000000..241febf1e1a --- /dev/null +++ b/packages/playground/src/wasm-float.ts @@ -0,0 +1,35 @@ +/** Portable helpers for operations without a WebAssembly instruction. + * Modules cross the compiler worker boundary, so these cannot capture its handle. + * The opcode/precision encoding is defined by celox-sir/src/float.rs. + */ +export function evaluateWasmFloat( + lhs: bigint, + rhs: bigint, + code: bigint, +): bigint { + if (code !== 4n && code !== 5n && code !== 260n && code !== 261n) { + throw new Error(`Unsupported WebAssembly floating-point helper: ${code}`); + } + const wide = (code & 256n) !== 0n; + const view = new DataView(new ArrayBuffer(8)); + const decode = (bits: bigint) => { + view.setBigUint64(0, BigInt.asUintN(64, bits), true); + return wide ? view.getFloat64(0, true) : view.getFloat32(0, true); + }; + const a = decode(lhs); + const b = decode(rhs); + // libm pow treats 1**NaN and (+/-1)**(+/-Infinity) as 1. + const result = + (code & 255n) === 4n + ? a % b + : a === 1 || + (Math.abs(a) === 1 && !Number.isFinite(b) && !Number.isNaN(b)) + ? 1 + : a ** b; + if (wide) { + view.setFloat64(0, result, true); + return view.getBigInt64(0, true); + } + view.setFloat32(0, result, true); + return BigInt(view.getUint32(0, true)); +} diff --git a/packages/playground/test/wasm-float.test.ts b/packages/playground/test/wasm-float.test.ts new file mode 100644 index 00000000000..b194036e3ea --- /dev/null +++ b/packages/playground/test/wasm-float.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from "vitest"; +import { evaluateWasmFloat } from "../src/wasm-float"; +import { createPlaygroundSimulator } from "../src/playground-simulator"; + +for (const wide of [false, true]) { + const bits = (value: number) => { + const view = new DataView(new ArrayBuffer(8)); + if (wide) { + view.setFloat64(0, value, true); + return view.getBigInt64(0, true); + } + view.setFloat32(0, value, true); + return BigInt(view.getUint32(0, true)); + }; + const run = (a: number, b: number, opcode: bigint) => + evaluateWasmFloat(bits(a), bits(b), opcode | (wide ? 256n : 0n)); + test(`f${wide ? 64 : 32} power and remainder preserve bit payloads`, () => { + expect(run(2, 3, 5n)).toBe(bits(8)); + expect(run(-2, 3, 5n)).toBe(bits(-8)); + expect(run(1, Number.NaN, 5n)).toBe(bits(1)); + expect(run(-1, Number.POSITIVE_INFINITY, 5n)).toBe(bits(1)); + expect(run(-7.5, 2, 4n)).toBe(bits(-1.5)); + expect(run(-4, 2, 4n)).toBe(bits(-0)); + }); +} + +test("rejects helpers that should have been emitted as native WASM", () => { + expect(() => evaluateWasmFloat(0n, 0n, 34n)).toThrow(/Unsupported/); +}); + +test("transferred modules link the helper without a compiler handle", () => { + const text = (s: string) => [s.length, ...new TextEncoder().encode(s)]; + const section = (id: number, bytes: number[]) => [id, bytes.length, ...bytes]; + // run() calls f32 pow(0, 0) and drops its result. + const body = [0, 0x42, 0, 0x42, 0, 0x42, 5, 0x10, 0, 0x1a, 0x0b]; + const module = new WebAssembly.Module(new Uint8Array([ + 0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, + ...section(1, [2, 0x60, 3, 0x7e, 0x7e, 0x7e, 1, 0x7e, 0x60, 0, 0]), + ...section(2, [1, ...text("env"), ...text("celox_extern_4294967295"), 0, 0]), + ...section(3, [1, 1]), + ...section(7, [1, ...text("run"), 0, 1]), + ...section(10, [1, body.length, ...body]), + ])); + const sim = createPlaygroundSimulator({ + fourState: false, fourStateInitRegions: [], layout: {}, events: { clk: 0 }, + totalSize: 8, combModule: module, eventModules: { clk: module }, + phaseModules: {}, edgePlans: { fourState: false, events: {} }, + }); + expect(() => sim.tick()).not.toThrow(); +}); From f27f368637324c566606642da8e970b8b47e613d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 10:17:55 +0900 Subject: [PATCH 2/3] feat(cli): configure SV simulation timescales Taxi's BASE-R gearbox tests request 1ns/1fs, but the CLI had no way to pass that setting to compilation. Their 6.206206ns cocotb clocks failed with the source modules' 1ps simulation resolution. Add --timescale UNIT/PRECISION to run and vpi build, with matching root and target settings in celox.toml and a validated Rust builder option. The selected precision contributes to global scheduler resolution. Preserve explicit source units and delay rounding, finer source precision, and the separate mixed_timescale diagnostic policy. Keep 1ns/1ps when no option is supplied. Validation: - 17 project CLI tests, including precedence, invalid values, run, and attached-image precision. - 6 timing API tests across interpreter, Cranelift, native and WASM, plus mixed-language interface probes; 11 diagnostic-policy tests. - SV analyzer: 762 passed, 3 existing ignores; shared SV suite: 3242 passed, 90 existing ignores. - cocotb 2.1: all 5 integration tests passed; the new femtosecond-clock test also passed with 2.0.1. - Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1: 20 BASE-R cases passed at O1 with gearbox configurations 1/2 and USXGMII disabled; 220 other cases were filtered out. Original sources, parameters, and clock periods were retained. - Formatting, affected-crate all-target Clippy, and celox without default features passed. Change-Id: I6e723be119270564f5b71b08a7b83744d7eadba9 --- crates/celox-sv-analyzer/src/ast.rs | 2 +- .../celox-sv-analyzer/src/ast/interfaces.rs | 7 +- crates/celox-sv-analyzer/src/ast/packages.rs | 11 ++- .../celox-sv-analyzer/src/ast/timescales.rs | 35 +++++--- crates/celox-sv-analyzer/src/lib.rs | 6 +- crates/celox-sv-analyzer/src/parsed.rs | 3 +- crates/celox-vpi/src/bin/celox.rs | 2 + crates/celox-vpi/src/bin/celox/project.rs | 15 ++++ crates/celox-vpi/tests/cocotb_e2e.rs | 21 +++++ .../tests/fixtures/cocotb/test_fs_clock.py | 18 +++++ crates/celox-vpi/tests/project_cli.rs | 63 +++++++++++++++ crates/celox/src/diagnostic_policy.rs | 6 +- crates/celox/src/lib.rs | 3 + crates/celox/src/parser.rs | 6 +- crates/celox/src/simulator/builder.rs | 36 ++++++++- crates/celox/src/timescale.rs | 77 ++++++++++++++++++ crates/celox/tests/sv_timescale_options.rs | 80 +++++++++++++++++++ docs/guide/celox-toml.md | 15 ++++ docs/ja/guide/celox-toml.md | 15 ++++ 19 files changed, 389 insertions(+), 32 deletions(-) create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py create mode 100644 crates/celox/src/timescale.rs create mode 100644 crates/celox/tests/sv_timescale_options.rs diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 23794d3418f..6b4448933f1 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1428,7 +1428,7 @@ pub(crate) fn generated_time_declarations( sources: &[(&str, &std::path::Path)], roots: Option<&[&str]>, ) -> Result { - timescales::generated_source_declarations(sources, roots, false) + timescales::generated_source_declarations(sources, roots, crate::AnalysisOptions::default()) } const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000; diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index fabbf9e9a25..c7a6e0db247 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -89,7 +89,7 @@ pub fn interface_prototypes_with_options( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(), - options.allow_mixed_timescales, + options, )?) }; let trees = files @@ -97,9 +97,8 @@ pub fn interface_prototypes_with_options( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(); - let packages = - packages::Packages::analyze_with_options(&trees, None, options.allow_mixed_timescales) - .map_err(|error| error.with_warnings(source_warnings))?; + let packages = packages::Packages::analyze_with_options(&trees, None, options) + .map_err(|error| error.with_warnings(source_warnings))?; let package_warnings = packages.warnings().to_vec(); let mut used_names = design .modules diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index c32ab382d95..734d9669bc0 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -197,19 +197,19 @@ impl Packages { trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, ) -> Result { - Self::analyze_with_options(trees, roots, false) + Self::analyze_with_options(trees, roots, crate::AnalysisOptions::default()) } pub(crate) fn analyze_with_options( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Result { let mut warnings = Vec::new(); for (tree, _) in trees { super::warnings::append(&mut warnings, super::warnings::packages(tree)); } - match Self::analyze_with_roots_impl(trees, roots, allow_mixed_timescales) { + match Self::analyze_with_roots_impl(trees, roots, options) { Ok(packages) => Ok(packages.with_warnings(warnings)), Err(error) => Err(error.with_warnings(warnings)), } @@ -218,10 +218,9 @@ impl Packages { fn analyze_with_roots_impl( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Result { - let mut timescales = - timescales::Timescales::collect_with_options(trees, allow_mixed_timescales)?; + let mut timescales = timescales::Timescales::collect_with_options(trees, options)?; if let Some(roots) = roots { timescales.select_roots(roots); } diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 4b04f9a5316..6a2096d3e65 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -107,7 +107,7 @@ pub(super) struct Timescales { instantiated: HashSet, roots: Option>, specified: [u8; 2], - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, } /// Time-query state owned by one analysis, shared explicitly by nested scopes. @@ -361,7 +361,7 @@ fn time_declarations(unit: Option, precision: Option) -> String { pub(crate) fn generated_source_declarations( sources: &[(&str, &Path)], roots: Option<&[&str]>, - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Converted { let trees = sources .iter() @@ -372,7 +372,7 @@ pub(crate) fn generated_source_declarations( .iter() .map(|(tree, path)| (tree, *path)) .collect::>(), - allow_mixed_timescales, + options, )?; if let Some(roots) = roots { scales.select_roots(roots); @@ -516,13 +516,12 @@ impl Timescales { self.precision.unwrap_or(DEFAULT.precision) } fn including_tree(&self, tree: &SyntaxTree) -> Converted { - let local = - Self::collect_with_options(&[(tree, Path::new(""))], self.allow_mixed_timescales)?; + let local = Self::collect_with_options(&[(tree, Path::new(""))], self.options)?; let specified = [ self.specified[0] | local.specified[0], self.specified[1] | local.specified[1], ]; - if specified.contains(&3) && !self.allow_mixed_timescales { + if specified.contains(&3) && !self.options.allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); @@ -577,17 +576,29 @@ impl Timescales { #[cfg(test)] pub(super) fn collect(trees: &[(&SyntaxTree, &Path)]) -> Converted { - Self::collect_with_options(trees, false) + Self::collect_with_options(trees, crate::AnalysisOptions::default()) } pub(super) fn collect_with_options( trees: &[(&SyntaxTree, &Path)], - allow_mixed_timescales: bool, + options: crate::AnalysisOptions, ) -> Converted { #[cfg(test)] COLLECTIONS.with(|count| count.set(count.get() + 1)); + let default = match options.default_timescale { + Some((unit, precision)) + if (-15..=2).contains(&unit) + && (-15..=2).contains(&precision) + && precision <= unit => + { + Scale { unit, precision } + } + Some(_) => return Err(unsupported("invalid default time unit or precision")), + None => DEFAULT, + }; let mut design = Self { - allow_mixed_timescales, + precision: options.default_timescale.map(|(_, precision)| precision), + options, ..Self::default() }; // Each bit records whether a design element uses a default (1) or an @@ -686,8 +697,8 @@ impl Timescales { } directives.sort_by_key(|(at, _)| *at); let unit = Scale { - unit: unit_decl.0.unwrap_or(DEFAULT.unit), - precision: unit_decl.1.unwrap_or(DEFAULT.precision), + unit: unit_decl.0.unwrap_or(default.unit), + precision: unit_decl.1.unwrap_or(default.precision), }; if unit.precision > unit.unit { return Err(unsupported("timeprecision coarser than timeunit")); @@ -740,7 +751,7 @@ impl Timescales { }), ); } - if specified.contains(&3) && !allow_mixed_timescales { + if specified.contains(&3) && !options.allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index a9deafc2c07..b1a6961fb1a 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -44,10 +44,12 @@ pub use parsed::ParsedSource; /// simulator's two-state/four-state mode is known. pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; -/// Options for recoverable language compatibility checks. +/// Language compatibility checks and implementation-defined timing defaults. #[derive(Debug, Clone, Copy, Default)] pub struct AnalysisOptions { pub allow_mixed_timescales: bool, + /// Default unit/precision exponents; precision also bounds global resolution. + pub default_timescale: Option<(i32, i32)>, } /// Errors reported by the SystemVerilog analyzer. @@ -246,7 +248,7 @@ pub fn generated_time_declarations_with_options( roots: Option<&[&str]>, options: AnalysisOptions, ) -> Result { - ast::timescales::generated_source_declarations(sources, roots, options.allow_mixed_timescales) + ast::timescales::generated_source_declarations(sources, roots, options) } /// Parse and analyze a SystemVerilog source string. diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index fb1b1d798df..300a5369603 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -130,8 +130,7 @@ impl ParsedSource { } } } - let mut packages = - Packages::analyze_with_options(&trees, roots, options.allow_mixed_timescales)?; + let mut packages = Packages::analyze_with_options(&trees, roots, options)?; packages.interface_names = design_units .into_iter() .filter_map(|(name, kind)| { diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 46d2a3882eb..399a7fd538a 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -160,6 +160,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) + .sv_timescale(arguments.design.timescale) .signal_access(arguments.design.signal_access.clone()); let builder = arguments.design.apply_parameters(builder); let max_steps = if arguments.execution.unlimited { @@ -405,6 +406,7 @@ fn compile_native_design(design: &Design) -> Result let builder = celox::Simulator::from_sv_sources(refs, &design.top) .four_state(design.four_state.unwrap_or(false)) .diagnostic_policy(design.diagnostics.clone()) + .sv_timescale(design.timescale) .signal_access(design.signal_access.clone()) .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); let simulator = design diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index f3082b12cb5..99fa3b8341b 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -18,6 +18,9 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Default SV UNIT/PRECISION and global scheduler resolution, e.g. 1ns/1fs. + #[arg(long, value_name = "UNIT/PRECISION")] + timescale: Option, /// Use two-state simulation, resolving X/Z to zero. #[arg(long, conflicts_with = "four_state")] two_state: bool, @@ -102,6 +105,7 @@ struct Manifest { top: Option, opt_level: Option, four_state: Option, + timescale: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -135,6 +139,7 @@ struct Target { top: Option, opt_level: Option, four_state: Option, + timescale: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -152,6 +157,7 @@ pub(super) struct Design { pub top: String, pub opt_level: Option, pub four_state: Option, + pub timescale: Option, pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -281,6 +287,7 @@ impl DesignArgs { design.diagnostics = config.diagnostics.clone(); design.top = config.top.clone().unwrap_or_default(); let mut opt_level = config.opt_level.as_deref(); + let mut timescale = config.timescale.as_deref(); design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); @@ -300,6 +307,7 @@ impl DesignArgs { design.top.clone_from(top); } opt_level = target.opt_level.as_deref().or(opt_level); + timescale = target.timescale.as_deref().or(timescale); if let Some(paths) = &target.live_signals { design.signal_access.live_signals.clone_from(paths); } @@ -309,6 +317,7 @@ impl DesignArgs { design.max_steps = target.max_steps.or(design.max_steps); design.four_state = target.four_state.or(design.four_state); } + design.timescale = timescale.map(str::parse).transpose()?; design.opt_level = opt_level .map(|value| { celox::OptLevel::parse(value).ok_or_else(|| { @@ -334,6 +343,9 @@ impl DesignArgs { } })); design.opt_level = self.opt_level.or(design.opt_level); + if let Some(timescale) = self.timescale { + design.timescale = Some(timescale.parse()?); + } if self.two_state { design.four_state = Some(false); } @@ -390,6 +402,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && design.timescale.is_some() { + return Err("timescale requires SystemVerilog sources".into()); + } if !design.is_sv() && !design.sv_parameters.is_empty() { return Err("SV parameter literals require .sv/.v sources".to_string()); } diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index d2049d78e88..2e41b9b75ca 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -102,7 +102,27 @@ fn cocotb_observes_edges_before_nonblocking_updates() { check_cocotb_native_design(&["edge_phase.sv"], "test_edge_phase", "edge_precedes_nba"); } +#[test] +#[ignore = "requires a cocotb installation; CI runs this test explicitly"] +fn cocotb_accepts_femtosecond_clock_periods() { + check_cocotb_native_design_with_options( + &["edge_phase.sv"], + "test_fs_clock", + "femtosecond_clock", + &["--timescale", "1ns/1fs"], + ); +} + fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { + check_cocotb_native_design_with_options(source, module, filter, &[]); +} + +fn check_cocotb_native_design_with_options( + source: &[&str], + module: &str, + filter: &str, + options: &[&str], +) { let python = env::var_os("CELOX_COCOTB_PYTHON") .expect("CELOX_COCOTB_PYTHON must name the cocotb Python interpreter"); let python = python.to_string_lossy().into_owned(); @@ -115,6 +135,7 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { .arg("vpi") .arg("build") .args(source.iter().map(|path| fixture.join(path))) + .args(options) .args(["--top", "Top", "--output"]) .arg(&executable) .output() diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py b/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py new file mode 100644 index 00000000000..4d96c8c5a0d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py @@ -0,0 +1,18 @@ +"""The original 1ps SV scope can be driven by a 1fs-resolution testbench.""" +import cocotb +from cocotb.clock import Clock +from cocotb.triggers import RisingEdge, Timer +from cocotb.utils import get_sim_time + + +@cocotb.test() +async def femtosecond_clock(dut): + dut.d.value = 1 + clock = Clock(dut.clk, 6.206206, unit="ns") + cocotb.start_soon(clock.start()) + await RisingEdge(dut.clk) + first = get_sim_time(unit="fs") + await RisingEdge(dut.clk) + assert get_sim_time(unit="fs") - first == 6206206 + await Timer(1, unit="fs") + assert int(dut.q.value) == 1 diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index 06be274810f..d1b03347042 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -811,3 +811,66 @@ fn sv_cli_defaults_to_two_state_for_run_and_native_images() { let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); assert!(!instance.four_state()); } + +#[cfg(feature = "systemverilog")] +#[test] +fn timescale_reaches_run_and_native_images_with_target_and_cli_precedence() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#" +`timescale 1ns/1ps +module Top(input bit clk, output bit q); + always_ff @(posedge clk) q <= !q; + initial begin + $display("SCALE %0d %0d", $timeprecision(), $timeprecision($root)); + #1ns $finish; + end +endmodule +"#, + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" +sources = ["top.sv"] +top = "Top" +timescale = "1ns/10fs" +[targets.fine] +timescale = "1ns/1fs" +"#, + ) + .unwrap(); + for (options, precision) in [ + (vec![], -14), + (vec!["--target", "fine"], -15), + (vec!["--target", "fine", "--timescale", "10ns/100fs"], -13), + (vec!["--timescale", "1ns/10ps"], -12), + ] { + let output = invoke(root.path(), &[vec!["run"], options.clone()].concat()); + success(&output); + assert!( + String::from_utf8_lossy(&output.stdout).contains(&format!("SCALE -12 {precision}")), + "{output:?}" + ); + success(&invoke( + root.path(), + &[vec!["vpi", "build", "-o", "sim"], options].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + // Safety: the test compiled this trusted runtime itself. + let instance = + unsafe { celox::NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap(); + assert_eq!(instance.time_precision().exponent(), precision); + } + rejected( + &invoke(root.path(), &["run", "--timescale", "1ps/1ns"]), + "invalid timescale", + ); + fs::write( + root.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\ntimescale='1ns/2fs'", + ) + .unwrap(); + rejected(&invoke(root.path(), &["run"]), "invalid timescale"); +} diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index 181e0a112e6..c09f126e789 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -83,9 +83,13 @@ impl DiagnosticPolicy { } #[cfg(feature = "systemverilog")] - pub(crate) fn sv_options(&self) -> celox_frontend_sv::AnalysisOptions { + pub(crate) fn sv_options( + &self, + timescale: Option, + ) -> celox_frontend_sv::AnalysisOptions { celox_frontend_sv::AnalysisOptions { allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, + default_timescale: timescale.map(|scale| (scale.unit, scale.precision)), } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 364e49bfa1c..bebe2cb78c9 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -232,3 +232,6 @@ pub use diagnostic_policy::{DiagnosticLevel, DiagnosticPolicy}; mod signal_access; pub use signal_access::SignalAccessOptions; + +mod timescale; +pub use timescale::SvTimescale; diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 36c5b0bc558..77cac6a231b 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -590,6 +590,7 @@ pub fn parse_sv( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -610,7 +611,7 @@ pub fn parse_sv( &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), force_signals, ) .map_err(|error| match error { @@ -685,6 +686,7 @@ pub fn parse_mixed( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -834,7 +836,7 @@ pub fn parse_mixed( sv_top_parameters, &requests, &mut warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), ); let external = match external { Ok(external) => external, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 89059ee1f19..0bd27b87f59 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -305,6 +305,7 @@ fn analyze( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], preserve_element_storage_layout: bool, recover_comb_loops: bool, @@ -317,7 +318,7 @@ fn analyze( Vec, ) { #[cfg(not(feature = "systemverilog"))] - let _ = diagnostic_policy; + let _ = (diagnostic_policy, sv_timescale); symbol_table::clear(); attribute_table::clear(); @@ -399,7 +400,7 @@ fn analyze( sv_sources, Some(&references), &mut sv_probe_warnings, - diagnostic_policy.sv_options(), + diagnostic_policy.sv_options(sv_timescale), ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Analyzer(error) => parser::sv_analysis_error(error), @@ -605,6 +606,7 @@ fn analyze( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, preserve_element_storage_layout, testbench_random_seed, component_libraries, @@ -771,6 +773,7 @@ pub fn compile_to_sir_with_file_dependencies( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -887,6 +890,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -920,6 +924,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -980,6 +985,7 @@ fn compile_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1003,6 +1009,7 @@ fn compile_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1079,6 +1086,7 @@ pub fn compile_sv_to_sir( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, crate::backend::memory_layout::MemoryLayoutMode::Packed, &[], &[], @@ -1109,6 +1117,7 @@ fn compile_sv_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, force_signals: &[String], sv_param_literals: &[(String, String)], @@ -1152,6 +1161,7 @@ fn compile_sv_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, metadata.test.seed, component_libraries, @@ -1259,6 +1269,7 @@ pub fn compile_mixed_to_sir_with_file_dependencies( optimize_options, &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), + None, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -1292,6 +1303,7 @@ fn compile_mixed_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1315,6 +1327,7 @@ fn compile_mixed_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1378,6 +1391,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, + sv_timescale: Option, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1416,6 +1430,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1440,6 +1455,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1461,6 +1477,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, layout_mode, force_signals, sv_param_literals, @@ -1481,6 +1498,7 @@ fn compile_hdl_to_sir_with_layout_mode( optimize_options, diagnostics, diagnostic_policy, + sv_timescale, injected_manifests, layout_mode, recover_comb_loops, @@ -1534,6 +1552,8 @@ mod host { pub trace: crate::debug::TraceOptions, pub diagnostics: crate::RuntimeDiagnostics, pub diagnostic_policy: crate::DiagnosticPolicy, + /// Default SystemVerilog time unit and global scheduler precision. + pub sv_timescale: Option, /// When true, JIT-compiled functions emit trigger detection code for /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, @@ -1793,6 +1813,7 @@ mod host { trace: Default::default(), diagnostics: Default::default(), diagnostic_policy: Default::default(), + sv_timescale: None, emit_triggers: false, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), @@ -2220,6 +2241,13 @@ mod host { } /// Override recoverable compilation diagnostic severities. + /// Set default SV timing and contribute its precision to the scheduler. + /// Explicit source time declarations retain their units and rounding. + pub fn sv_timescale(mut self, timescale: Option) -> Self { + self.options.sv_timescale = timescale; + self + } + pub fn diagnostic_policy(mut self, policy: crate::DiagnosticPolicy) -> Self { self.options.diagnostic_policy = policy; self @@ -2589,6 +2617,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -2613,6 +2642,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3249,6 +3279,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3273,6 +3304,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, + self.options.sv_timescale, &injected_manifests, layout_mode, !self.options.native_force_support, diff --git a/crates/celox/src/timescale.rs b/crates/celox/src/timescale.rs new file mode 100644 index 00000000000..fdd1f47e68e --- /dev/null +++ b/crates/celox/src/timescale.rs @@ -0,0 +1,77 @@ +//! Simulation default time unit and scheduler precision. + +/// Default SV time unit/precision. Explicit source declarations take precedence; +/// the precision also contributes to the global scheduler resolution. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SvTimescale { + pub(crate) unit: i32, + pub(crate) precision: i32, +} + +impl std::str::FromStr for SvTimescale { + type Err = String; + + fn from_str(value: &str) -> Result { + fn exponent(value: &str) -> Option { + let value = value.trim(); + let split = value.find(|c: char| !c.is_ascii_digit())?; + let magnitude = match &value[..split] { + "1" => 0, + "10" => 1, + "100" => 2, + _ => return None, + }; + let unit = match &value[split..] { + "s" => 0, + "ms" => -3, + "us" => -6, + "ns" => -9, + "ps" => -12, + "fs" => -15, + _ => return None, + }; + Some(unit + magnitude) + } + let invalid = || { + format!( + "invalid timescale `{value}`: expected UNIT/PRECISION (1, 10, or 100 s/ms/us/ns/ps/fs), with precision no coarser than unit" + ) + }; + let (unit, precision) = value.split_once('/').ok_or_else(invalid)?; + let unit = exponent(unit).ok_or_else(invalid)?; + let precision = exponent(precision).ok_or_else(invalid)?; + if precision > unit { + return Err(invalid()); + } + Ok(Self { unit, precision }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn validates_time_magnitudes_units_and_precision_order() { + for (text, unit, precision) in [ + ("1ns/1fs", -9, -15), + ("100s / 10fs", 2, -14), + ("10ps/1ps", -11, -12), + ] { + assert_eq!( + text.parse::().unwrap(), + SvTimescale { unit, precision } + ); + } + for text in [ + "1ns", + "1ns/1ps/1fs", + "2ns/1fs", + "1ps/1ns", + "1ns/0fs", + "1ns/1as", + "1.0ns/1fs", + ] { + assert!(text.parse::().is_err(), "{text}"); + } + } +} diff --git a/crates/celox/tests/sv_timescale_options.rs b/crates/celox/tests/sv_timescale_options.rs new file mode 100644 index 00000000000..41c62323b46 --- /dev/null +++ b/crates/celox/tests/sv_timescale_options.rs @@ -0,0 +1,80 @@ +#![cfg(feature = "systemverilog")] +//! Celox's default timing configuration must preserve authored scope rounding. +use std::path::Path; + +macro_rules! timing { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let source = r#" +module Child(output bit value); + timeunit 1ns / 1ps; + initial begin value = 0; #1.5ps value = 1; end +endmodule +module Top(output bit default_value, explicit_value, queries); + Child child(explicit_value); + assign queries = ($timeunit() == -9) && ($timeprecision() == -15) + && ($timeprecision(child) == -12) && ($timeprecision($root) == -15); + initial begin default_value = 0; #1.5ps default_value = 1; end +endmodule +"#; + let mut policy = celox::DiagnosticPolicy::default(); + policy.set_override("mixed_timescale=allow").unwrap(); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("configured_timing.sv"))], + "Top", + ) + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .diagnostic_policy(policy) + .$backend() + .unwrap(); + sim.run_until(1499).unwrap(); + assert_eq!(sim.get(sim.signal("queries")), 1u8.into()); + assert_eq!(sim.get(sim.signal("default_value")), 0u8.into()); + sim.run_until(1500).unwrap(); + assert_eq!(sim.get(sim.signal("default_value")), 1u8.into()); + sim.run_until(1999).unwrap(); + assert_eq!(sim.get(sim.signal("explicit_value")), 0u8.into()); + sim.run_until(2000).unwrap(); + assert_eq!(sim.get(sim.signal("explicit_value")), 1u8.into()); + } + }; +} +timing!(interpreter, build_interpreter); +timing!(cranelift, build); +timing!(wasm, build_wasm); +#[cfg(target_arch = "x86_64")] +timing!(native, build_native); + +#[test] +fn configuring_defaults_does_not_relax_mixed_timescale_diagnostics() { + let source = "module Child; timeunit 1ns/1ps; endmodule module Top; Child child(); endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("mixed.sv"))], "Top") + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .build_interpreter() + .err() + .unwrap(); + assert!( + error + .to_string() + .contains("mixed explicit and default time"), + "{error}" + ); +} + +#[test] +fn mixed_language_interface_probes_receive_configured_timing() { + let veryl = "module Top(a: input logic<8>, y: output logic<8>) { inst bus: $sv::Bus; assign bus.req = a; assign y = bus.rsp; }"; + let bus = "interface Bus; logic [7:0] req, rsp; assign rsp = req + ($timeprecision($root) == -15); endinterface"; + let mut sim = celox::Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(bus, Path::new("bus.sv"))], + "Top", + ) + .sv_timescale(Some("1ns/1fs".parse().unwrap())) + .build_interpreter() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 97239f5edcc..7f26b211bcf 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -129,6 +129,21 @@ The Vite plugin picks up `test_veryl/` automatically and generates type definiti - The Vite plugin regenerates types for test sources on hot reload, just like for production sources. - `[simulation]` settings apply to every `Simulation.fromProject` / `Simulation.create` call within the project. A per-call `{ maxSteps }` option always takes precedence over the `celox.toml` value. + +### CLI SystemVerilog timing + +For `celox run` and `celox vpi build`, set `timescale = "1ns/1fs"` at the +manifest root or in `[targets.NAME]`. `--timescale 1ns/1fs` overrides the selected +target, which overrides the root setting. The default remains `1ns/1ps`. + +This sets the default time unit and precision for scopes without source timing +declarations. The configured precision also contributes to the global scheduler +resolution, so cocotb can schedule femtosecond clock periods even when an SV +module declares `1ns/1ps`. Explicit `timeunit`, `timeprecision`, and `` `timescale `` +settings retain their scope units and delay rounding. The global resolution is +the finest configured or declared precision. Values use magnitudes 1, 10, or 100 +and units `s`, `ms`, `us`, `ns`, `ps`, or `fs`; precision cannot be coarser than unit. + ### `[diagnostics]` Override individual compilation diagnostics by their displayed code: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index e50629a9358..afbe5a31c7b 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -117,6 +117,21 @@ Vite プラグインは `test_veryl/` を自動的に検出し、そこで宣言 - Vite プラグインは本番ソースと同様に、ホットリロード時にテストソースの型も再生成します。 - `[simulation]` の設定は、プロジェクト内の `Simulation.fromProject` / `Simulation.create` 呼び出しすべてに適用されます。呼び出し時に `{ maxSteps }` を指定すると、常に `celox.toml` の値より優先されます。 + +### CLI の SystemVerilog 時間設定 + +`celox run` と `celox vpi build` では、ルートまたは `[targets.NAME]` に +`timescale = "1ns/1fs"` を指定できます。優先順位は `--timescale 1ns/1fs`、 +選択ターゲット、ルート設定の順です。未指定時は従来どおり `1ns/1ps` です。 + +時間宣言のないスコープの既定単位・精度を設定し、指定した精度を全体の +スケジューラ精度にも反映します。SV モジュールが `1ns/1ps` を宣言していても、 +cocotb から fs 単位のクロックを駆動できます。明示された `timeunit`、 +`timeprecision`、`` `timescale `` によるスコープ内の単位と遅延の丸めは維持します。 +全体の精度は、設定とソース宣言のうち最も細かい値になります。値は倍率 +1・10・100 と単位 `s`・`ms`・`us`・`ns`・`ps`・`fs` を使い、精度を単位より +粗くする指定はエラーです。 + ### `[diagnostics]` 診断に表示されるコードを使って、コンパイル時の診断レベルを個別に変更できます。 From 388c2141216f902aa6afb8ebe8a2e459a86ffdfb Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:07:59 +0900 Subject: [PATCH 3/3] fix(sv): fill unbased parameter overrides to their declared width Overriding a 58-bit parameter with '1 through -G or the Rust builder retained only 32 one bits, corrupting Taxi LFSR initialization. Apply the declaration width and signedness after selecting the override, including the final override pass, before binding dependent parameters. Extend API and CLI coverage above 32 bits and check signed fills, dependent parameters, and wide X/Z overrides. Validation: - SV analyzer: 770 passed, 3 existing ignores. - Literal-parameter API regression passes on all four backend variants; project CLI suite: 17 passed. - Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1: original 58-bit scramble and descramble configurations pass at O1 with the original '1 argument and cocotb 2.0.1. - Formatting and all-target Clippy for the affected crates pass. Change-Id: If5f1b4a1bc351fcdacd025ea7d9d0829360d4b2c --- .../celox-sv-analyzer/src/ast/parameters.rs | 8 +++-- .../src/ast/parameters/tests.rs | 31 +++++++++++++++++++ crates/celox-vpi/tests/project_cli.rs | 4 +-- .../frontends/systemverilog/hierarchy.rs | 13 +++++--- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 8bd0afb46cf..77f6b969d1d 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -119,7 +119,11 @@ pub(super) fn apply_parameter_overrides( } for parameter in parameters { if let Some(value) = overrides.get(parameter.name()) { - parameter.value = Some(value.clone()); + parameter.value = normalize_unbased_unsized_parameter_value( + Some(value.clone()), + parameter.declared_width(), + parameter.declared_signed(), + ); } } Ok(()) @@ -431,7 +435,6 @@ pub(super) fn parameters_from_native_with_environment( } else { None }; - value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); // Apply overrides as each declaration is collected so later // parameter initializers (including casts) are evaluated from the // specialized values rather than defaults that will be replaced @@ -439,6 +442,7 @@ pub(super) fn parameters_from_native_with_environment( if !is_local && let Some(override_value) = parameter_overrides.get(&name) { value = Some(override_value.clone()); } + value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); if value .as_ref() .is_some_and(|expression| is_unbounded(expression, const_env)) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index a1ea6d0ef37..3ea1ba6bf94 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -1385,3 +1385,34 @@ fn logical_type_inference_requires_operand_types_outside_bounded_proofs() { }), ); } + +#[test] +fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() { + let tree = crate::source_tree::parse_scope_fixture( + "module Top #(parameter logic [57:0] FILL=0, \ + parameter logic signed [57:0] SIGNED_FILL=0, \ + parameter logic [57:0] COPY=FILL, parameter NEGATIVE=SIGNED_FILL < 0); endmodule", + Path::new("unbased_parameter_overrides.sv"), + ) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + for (literal, unsigned, signed) in [("'1", (1i128 << 58) - 1, -1), ("'0", 0, 0)] { + let overrides = ["FILL", "SIGNED_FILL"] + .into_iter() + .map(|name| (name.into(), ConstExpr::Literal(literal.into()))) + .collect(); + let mut parameters = + parameters_from_scope(&tree, &HashMap::default(), &HashMap::default(), &overrides) + .unwrap(); + for reapplied in [false, true] { + if reapplied { + apply_parameter_overrides(&mut parameters, &overrides).unwrap(); + } + let values = const_env_from_parameters(&tree.state, ¶meters); + assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}"); + assert_eq!(values["SIGNED_FILL"], signed); + assert_eq!(values["COPY"], unsigned); + assert_eq!(values["NEGATIVE"], i128::from(signed < 0)); + } + } +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index d1b03347042..43426385fbc 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -596,11 +596,11 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { let root = tempfile::tempdir().unwrap(); let source = r#" module Top #(parameter VENDOR="GENERIC", parameter NEG=3, - parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [64:0] WIDE=0, parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0)(output logic matched); assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) - && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (WIDE == 65'h10000000000000001) && (FILL == 58'h3ffffffffffffff) && (UNKNOWN === 4'b10xz); initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); $display("ok"); $finish; end diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index f1baf76a403..c1dc0f96413 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -368,12 +368,16 @@ sv_backends! { @setup { let source = r#" module Top #(parameter TEXT="default", parameter NEG=0, - parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, - parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0, + parameter logic [57:0] X=0, parameter logic [57:0] Z=0, + parameter logic [57:0] COPY=FILL)(output logic matched); assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) - && (FILL==12'hfff) && (UNKNOWN===4'b10xz) - && (WIDE==65'h10000000000000001) && (FINAL==7); + && (FILL==58'h3ffffffffffffff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7) + && (COPY==58'h3ffffffffffffff) + && (X===58'bx) && (Z===58'bz); endmodule "#; } @@ -383,6 +387,7 @@ sv_backends! { .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") .param_literal("WIDE", "65'h10000000000000001") .param_literal("FINAL", "-1").param("FINAL", 7) + .param_literal("X", "'x").param_literal("Z", "'z") .four_state(true).opt_level(celox::OptLevel::O2); assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); }