diff --git a/Cargo.lock b/Cargo.lock index d76de844ab8..9638a70c314 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -404,6 +404,7 @@ dependencies = [ "celox-frontend-sdk", "celox-frontend-sv", "celox-frontend-veryl", + "celox-heap", "celox-macros", "celox-runtime", "celox-sir", @@ -648,6 +649,13 @@ dependencies = [ "veryl-parser", ] +[[package]] +name = "celox-heap" +version = "0.11.0" +dependencies = [ + "fxhash", +] + [[package]] name = "celox-macros" version = "0.11.0" @@ -800,6 +808,7 @@ name = "celox-testbench" version = "0.11.0" dependencies = [ "celox-design", + "celox-heap", "num-bigint", "num-traits", "serde", diff --git a/Cargo.toml b/Cargo.toml index 853335b6b46..76c0db9690d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "crates/celox-frontend-sdk", "crates/celox-frontend-sv", "crates/celox-frontend-veryl", + "crates/celox-heap", "crates/celox-sir", "crates/celox-sir-opt", "crates/celox-slt", @@ -65,6 +66,7 @@ celox-frontend-core = { version = "=0.11.0", path = "crates/celox-frontend-c celox-frontend-sdk = { version = "=0.11.0", path = "crates/celox-frontend-sdk" } # x-release-please-version celox-frontend-sv = { version = "=0.11.0", path = "crates/celox-frontend-sv" } # x-release-please-version celox-frontend-veryl = { version = "=0.11.0", path = "crates/celox-frontend-veryl" } # x-release-please-version +celox-heap = { version = "=0.11.0", path = "crates/celox-heap" } # x-release-please-version celox-macros = { version = "=0.11.0", path = "crates/celox-macros" } # x-release-please-version celox-napi = { version = "=0.11.0", path = "crates/celox-napi" } # x-release-please-version celox-runtime = { version = "=0.11.0", path = "crates/celox-runtime" } # x-release-please-version diff --git a/crates/celox-backend-arm64/src/isel/extern_call.rs b/crates/celox-backend-arm64/src/isel/extern_call.rs index 0762769bb20..90275d538e4 100644 --- a/crates/celox-backend-arm64/src/isel/extern_call.rs +++ b/crates/celox-backend-arm64/src/isel/extern_call.rs @@ -167,3 +167,57 @@ pub(super) fn lower_float( }); define_extern_result(ctx, block, dst, result); } + +// Native FP operations keep the existing payload register/ABI convention. +pub(super) fn lower_native_float_binary( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + lhs: RegisterId, + rhs: RegisterId, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, +) -> bool { + if matches!( + op, + celox_sir::FloatBinaryOp::Rem | celox_sir::FloatBinaryOp::Pow + ) { + return false; + } + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::FloatBinary { + dst: result, + lhs: ctx.reg_map.get(lhs), + rhs: ctx.reg_map.get(rhs), + op, + precision, + }); + define_extern_result(ctx, block, dst, result); + true +} +pub(super) fn lower_native_float_unary( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + src: RegisterId, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, +) -> bool { + if !matches!( + op, + celox_sir::FloatUnaryOp::Neg + | celox_sir::FloatUnaryOp::ToBool + | celox_sir::FloatUnaryOp::Convert { .. } + ) { + return false; + } + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::FloatUnary { + dst: result, + src: ctx.reg_map.get(src), + op, + precision, + }); + define_extern_result(ctx, block, dst, result); + true +} diff --git a/crates/celox-backend-arm64/src/isel/instruction.rs b/crates/celox-backend-arm64/src/isel/instruction.rs index fc826bb6ca3..d29adb87c54 100644 --- a/crates/celox-backend-arm64/src/isel/instruction.rs +++ b/crates/celox-backend-arm64/src/isel/instruction.rs @@ -1993,6 +1993,11 @@ pub(super) fn lower_instruction( SIRInstruction::Binary(dst, lhs, op, rhs) => { if let BinaryOp::Float { op, precision } = op { + if extern_call::lower_native_float_binary( + ctx, block, *dst, *lhs, *rhs, *op, *precision, + ) { + return; + } extern_call::lower_float( ctx, block, @@ -2793,6 +2798,9 @@ pub(super) fn lower_instruction( SIRInstruction::Unary(dst, op, src) => { if let UnaryOp::Float { op, precision } = op { + if extern_call::lower_native_float_unary(ctx, block, *dst, *src, *op, *precision) { + return; + } extern_call::lower_float( ctx, block, diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 403ea737368..3456a2c8be1 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -1,3 +1,4 @@ +mod floating; mod partial_load; mod reductions; mod shifts; diff --git a/crates/celox-backend-arm64/src/isel/tests/floating.rs b/crates/celox-backend-arm64/src/isel/tests/floating.rs new file mode 100644 index 00000000000..6e8cea9c54b --- /dev/null +++ b/crates/celox-backend-arm64/src/isel/tests/floating.rs @@ -0,0 +1,223 @@ +use super::*; +use celox_sir::{FloatBinaryOp as F, FloatPrecision as P, FloatUnaryOp as U}; + +fn float_unit( + op: SIRInstruction, + precision: P, +) -> (ExecutionUnit, MemoryLayout) { + let absolute = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId::default(), + }; + let address = RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, absolute); + let mut unit = scalar_store_unit(address, false); + let width = match precision { + P::F32 => 32, + P::F64 => 64, + }; + for ty in unit.register_map.values_mut() { + *ty = RegisterType::Bit { + width, + signed: false, + }; + } + let result_width = match &op { + SIRInstruction::Binary( + _, + _, + BinaryOp::Float { + op: F::Eq | F::Ne | F::Lt | F::Le | F::Gt | F::Ge, + .. + }, + _, + ) + | SIRInstruction::Unary(_, UnaryOp::Float { op: U::ToBool, .. }, _) => 1, + SIRInstruction::Unary( + _, + UnaryOp::Float { + op: U::Convert { to: P::F32 }, + .. + }, + _, + ) => 32, + SIRInstruction::Unary( + _, + UnaryOp::Float { + op: U::Convert { to: P::F64 }, + .. + }, + _, + ) => 64, + _ => width, + }; + unit.register_map.insert( + RegisterId(2), + RegisterType::Bit { + width: result_width, + signed: false, + }, + ); + let block = unit.blocks.get_mut(&SirBlockId(0)).unwrap(); + block.instructions[0] = SIRInstruction::Imm( + RegisterId(0), + SIRValue::new(match precision { + P::F32 => 1.5f32.to_bits() as u64, + P::F64 => 1.5f64.to_bits(), + }), + ); + block.instructions[1] = SIRInstruction::Imm( + RegisterId(1), + SIRValue::new(match precision { + P::F32 => 2.0f32.to_bits() as u64, + P::F64 => 2.0f64.to_bits(), + }), + ); + block.instructions[2] = op; + block.instructions[3] = SIRInstruction::Store( + address, + SIROffset::Static(0), + result_width, + RegisterId(2), + Vec::new(), + Vec::new(), + ); + (unit, layout_for(absolute, 64, false)) +} + +#[test] +fn basic_float_operations_select_native_mir_and_emit_without_helpers() { + for precision in [P::F32, P::F64] { + for op in [ + F::Add, + F::Sub, + F::Mul, + F::Div, + F::Eq, + F::Ne, + F::Lt, + F::Le, + F::Gt, + F::Ge, + ] { + let (unit, layout) = float_unit( + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Float { op, precision }, + RegisterId(1), + ), + precision, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!( + mir.blocks.iter().flat_map(|b| &b.insts).any( + |i| matches!(i, MInst::FloatBinary { op: selected, .. } if *selected == op) + ) + ); + assert!( + !mir.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::CallExtern { .. })) + ); + let code = crate::scalar::emit_prepared_eu( + &unit, + &layout, + false, + "eval_comb", + false, + None, + || false, + ) + .unwrap(); + let opcode = match op { + F::Add => 0x1e21_2800, + F::Sub => 0x1e21_3800, + F::Mul => 0x1e21_0800, + F::Div => 0x1e21_1800, + _ => 0x1e21_2000, + } | if precision == P::F64 { 0x0040_0000 } else { 0 }; + assert!( + code.code + .as_chunks::<4>() + .0 + .iter() + .any(|word| u32::from_le_bytes(*word) == opcode), + "missing {op:?}.{precision:?} opcode" + ); + #[cfg(all(target_arch = "aarch64", target_os = "linux"))] + { + let jit = crate::jit_mem::JitCode::new(&code.code).unwrap(); + let mut state = vec![0u8; layout.merged_total_size]; + assert_eq!(unsafe { jit.call(&mut state) }, 0); + let a = if precision == P::F32 { + 1.5f32.to_bits() as u64 + } else { + 1.5f64.to_bits() + }; + let b = if precision == P::F32 { + 2.0f32.to_bits() as u64 + } else { + 2.0f64.to_bits() + }; + assert_eq!( + u64::from_le_bytes(state[..8].try_into().unwrap()), + celox_design::eval_float_binary(op, precision, a, b) + ); + } + } + for op in [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ] { + let (unit, layout) = float_unit( + SIRInstruction::Unary( + RegisterId(2), + UnaryOp::Float { op, precision }, + RegisterId(0), + ), + precision, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!( + mir.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::FloatUnary { .. })) + ); + let code = crate::scalar::emit_prepared_eu( + &unit, + &layout, + false, + "eval_comb", + false, + None, + || false, + ) + .unwrap(); + assert!(!code.code.is_empty()); + } + } +} + +#[test] +fn complex_float_operations_keep_helper_calls() { + for op in [F::Rem, F::Pow] { + let (unit, layout) = float_unit( + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Float { + op, + precision: P::F64, + }, + RegisterId(1), + ), + P::F64, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!(mir.blocks.iter().flat_map(|b| &b.insts).any(|i| matches!(i, MInst::CallExtern { func, .. } if *func == celox_sir::float::FLOAT_HELPER_ID))); + } +} diff --git a/crates/celox-backend-arm64/src/mir.rs b/crates/celox-backend-arm64/src/mir.rs index 5192b5090e8..c576398d764 100644 --- a/crates/celox-backend-arm64/src/mir.rs +++ b/crates/celox-backend-arm64/src/mir.rs @@ -285,6 +285,21 @@ impl SparseCommitDescriptor { /// Word-level AArch64 operations before physical-register substitution. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum MInst { + /// IEEE payloads use ordinary virtual registers; emission stages operands + /// through caller-clobbered SIMD scratch registers for native FP execution. + FloatBinary { + dst: VReg, + lhs: VReg, + rhs: VReg, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, + }, + FloatUnary { + dst: VReg, + src: VReg, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, + }, Mov { dst: VReg, src: VReg, @@ -686,7 +701,9 @@ pub(crate) enum MInst { impl MInst { pub(crate) fn def(&self) -> Option { match self { - Self::Mov { dst, .. } + Self::FloatBinary { dst, .. } + | Self::FloatUnary { dst, .. } + | Self::Mov { dst, .. } | Self::Mov32 { dst, .. } | Self::LoadImm { dst, .. } | Self::BitExtract { dst, .. } @@ -771,7 +788,9 @@ impl MInst { pub(crate) fn def_mut(&mut self) -> Option<&mut VReg> { match self { Self::CallExtern { dst, .. } => dst.as_mut(), - Self::Mov { dst, .. } + Self::FloatBinary { dst, .. } + | Self::FloatUnary { dst, .. } + | Self::Mov { dst, .. } | Self::Mov32 { dst, .. } | Self::LoadImm { dst, .. } | Self::BitExtract { dst, .. } @@ -883,7 +902,8 @@ impl MInst { | Self::ReleaseStorePtrIndexed { ptr, index, src, .. } => vec![*ptr, *index, *src], - Self::Add { lhs, rhs, .. } + Self::FloatBinary { lhs, rhs, .. } + | Self::Add { lhs, rhs, .. } | Self::Add32 { lhs, rhs, .. } | Self::Sub { lhs, rhs, .. } | Self::Sub32 { lhs, rhs, .. } @@ -905,7 +925,8 @@ impl MInst { | Self::URem { lhs, rhs, .. } | Self::SDiv { lhs, rhs, .. } | Self::SRem { lhs, rhs, .. } => vec![*lhs, *rhs], - Self::BitExtract { src, .. } + Self::FloatUnary { src, .. } + | Self::BitExtract { src, .. } | Self::AndImm { src, .. } | Self::AndImm32 { src, .. } | Self::OrImm { src, .. } @@ -1019,7 +1040,8 @@ impl MInst { rewrite(index); rewrite(src); } - Self::Add { lhs, rhs, .. } + Self::FloatBinary { lhs, rhs, .. } + | Self::Add { lhs, rhs, .. } | Self::Add32 { lhs, rhs, .. } | Self::Sub { lhs, rhs, .. } | Self::Sub32 { lhs, rhs, .. } @@ -1044,7 +1066,8 @@ impl MInst { rewrite(lhs); rewrite(rhs); } - Self::BitExtract { src, .. } + Self::FloatUnary { src, .. } + | Self::BitExtract { src, .. } | Self::AndImm { src, .. } | Self::AndImm32 { src, .. } | Self::OrImm { src, .. } diff --git a/crates/celox-backend-arm64/src/scalar.rs b/crates/celox-backend-arm64/src/scalar.rs index 6a8a4268034..9ad56a21387 100644 --- a/crates/celox-backend-arm64/src/scalar.rs +++ b/crates/celox-backend-arm64/src/scalar.rs @@ -650,6 +650,90 @@ fn emit_instruction( let is_next = |target| next_block.is_some_and(|next| labels[&next] == labels[&target]); match instruction { MInst::CallExtern { .. } => unreachable!("the block loop emits extern calls"), + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => { + use celox_sir::{FloatBinaryOp as F, FloatPrecision as P}; + let (dst, lhs, rhs) = ( + resolve(assignment, *dst)?, + resolve(assignment, *lhs)?, + resolve(assignment, *rhs)?, + ); + // v0/v1 are caller-clobbered scratch; persistent loop state uses v29/v31. + match precision { + P::F32 => { + dynasm!(ops ; .arch aarch64 ; fmov s0, W(lhs) ; fmov s1, W(rhs)); + match op { + F::Add => dynasm!(ops ; .arch aarch64 ; fadd s0, s0, s1), + F::Sub => dynasm!(ops ; .arch aarch64 ; fsub s0, s0, s1), + F::Mul => dynasm!(ops ; .arch aarch64 ; fmul s0, s0, s1), + F::Div => dynasm!(ops ; .arch aarch64 ; fdiv s0, s0, s1), + _ => dynasm!(ops ; .arch aarch64 ; fcmp s0, s1), + } + } + P::F64 => { + dynasm!(ops ; .arch aarch64 ; fmov d0, X(lhs) ; fmov d1, X(rhs)); + match op { + F::Add => dynasm!(ops ; .arch aarch64 ; fadd d0, d0, d1), + F::Sub => dynasm!(ops ; .arch aarch64 ; fsub d0, d0, d1), + F::Mul => dynasm!(ops ; .arch aarch64 ; fmul d0, d0, d1), + F::Div => dynasm!(ops ; .arch aarch64 ; fdiv d0, d0, d1), + _ => dynasm!(ops ; .arch aarch64 ; fcmp d0, d1), + } + } + } + match op { + F::Eq => dynasm!(ops ; .arch aarch64 ; cset X(dst), eq), + F::Ne => dynasm!(ops ; .arch aarch64 ; cset X(dst), ne), + // FCMP unordered has NZCV=0011: MI/LS/GT/GE all reject NaN. + F::Lt => dynasm!(ops ; .arch aarch64 ; cset X(dst), mi), + F::Le => dynasm!(ops ; .arch aarch64 ; cset X(dst), ls), + F::Gt => dynasm!(ops ; .arch aarch64 ; cset X(dst), gt), + F::Ge => dynasm!(ops ; .arch aarch64 ; cset X(dst), ge), + F::Add | F::Sub | F::Mul | F::Div => match precision { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov W(dst), s0), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov X(dst), d0), + }, + F::Rem | F::Pow => unreachable!("complex float operations use helpers"), + } + } + MInst::FloatUnary { + dst, + src, + op, + precision, + } => { + use celox_sir::{FloatPrecision as P, FloatUnaryOp as F}; + let (dst, src) = (resolve(assignment, *dst)?, resolve(assignment, *src)?); + match precision { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov s0, W(src)), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov d0, X(src)), + } + match (op, precision) { + (F::Neg, P::F32) => dynasm!(ops ; .arch aarch64 ; fneg s0, s0), + (F::Neg, P::F64) => dynasm!(ops ; .arch aarch64 ; fneg d0, d0), + (F::ToBool, P::F32) => dynasm!(ops ; .arch aarch64 ; fcmp s0, #0.0), + (F::ToBool, P::F64) => dynasm!(ops ; .arch aarch64 ; fcmp d0, #0.0), + (F::Convert { to: P::F64 }, P::F32) => dynasm!(ops ; .arch aarch64 ; fcvt d0, s0), + (F::Convert { to: P::F32 }, P::F64) => dynasm!(ops ; .arch aarch64 ; fcvt s0, d0), + (F::Convert { .. }, _) => {} + _ => unreachable!("integer float conversions use helpers"), + } + match op { + F::ToBool => dynasm!(ops ; .arch aarch64 ; cset X(dst), ne), + _ => match match op { + F::Convert { to } => to, + _ => precision, + } { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov W(dst), s0), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov X(dst), d0), + }, + } + } MInst::Mov { dst, src } => { let (dst, src) = (resolve(assignment, *dst)?, resolve(assignment, *src)?); if dst != src { diff --git a/crates/celox-backend-cranelift/src/translator/arith.rs b/crates/celox-backend-cranelift/src/translator/arith.rs index e887df70db5..3cc7fa957dd 100644 --- a/crates/celox-backend-cranelift/src/translator/arith.rs +++ b/crates/celox-backend-cranelift/src/translator/arith.rs @@ -304,7 +304,8 @@ impl SIRTranslator { *dst, *lhs, Some(*rhs), - celox_sir::float::binary_code(*op, *precision), + super::core::FloatOperation::Binary(*op), + *precision, ); return; } @@ -1407,7 +1408,8 @@ impl SIRTranslator { *dst, *rhs, None, - celox_sir::float::unary_code(*op, *precision), + super::core::FloatOperation::Unary(*op), + *precision, ); return; } diff --git a/crates/celox-backend-cranelift/src/translator/core.rs b/crates/celox-backend-cranelift/src/translator/core.rs index f782f05885d..9b475b61111 100644 --- a/crates/celox-backend-cranelift/src/translator/core.rs +++ b/crates/celox-backend-cranelift/src/translator/core.rs @@ -12,6 +12,13 @@ use crate::{ }; use super::MemoryLayout; +use celox_sir::{FloatBinaryOp as FB, FloatPrecision, FloatUnaryOp as FU}; + +#[derive(Clone, Copy)] +pub(super) enum FloatOperation { + Binary(FB), + Unary(FU), +} /// Pre-load trigger signal values at function entry for register-based /// edge detection. Only needed when `emit_triggers` is enabled (Simulation mode). @@ -518,10 +525,14 @@ impl SIRTranslator { dst: RegisterId, lhs: RegisterId, rhs: Option, - code: u64, + op: FloatOperation, + precision: FloatPrecision, ) { let a = state.regs[&lhs].first_value(state.builder); - let a = if matches!(code & 255, 34 | 35) { + let a = if matches!( + op, + FloatOperation::Unary(FU::FromSigned { .. } | FU::FromUnsigned { .. }) + ) { if let Some(mask) = state.regs[&lhs].first_mask(state.builder) { let known = state.builder.ins().bnot(mask); state.builder.ins().band(a, known) @@ -547,6 +558,106 @@ impl SIRTranslator { } else { state.builder.ins().iconst(types::I64, 0) }; + if !matches!( + op, + FloatOperation::Binary(FB::Rem | FB::Pow) + | FloatOperation::Unary(FU::ToSigned { .. } | FU::ToUnsigned { .. }) + ) { + let ty = if precision == FloatPrecision::F64 { + types::F64 + } else { + types::F32 + }; + let result = if let FloatOperation::Unary( + FU::FromSigned { width } | FU::FromUnsigned { width }, + ) = op + { + let mut integer = a; + if width < 64 { + integer = state.builder.ins().ishl_imm_u(integer, (64 - width) as i64); + integer = if matches!(op, FloatOperation::Unary(FU::FromSigned { .. })) { + state.builder.ins().sshr_imm_u(integer, (64 - width) as i64) + } else { + state.builder.ins().ushr_imm_u(integer, (64 - width) as i64) + }; + } + if matches!(op, FloatOperation::Unary(FU::FromSigned { .. })) { + state.builder.ins().fcvt_from_sint(ty, integer) + } else { + state.builder.ins().fcvt_from_uint(ty, integer) + } + } else { + let float_bits = |builder: &mut FunctionBuilder, bits| { + let bits = if ty == types::F32 { + builder.ins().ireduce(types::I32, bits) + } else { + bits + }; + builder.ins().bitcast(ty, MemFlags::new(), bits) + }; + let a = float_bits(state.builder, a); + let b = float_bits(state.builder, b); + match op { + FloatOperation::Binary(FB::Add) => state.builder.ins().fadd(a, b), + FloatOperation::Binary(FB::Sub) => state.builder.ins().fsub(a, b), + FloatOperation::Binary(FB::Mul) => state.builder.ins().fmul(a, b), + FloatOperation::Binary(FB::Div) => state.builder.ins().fdiv(a, b), + FloatOperation::Binary( + comparison @ (FB::Eq | FB::Ne | FB::Lt | FB::Le | FB::Gt | FB::Ge), + ) => { + let condition = match comparison { + FB::Eq => FloatCC::Equal, + FB::Ne => FloatCC::NotEqual, + FB::Lt => FloatCC::LessThan, + FB::Le => FloatCC::LessThanOrEqual, + FB::Gt => FloatCC::GreaterThan, + FB::Ge => FloatCC::GreaterThanOrEqual, + _ => unreachable!(), + }; + state.builder.ins().fcmp(condition, a, b) + } + FloatOperation::Unary(FU::Neg) => state.builder.ins().fneg(a), + FloatOperation::Unary(FU::ToBool) => { + let zero = if ty == types::F32 { + state.builder.ins().f32const(0.0) + } else { + state.builder.ins().f64const(0.0) + }; + state.builder.ins().fcmp(FloatCC::NotEqual, a, zero) + } + FloatOperation::Unary(FU::Convert { + to: FloatPrecision::F32, + }) if ty == types::F64 => state.builder.ins().fdemote(types::F32, a), + FloatOperation::Unary(FU::Convert { + to: FloatPrecision::F64, + }) if ty == types::F32 => state.builder.ins().fpromote(types::F64, a), + FloatOperation::Unary(FU::Convert { .. }) => a, + _ => unreachable!("known floating operation"), + } + }; + let result_ty = state.builder.func.dfg.value_type(result); + let result = if result_ty == types::F32 { + let raw = state + .builder + .ins() + .bitcast(types::I32, MemFlags::new(), result); + state.builder.ins().uextend(types::I64, raw) + } else if result_ty == types::F64 { + state + .builder + .ins() + .bitcast(types::I64, MemFlags::new(), result) + } else { + state.builder.ins().uextend(types::I64, result) + }; + let value = self.extern_call_result(state, dst, result); + state.regs.insert(dst, value); + return; + } + let code = match op { + FloatOperation::Binary(op) => celox_sir::float::binary_code(op, precision), + FloatOperation::Unary(op) => celox_sir::float::unary_code(op, precision), + }; let c = state.builder.ins().iconst(types::I64, code as i64); let address = state.builder.ins().iconst( types::I64, diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index aee519a5087..0aa506964df 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -6677,6 +6677,16 @@ mod bit_count_tests { f64::MAX.to_bits() }, ]); + for &value in &inputs { + for op in [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ] { + cases.push((op, p, p.width(), value, 0)); + } + } for width in [1, 3, 8, 32, 64] { for round in [false, true] { for &value in &inputs { @@ -6776,6 +6786,14 @@ mod bit_count_tests { for four_state in [false, true] { for (op, a, b, expected) in [ (F::Add, 1.25, 2.5, 3.75), + (F::Sub, 2.5, 1.25, 1.25), + (F::Add, f64::NAN, 1.0, f64::NAN), + (F::Eq, f64::NAN, 1.0, 0.0), + (F::Ne, f64::NAN, 1.0, 1.0), + (F::Lt, f64::NAN, 1.0, 0.0), + (F::Le, -0.0, 0.0, 1.0), + (F::Gt, -0.0, 0.0, 0.0), + (F::Ge, -0.0, 0.0, 1.0), (F::Div, 1.0, 0.0, f64::INFINITY), (F::Mul, -0.0, 2.0, -0.0), ] { @@ -6833,14 +6851,47 @@ mod bit_count_tests { register_map, }; let layout = layout(width, four_state); + let options = CompileOptions { + four_state, + emit_triggers: false, + cranelift: CraneliftOptions::default(), + }; + let mut engine = JitEngine::new(layout.clone(), &options).unwrap(); + let mut clif = String::new(); + engine + .compile_units(std::slice::from_ref(&unit), Some(&mut clif), None, None) + .unwrap(); + assert!( + !clif.contains("call_indirect"), + "basic FP operation used a helper: {clif}" + ); 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)) - ); + let actual = read_bits_at(&output, OUTPUT_OFFSET, 0, width) + .to_u64_digits() + .first() + .copied() + .unwrap_or(0); + if expected.is_nan() { + assert!(if precision == P::F32 { + f32::from_bits(actual as u32).is_nan() + } else { + f64::from_bits(actual).is_nan() + }); + } else { + let comparison = + matches!(op, F::Eq | F::Ne | F::Lt | F::Le | F::Gt | F::Ge); + assert_eq!( + actual, + if comparison { + expected as u64 + } else { + bits(expected) + } + ); + } } } } diff --git a/crates/celox-backend-x86/src/backend/native/emit.rs b/crates/celox-backend-x86/src/backend/native/emit.rs index f7297669f95..39a76440b4e 100644 --- a/crates/celox-backend-x86/src/backend/native/emit.rs +++ b/crates/celox-backend-x86/src/backend/native/emit.rs @@ -15,6 +15,7 @@ mod arithmetic; mod control_flow; mod diagnostics; mod extern_call; +mod floating; mod folded_operands; mod instruction; mod memory; diff --git a/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs b/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs index 24303771977..e1e5f41606c 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs @@ -36,7 +36,9 @@ pub(super) fn log_mir_stats(label: &str, stage: &str, func: &crate::native::mir: phi += block.phis.len(); for inst in &block.insts { match inst { - MInst::X86Simd(X86SimdInst::Zero128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) => alu += 1, MInst::X86Simd(X86SimdInst::Scratch128 { .. }) => {} diff --git a/crates/celox-backend-x86/src/backend/native/emit/floating.rs b/crates/celox-backend-x86/src/backend/native/emit/floating.rs new file mode 100644 index 00000000000..d1311784bf9 --- /dev/null +++ b/crates/celox-backend-x86/src/backend/native/emit/floating.rs @@ -0,0 +1,104 @@ +//! Scalar SSE2 floating point. GPR payloads are the storage ABI; XMM0/1 +//! are ephemeral, with clobbers declared in x86_slp::clobbers_xmm. +use super::*; +use celox_sir::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; + +pub(super) fn emit_binary( + asm: &mut EmitAssembler, + assignment: &AssignmentMap, + dst: VReg, + lhs: VReg, + rhs: VReg, + op: B, + precision: P, +) -> Result<(), IcedError> { + let (lhs, rhs) = if matches!(op, B::Gt | B::Ge) { + (rhs, lhs) + } else { + (lhs, rhs) + }; + asm.movq(xmm0, preg_to_reg64(resolve(assignment, lhs)))?; + asm.movq(xmm1, preg_to_reg64(resolve(assignment, rhs)))?; + let predicate = match op { + B::Eq => Some(0), + B::Ne => Some(4), + B::Lt | B::Gt => Some(1), + B::Le | B::Ge => Some(2), + _ => None, + }; + if let Some(predicate) = predicate { + match precision { + P::F32 => asm.cmpss(xmm0, xmm1, predicate)?, + P::F64 => asm.cmpsd_3(xmm0, xmm1, predicate)?, + } + let output = preg_to_reg32(resolve(assignment, dst)); + asm.movd(output, xmm0)?; + asm.and(output, 1)?; + } else { + match (op, precision) { + (B::Add, P::F32) => asm.addss(xmm0, xmm1)?, + (B::Add, P::F64) => asm.addsd(xmm0, xmm1)?, + (B::Sub, P::F32) => asm.subss(xmm0, xmm1)?, + (B::Sub, P::F64) => asm.subsd(xmm0, xmm1)?, + (B::Mul, P::F32) => asm.mulss(xmm0, xmm1)?, + (B::Mul, P::F64) => asm.mulsd(xmm0, xmm1)?, + (B::Div, P::F32) => asm.divss(xmm0, xmm1)?, + (B::Div, P::F64) => asm.divsd(xmm0, xmm1)?, + _ => unreachable!("unsupported native scalar FP binary operation"), + } + match precision { + P::F32 => asm.movd(preg_to_reg32(resolve(assignment, dst)), xmm0)?, + P::F64 => asm.movq(preg_to_reg64(resolve(assignment, dst)), xmm0)?, + } + } + Ok(()) +} + +pub(super) fn emit_unary( + asm: &mut EmitAssembler, + assignment: &AssignmentMap, + dst: VReg, + src: VReg, + op: U, + precision: P, +) -> Result<(), IcedError> { + let input = preg_to_reg64(resolve(assignment, src)); + let output = preg_to_reg64(resolve(assignment, dst)); + match op { + U::Neg => { + if precision == P::F32 { + let output = preg_to_reg32(resolve(assignment, dst)); + asm.mov(output, preg_to_reg32(resolve(assignment, src)))?; + asm.btc(output, 31)?; + } else { + asm.mov(output, input)?; + asm.btc(output, 63)?; + } + } + U::ToBool => { + asm.movq(xmm0, input)?; + asm.pxor(xmm1, xmm1)?; + match precision { + P::F32 => asm.cmpss(xmm0, xmm1, 4)?, + P::F64 => asm.cmpsd_3(xmm0, xmm1, 4)?, + } + let output = preg_to_reg32(resolve(assignment, dst)); + asm.movd(output, xmm0)?; + asm.and(output, 1)?; + } + U::Convert { to } => { + asm.movq(xmm0, input)?; + match (precision, to) { + (P::F32, P::F64) => asm.cvtss2sd(xmm0, xmm0)?, + (P::F64, P::F32) => asm.cvtsd2ss(xmm0, xmm0)?, + _ => {} + } + match to { + P::F32 => asm.movd(preg_to_reg32(resolve(assignment, dst)), xmm0)?, + P::F64 => asm.movq(output, xmm0)?, + } + } + _ => unreachable!("unsupported native scalar FP unary operation"), + } + Ok(()) +} diff --git a/crates/celox-backend-x86/src/backend/native/emit/instruction.rs b/crates/celox-backend-x86/src/backend/native/emit/instruction.rs index 3df0f78a792..021643a28eb 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/instruction.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/instruction.rs @@ -14,6 +14,23 @@ pub(super) fn emit_inst( let context = asm.context; let mut bound_continuation = false; match inst { + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => { + floating::emit_binary(asm, assignment, *dst, *lhs, *rhs, *op, *precision)?; + } + MInst::FloatUnary { + dst, + src, + op, + precision, + } => { + floating::emit_unary(asm, assignment, *dst, *src, *op, *precision)?; + } MInst::ExternArg { index, src } => { extern_call::emit_extern_arg(asm, *index, preg_to_reg64(resolve(assignment, *src)))?; } 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 259e46e30cb..1823a0f87de 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 @@ -132,6 +132,56 @@ pub(super) fn lower_float( rhs: Option, code: u64, ) { + use celox_sir::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; + let precision = if code & 256 == 0 { P::F32 } else { P::F64 }; + let opcode = code & 255; + let binary = match opcode { + 0 => Some(B::Add), + 1 => Some(B::Sub), + 2 => Some(B::Mul), + 3 => Some(B::Div), + 6 => Some(B::Eq), + 7 => Some(B::Ne), + 8 => Some(B::Lt), + 9 => Some(B::Le), + 10 => Some(B::Gt), + 11 => Some(B::Ge), + _ => None, + }; + let unary = match opcode { + 32 => Some(U::Neg), + 33 => Some(U::ToBool), + 38 => Some(U::Convert { to: P::F32 }), + 39 => Some(U::Convert { to: P::F64 }), + _ => None, + }; + if let Some(op) = binary { + block.push(MInst::FloatBinary { + dst: ctx.reg_map.get(dst), + lhs: ctx.reg_map.get(lhs), + rhs: ctx.reg_map.get(rhs.expect("binary FP SIR operand")), + op, + precision, + }); + } else if let Some(op) = unary { + block.push(MInst::FloatUnary { + dst: ctx.reg_map.get(dst), + src: ctx.reg_map.get(lhs), + op, + precision, + }); + } + if binary.is_some() || unary.is_some() { + if ctx.four_state { + let zero = ctx.alloc_vreg(SpillDesc::remat(0)); + block.push(MInst::LoadImm { + dst: zero, + value: 0, + }); + ctx.set_mask(dst, zero); + } + return; + } 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); 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 index 2b17451218e..0f84c576ace 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs @@ -123,7 +123,7 @@ fn float_helpers_preserve_live_registers_and_narrow_mux_results() { .flat_map(|block| &block.insts) .filter(|inst| matches!(inst, MInst::CallExtern { .. })) .count(), - 3 + 1 ); let allocation = regalloc::run_regalloc(&mut function).unwrap(); assert!( @@ -167,3 +167,185 @@ fn float_helpers_preserve_live_registers_and_narrow_mux_results() { } } } + +#[test] +fn scalar_float_mir_executes_without_helper_for_ieee_edges() { + use celox_design::{eval_float_binary, eval_float_unary}; + let binary = [ + F::Add, + F::Sub, + F::Mul, + F::Div, + F::Eq, + F::Ne, + F::Lt, + F::Le, + F::Gt, + F::Ge, + ]; + for precision in [P::F32, P::F64] { + let width = precision.width(); + let unary = [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ]; + for four_state in [false, true] { + 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(); + const BASE: usize = 64; + let slots = 2 + binary.len() + unary.len(); + layout.four_state = four_state; + layout.offsets.insert(abs, BASE); + layout.widths.insert(abs, slots * 64); + layout.is_4states.insert(abs, false); + layout.total_size = BASE + slots * 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 = [(RegisterId(0), bit(width)), (RegisterId(1), bit(width))] + .into_iter() + .collect::>(); + let mut instructions = vec![ + SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), width), + SIRInstruction::Load(RegisterId(1), addr, SIROffset::Static(64), width), + ]; + for (index, op) in binary.iter().copied().enumerate() { + let reg = RegisterId(index + 2); + let result_width = if index >= 4 { 1 } else { width }; + types.insert(reg, bit(result_width)); + instructions.push(SIRInstruction::Binary( + reg, + RegisterId(0), + BinaryOp::Float { op, precision }, + RegisterId(1), + )); + instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static((index + 2) * 64), + result_width, + reg, + vec![], + vec![], + )); + } + for (index, op) in unary.iter().copied().enumerate() { + let slot = index + 2 + binary.len(); + let reg = RegisterId(slot); + let result_width = match op { + U::ToBool => 1, + U::Convert { to } => to.width(), + _ => width, + }; + types.insert(reg, bit(result_width)); + instructions.push(SIRInstruction::Unary( + reg, + UnaryOp::Float { op, precision }, + RegisterId(0), + )); + instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static(slot * 64), + result_width, + reg, + vec![], + vec![], + )); + } + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + register_map: types, + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions, + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + }; + unit.verify(); + let mut function = lower_execution_unit(&unit, &layout, four_state); + mir_legalize::legalize(&mut function); + mir_opt::optimize(&mut function); + assert_eq!( + function + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| matches!(i, MInst::FloatBinary { .. })) + .count(), + binary.len() + ); + assert!( + !function + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::CallExtern { .. })) + ); + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + 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 payload = |x: f64| match precision { + P::F32 => (x as f32).to_bits() as u64, + P::F64 => x.to_bits(), + }; + let mut values = [ + 0.0, + -0.0, + 1.5, + -2.25, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ] + .map(payload) + .to_vec(); + values.extend(match precision { + P::F32 => vec![1, 0x7f7fffff, 0x7fc12345], + P::F64 => vec![1, 0x7fefffffffffffff, 0x7ff8123456789abc], + }); + for &a in &values { + for &b in &values { + let mut memory = vec![0u8; emitted.required_state_size as usize]; + memory[BASE..BASE + 8].copy_from_slice(&a.to_le_bytes()); + memory[BASE + 8..BASE + 16].copy_from_slice(&b.to_le_bytes()); + // No extern-function header: a hidden helper call would crash. + assert_eq!(unsafe { jit.call(&mut memory) }, 0); + for (index, expected) in binary + .iter() + .map(|&op| eval_float_binary(op, precision, a, b)) + .chain(unary.iter().map(|&op| eval_float_unary(op, precision, a))) + .enumerate() + { + let offset = BASE + (index + 2) * 8; + let actual = + u64::from_le_bytes(memory[offset..offset + 8].try_into().unwrap()); + assert_eq!( + actual, expected, + "{precision:?} four_state={four_state} op={index} a={a:x} b={b:x}" + ); + } + } + } + } + } +} diff --git a/crates/celox-backend-x86/src/backend/native/memory_effect.rs b/crates/celox-backend-x86/src/backend/native/memory_effect.rs index f24379cb523..5016f24fd1b 100644 --- a/crates/celox-backend-x86/src/backend/native/memory_effect.rs +++ b/crates/celox-backend-x86/src/backend/native/memory_effect.rs @@ -233,7 +233,9 @@ pub(crate) fn reads(inst: &MInst) -> MemoryEffects { MInst::ExternArg { .. } | MInst::CallExtern { .. } | MInst::ExternResult { .. } => { MemoryEffects::unknown(UnknownMemory::Direct(BaseReg::SimState)) } - MInst::X86Simd(X86SimdInst::Scratch128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) => MemoryEffects::NONE, @@ -327,7 +329,9 @@ pub(crate) fn writes(inst: &MInst) -> MemoryEffects { MInst::ExternArg { .. } | MInst::CallExtern { .. } | MInst::ExternResult { .. } => { MemoryEffects::unknown(UnknownMemory::Direct(BaseReg::SimState)) } - MInst::X86Simd(X86SimdInst::Scratch128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) diff --git a/crates/celox-backend-x86/src/backend/native/mir.rs b/crates/celox-backend-x86/src/backend/native/mir.rs index 473fc171ba8..2787230575d 100644 --- a/crates/celox-backend-x86/src/backend/native/mir.rs +++ b/crates/celox-backend-x86/src/backend/native/mir.rs @@ -702,6 +702,21 @@ pub const SPARSE_SUMMARY_GROUP: usize = 4; /// handles x86-64's 2-operand constraint by inserting mov when needed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MInst { + /// Scalar IEEE operation on raw GPR payloads. Emission uses XMM0/XMM1; + /// their clobbers are visible to vector allocation and spill caching. + FloatBinary { + dst: VReg, + lhs: VReg, + rhs: VReg, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, + }, + FloatUnary { + dst: VReg, + src: VReg, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, + }, /// Explicit target-specific SIMD instruction with its own register class. X86Simd(X86SimdInst), @@ -1112,6 +1127,19 @@ pub enum MInst { impl fmt::Display for MInst { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => write!(f, "{dst} = fp.{op:?}.{precision:?} {lhs}, {rhs}"), + MInst::FloatUnary { + dst, + src, + op, + precision, + } => write!(f, "{dst} = fp.{op:?}.{precision:?} {src}"), MInst::X86Simd(X86SimdInst::Scratch128 { dst }) => { write!(f, "{dst} = x86.scratch.v128") } @@ -1511,7 +1539,9 @@ impl MInst { /// Returns the destination VReg, if any. pub fn def(&self) -> Option { match self { - MInst::Mov { dst, .. } + MInst::FloatBinary { dst, .. } + | MInst::FloatUnary { dst, .. } + | MInst::Mov { dst, .. } | MInst::Mov32 { dst, .. } | MInst::LoadImm { dst, .. } | MInst::Scratch { dst } @@ -1601,7 +1631,9 @@ impl MInst { /// silently omit a defining opcode while still compiling successfully. pub fn def_mut(&mut self) -> Option<&mut VReg> { match self { - MInst::Mov { dst, .. } + MInst::FloatBinary { dst, .. } + | MInst::FloatUnary { dst, .. } + | MInst::Mov { dst, .. } | MInst::Mov32 { dst, .. } | MInst::LoadImm { dst, .. } | MInst::Scratch { dst } @@ -1688,7 +1720,9 @@ impl MInst { /// Returns the VRegs used by this instruction (max 3, no heap allocation). pub fn uses(&self) -> Uses { match self { - MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => Uses::one(*src), + MInst::FloatUnary { src, .. } | MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { + Uses::one(*src) + } MInst::X86Simd(X86SimdInst::Pack128 { low, high, .. }) => Uses::two(*low, *high), MInst::LoadImm { .. } | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) @@ -1732,7 +1766,8 @@ impl MInst { MInst::ReleaseStorePtrIndexed { ptr, index, src, .. } => Uses::three(*ptr, *index, *src), - MInst::Add { lhs, rhs, .. } + MInst::FloatBinary { lhs, rhs, .. } + | MInst::Add { lhs, rhs, .. } | MInst::Add32 { lhs, rhs, .. } | MInst::Sub { lhs, rhs, .. } | MInst::Sub32 { lhs, rhs, .. } @@ -1824,7 +1859,7 @@ impl MInst { /// Replace all occurrences of `old` with `new` in the use operands. pub fn rewrite_use(&mut self, old: VReg, new: VReg) { match self { - MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { + MInst::FloatUnary { src, .. } | MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { if *src == old { *src = new; } @@ -1930,7 +1965,8 @@ impl MInst { *src = new; } } - MInst::Add { lhs, rhs, .. } + MInst::FloatBinary { lhs, rhs, .. } + | MInst::Add { lhs, rhs, .. } | MInst::Add32 { lhs, rhs, .. } | MInst::Sub { lhs, rhs, .. } | MInst::Sub32 { lhs, rhs, .. } diff --git a/crates/celox-backend-x86/src/backend/native/mir_verify.rs b/crates/celox-backend-x86/src/backend/native/mir_verify.rs index e08e314c566..379450301a4 100644 --- a/crates/celox-backend-x86/src/backend/native/mir_verify.rs +++ b/crates/celox-backend-x86/src/backend/native/mir_verify.rs @@ -323,6 +323,23 @@ fn verify_instruction_constraints( inst: &MInst, ) -> Result<(), MirVerifyError> { match inst { + MInst::FloatBinary { + op: celox_sir::FloatBinaryOp::Rem | celox_sir::FloatBinaryOp::Pow, + .. + } + | MInst::FloatUnary { + op: + celox_sir::FloatUnaryOp::FromSigned { .. } + | celox_sir::FloatUnaryOp::FromUnsigned { .. } + | celox_sir::FloatUnaryOp::ToSigned { .. } + | celox_sir::FloatUnaryOp::ToUnsigned { .. }, + .. + } => Err(MirVerifyError::instruction( + "OPCODE.FLOAT_NATIVE", + block, + index, + "floating-point operation requires helper lowering", + )), MInst::ShrImm { imm, .. } | MInst::ShlImm { imm, .. } | MInst::SarImm { imm, .. } if *imm >= 64 => { diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs b/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs index d7fc74597ec..adc1c89eee3 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs @@ -1217,6 +1217,7 @@ fn unconstrained_schedulable_at( /// cannot silently turn it into a scheduling barrier (or make it movable). fn is_pressure_schedulable_kind(inst: &MInst) -> bool { match inst { + MInst::FloatBinary { .. } | MInst::FloatUnary { .. } => true, MInst::Mov { .. } | MInst::X86Simd(_) | MInst::Mov32 { .. } diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs b/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs index ce76e3107b7..9d794451cb2 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs @@ -369,6 +369,8 @@ fn next_use_bucket(next_use: u32) -> &'static str { fn inst_opcode(inst: &MInst) -> &'static str { match inst { + MInst::FloatBinary { .. } => "float_binary", + MInst::FloatUnary { .. } => "float_unary", MInst::X86Simd(X86SimdInst::Scratch128 { .. }) => "x86_scratch_v128", MInst::X86Simd(X86SimdInst::Zero128 { .. }) => "x86_zero_v128", MInst::X86Simd(X86SimdInst::Pack128 { .. }) => "x86_pack_v2i64", diff --git a/crates/celox-backend-x86/src/backend/native/x86_slp.rs b/crates/celox-backend-x86/src/backend/native/x86_slp.rs index ec24af8c894..7c1728aa1cc 100644 --- a/crates/celox-backend-x86/src/backend/native/x86_slp.rs +++ b/crates/celox-backend-x86/src/backend/native/x86_slp.rs @@ -870,6 +870,7 @@ fn blocks_vector_live_range(inst: &MInst, shift_encoding: VariableShiftEncoding) pub(crate) fn clobbers_xmm(inst: &MInst, register: X86PhysVec) -> bool { match inst { + MInst::FloatBinary { .. } | MInst::FloatUnary { .. } => register.0 <= 1, MInst::PackedLaneCompare { .. } => register.0 <= 5, MInst::PackedByteAffineCompare { .. } => register.0 <= 4, MInst::MemCopy { .. } => register.0 == 0, @@ -885,6 +886,50 @@ mod tests { use super::*; use crate::native::mir::{BlockId, MBlock, PhiNode, SpillDesc, VRegAllocator}; + #[test] + fn float_temporaries_do_not_clobber_live_simd_values() { + let mut scalar = VRegAllocator::new(); + let input = scalar.alloc(); + let output = scalar.alloc(); + let mut func = MFunction::new(scalar, vec![SpillDesc::transient(); 2]); + let vectors = (0..9).map(|_| func.alloc_x86_vec()).collect::>(); + let mut block = MBlock::new(BlockId(0)); + for &dst in &vectors { + block.push(MInst::X86Simd(X86SimdInst::Zero128 { dst })); + } + block.push(MInst::LoadImm { + dst: input, + value: 1.5f64.to_bits(), + }); + block.push(MInst::FloatBinary { + dst: output, + lhs: input, + rhs: input, + op: celox_sir::FloatBinaryOp::Add, + precision: celox_sir::FloatPrecision::F64, + }); + for (index, &src) in vectors.iter().enumerate() { + block.push(MInst::X86Simd(X86SimdInst::Store128 { + base: BaseReg::SimState, + offset: (index * 16) as i32, + src, + })); + } + block.push(MInst::Return); + func.blocks.push(block); + for tick_loop in [false, true] { + let allocation = allocate(&func, 0, tick_loop); + for (_, location) in allocation.assignments { + if let X86VectorLocation::Register(register) = location { + assert!(register.0 > 1, "FP clobbers must exclude XMM0/1"); + } + } + if !tick_loop { + assert!(allocation.spilled_values >= 2); + } + } + } + #[test] fn shared_adjacent_load_pair_becomes_one_vector_value() { let mut scalar = VRegAllocator::new(); diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 513374414a3..385e71c53f8 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -54,6 +54,28 @@ pub struct VariableMetadata { /// Per-dimension sizes for array ports (for example, `[4]` for `logic<32>[4]`). /// Empty means scalar. pub array_dims: Vec, + /// What each element holds. Handle elements are 32-bit two-state slots. + #[serde(default)] + pub value_kind: ValueKind, +} + +/// Bit width of a handle element in state memory. +pub const HANDLE_WIDTH: usize = 32; + +/// What a state element holds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ValueKind { + /// Packed bits. + #[default] + Bits, + /// A handle of a string in the simulator's heap. + StrRef, +} + +impl ValueKind { + pub fn is_handle(self) -> bool { + self != Self::Bits + } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -1604,6 +1626,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: vec![4], + value_kind: Default::default(), }; assert_eq!(metadata.width, 32); @@ -1621,6 +1644,7 @@ mod tests { kind: DomainKind::ClockPosedge, type_kind: PortTypeKind::Clock, array_dims: Vec::new(), + value_kind: Default::default(), }, ); design.events.aliases.insert(11, 10); @@ -1649,6 +1673,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } @@ -1681,6 +1706,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 77ddc67441f..6c6f6e61d6a 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1058,6 +1058,7 @@ impl HiddenObjects<'_> { PortTypeKind::Bit }, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![width], @@ -1821,6 +1822,7 @@ pub fn lower_frontend_artifact( kind, type_kind, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![signal.value_type().width()], diff --git a/crates/celox-frontend-core/src/symbolic/comb_startup.rs b/crates/celox-frontend-core/src/symbolic/comb_startup.rs index c5a0a931727..d407ca21ae0 100644 --- a/crates/celox-frontend-core/src/symbolic/comb_startup.rs +++ b/crates/celox-frontend-core/src/symbolic/comb_startup.rs @@ -116,6 +116,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: vec![2], + value_kind: Default::default(), }, )] .into_iter() diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index da653ee9f27..008f9d44bc0 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -501,6 +501,7 @@ pub fn declare_counter_slots( kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![EVENT_COUNTER_WIDTH], diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d11a1ca6c1d..908fa9d4863 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -97,6 +97,7 @@ impl SvVariable { kind: self.domain_kind, type_kind: self.type_kind, array_dims: self.array_dims.clone(), + value_kind: Default::default(), }, unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 7b8dd5ae2a7..216018f79ad 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -460,6 +460,11 @@ pub(crate) fn project_module_with_ids( .iter() .filter_map(|value| *value) .collect(), + value_kind: if variable.r#type.is_string() { + celox_design::ValueKind::StrRef + } else { + celox_design::ValueKind::Bits + }, }, packed_dims, unpacked_ranges: Vec::new(), diff --git a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs index 3f6ee374de7..50e53826b44 100644 --- a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs +++ b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs @@ -228,7 +228,10 @@ fn collect_dims(module: &Module, var_id: VarId) -> Result, ParserErro // Enums and aggregates encode their packed width in TypeKind rather // than the width Shape. Even a one-bit struct/union needs that dimension: // Veryl represents member access as a select into the packed aggregate. - if width.is_empty() { + if var_type.is_string() { + // A string element is a handle into the simulator's heap. + dims.push(celox_design::HANDLE_WIDTH); + } else if width.is_empty() { if let Some(kind_width) = var_type.kind.width() && (kind_width > 1 || (kind_width == 1 && var_type.is_struct_union())) { diff --git a/crates/celox-frontend-veryl/src/lowering/latch.rs b/crates/celox-frontend-veryl/src/lowering/latch.rs index caf62fef54c..46640c1aed7 100644 --- a/crates/celox-frontend-veryl/src/lowering/latch.rs +++ b/crates/celox-frontend-veryl/src/lowering/latch.rs @@ -69,6 +69,7 @@ pub(crate) fn lower_retained_comb_process( kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, packed_dims: Vec::new(), unpacked_ranges: Vec::new(), diff --git a/crates/celox-frontend-veryl/src/lowering/types.rs b/crates/celox-frontend-veryl/src/lowering/types.rs index 78134de525d..562cc3527cb 100644 --- a/crates/celox-frontend-veryl/src/lowering/types.rs +++ b/crates/celox-frontend-veryl/src/lowering/types.rs @@ -4,9 +4,14 @@ use crate::ParserError; /// Resolve the total storage size of a variable. pub fn resolve_total_width(module: &Module, variable: &Variable) -> Result { - let width = variable.total_width().ok_or_else(|| { - ParserError::unresolved_width(module, variable, variable.r#type.to_string()) - })?; + // A string element is a handle into the simulator's heap. + let width = if variable.r#type.is_string() { + celox_design::HANDLE_WIDTH + } else { + variable.total_width().ok_or_else(|| { + ParserError::unresolved_width(module, variable, variable.r#type.to_string()) + })? + }; let array = variable.r#type.total_array().ok_or_else(|| { ParserError::unresolved_width(module, variable, variable.r#type.to_string()) })?; diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index b427e7f8268..11a0b377b6e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -1556,7 +1556,7 @@ impl ExprCompiler<'_> { } ops.push(TbOpcode::LoadString { location: Self::state_location_at(address, 0), - elements: info.width, + elements: info.width / celox_design::HANDLE_WIDTH, }); } @@ -3922,6 +3922,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, }; diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml new file mode 100644 index 00000000000..477e1d8a232 --- /dev/null +++ b/crates/celox-heap/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "celox-heap" +version.workspace = true +publish = ["crates-io"] +authors.workspace = true +repository.workspace = true +license.workspace = true +description = "Runtime heap of dynamic values referenced by handles in Celox state" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +fxhash = { workspace = true } + +[lints] +workspace = true diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs new file mode 100644 index 00000000000..d52b3b146d9 --- /dev/null +++ b/crates/celox-heap/src/lib.rs @@ -0,0 +1,217 @@ +//! The runtime heap of a simulator. +//! +//! Dynamic values live here and state memory refers to them by 32-bit +//! handles, never by address, so state images stay position independent. +//! Strings are interned and immutable: equal contents have equal handles, so +//! stores, commits, change detection and `==` compare handles as integers. +//! +//! References from state memory are not counted. A collection marks the +//! entries reachable from the handles the caller passes as roots and frees +//! the rest; callers collect only where every copy of a handle is in a place +//! they can enumerate. + +use std::sync::Arc; + +use fxhash::FxHashMap as HashMap; + +/// A reference to a heap entry, as stored in state memory. +pub type Handle = u32; + +/// Byte width of a handle slot in state memory. +pub const HANDLE_BYTES: usize = 4; + +/// The handle of `""`, the value of zero-initialized state memory. +pub const EMPTY_STRING: Handle = 0; + +/// Entries created since the last collection before another one is due, +/// unless the live set is larger. +const MIN_COLLECTION_INTERVAL: usize = 1024; + +/// Dynamic strings referenced by [`Handle`]. +#[derive(Clone, Debug)] +pub struct Heap { + strings: Vec>>, + lookup: HashMap, Handle>, + free: Vec, + /// Entries below this handle are never collected. + pinned: usize, + created: usize, + live_after_collection: usize, +} + +impl Default for Heap { + fn default() -> Self { + Self::new() + } +} + +impl Heap { + pub fn new() -> Self { + let empty: Arc<[u8]> = Arc::from(&[][..]); + let mut lookup = HashMap::default(); + lookup.insert(empty.clone(), EMPTY_STRING); + Self { + strings: vec![Some(empty)], + lookup, + free: Vec::new(), + pinned: 1, + created: 0, + live_after_collection: 1, + } + } + + /// The handle of the string `bytes`, creating it if needed. NUL bytes are + /// removed first, as assigning a literal to a string does (IEEE 1800-2023 + /// 6.16). + pub fn intern(&mut self, bytes: &[u8]) -> Handle { + if bytes.contains(&0) { + let stripped: Vec = bytes.iter().copied().filter(|&byte| byte != 0).collect(); + return self.intern_stripped(&stripped); + } + self.intern_stripped(bytes) + } + + fn intern_stripped(&mut self, bytes: &[u8]) -> Handle { + if let Some(&handle) = self.lookup.get(bytes) { + return handle; + } + let value: Arc<[u8]> = Arc::from(bytes); + let handle = match self.free.pop() { + Some(handle) => { + self.strings[handle as usize] = Some(value.clone()); + handle + } + None => { + let handle = Handle::try_from(self.strings.len()) + .expect("the heap has more strings than handles can name"); + self.strings.push(Some(value.clone())); + handle + } + }; + self.lookup.insert(value, handle); + self.created += 1; + handle + } + + /// The contents of `handle`. A handle that names no string reads as `""`, + /// so a value written into a handle slot by the host cannot crash a read. + pub fn string(&self, handle: Handle) -> &[u8] { + self.strings + .get(handle as usize) + .and_then(Option::as_deref) + .unwrap_or_default() + } + + /// Whether `handle` names a live string. + pub fn contains(&self, handle: Handle) -> bool { + self.strings + .get(handle as usize) + .is_some_and(Option::is_some) + } + + /// The number of live strings, including `""`. + pub fn len(&self) -> usize { + self.strings.len() - self.free.len() + } + + pub fn is_empty(&self) -> bool { + false + } + + /// Bytes of string contents, excluding allocator overhead. + pub fn content_size(&self) -> usize { + self.strings.iter().flatten().map(|value| value.len()).sum() + } + + /// Whether enough entries were created since the last collection to make + /// another worthwhile. The interval grows with the live set, so the cost + /// of collecting stays proportional to the allocation that triggered it. + pub fn should_collect(&self) -> bool { + self.created >= MIN_COLLECTION_INTERVAL.max(self.live_after_collection) + } + + /// Free every unpinned entry that no handle in `roots` refers to. Roots + /// that name no entry are ignored. + pub fn collect(&mut self, roots: impl IntoIterator) { + let mut marked = vec![false; self.strings.len()]; + marked[..self.pinned].fill(true); + for root in roots { + if let Some(mark) = marked.get_mut(root as usize) { + *mark = true; + } + } + for (handle, live) in marked.into_iter().enumerate() { + if live { + continue; + } + if let Some(value) = self.strings[handle].take() { + self.lookup.remove(&value); + self.free.push(handle as Handle); + } + } + self.created = 0; + self.live_after_collection = self.len(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interning_gives_equal_contents_equal_handles() { + let mut heap = Heap::new(); + let a = heap.intern(b"abc"); + assert_eq!(heap.intern(b"abc"), a); + assert_ne!(heap.intern(b"abd"), a); + assert_eq!(heap.intern(b""), EMPTY_STRING); + assert_eq!(heap.string(a), b"abc"); + } + + #[test] + fn nul_bytes_are_removed() { + let mut heap = Heap::new(); + let a = heap.intern(b"a\0b\0"); + assert_eq!(heap.string(a), b"ab"); + assert_eq!(heap.intern(b"ab"), a); + assert_eq!(heap.intern(b"\0\0"), EMPTY_STRING); + } + + #[test] + fn unknown_handles_read_as_empty() { + let heap = Heap::new(); + assert_eq!(heap.string(12345), b""); + assert!(!heap.contains(12345)); + } + + #[test] + fn collection_frees_unreachable_strings_and_reuses_handles() { + let mut heap = Heap::new(); + let kept = heap.intern(b"kept"); + let dropped = heap.intern(b"dropped"); + heap.collect([kept, 999]); + assert_eq!(heap.string(kept), b"kept"); + assert!(!heap.contains(dropped)); + assert!(heap.contains(EMPTY_STRING)); + // A freed handle is reused, and its old contents are gone from the + // intern table. + let again = heap.intern(b"new"); + assert_eq!(again, dropped); + assert_eq!(heap.string(again), b"new"); + assert_ne!(heap.intern(b"dropped"), kept); + } + + #[test] + fn collection_is_due_after_enough_allocation() { + let mut heap = Heap::new(); + for index in 0..MIN_COLLECTION_INTERVAL - 1 { + heap.intern(index.to_string().as_bytes()); + } + assert!(!heap.should_collect()); + heap.intern(b"one more"); + assert!(heap.should_collect()); + heap.collect([]); + assert!(!heap.should_collect()); + assert_eq!(heap.len(), 1); + } +} diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index a377679d3ba..98c61ea0cf8 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -34,11 +34,16 @@ //! counted count u32, then per signal: signal str | 3 × counter u32 //! write count u32, then per host write: signal str | value bytes | mask bytes //! host pending u8 | finished u8 +//! strings (only with FLAG_STRINGS): count u32, then per string: bytes //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 //! bytes: byte length u32 | little-endian bytes //! ``` //! +//! The value of a string object is one little-endian u32 per element: 0 for +//! `""`, otherwise one more than the index of its contents in the strings +//! section. Files without strings keep the earlier encoding. +//! //! Version 1 files, which have no process section, still load. A file whose //! processes have nothing to record is written as version 1, which older //! builds read too. @@ -52,6 +57,8 @@ const FLAG_SCHEDULE: u16 = 1 << 1; /// The schedule lists events whose signal was x or z. Set only when there are /// any, so other files keep their earlier encoding. const FLAG_UNKNOWN_EVENTS: u16 = 1 << 2; +/// String objects refer to a strings section after the schedule. +const FLAG_STRINGS: u16 = 1 << 3; /// How a state object gets its value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -175,6 +182,8 @@ pub struct StateFile { pub four_state: bool, pub objects: Vec, pub schedule: Option, + /// Contents of the strings that string objects refer to. + pub strings: Vec>, } /// A state file that could not be read. @@ -225,6 +234,9 @@ impl StateFile { flags |= FLAG_UNKNOWN_EVENTS; } } + if !self.strings.is_empty() { + flags |= FLAG_STRINGS; + } put_u16(w, flags)?; put_len(w, self.objects.len())?; for object in &self.objects { @@ -276,6 +288,12 @@ impl StateFile { put_processes(w, processes)?; } } + if !self.strings.is_empty() { + put_len(w, self.strings.len())?; + for string in &self.strings { + put_bytes(w, string)?; + } + } Ok(()) } @@ -364,6 +382,13 @@ impl StateFile { } else { None }; + let strings = if flags & FLAG_STRINGS != 0 { + (0..get_u32(r)?) + .map(|_| get_len_bytes(r)) + .collect::>()? + } else { + Vec::new() + }; let mut rest = [0; 1]; if r.read(&mut rest)? != 0 { return Err(StateFileError::Malformed( @@ -374,6 +399,7 @@ impl StateFile { four_state, objects, schedule, + strings, }) } @@ -741,9 +767,23 @@ mod tests { finished: false, }, }), + strings: Vec::new(), } } + #[test] + fn strings_round_trip_after_the_schedule() { + let mut file = sample(); + file.strings = vec![b"abc".to_vec(), Vec::new(), b"\xff".to_vec()]; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + file.schedule = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + #[test] fn files_without_process_state_are_version_1() { let mut file = sample(); diff --git a/crates/celox-testbench/Cargo.toml b/crates/celox-testbench/Cargo.toml index 2c373de4040..866bf086d7d 100644 --- a/crates/celox-testbench/Cargo.toml +++ b/crates/celox-testbench/Cargo.toml @@ -11,6 +11,7 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-heap = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } serde = { workspace = true } diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 5d5c95342a1..24217b7e149 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -16,9 +16,6 @@ pub use format::{ }; pub use vm::{CompiledExpr, TestbenchValue}; -/// Dynamic string values, addressed by a bound variable and flattened array index. -pub type TestbenchStrings = std::collections::BTreeMap<(usize, usize), Vec>; - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { pub address: A, @@ -521,10 +518,14 @@ pub enum ExprOpcode { byte_size: usize, }, ConstString(Vec), + /// Pop the bit offset of a string element within the variable at + /// `location`, which holds `elements` heap handles, and push its contents. + /// An offset past the last element reads `""`. LoadString { location: L, elements: usize, }, + /// Pop a string and store its heap handle at `location`. StoreString { location: L, }, diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs index 3bba0da9720..fcd6d4e0444 100644 --- a/crates/celox-testbench/src/vm.rs +++ b/crates/celox-testbench/src/vm.rs @@ -110,15 +110,16 @@ impl CompiledExpr { memory: *mut u8, on_write: impl FnMut(usize, usize), ) -> TestbenchValue { - self.eval_with_strings(memory, &mut crate::TestbenchStrings::new(), on_write) + self.eval_with_heap(memory, None, on_write) } - /// Evaluate using the simulator-owned string storage. Values are copied on - /// load so assigning another variable cannot alias a mutable string. - pub fn eval_with_strings( + /// Evaluate with the simulator's heap, which string variables refer to. + /// Without a heap, string variables read as `""` and string stores are + /// dropped instead of writing a handle no heap knows. + pub fn eval_with_heap( &self, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + mut heap: Option<&mut celox_heap::Heap>, mut on_write: impl FnMut(usize, usize), ) -> TestbenchValue { let mut stack: Vec = Vec::with_capacity(16); @@ -126,7 +127,7 @@ impl CompiledExpr { let ops = self.bytecode.ops(); while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, strings, &mut on_write); + self.exec_at(ops, &mut pc, &mut stack, memory, &mut heap, &mut on_write); } stack.pop().unwrap_or_else(|| { debug_assert!(false, "testbench bytecode: stack empty after evaluation"); @@ -143,7 +144,7 @@ impl CompiledExpr { pc: &mut usize, stack: &mut Vec, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + heap: &mut Option<&mut celox_heap::Heap>, on_write: &mut impl FnMut(usize, usize), ) { match &ops[*pc] { @@ -152,14 +153,17 @@ impl CompiledExpr { *pc += 1; } TbOpcode::LoadString { location, elements } => { - let index = stack.pop().expect("string index").to_u64() as usize; - let value = if index < *elements { - strings - .get(&(*location, index)) - .cloned() - .unwrap_or_default() - } else { - Vec::new() + let index = stack.pop().expect("string element offset").to_u64() as usize + / celox_design::HANDLE_WIDTH; + let value = match heap { + Some(heap) if index < *elements => { + let offset = location + index * celox_heap::HANDLE_BYTES; + // SAFETY: bound bytecode addresses a handle slot of + // `elements` handles in this memory image. + let handle = unsafe { read_handle(memory, offset) }; + heap.string(handle).to_vec() + } + _ => Vec::new(), }; stack.push(TestbenchValue::String(value)); *pc += 1; @@ -168,7 +172,19 @@ impl CompiledExpr { let TestbenchValue::String(value) = stack.pop().expect("string store value") else { unreachable!("string store requires a string value"); }; - strings.insert((*location, 0), value); + if let Some(heap) = heap { + let handle = heap.intern(&value); + // SAFETY: bound bytecode addresses a handle slot in this + // memory image. + unsafe { + std::ptr::copy_nonoverlapping( + handle.to_le_bytes().as_ptr(), + memory.add(*location), + celox_heap::HANDLE_BYTES, + ); + } + on_write(*location, celox_heap::HANDLE_BYTES); + } *pc += 1; } TbOpcode::ConstU64(v) => { @@ -326,14 +342,14 @@ impl CompiledExpr { if !cond.is_zero() { let then_end = *pc + then_len; while *pc < then_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } *pc += else_len; // skip else block } else { *pc += then_len; // skip then block let else_end = *pc + else_len; while *pc < else_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } } } @@ -998,6 +1014,20 @@ fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { } } +/// Read the handle stored at `offset`. +/// +/// # Safety +/// +/// `memory + offset` must be valid for reading a handle. +unsafe fn read_handle(memory: *const u8, offset: usize) -> celox_heap::Handle { + let mut bytes = [0; celox_heap::HANDLE_BYTES]; + // SAFETY: guaranteed by the caller. + unsafe { + std::ptr::copy_nonoverlapping(memory.add(offset), bytes.as_mut_ptr(), bytes.len()); + } + celox_heap::Handle::from_le_bytes(bytes) +} + #[cfg(test)] mod float_tests { use super::*; diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 399a7fd538a..78161e8e44f 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -943,6 +943,7 @@ mod tests { object("next", StateRole::Comb, stale, 0), ], schedule: None, + strings: Vec::new(), } } diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index bddbd054b93..2a6c3e241dc 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -52,6 +52,7 @@ celox-sir-opt = { workspace = true, default-features = false } celox-slt = { workspace = true } celox-state-layout = { workspace = true } celox-runtime = { workspace = true } +celox-heap = { workspace = true } celox-testbench = { workspace = true } fxhash = { workspace = true } thiserror = { workspace = true } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index efb2aef7073..e8d0992c26a 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2,6 +2,8 @@ mod builder; #[cfg(feature = "host-runtime")] mod checkpoint; mod error; +#[cfg(feature = "host-runtime")] +mod heap; #[cfg(feature = "systemverilog")] pub(crate) mod mixed; #[cfg(feature = "host-runtime")] @@ -121,8 +123,10 @@ mod host { /// cross-codegen builds or unsupported hosts. pub struct Simulator { pub(crate) backend: B, - /// Dynamic testbench strings, keyed by the bound variable location. - pub(crate) testbench_strings: celox_testbench::TestbenchStrings, + /// Dynamic values that handle slots in state memory refer to. + pub(crate) heap: celox_heap::Heap, + /// Byte offsets of every handle slot in state memory. + pub(super) handle_slots: std::sync::OnceLock>, file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, @@ -830,7 +834,8 @@ mod host { dirty: false, declaration_phase: false, warnings, - testbench_strings: Default::default(), + heap: Default::default(), + handle_slots: Default::default(), file_io: Default::default(), pending_host_events: Default::default(), components: Default::default(), @@ -2170,6 +2175,16 @@ mod host { .iter() .filter_map(|address| self.program.design.variable(address)) .filter(|variable| instance.resolves_path_to(&variable.path, variable.address)) + // A handle slot holds a heap reference, not a value to + // show; strings have no VCD representation yet. + .filter(|variable| { + !self + .program + .design + .state_objects + .get(&variable.address) + .is_some_and(|metadata| metadata.value_kind.is_handle()) + }) .collect(); sorted_vars.sort_by(|a, b| a.path.cmp(&b.path)); diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 68aae41ca47..772c839cada 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -92,7 +92,7 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - testbench_strings: celox_testbench::TestbenchStrings, + heap: celox_heap::Heap, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. @@ -102,7 +102,7 @@ pub struct Checkpoint { impl Checkpoint { /// Bytes in the saved memory image and string contents, excluding allocator overhead. pub fn state_size(&self) -> usize { - self.image.len() + self.testbench_strings.values().map(Vec::len).sum::() + self.image.len() + self.heap.content_size() } } @@ -159,7 +159,7 @@ impl Simulator { } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), - testbench_strings: self.testbench_strings.clone(), + heap: self.heap.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, frozen: self.frozen, @@ -179,8 +179,7 @@ impl Simulator { checkpoint .image .restore_into(&mut self.backend, fingerprint)?; - self.testbench_strings - .clone_from(&checkpoint.testbench_strings); + self.heap.clone_from(&checkpoint.heap); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs new file mode 100644 index 00000000000..accc54b560d --- /dev/null +++ b/crates/celox/src/simulator/heap.rs @@ -0,0 +1,73 @@ +//! Collecting the heap that handle slots in state memory refer to. + +use std::sync::Arc; + +use celox_heap::{HANDLE_BYTES, Handle}; + +use super::host::Simulator; +use crate::backend::SimBackend; + +impl Simulator { + /// Byte offsets of every handle slot in the stable and working regions. + pub(crate) fn handle_slots(&self) -> Arc<[usize]> { + self.handle_slots + .get_or_init(|| { + let layout = self.backend.layout(); + let mut slots = Vec::new(); + for (address, metadata) in &self.program.design.state_objects { + if !metadata.value_kind.is_handle() { + continue; + } + debug_assert!( + !layout.sparse_offsets.contains_key(address), + "handle slots are never sparse FF targets" + ); + let elements = metadata.width / celox_design::HANDLE_WIDTH; + let bases = layout.offsets.get(address).copied().into_iter().chain( + layout + .working_offsets + .get(address) + .map(|offset| layout.working_base_offset + offset), + ); + for base in bases { + slots.extend((0..elements).map(|index| base + index * HANDLE_BYTES)); + } + } + slots.sort_unstable(); + slots.into() + }) + .clone() + } + + /// The handles held by the handle slots of state memory. + pub(crate) fn handle_roots(&self) -> Vec { + let (memory, len) = self.backend.memory_as_ptr(); + self.handle_slots() + .iter() + .filter(|&&offset| offset + HANDLE_BYTES <= len) + .map(|&offset| { + let mut bytes = [0; HANDLE_BYTES]; + // SAFETY: the slot lies inside the `len` bytes of the image. + unsafe { + std::ptr::copy_nonoverlapping( + memory.add(offset), + bytes.as_mut_ptr(), + HANDLE_BYTES, + ); + } + Handle::from_le_bytes(bytes) + }) + .collect() + } + + /// Collect the heap if enough was allocated since the last collection. + /// State memory and `extra_roots` must hold every live handle: the + /// caller runs this only where no copy of a handle is anywhere else. + pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { + if !self.heap.should_collect() { + return; + } + let roots = self.handle_roots(); + self.heap.collect(roots.into_iter().chain(extra_roots)); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index b7b465d948e..96f30a45e94 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -40,6 +40,8 @@ pub enum StateError { /// matching code keeps compiling. #[error("the state of the simulation's processes could not be recorded")] Processes, + /// Not returned: state files record strings by their contents. Kept so + /// that matching code keeps compiling. #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] TestbenchStrings, } @@ -105,6 +107,9 @@ struct NamedObject { path: String, signal: SignalRef, role: StateRole, + /// Whether the elements are string handles, which a file records as + /// references to its strings section. + strings: bool, } /// The state objects of a built design, with the paths and roles that state @@ -121,8 +126,22 @@ pub struct StateSchema { impl StateSchema { /// Save the value of every state object of `backend` as last evaluated. + /// String objects read as `""`; use [`Self::capture_with_heap`] for a + /// backend whose strings live in a heap. pub fn capture(&self, backend: &B) -> StateFile { - let objects = self + self.capture_with_heap(backend, &celox_heap::Heap::new()) + } + + /// Save the value of every state object of `backend`, with the contents + /// of its strings from `heap`. + pub fn capture_with_heap( + &self, + backend: &B, + heap: &celox_heap::Heap, + ) -> StateFile { + let mut strings = Vec::new(); + let mut file_ids: HashMap = HashMap::default(); + let mut objects: Vec = self .objects .iter() .map(|object| { @@ -149,10 +168,36 @@ impl StateSchema { } }) .collect(); + // Number strings by first use in path order, so equal states save + // equal files. + for (object, named) in objects.iter_mut().zip(&self.objects) { + if !named.strings { + continue; + } + for element in object + .value + .as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>() + .0 + { + let handle = celox_heap::Handle::from_le_bytes(*element); + let contents = heap.string(handle); + let id = if contents.is_empty() { + 0 + } else { + // Interning gives each contents one handle. + *file_ids.entry(handle).or_insert_with(|| { + strings.push(contents.to_vec()); + strings.len() as u32 + }) + }; + element.copy_from_slice(&id.to_le_bytes()); + } + } StateFile { four_state: self.four_state, objects, schedule: None, + strings, } } @@ -166,6 +211,16 @@ impl StateSchema { &self, backend: &mut B, file: &StateFile, + ) -> Result<(), StateMismatch> { + self.load_with_heap(backend, &mut celox_heap::Heap::new(), file) + } + + /// Like [`Self::load`], creating the file's strings in `heap`. + pub fn load_with_heap( + &self, + backend: &mut B, + heap: &mut celox_heap::Heap, + file: &StateFile, ) -> Result<(), StateMismatch> { let saved: BTreeMap<&str, &StateObject> = file .objects @@ -184,7 +239,7 @@ impl StateSchema { if let Some(saved) = saved.get(object.path.as_str()) && saved.width == object.signal.width { - seeds.push((object.signal, *saved)); + seeds.push((object, *saved)); } continue; } @@ -197,7 +252,7 @@ impl StateSchema { object.signal.width, )); } - Some(saved) => writes.push((object.signal, *saved)), + Some(saved) => writes.push((object, *saved)), } } let declared: std::collections::BTreeSet<&str> = self @@ -213,8 +268,22 @@ impl StateSchema { if !mismatch.is_empty() { return Err(mismatch); } - for (signal, object) in seeds.into_iter().chain(writes) { - let value = BigUint::from_bytes_le(&object.value); + for (named, object) in seeds.into_iter().chain(writes) { + let signal = named.signal; + let value = if named.strings { + let mut value = object.value.clone(); + for element in value.as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>().0 { + let id = u32::from_le_bytes(*element) as usize; + let contents = id + .checked_sub(1) + .and_then(|index| file.strings.get(index)) + .map_or(&[][..], Vec::as_slice); + element.copy_from_slice(&heap.intern(contents).to_le_bytes()); + } + BigUint::from_bytes_le(&value) + } else { + BigUint::from_bytes_le(&object.value) + }; let mask = object .mask .as_deref() @@ -246,9 +315,6 @@ impl Simulator { /// a read would return. pub fn save_state(&mut self) -> Result { self.check_host_checkpoint_support()?; - if !self.testbench_strings.is_empty() { - return Err(StateError::TestbenchStrings); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -256,7 +322,9 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - Ok(self.state_schema().capture(&self.backend)) + Ok(self + .state_schema() + .capture_with_heap(&self.backend, &self.heap)) } /// Load the state saved in `file`, matching objects by path. @@ -279,9 +347,6 @@ impl Simulator { file: &StateFile, time: u64, ) -> Result<(), StateError> { - if !self.testbench_strings.is_empty() { - return Err(StateError::TestbenchStrings); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -289,7 +354,7 @@ impl Simulator { // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; self.state_schema() - .load(&mut self.backend, file) + .load_with_heap(&mut self.backend, &mut self.heap, file) .map_err(StateError::Mismatch)?; for address in &self.program.runtime_schema.time_slots { self.backend.set( @@ -355,6 +420,9 @@ impl Simulator { } else { StateRole::State }, + strings: self.program.design.state_objects.get(address).is_some_and( + |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, + ), }); } index = end; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 1c305ebff5d..23fb0943e78 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -99,18 +99,14 @@ fn eval_expr( ) -> TbValue { let (memory, _) = sim.backend.memory_as_ptr(); let trace = sim.backend.layout().trace.as_ref(); - expr.eval_with_strings( - memory.cast_mut(), - &mut sim.testbench_strings, - |offset, len| { - if let Some(trace) = trace { - // SAFETY: bytecode is bound to this simulator's memory layout. - unsafe { - trace.mark_range(memory.cast_mut(), offset, len); - } + expr.eval_with_heap(memory.cast_mut(), Some(&mut sim.heap), |offset, len| { + if let Some(trace) = trace { + // SAFETY: bytecode is bound to this simulator's memory layout. + unsafe { + trace.mark_range(memory.cast_mut(), offset, len); } - }, - ) + } + }) } pub(crate) fn eval_backend_expr( @@ -253,12 +249,19 @@ fn sim_set_target( value: TbValue, ) { if let TbValue::String(bytes) = value { + // A selection names a string element by its bit offset. let index = target.selection.as_ref().map_or(0, |selection| { - eval_expr(sim, &selection.offset).to_u64() as usize + eval_expr(sim, &selection.offset).to_u64() as usize / celox_design::HANDLE_WIDTH }); - if index < target.signal.width { - sim.testbench_strings - .insert((target.signal.offset, index), bytes); + if index < target.signal.width / celox_design::HANDLE_WIDTH { + let handle = sim.heap.intern(&bytes); + let element = SignalRef { + offset: target.signal.offset + index * celox_heap::HANDLE_BYTES, + width: celox_design::HANDLE_WIDTH, + is_4state: false, + array_layout: None, + }; + sim.set(element, handle); } return; } @@ -290,6 +293,32 @@ fn sim_set_target( ); } +/// Collect the heap between concurrent process polls. The saved temporaries of +/// suspended processes are outside state memory, so their handles are roots. +fn collect_testbench_heap( + sim: &mut Simulator, + private_signals: &[SignalRef], + locals: &[Vec<(BigUint, BigUint)>], +) { + if !sim.heap.should_collect() { + return; + } + let slots = sim.handle_slots(); + let saved_roots: Vec = private_signals + .iter() + .enumerate() + .filter(|(_, signal)| slots.binary_search(&signal.offset).is_ok()) + .flat_map(|(index, signal)| { + let elements = signal.width / celox_design::HANDLE_WIDTH; + locals.iter().flat_map(move |process| { + let digits = process[index].0.to_u32_digits(); + (0..elements).map(move |element| digits.get(element).copied().unwrap_or(0)) + }) + }) + .collect(); + sim.maybe_collect_heap(saved_roots); +} + fn execution_random_seed(seed: Option) -> u64 { seed.unwrap_or_else(rand::random) } @@ -1797,6 +1826,9 @@ fn exec_testbench( Poll::Pending => debug_assert!(wait.borrow().is_some()), } } + // No process is running, so every string handle is in state memory or + // in a suspended process's saved temporaries. + collect_testbench_heap(&mut sim.borrow_mut(), testbench.private_signals(), &locals); for wait in &waits { if let Some(wait) = wait.borrow().as_ref() && wait.remaining != 0 @@ -1973,6 +2005,9 @@ fn exec_detailed( ) -> ExecResult { for stmt in stmts { let r = exec_one_detailed(sim, stmt, ctx); + // Only a single process runs here, so between statements every string + // handle is in state memory. + sim.maybe_collect_heap([]); // Stop on control-flow transfers or hard errors. Assertion failures that // are allowed to continue return `Continue` and are recorded in `ctx`. if matches!( diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 2e76af89cd5..70aabb29492 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -330,3 +330,156 @@ fn event_expressions_with_effects_are_rejected() { assert!(error.contains(construct), "{event}: {error}"); } } + +/// Timing features Celox does not implement yet are rejected with a message +/// naming the construct and its tracking issue, instead of being ignored. +/// The comments name the issue that implements a feature when the message +/// still points to the roadmap. +#[test] +fn unimplemented_timing_features_are_rejected() { + for (body, construct, issue) in [ + ("bit a; initial @(a iff a);", "iff-qualified event", 1444), + ("initial fork #1; join", "fork-join block", 88), + ("initial fork #1; join_none", "fork-join block", 88), + // #1711 names the construct. + ( + "event e; initial -> e;", + "unsupported internal data type", + 88, + ), + ( + "bit a, b; initial a = #1 b;", + "intra-assignment timing control", + 88, + ), + ( + "bit a, b; initial a <= #1 b;", + "intra-assignment timing control", + 88, + ), + ( + "bit a, b, c; initial a = @(posedge c) b;", + "intra-assignment timing control", + 88, + ), + ("initial wait fork;", "wait fork statement", 88), + // #1711 names the construct. + ("initial disable fork;", "disable statement", 88), + ( + "bit a; task t(input bit x); wait (a ^ x); endtask initial t(0);", + "wait condition reading a static task argument", + 88, + ), + ( + "bit a; task t(input bit x); @(a ^ x); endtask initial t(0);", + "event expression reading a static task argument", + 88, + ), + ( + "bit a; function automatic bit f(); a = ~a; return a; endfunction initial @(f());", + "impure call `f` in an event expression", + 88, + ), + ( + "bit q; task t(); int s = 1; #1 q = s; endtask initial t();", + "static local in a timed task", + 88, + ), + ( + "bit a, y; assign #1 y = a;", + "delayed continuous assignment", + 444, + ), + // #1708: a plain `always` that is not a flip-flop runs as a process. + ( + "bit [3:0] v; int n; always @(posedge v[0]) n++;", + "always_ff event expression", + 464, + ), + ( + "bit [3:0] v; int n; always @(posedge v) n++;", + "multi-bit always_ff event signal", + 88, + ), + ( + "bit a, b; int n; always @(posedge a or posedge b) n <= n + 1;", + "always_ff event control", + 88, + ), + // #1709 + ( + "bit [7:0] m[4]; initial #1 m[1] <= 5;", + "nonblocking assignment to an unpacked array in a process", + 88, + ), + ( + "bit [3:0] q; int i = 2; initial #1 q[i] <= 1;", + "nonblocking assignment with a run-time position in a process", + 88, + ), + ( + "bit [3:0] q; initial #1 q[5] <= 1;", + "nonblocking assignment outside its target", + 88, + ), + // #1710 + ( + "bit q; task t(); #1 q = 1; endtask always @* t();", + "timed task call in a combinational process", + 88, + ), + ] { + let source = format!("module Top; {body} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("unimplemented.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`{body}` must be rejected")) + .to_string(); + // The report wraps long lines behind a `│` gutter. + let error = error + .split(|c: char| c.is_whitespace() || c == '│') + .filter(|word| !word.is_empty()) + .collect::>() + .join(" "); + assert!( + error.contains(&format!("[tracking issue #{issue}]")) + && error.contains(&format!("Unsupported SystemVerilog construct: {construct}")), + "{body}: {error}" + ); + } +} + +/// Only `initial` and `always` processes may suspend (IEEE 1800-2023 +/// 9.2.2.2, 9.2.2.4 and 13.4); a timing control elsewhere is an error. +#[test] +fn timing_controls_outside_suspendable_processes_are_rejected() { + for (body, construct) in [ + ( + "bit a, y; always_comb begin #1 y = a; end", + "delay control in an always_comb or always_ff body", + ), + ( + "bit clk, a, q; always_ff @(posedge clk) begin @(a); q <= a; end", + "event control in an always_comb or always_ff body", + ), + // #1711 reports this as illegal rather than unsupported. + ( + "bit a; function automatic bit f(); #1; return a; endfunction", + "delay control in a subroutine", + ), + ] { + let source = format!("module Top; {body} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("outside.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`{body}` must be rejected")) + .to_string(); + assert!(error.contains(construct), "{body}: {error}"); + } +} diff --git a/crates/celox/tests/native_mir.rs b/crates/celox/tests/native_mir.rs index 989e8cbf515..85664ec41d3 100644 --- a/crates/celox/tests/native_mir.rs +++ b/crates/celox/tests/native_mir.rs @@ -159,3 +159,77 @@ fn trace_contains_the_exact_fused_native_pipeline() { "trace must not independently re-lower source execution units" ); } + +/// FP ports keep the test free of integer-conversion helpers: the complete +/// frontend -> optimized SIR -> MIR path must preserve numeric FP operations. +#[test] +fn scalar_float_arithmetic_stays_explicit_in_mir() { + for (ty, precision) in [("f32", "F32"), ("f64", "F64")] { + for optimize in [false, true] { + let source = format!( + r#"module Top(a: input {ty}, b: input {ty}, + y_add: output {ty}, y_sub: output {ty}, + y_mul: output {ty}, y_div: output {ty}, + y_neg: output {ty}, y_lt: output bit, y_ne: output bit) {{ + assign y_add = a + b; + assign y_sub = a - b; + assign y_mul = a * b; + assign y_div = a / b; + assign y_neg = -a; + assign y_lt = a <: b; + assign y_ne = a != b; + }}"# + ); + let result = SimulatorBuilder::new(&source, "Top") + .optimize(optimize) + .trace_mir() + .build_with_trace(); + if let Err(error) = &result.res { + panic!("FP source compilation failed: {error:?}"); + } + let mir = result.trace.mir.as_deref().expect("native MIR trace"); + for op in ["Add", "Sub", "Mul", "Div", "Neg", "Lt", "Ne"] { + assert!( + mir.contains(&format!("fp.{op}.{precision}")) + || (mir.contains(&format!("op: {op},")) + && mir.contains(&format!("precision: {precision},"))), + "missing {op} ({ty}, optimize={optimize}):\n{mir}" + ); + } + assert!( + !mir.contains("extern") && !mir.contains("CallExtern"), + "unexpected FP helper:\n{mir}" + ); + let mut sim = result.unwrap(); + let a = sim.signal("a"); + let b = sim.signal("b"); + let bits = |x: f64| { + if ty == "f32" { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } + }; + sim.modify(|io| { + io.set(a, bits(3.5)); + io.set(b, bits(-2.0)); + }) + .unwrap(); + for (name, expected) in [ + ("y_add", 1.5), + ("y_sub", 5.5), + ("y_mul", -7.0), + ("y_div", -1.75), + ("y_neg", -3.5), + ] { + assert_eq!( + sim.get(sim.signal(name)), + bits(expected).into(), + "{name} ({ty})" + ); + } + assert_eq!(sim.get(sim.signal("y_lt")), 0u32.into()); + assert_eq!(sim.get(sim.signal("y_ne")), 1u32.into()); + } + } +} diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 2736f0d1198..574530a26d4 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -146,12 +146,6 @@ fn checkpoint_restores_string_values() { ); let saved = sim.checkpoint().unwrap(); assert_eq!(saved.state_size(), empty_size + b"saved string".len()); - assert!( - sim.save_state() - .unwrap_err() - .to_string() - .contains("dynamic testbench strings") - ); sim.set(mode, 1u32); assert_eq!( run_compiled_testbench(&mut sim, &program), @@ -165,6 +159,159 @@ fn checkpoint_restores_string_values() { ); } +#[test] +fn state_files_restore_string_values_by_contents() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let source = r#" + #[test(Top)] module Top { + var text: string; + var names: string[3]; + var mode: u32; + initial { + if mode == 0 { + text = "saved string"; + names[1] = "one"; + names[2] = "two"; + } else if mode == 1 { + text = "replacement"; + names[1] = "uno"; + } else { + $assert(text == "saved string", "[%s]", text); + $assert(names[0] == "", "[%s]", names[0]); + $assert(names[1] == "one", "[%s]", names[1]); + $assert(names[2] == "two", "[%s]", names[2]); + } + $finish(); + } + } + "#; + let mut sim = celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let mode = sim.signal("mode"); + sim.set(mode, 0u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let saved = sim.save_state().unwrap(); + assert_eq!( + saved.strings, + [b"one".to_vec(), b"two".to_vec(), b"saved string".to_vec()] + ); + let mut bytes = Vec::new(); + saved.write_to(&mut bytes).unwrap(); + let saved = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + + sim.set(mode, 1u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // A fresh simulator has none of the saved strings in its heap, so the + // file must carry their contents. + for target in [ + &mut sim, + &mut celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(), + ] { + target.load_state(&saved).unwrap(); + let mode = target.signal("mode"); + target.set(mode, 2u32); + assert_eq!( + run_compiled_testbench(target, &program), + celox::TestResult::Pass + ); + } +} + +#[test] +fn collected_heap_keeps_reachable_strings() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + // More distinct strings than one collection interval. + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = \"{value}\"; clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + inst clk: $tb::clock_gen; + initial {{ + kept = "kept"; + {assignments} + $assert(kept == "kept", "[%s]", kept); + $assert(text == "value 1499", "[%s]", text); + $finish(); + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // Without a collection the heap would hold every value. + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + +#[test] +fn concurrent_processes_keep_strings_across_collections() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = identity(\"{value}\"); clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + var done: bit; + inst clk: $tb::clock_gen; + function identity(value: input string) -> string {{ + return value; + }} + initial {{ + kept = identity("kept"); + clk.next(1600); + $assert(kept == "kept", "[%s]", kept); + $assert(done == 1); + $finish(); + }} + initial {{ + {assignments} + $assert(text == "value 1499", "[%s]", text); + done = 1; + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + #[test] fn unsupported_string_concatenation_is_rejected() { for expression in ["{a, b}", "{a repeat 2}"] { diff --git a/crates/lydite-celox/src/tests.rs b/crates/lydite-celox/src/tests.rs index 92f08e7a69d..0dc77c141c7 100644 --- a/crates/lydite-celox/src/tests.rs +++ b/crates/lydite-celox/src/tests.rs @@ -462,6 +462,7 @@ fn exported_array_width_is_total_not_per_element() { kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: array_dims.to_vec(), + value_kind: Default::default(), }) }; assert_eq!(shape(64, &[2]).unwrap(), (32, 2)); diff --git a/crates/lydite-celox/tests/fixtures/array_read_write2.json b/crates/lydite-celox/tests/fixtures/array_read_write2.json index 0ab8cb5adb8..26d02f21004 100644 --- a/crates/lydite-celox/tests/fixtures/array_read_write2.json +++ b/crates/lydite-celox/tests/fixtures/array_read_write2.json @@ -1 +1 @@ -{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} +{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 4f2bcd15a00..cbe8d605be0 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -42,14 +42,30 @@ synthesis and is tested at the design level. | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | +### Timing controls {#timing-controls} + +In a timed `Simulation`, `initial` and plain `always` processes can suspend: + +| Control | Supported | +| --- | --- | +| `#delay` | integral delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero | +| `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads | +| `wait (condition)` | any condition; an X or Z condition counts as false | +| Assignments | blocking and nonblocking; nonblocking updates take effect in the NBA region of the time slot | + +An `always` with a sensitivity list other than `@*`, such as +`always @(a or b)`, runs as a process too. A `Simulator` runs no processes, +so such a design simulates without them there; use `Simulation`, or write +`always @*` or `always_comb` ([#1712](https://github.com/celox-sim/celox/issues/1712)). + ### Timed task calls An `initial` or ordinary `always` process can call tasks containing `#delay`, `@(event)` and `wait (condition)`, including through nested tasks. Calls are inlined into the caller's resumable state machine. A normal edge-sensitive `always` that calls a timed task waits for that task to return before rearming -its event control. Functions, `always_comb`, `always @*` and `always_ff` cannot -call a timed task. +its event control. Functions, `always_comb` and `always_ff` cannot call a timed +task, and `always @*` cannot yet ([#1710](https://github.com/celox-sim/celox/issues/1710)). Automatic task arguments and locals have separate storage for each activation and survive suspension. Module-local static task arguments remain shared. Inputs and inouts @@ -74,12 +90,12 @@ stream (IEEE 1800-2023 18.12). Constraints (`with`), class methods, enum variables, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. -### Time literal delays +### Time literal delays {#time-literal-delays} Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and `#40ps`, with all six units from `fs` to `s`. Values round at the declaring scope's precision before conversion to scheduler ticks (5.8, 3.14.1). Real-valued -arithmetic expressions remain unsupported. +delays are not supported yet ([#1707](https://github.com/celox-sim/celox/issues/1707)). ### Built-in functions and tasks @@ -103,10 +119,17 @@ it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). - Classes. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. -- Behavioral and verification constructs: `final`, intra-assignment timing controls, +- Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), - named events, `fork` / `join`, concurrent assertions, `force` / `release`. -- Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. Level-sensitive sensitivity lists other than `@*` are unsupported. + named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. +- Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), + real-valued delays ([#1707](https://github.com/celox-sim/celox/issues/1707)), package-scoped delay values + ([#1710](https://github.com/celox-sim/celox/issues/1710)), impure function calls in event expressions, and + `wait` or event expressions reading a static task argument. Nonblocking + assignments in a process cannot yet target an unpacked array element, a + run-time position or a constant position outside the target + ([#1709](https://github.com/celox-sim/celox/issues/1709)). +- Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. - Ports and instances: non-ANSI port declarations ([#426](https://github.com/celox-sim/celox/issues/426)), `ref` ports ([#427](https://github.com/celox-sim/celox/issues/427)), wildcard `.*` connections ([#442](https://github.com/celox-sim/celox/issues/442)), gate primitives ([#457](https://github.com/celox-sim/celox/issues/457)), @@ -115,7 +138,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs, strings and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a - plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. + plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. A plain `always` with + such an edge, a multi-bit edge signal, or several edges without a reset is + rejected too, until it runs as a process ([#1708](https://github.com/celox-sim/celox/issues/1708)). - Combinational processes: nonblocking assignments inside `always_comb` ([#453](https://github.com/celox-sim/celox/issues/453)). - Loops: a procedural loop unrolls at most 10,000 iterations; a combinational @@ -290,6 +315,27 @@ their argument expressions (IEEE 1800-2023 9.4.2.2 and 9.2.2.2.1). Nonblocking latch assignments (`<=`) require NBA scheduling and remain unsupported, including when the inference option is enabled. +### Event and level waits {#timing-semantics} + +- An event control waits for a change that happens after it begins + (IEEE 1800-2023 9.4.2). In `a = 1; @(a ^ b);` the write to `a` is not an + event of the wait; the process resumes when `a` or `b` changes later. + Icarus 13.0 wakes on the earlier write; Verilator 5.052 agrees with Celox. +- `posedge` and `negedge` of a multi-bit expression follow its least + significant bit (Table 9-2): `@(posedge v)` ignores `v[3]`, and + `@(posedge v[3])` follows it. Transitions through X and Z count as in that + table, so `0` to `x` is a `posedge`. +- Continuous assignments, combinational processes and event expressions see + a process's writes when that process reaches a timing control or ends. + After `b = 1; a = 1;`, `a ^ b` has not changed, and a pulse + `a = 1; a = 0;` wakes `@(a)` but not `@(a ^ b)`; write `#0` between the + writes to make the pulse visible. IEEE 1800-2023 4.7 permits this order; + Icarus evaluates the expression at each write. +- A waiter does not yet see a value that one evaluation of `always_comb`, an + edge-triggered `always` or `always_ff` writes and then overwrites, as in + `y = 0; if (a) y = 1;` ([#1706](https://github.com/celox-sim/celox/issues/1706)). `always @*` already + reports that write. + ### Variable lifetimes Variable lifetimes follow IEEE 1800-2023 6.21. A variable declared in a diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index dea1c106dc5..7623b7ee719 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -55,14 +55,15 @@ compilation unit; choose the top by its SystemVerilog module name. | What your test needs | API | | --- | --- | | Set inputs, evaluate logic and advance clock events from Rust | `Simulator::from_sv_sources` | -| Advance simulation time and run supported `initial` processes | `Simulation::from_sv_sources` | +| Advance simulation time and run `initial` and `always` processes with timing controls | `Simulation::from_sv_sources` | | Include both Veryl and SystemVerilog sources | `Simulator::from_mixed_sources` | `Simulator::tick` drives the rising edge of the selected event. `Simulation` -tracks time and runs scheduled edges. Constant initialization applies to both; -`initial` blocks that read design state or call system tasks need `Simulation` -to execute as processes. Timing controls within SV `initial` blocks remain -restricted; see [unsupported constructs](./systemverilog-reference#what-is-not-supported). +tracks time and runs scheduled edges. Constant initialization applies to both. +`initial` blocks that read design state or call system tasks, processes with +timing controls and `always` blocks with a sensitivity list other than `@*` run +as processes and need `Simulation`; a `Simulator` does not run them +([#1712](https://github.com/celox-sim/celox/issues/1712)). Use `.four_state(true)` on the builder when your test needs X/Z values. The [4-state guide](./four-state) explains the state model. For time units, @@ -78,6 +79,7 @@ The main supported areas are: | Design structure | Modules, hierarchy, parameters, generate blocks, packages, interfaces and modports | | Data | Packed vectors, multidimensional packed arrays, structs, enums and unpacked memories | | RTL processes | `assign`, `always_comb`, `always @*`, blocking `always_latch`, edge-triggered `always` and `always_ff` | +| Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | | Simulation helpers | Immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | @@ -89,7 +91,10 @@ ports, types, statements or system functions before porting a design. Common reasons a design needs changes are: -- Class-based verification, concurrent assertions and tasks with timing controls. +- Class-based verification and concurrent assertions. +- `fork` / `join`, named events, intra-assignment timing such as `a = #1 b`, + `iff` in event controls ([#1444](https://github.com/celox-sim/celox/issues/1444)) and real-valued delays + ([#1707](https://github.com/celox-sim/celox/issues/1707)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. - Strings, `real`, unpacked structs and several interface features. @@ -120,6 +125,7 @@ and the supported types and call sites. ## Find a specific behavior {#semantics-worth-knowing} - [Initialization, scopes, variable lifetimes and memory files](./systemverilog-reference#semantics-worth-knowing) +- [Event and level waits in processes](./systemverilog-reference#timing-semantics) - [Time units, precision and time queries](./systemverilog-reference#time-and-precision) - [Random seeds and reproducibility](./systemverilog-reference#random-numbers) diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 2afc09c893b..c2ec6c42dbe 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -186,6 +186,7 @@ for. | `celox-backend-x86` | x86 MIR, instruction selection, target allocation policy, and machine-code emission | Frontend or runtime policy | | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | +| `celox-heap` | Dynamic values referenced by handles from state memory, and their collection | Root discovery, layouts, or scheduling | | `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | | `celox-runtime` | Events, timed scheduling, VCD output, testbench execution, and backend contracts | Frontend, SIR optimization, or concrete backend internals | | `celox` | Public API, compilation orchestration, and backend selection | New reusable compiler algorithms | diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index b7e4c3e542e..50ec446cad0 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -41,12 +41,29 @@ outline: [2, 3] | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | +### タイミング制御 {#timing-controls} + +時間を持つ `Simulation` では、`initial` と通常の `always` のプロセスが中断できます。 + +| 制御 | 対応範囲 | +| --- | --- | +| `#delay` | 整数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | +| `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` | +| `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | +| 代入 | ブロッキング代入とノンブロッキング代入。ノンブロッキング代入はそのタイムスロットの NBA 領域で反映 | + +`always @(a or b)` のように `@*` 以外のセンシティビティリストを持つ `always` も +プロセスとして実行します。`Simulator` はプロセスを実行しないため、そこではこのプロセス抜きで +シミュレーションされます。`Simulation` を使うか、`always @*` / `always_comb` で記述してください +([#1712](https://github.com/celox-sim/celox/issues/1712))。 + ### 時間待ちを含む task `initial` と通常の `always` から、`#delay`・`@(event)`・`wait (condition)` を 含む task を呼び出せます。task のネストも可能です。呼び出しは呼び出し元の状態機械に インライン展開されます。エッジ待ちの `always` は task の完了後に次のエッジを待ちます。 -function・`always_comb`・`always @*`・`always_ff` からの時間待ち task 呼び出しは拒否します。 +function・`always_comb`・`always_ff` からの時間待ち task 呼び出しは拒否します。 +`always @*` からの呼び出しも現在は拒否します([#1710](https://github.com/celox-sim/celox/issues/1710))。 automatic な引数とローカル変数は呼び出しごとに独立し、中断中も保持されます。 module 内の static task の引数は共有されます。input/inout は呼び出し時にコピーされ、output/inout は @@ -67,11 +84,11 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task `with` 制約、class メソッド、enum 変数、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 -### 時間リテラルによる遅延 +### 時間リテラルによる遅延 {#time-literal-delays} 遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に 対応します。宣言スコープの時間精度で丸めてから scheduler の tick に変換します -(5.8、3.14.1)。実数の算術式は引き続き未対応です。 +(5.8、3.14.1)。実数の遅延はまだ未対応です([#1707](https://github.com/celox-sim/celox/issues/1707))。 ### 組み込み関数とタスク @@ -97,15 +114,23 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - interface のポート、`inout` / `ref` / 式を使う modport、virtual interface など。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 -- 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 - named event、`fork` / `join`、並行アサーション、`force` / `release`。 -- `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。`@*` 以外のレベルセンシティブなセンシティビティリストは未対応です。 +- 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 + named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、並行アサーション、`force` / `release`。 +- プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、 + 実数の遅延([#1707](https://github.com/celox-sim/celox/issues/1707))、package スコープの遅延値 + ([#1710](https://github.com/celox-sim/celox/issues/1710))、イベント式内の impure な関数呼び出し、 + static task 引数を読む `wait` 条件とイベント式。プロセス内のノンブロッキング代入は、 + unpacked 配列の要素、実行時に決まる位置、代入先の範囲外の定数位置をまだ代入先にできません + ([#1709](https://github.com/celox-sim/celox/issues/1709))。 +- `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、文字列、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ - オペランド([#464](https://github.com/celox-sim/celox/issues/464))。 + オペランド([#464](https://github.com/celox-sim/celox/issues/464))。このようなエッジ、複数ビットのエッジ信号、リセットを持たない + 複数のエッジを持つ通常の `always` も、プロセスとして実行できるようになるまで拒否します + ([#1708](https://github.com/celox-sim/celox/issues/1708))。 - 組み合わせ回路のプロセス:`always_comb` 内のノンブロッキング代入([#453](https://github.com/celox-sim/celox/issues/453))。 - ループ:手続き的なループの展開は 10,000 回までです。反復回数が実行時に決まる組み合わせ 回路のループは、カウンタ形式の `for` である必要があります。loop-generate は 10,000 回を @@ -216,6 +241,24 @@ Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatche 感度に寄与します(IEEE 1800-2023 9.4.2.2、9.2.2.2.1)。 ノンブロッキング代入(`<=`)には NBA スケジューリングが必要であり、推論を許可しても未対応です。 +### イベント待ちとレベル待ち {#timing-semantics} + +- イベント制御は、開始した後に起きた変化を待ちます(IEEE 1800-2023 9.4.2)。 + `a = 1; @(a ^ b);` の `a` への書き込みはこの待ちのイベントにならず、 + その後に `a` か `b` が変化したときに再開します。 + Icarus 13.0 は先の書き込みで起床し、Verilator 5.052 は Celox と同じ結果になります。 +- 複数ビットの式の `posedge` / `negedge` は最下位ビットで判定します(Table 9-2)。 + `@(posedge v)` は `v[3]` を無視し、`@(posedge v[3])` は `v[3]` に従います。 + X / Z を経由する遷移も同表に従い、`0` から `x` は `posedge` です。 +- 継続代入、組み合わせ回路のプロセス、イベント式は、書き込んだプロセスがタイミング制御に + 達するか終了した時点でその書き込みを参照します。`b = 1; a = 1;` の後でも `a ^ b` は + 変化しておらず、パルス `a = 1; a = 0;` は `@(a)` を起こしますが `@(a ^ b)` は起こしません。 + パルスを見せるには書き込みの間に `#0` を入れてください。この順序は IEEE 1800-2023 4.7 で + 許されています。Icarus は書き込みごとに式を評価します。 +- `always_comb`、エッジで起動する `always`、`always_ff` の1回の評価の中で書いてから上書きした値 + (`y = 0; if (a) y = 1;` など)は、まだ待ち側から見えません + ([#1706](https://github.com/celox-sim/celox/issues/1706))。`always @*` ではすでに見えます。 + ### 変数の寿命 変数の寿命は IEEE 1800-2023 6.21 に従います。プロセスのブロック、関数、タスクの中で宣言した diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 597911784a7..c341643e4eb 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -52,15 +52,15 @@ assert_eq!(sim.get(q), 1u8.into()); | テストで行いたいこと | API | | --- | --- | | Rust から入力を設定し、論理を評価してクロックイベントを進める | `Simulator::from_sv_sources` | -| シミュレーション時刻を進め、対応する `initial` プロセスを実行する | `Simulation::from_sv_sources` | +| シミュレーション時刻を進め、タイミング制御を持つ `initial` / `always` プロセスを実行する | `Simulation::from_sv_sources` | | Veryl と SystemVerilog のソースを一緒に扱う | `Simulator::from_mixed_sources` | `Simulator::tick` は指定イベントの立ち上がりエッジを駆動します。 `Simulation` は時刻を管理し、スケジュールされたエッジを実行します。 -定数による初期化はどちらにも適用されますが、デザインの状態を読む、またはシステムタスクを呼ぶ -`initial` ブロックをプロセスとして実行するには `Simulation` が必要です。 -SV の `initial` 内のタイミング制御には制約があるため、 -[未対応の構文](./systemverilog-reference#what-is-not-supported)も確認してください。 +定数による初期化はどちらにも適用されます。デザインの状態を読む、またはシステムタスクを呼ぶ +`initial` ブロック、タイミング制御を持つプロセス、`@*` 以外のセンシティビティリストを持つ +`always` はプロセスとして実行するため `Simulation` が必要です。`Simulator` はこれらを実行しません +([#1712](https://github.com/celox-sim/celox/issues/1712))。 X/Z を扱う場合は builder に `.four_state(true)` を指定します。 状態モデルは [4 値シミュレーション](./four-state)、時刻、`$stop`、メモリの読み込みなどは @@ -75,6 +75,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 | デザイン構造 | モジュール階層、パラメータ、generate、package、interface と modport | | データ | packed ベクタ、多次元 packed 配列、構造体、enum、unpacked メモリ | | RTL のプロセス | `assign`、`always_comb`、`always @*`、ブロッキング代入の `always_latch`、エッジで起動する `always` と `always_ff` | +| 時間を持つプロセス | `#delay`(`#5ns` などの時間リテラルを含む)、変数・エッジ・選択・式・`@*` に対する `@(...)`、`wait (...)`、ノンブロッキング代入、タイミング制御を持つ task 呼び出しを使う `initial` と `always` | | 演算と制御 | 算術、部分選択、assignment pattern、分岐、ループ、関数 | | シミュレーション補助 | 即時アサーション、表示タスク、`$readmemh` / `$readmemb`、時刻の取得、乱数 | @@ -85,7 +86,9 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 デザインの変更が必要になりやすいのは、次の機能です。 -- クラスを使う検証、並行アサーション、タイミング制御を持つ task。 +- クラスを使う検証、並行アサーション。 +- `fork` / `join`、named event、`a = #1 b` のような代入内のタイミング制御、 + イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))、実数の遅延([#1707](https://github.com/celox-sim/celox/issues/1707))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 - 文字列、`real`、unpacked 構造体、interface の一部の機能。 @@ -113,6 +116,7 @@ C と SV の型を一致させる必要があるため、どちらも `unsafe` A ## 個別の挙動を調べる {#知っておくべき挙動} - [初期化、スコープ、変数の寿命、メモリファイル](./systemverilog-reference#semantics-worth-knowing) +- [プロセス内のイベント待ちとレベル待ち](./systemverilog-reference#timing-semantics) - [時間単位、精度、時刻の取得](./systemverilog-reference#time-and-precision) - [乱数のシードと再現性](./systemverilog-reference#random-numbers) diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 4e8b5afe6ef..4751671c3c4 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -25,6 +25,7 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen + celox-heap celox-testbench celox-sir celox-state-layout