diff --git a/crates/celox-backend-x86/src/backend/native/emit.rs b/crates/celox-backend-x86/src/backend/native/emit.rs index 39a76440b4e..329e4c68f77 100644 --- a/crates/celox-backend-x86/src/backend/native/emit.rs +++ b/crates/celox-backend-x86/src/backend/native/emit.rs @@ -815,6 +815,32 @@ pub fn emit( ) } +/// Emit a caller with disjoint storage above every generated callee's arena. +/// Pass `required_state_size` from each reachable callee's `EmitResult`; +/// each callee must itself have been emitted with its own callees' extents. +/// `state_size` describes the common semantic state, not an arena reservation. +pub fn emit_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + callee_ends: &[usize], +) -> Result { + verify_emission_inputs(func, assignment, spill_frame_size, false)?; + let plan = SsaDestructionPlan::build(func, assignment)?; + plan.verify(func, assignment, spill_frame_size)?; + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + &plan, + false, + false, + callee_ends, + ) +} + /// Direct emitter tests do not carry a complete `MemoryLayout`. Place their /// native arena beyond every statically named SimState byte plus a guard so /// test-owned sentinel bytes cannot alias prologue/scratch storage. @@ -845,11 +871,12 @@ pub(crate) fn emit_with_plan( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, false)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -857,6 +884,7 @@ pub(crate) fn emit_with_plan( plan, false, false, + callee_ends, ) } @@ -865,12 +893,13 @@ fn emit_with_plan_tick_loop( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, check_runtime_events: bool, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, true)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -878,6 +907,7 @@ fn emit_with_plan_tick_loop( plan, true, check_runtime_events, + callee_ends, ) } @@ -1043,6 +1073,45 @@ fn emit_planned( tick_loop: bool, check_runtime_events: bool, ) -> Result { + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + plan, + tick_loop, + check_runtime_events, + &[], + ) +} + +/// Callee extents include their own recursively reserved callees. The state +/// pointer stays unchanged; only the caller's private arena is placed above +/// those complete extents. Merely using the same semantic state size for both +/// functions is not sufficient to isolate live spills and pinned saves. +fn emit_planned_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + plan: &SsaDestructionPlan, + tick_loop: bool, + check_runtime_events: bool, + callee_ends: &[usize], +) -> Result { + let has_kernels = func.blocks.iter().flat_map(|b| &b.insts).any(|inst| + matches!(inst, MInst::CallExtern { func, .. } if celox_sir::extern_abi::native_kernel_index(*func).is_some())); + if has_kernels && (callee_ends.is_empty() || callee_ends.contains(&0)) { + return Err(EmitInputError::new( + "EMIT.NATIVE_CALLEE_ARENA", + None, + None, + None, + "generated kernel calls require the callees' complete required_state_size extents", + ) + .into()); + } + let state_size = callee_ends.iter().copied().fold(state_size, usize::max); let mut uses_bmi2 = false; let mut uses_avx = false; let mut uses_popcnt = false; @@ -1297,6 +1366,30 @@ fn emit_planned( asm.jmp(epilogue_label)?; } } + MInst::CallExtern { func, arg_count } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + extern_call::emit_call_extern(&mut asm, *func, *arg_count)?; + // The call restored our state base and pinned registers. + // RAX still holds the complete signed callee status. + asm.test(rax, rax)?; + if tick_loop { + let mut success = asm.create_label(); + asm.jz(success)?; + // Match ReturnError's completed-tick accounting while + // retaining RAX for the common epilogue. + asm.movq(r10, xmm15)?; + asm.dec(r10)?; + asm.movq(xmm15, r10)?; + asm.jmp(epilogue_label)?; + asm.set_label(&mut success)?; + // A following MIR block may start here; code_asm + // cannot bind two labels to the same instruction. + asm.nop()?; + } else { + asm.jnz(epilogue_label)?; + } + } MInst::ReturnError { code } => { if tick_loop { asm.movq(rax, xmm15)?; diff --git a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs index 3c40c1e1030..35867c2a8a5 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs @@ -50,8 +50,10 @@ pub(super) fn set_call_area( } /// The XMM registers a call must save: pinned ones the callee may change. -fn saved_xmms(context: &EmissionContext) -> impl Iterator { - let saved = context.pinned_xmms & !C_PRESERVED_XMMS; +fn saved_xmms(context: &EmissionContext, native_kernel: bool) -> impl Iterator { + // Generated x86 functions use SysV on every host, including Windows. + let preserved = if native_kernel { 0 } else { C_PRESERVED_XMMS }; + let saved = context.pinned_xmms & !preserved; (0..16).filter(move |index| saved & (1 << index) != 0) } @@ -98,11 +100,12 @@ pub(super) fn emit_call_extern( let context = asm.context; let area = call_area(&context); let strategy = state_base_strategy(&context); + let kernel = celox_sir::extern_abi::native_kernel_index(func); // RBX is callee-saved in every C ABI and free here: it holds the state // pointer while the segment base belongs to C code. emit_state_base(asm, rbx)?; - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), xmm_register(index), @@ -119,14 +122,15 @@ pub(super) fn emit_call_extern( StateBaseStrategy::R15 => {} } - let (registers, shadow): (&[AsmRegister64], i32) = if cfg!(target_os = "windows") { - (&[rcx, rdx, r8, r9], 32) - } else { - (&[rdi, rsi, rdx, rcx, r8, r9], 0) - }; + let (registers, shadow): (&[AsmRegister64], i32) = + if cfg!(target_os = "windows") && kernel.is_none() { + (&[rcx, rdx, r8, r9], 32) + } else { + (&[rdi, rsi, rdx, rcx, r8, r9], 0) + }; // The heap helper takes the state pointer before the staged arguments. let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; - let leading = usize::from(heap); + let leading = usize::from(heap || kernel.is_some()); let arg_count = usize::from(arg_count) + leading; let stack_args = arg_count.saturating_sub(registers.len()) as i32; // Generated code is entered with RSP = 8 (mod 16) and never moves it. @@ -158,7 +162,7 @@ pub(super) fn emit_call_extern( } else if heap { -16 } else { - i32::try_from(u64::from(func) * 8).expect("extern function index") + i32::try_from(u64::from(kernel.unwrap_or(func)) * 8).expect("extern function index") }; asm.mov(rax, qword_ptr(rax + offset))?; asm.call(rax)?; @@ -170,7 +174,7 @@ pub(super) fn emit_call_extern( StateBaseStrategy::Gs => asm.wrgsbase(rbx)?, StateBaseStrategy::R15 => {} } - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( xmm_register(index), qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), diff --git a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs index 73fc6a8af8c..92855fcad1b 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs @@ -336,12 +336,19 @@ fn emit_prepared_eu_inner( let state_size = options .arena_base .map_or(semantic_size, |base| base.max(semantic_size)); + let native_callee_end = [options.arena_base.unwrap_or(0)]; + let callee_ends = if options.arena_base.is_some() { + &native_callee_end[..] + } else { + &[] + }; let result = if label == "eval_comb_apply_ff" && options.native_tick_loop { emit_with_plan_tick_loop( &mfunc, &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, check_runtime_events, )? @@ -351,6 +358,7 @@ fn emit_prepared_eu_inner( &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, )? }; diff --git a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs index 94d09772410..93aa15c764e 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs @@ -172,3 +172,308 @@ fn extern_calls_preserve_live_values_with_a_segment_state_base() { run(StateBaseStrategy::Gs, false); run(StateBaseStrategy::Gs, true); } + +/// The implicit state argument and signed status must survive ABI register +/// clobbers, spills across the call, and both state-base strategies. +extern "sysv64" fn kernel_with_status(state: *mut u8) -> i64 { + let _ = trashing_weighted_sum(1, 2, 3, 4, 5, 6, 7, 8); + // SAFETY: the generated caller passes this test's complete state buffer. + unsafe { *state.add(RESULT + 16).cast::() } +} + +#[test] +fn native_kernel_calls_preserve_live_values_and_propagate_signed_status() { + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + let mut function = live_across_calls(strategy); + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG; + *arg_count = 0; + } + } + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let emitted = emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + RESULT + 24, + &plan, + tick_loop, + false, + &[RESULT + 24], // This Rust ABI surrogate uses no private native arena. + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let table = [kernel_with_status as *const () as usize]; + let event_sequence = 0u64; + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut memory = vec![0u64; emitted.required_state_size as usize / 8 + 1]; + memory[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + memory[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&event_sequence as *const u64) as u64; + memory[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + memory[(RESULT + 16) / 8] = status as u64; + let values = (1..=LIVE as u64).collect::>(); + memory[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&values); + let calls = CALLS.get(); + assert_eq!(unsafe { (jit.fn_ptr)(memory.as_mut_ptr().cast()) }, status); + assert_eq!(CALLS.get() - calls, if status == 0 { 2 } else { 1 }); + if status == 0 { + assert_eq!(&memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &values); + } else { + assert!( + memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE] + .iter() + .all(|&v| v == 0) + ); + } + } + } + } +} + +fn generated_kernel( + strategy: StateBaseStrategy, + input_base: usize, + callee: Option, +) -> MFunction { + let mut function = live_across_calls(strategy); + for inst in &mut function.blocks[0].insts { + if let MInst::Load { offset, .. } = inst { + *offset += input_base as i32 - BASE as i32; + } + } + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + match callee { + Some(callee) => { + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | callee; + *arg_count = 0; + } + } + } + None => { + instructions.retain(|inst| !matches!(inst, MInst::CallExtern { .. })); + for inst in instructions.iter_mut() { + if let MInst::ExternResult { dst } = inst { + *inst = MInst::LoadImm { + dst: *dst, + value: 0, + }; + } + } + // Prevent memory-backed reload recipes: each loaded value must + // survive an overwrite of its source before it is published. + let position = instructions + .iter() + .position(|inst| matches!(inst, MInst::LoadImm { .. })) + .unwrap(); + let MInst::LoadImm { dst: zero, .. } = instructions[position] else { + unreachable!() + }; + instructions.splice( + position + 1..position + 1, + (0..LIVE).map(|index| MInst::Store { + base: BaseReg::SimState, + offset: (input_base + index * 8) as i32, + src: zero, + size: OpSize::S64, + }), + ); + } + } + function +} + +#[test] +fn generated_callee_spills_do_not_overwrite_live_caller_values() { + const STATE_SIZE: usize = 4096; + let mut child = generated_kernel(StateBaseStrategy::R15, 1024, None); + let allocation = regalloc::run_regalloc(&mut child).unwrap(); + assert!(allocation.spill_frame_size > 0, "callee must really spill"); + let plan = SsaDestructionPlan::build(&child, &allocation.assignment).unwrap(); + let child_code = emit_planned( + &child, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &plan, + false, + false, + ) + .unwrap(); + let child_jit = JitCode::new(&child_code.code).unwrap(); + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "caller must retain real spilled values" + ); + assert!( + matches!(emit(&caller, &allocation.assignment, allocation.spill_frame_size), + Err(EmitError::Input(ref error)) if error.rule == "EMIT.NATIVE_CALLEE_ARENA") + ); + let caller_code = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &[child_code.required_state_size as usize], + ) + .unwrap(); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [child_jit.fn_ptr as usize]; + let mut state = vec![ + 0u64; + caller_code + .required_state_size + .max(child_code.required_state_size) as usize + / 8 + + 1 + ]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!(unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, 0); + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); +} + +fn compile_generated( + mut function: MFunction, + state_size: usize, + callees: &[usize], + tick_loop: bool, +) -> EmitResult { + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "every generated level must really spill" + ); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let options = crate::X86BackendOptions::default().with_native_callees(callees.iter().copied()); + let bounds = options.arena_base.into_iter().collect::>(); + emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + state_size, + &plan, + tick_loop, + false, + &bounds, + ) + .unwrap() +} + +#[test] +fn nested_generated_kernels_have_disjoint_arenas_and_propagate_status() { + const STATE_SIZE: usize = 4096; + const COMPLETED: usize = 2048; + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut leaf = generated_kernel(strategy, 1024, None); + if status != 0 { + *leaf.blocks[0].insts.last_mut().unwrap() = MInst::ReturnError { code: status }; + } + let leaf_code = compile_generated(leaf, STATE_SIZE, &[], false); + let leaf_jit = JitCode::new(&leaf_code.code).unwrap(); + let middle = generated_kernel(strategy, 512, Some(0)); + let middle_code = compile_generated( + middle, + STATE_SIZE, + &[leaf_code.required_state_size as usize], + false, + ); + let middle_jit = JitCode::new(&middle_code.code).unwrap(); + let mut caller = generated_kernel(strategy, BASE, Some(1)); + let marker = caller.vregs.alloc(); + caller.spill_descs.push(SpillDesc::remat(0x51)); + let instructions = &mut caller.blocks[0].insts; + let end = instructions.len() - 1; + instructions.splice( + end..end, + [ + MInst::LoadImm { + dst: marker, + value: 0x51, + }, + MInst::Store { + base: BaseReg::SimState, + offset: COMPLETED as i32, + src: marker, + size: OpSize::S64, + }, + ], + ); + let caller_code = compile_generated( + caller, + STATE_SIZE, + &[middle_code.required_state_size as usize], + tick_loop, + ); + assert!(middle_code.required_state_size > leaf_code.required_state_size); + assert!(caller_code.required_state_size > middle_code.required_state_size); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [leaf_jit.fn_ptr as usize, middle_jit.fn_ptr as usize]; + let mut state = vec![0u64; caller_code.required_state_size as usize / 8 + 1]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let sequence = 0u64; + state[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&sequence as *const u64) as u64; + state[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[512 / 8 + i] = 1000 + i as u64; + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!( + unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, + status, + "{strategy:?}, tick={tick_loop}" + ); + assert_eq!(state[COMPLETED / 8], if status == 0 { 0x51 } else { 0 }); + if status == 0 { + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); + } + } + } + } +} + +#[test] +fn generated_callee_arena_overflow_is_rejected() { + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + let result = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + 4096, + &[usize::MAX], + ); + assert!( + matches!(result, Err(EmitError::Input(ref error)) if error.rule=="EMIT.NATIVE_ARENA_RANGE") + ); +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/slice.rs index 3f9787c512a..4e96c282003 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/slice.rs @@ -7,6 +7,11 @@ impl ISelContext<'_> { &mut self, inst: &SIRInstruction, ) { + if matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + { + self.reg_addrs.clear(); + } if let Some(write) = inst.memory_write() && write.width != 0 { diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs index 116d86e88b2..591039fb94c 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs @@ -140,8 +140,14 @@ fn slice_preserves_loaded_value_across_store() { ); } if overlapping { - // Dynamic stores and commits also invalidate a static load. + // Dynamic stores, commits and opaque kernels invalidate + // a static load before any direct slice reload. for write in [ + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: vec![], + }, SIRInstruction::Store( input, SIROffset::Dynamic(replacement), diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs index cc6c401f0bd..e376073f7f8 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs @@ -98,8 +98,7 @@ pub const ALLOCATABLE_REGS: &[PhysReg] = &[ /// The registers an extern call changes: those a C function need not /// preserve, and RBX, which holds the state pointer during the call sequence. -#[cfg(not(target_os = "windows"))] -const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ +const NATIVE_KERNEL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, PhysReg::RCX, PhysReg::RDX, @@ -111,6 +110,8 @@ const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::R11, PhysReg::RBX, ]; +#[cfg(not(target_os = "windows"))] +const EXTERN_CALL_CLOBBERS: &[PhysReg] = NATIVE_KERNEL_CLOBBERS; #[cfg(target_os = "windows")] const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, @@ -223,6 +224,11 @@ pub fn clobbers(inst: &MInst) -> &'static [PhysReg] { // Return. Model the clobber at the allocation boundary instead so // only genuinely live-through values are moved to their homes. MInst::SparseCommitWorklist { .. } => ALLOCATABLE_REGS, + MInst::CallExtern { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + NATIVE_KERNEL_CLOBBERS + } MInst::CallExtern { .. } => EXTERN_CALL_CLOBBERS, _ => &[], } diff --git a/crates/celox-backend-x86/src/lib.rs b/crates/celox-backend-x86/src/lib.rs index 6d35faf9394..91afba2f67c 100644 --- a/crates/celox-backend-x86/src/lib.rs +++ b/crates/celox-backend-x86/src/lib.rs @@ -59,11 +59,25 @@ pub struct X86BackendOptions { pub native_tick_loop: bool, /// Physical state offset where the function's private spill, scratch, /// and save arena begins. `None` places it directly after the semantic - /// state. Functions that may run concurrently need disjoint arenas. + /// state. Functions that may run concurrently or call generated kernels + /// need disjoint arenas. Kernel callers must reserve at least every + /// callee's complete `required_state_size`; use `with_native_callees`. pub arena_base: Option, pub diagnostics: NativeDiagnostics, } +impl X86BackendOptions { + /// Place this function's private arena above all generated callees. + /// Sizes must be their complete emitted `required_state_size`, including + /// reservations for nested callees, rather than the semantic state size. + pub fn with_native_callees(mut self, sizes: impl IntoIterator) -> Self { + if let Some(end) = sizes.into_iter().max() { + self.arena_base = Some(self.arena_base.map_or(end, |base| base.max(end))); + } + self + } +} + impl Default for X86BackendOptions { fn default() -> Self { Self { diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 77e3c065724..dc586ef7f0e 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -337,6 +337,7 @@ fn interface_signatures_collecting( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -949,6 +950,7 @@ fn lower_package_states( &[], LevelLists::Processes, &HashMap::default(), + &HashMap::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -3171,24 +3173,44 @@ fn demote_level_lists( changed } -// Use elaboration provenance rather than treating every '$' as a separator: -// legal authored identifiers may themselves contain '$'. +// Candidate indices only locate a declaration; source provenance decides +// whether this is an interface path. Authored '$' names stay intact. +fn restore_interface_path( + name: &str, + paths: &HashMap, +) -> Option> { + if let Some(path) = paths.get(name) { + return path.restore(name); + } + for (separator, _) in name.match_indices('$') { + let member = &name[separator + 1..]; + let mut handle = &name[..separator]; + while let Some(indexed) = handle.strip_suffix(']') { + let Some((base, index)) = indexed.rsplit_once('[') else { + break; + }; + if index.parse::().is_err() { + break; + } + let key = format!("{base}${member}"); + if let Some(path) = paths.get(&key).filter(|path| path.arrayed) + && let Some(restored) = path.restore(name) + { + return Some(restored); + } + handle = base; + } + } + None +} + fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvModule) { for variable in module.variables.values_mut() { variable.path = variable .path .iter() .flat_map(|segment| { - source - .interface_member_paths - .get(segment) - .and_then(|path| path.restore(segment)) - .or_else(|| { - source - .interface_member_paths - .values() - .find_map(|path| path.restore(segment)) - }) + restore_interface_path(segment, &source.interface_member_paths) .unwrap_or_else(|| vec![segment.clone()]) }) .collect(); @@ -3367,6 +3389,7 @@ fn specialize_module( &local_forces, level_lists, hierarchical.foreign_writes, + &module.interface_member_paths, )?; propagate_force_signals(&mut lowered.instances, &key.force_signals); lowered.sim_module.time_precision = Some( @@ -3480,6 +3503,7 @@ fn lower_module( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { lower_module_with_overrides( module, @@ -3491,6 +3515,7 @@ fn lower_module( force_signals, level_lists, foreign_writes, + reflected_paths, ) } @@ -3573,6 +3598,7 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + reflected_paths: &HashMap, ) -> Result { let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); @@ -3777,7 +3803,14 @@ fn lower_module_with_overrides( // Retain integral parameters for external observation, without adding them // to name_to_id: HDL expressions must still fold parameter references as // constants rather than introduce runtime loads. - for parameter in module.parameters() { + // Interface declarations are flattened into imported symbols, rather + // than authored module parameters. Retain their instance-local values as + // well; package imports remain owned by their package (IEEE 37.10). + let interface_parameters = module + .imported_parameters() + .iter() + .filter(|parameter| restore_interface_path(parameter.name(), reflected_paths).is_some()); + for parameter in module.parameters().iter().chain(interface_parameters) { let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else { continue; }; @@ -11289,3 +11322,52 @@ endmodule ); } } + +#[cfg(test)] +mod interface_reflection_tests { + use super::*; + + #[test] + fn indexed_interface_paths_require_declaration_provenance() { + let paths = [ + ( + "authored$bus$extra$width", + ["authored$bus", "extra$width"], + false, + ), + ("lanes$extra$width", ["lanes", "extra$width"], true), + ("g[3].lanes$W", ["g[3].lanes", "W"], true), + ] + .into_iter() + .map(|(key, segments, arrayed)| { + ( + key.to_string(), + sv::InterfaceMemberPath { + segments: segments.into_iter().map(str::to_string).collect(), + arrayed, + }, + ) + }) + .collect(); + for (name, expected) in [ + ("authored$bus$extra$width", ["authored$bus", "extra$width"]), + ("lanes[1][-2]$extra$width", ["lanes[1][-2]", "extra$width"]), + ("g[3].lanes[7]$W", ["g[3].lanes[7]", "W"]), + ] { + assert_eq!( + restore_interface_path(name, &paths), + Some(expected.into_iter().map(str::to_string).collect()), + "{name}" + ); + } + for name in [ + "lanes$not_declared", + "lanes[foo]$extra$width", + "authored$bus[0]$extra$width", + "normal$parameter", + "g[2].lanes[7]$W", + ] { + assert_eq!(restore_interface_path(name, &paths), None, "{name}"); + } + } +} diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs index b776566c169..6eb245ae5be 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs @@ -578,6 +578,29 @@ impl StateSsa { for (instruction_index, instruction) in block.instructions.iter().enumerate() { let mut instruction_effects = InstructionEffects::default(); match instruction { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + // An outlined native callee observes the old state and + // may replace every slot, including pending FF state. + for (slot, fact) in facts.iter_mut().enumerate() { + fact.escapes = true; + fact.has_kill = true; + fact.def_blocks.insert(block_id); + if !defined.contains(&slot) { + fact.upward_use_blocks.insert(block_id); + } + defined.insert(slot); + instruction_effects.uses.push(UseEffect { + slot, + destination: None, + }); + instruction_effects.defs.push(DefEffect { + slot, + kind: DefEffectKind::Kill, + }); + } + } SIRInstruction::Load(destination, addr, offset, width) if addr.region == region => { @@ -1314,6 +1337,72 @@ mod tests { .expect("destination has a StateSSA use") } + #[test] + fn native_kernel_call_observes_and_kills_every_state_region() { + for region in [STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION] { + let addr = address(region, 0); + let eu = unit( + vec![block( + 0, + vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(3u8)), + SIRInstruction::Store( + addr, + SIROffset::Static(0), + 8, + RegisterId(0), + Vec::new(), + Vec::new(), + ), + SIRInstruction::Load(RegisterId(1), addr, SIROffset::Static(0), 8), + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }, + SIRInstruction::Load(RegisterId(2), addr, SIROffset::Static(0), 8), + ], + SIRTerminator::Return, + )], + (0..3).map(|i| (RegisterId(i), bit(8))), + ); + eu.verify_result().unwrap(); + let cfg = SirCfg::analyze(&eu).unwrap(); + let state = StateSsa::analyze_all_loads(&eu, &cfg, region).unwrap(); + let MemoryAccessKind::Use { + reaching: before, .. + } = use_access(&state, RegisterId(1)).kind + else { + panic!("load") + }; + let MemoryAccessKind::Use { + reaching: after, .. + } = use_access(&state, RegisterId(2)).kind + else { + panic!("load") + }; + assert_ne!(before, after); + assert!(matches!( + state.accesses[after.0].kind, + MemoryAccessKind::Kill { .. } + )); + assert!(state.slots[0].escapes && state.slots[0].has_kill); + assert!( + state + .accesses + .iter() + .any(|access| access.instruction == Some(3) + && matches!( + access.kind, + MemoryAccessKind::Use { + destination: None, + .. + } + )) + ); + } + } + #[test] fn version_snapshots_preserve_versions_across_multiple_checkpoints() { let stable = address(STABLE_REGION, 0); diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs index 066d74dd102..5f020e0d092 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs @@ -29,6 +29,19 @@ pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit, partial: bool) { use crate::HashMap; + // An image-local callee can observe or publish any working slot. Its + // contents are outside this function's proof of independent publication. + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + return; + } // Phase 1: Scan — collect info about each WORKING variable struct VarInfo { diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs index 53d462dd880..7036ac44bc9 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs @@ -865,6 +865,19 @@ pub(crate) fn promote_eval_apply_working_round_trips_with_mode( eu: &mut ExecutionUnit, two_state: bool, ) -> bool { + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + // The callee can consume pending values or publish working state. + // Keep this function's memory form until StateSSA models that callee. + return false; + } let Ok(cfg) = SirCfg::analyze(eu) else { return false; }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs index b9254cab4e3..7379d0dc3f1 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs @@ -140,6 +140,11 @@ fn forward_and_simplify( // are always inserted after this rewrite, so one lookup is sufficient. apply_aliases_to_inst(inst, &aliases); match inst { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + known_stores.clear(); + } SIRInstruction::Store(addr, offset, width, src, _triggers, _) if offset.constant_bit_offset().is_some() => { @@ -469,6 +474,64 @@ mod tests { } } + #[test] + fn native_kernel_call_invalidates_prior_state_stores() { + let mut builder = celox_sir::SIRBuilder::new(); + let before = builder.alloc_bit(8, false); + let after = builder.alloc_bit(8, false); + builder.emit(SIRInstruction::Imm(before, SIRValue::new(42u8))); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(0), + 8, + before, + Vec::new(), + Vec::new(), + )); + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }); + builder.emit(SIRInstruction::Load( + after, + address(), + SIROffset::Static(0), + 8, + )); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(8), + 8, + after, + Vec::new(), + Vec::new(), + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + StoreLoadForwardingPass.run(&mut unit, &PassOptions::default()); + unit.verify_result().unwrap(); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .any(|inst| matches!(inst, SIRInstruction::Load(dst, ..) if *dst == after)) + ); + let saved = unit.clone(); + super::super::pass_eliminate_working_round_trip::eliminate_working_round_trip( + &mut unit, + &[], + ); + assert_eq!(unit.blocks, saved.blocks); + assert!(!super::super::pass_global_store_load_forwarding::promote_eval_apply_working_round_trips(&mut unit)); + assert_eq!(unit.blocks, saved.blocks); + } + #[test] fn removes_deep_dead_producer_chain_and_preserves_live_store() { let mut instructions = vec![ diff --git a/crates/celox-sir/src/extern_abi.rs b/crates/celox-sir/src/extern_abi.rs index 8956d1f4b86..61474070b68 100644 --- a/crates/celox-sir/src/extern_abi.rs +++ b/crates/celox-sir/src/extern_abi.rs @@ -17,6 +17,21 @@ use crate::RegisterType; /// user extern function table. pub const HEAP_HELPER_ID: u32 = u32::MAX - 1; +/// Native-only call to another compiled function in the same image. The low +/// 30 bits index the extern address table. It takes the implicit state pointer, +/// no explicit arguments or result, and propagates a nonzero status to its +/// caller. The callee may read and write arbitrary simulation state. +pub const NATIVE_KERNEL_CALL_TAG: u32 = 0x8000_0000; + +/// Decode a native kernel call, excluding the heap and floating-point helpers. +pub const fn native_kernel_index(function: u32) -> Option { + if function & 0xc000_0000 == NATIVE_KERNEL_CALL_TAG { + Some(function & 0x3fff_ffff) + } else { + None + } +} + /// The number of arguments of an extern call to [`HEAP_HELPER_ID`]. pub const HEAP_HELPER_ARGUMENTS: usize = 4; diff --git a/crates/celox-sir/src/verify.rs b/crates/celox-sir/src/verify.rs index b5d4acd8c0d..82d442b791a 100644 --- a/crates/celox-sir/src/verify.rs +++ b/crates/celox-sir/src/verify.rs @@ -632,6 +632,16 @@ fn verify_instruction_types( same_width(*old, *new, "TYPE.CAPTURE_COMPARE_OPERANDS")?; } SIRInstruction::ExternCall { dst, func, args } => { + if crate::extern_abi::native_kernel_index(*func).is_some() + && (dst.is_some() || !args.is_empty()) + { + return Err(SirVerifyError::instruction( + "TYPE.NATIVE_KERNEL_CALL_SIGNATURE", + block, + index, + "a native kernel call has only an implicit state pointer", + )); + } if *func == crate::extern_abi::HEAP_HELPER_ID && args.len() != crate::extern_abi::HEAP_HELPER_ARGUMENTS { diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index 7fddf6b39ec..58db650b9d5 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -267,6 +267,43 @@ pub(in crate::ast) fn specialize( } depth.set(depth.get() + 1); let _nesting = Nesting(depth); + // Parameter binding and body construction have large temporary values. + // Keep those phases off the stack while resolving an inherited class. + let pending = match prepare(tree, generic, arguments, context)? { + Preparation::Existing(name) => return Ok(name), + Preparation::Pending(pending) => pending, + }; + tree.state + .class_specializations_building + .borrow_mut() + .push(pending.name.clone()); + let _building = Building(&tree.state.class_specializations_building); + let bases = bind_bases(tree, generic, &pending.env, &pending.aliases)?; + finish_specialization(tree, generic, pending, bases) +} + +struct PendingSpecialization { + name: String, + parameters: Parameters, + env: HashMap, + aliases: HashMap, +} + +enum Preparation { + Existing(String), + Pending(Box), +} + +// These boundaries keep the recursive inheritance frame small in debug and +// optimized builds alike; the specialization limit must produce a diagnostic +// before the host thread runs out of stack. +#[inline(never)] +fn prepare( + tree: &AnalysisContext<'_>, + generic: &str, + arguments: &[Argument], + context: &PackedDimensions, +) -> Converted { let native = tree.declarations(); let declaration = super::declaration(tree, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; @@ -375,7 +412,7 @@ pub(in crate::ast) fn specialize( .borrow() .contains(&name) { - return Ok(name); + return Ok(Preparation::Existing(name)); } if tree.state.class_specializations_frozen.get() { return Err(unsupported(format!( @@ -387,11 +424,24 @@ pub(in crate::ast) fn specialize( "more than {MAX_SPECIALIZATIONS} class specializations" ))); } - tree.state - .class_specializations_building - .borrow_mut() - .push(name.clone()); - let _building = Building(&tree.state.class_specializations_building); + Ok(Preparation::Pending(Box::new(PendingSpecialization { + name, + parameters, + env, + aliases, + }))) +} + +#[inline(never)] +fn bind_bases( + tree: &AnalysisContext<'_>, + generic: &str, + env: &HashMap, + aliases: &HashMap, +) -> Converted> { + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The bases are named in the scope of the parameters; a class does not // inherit the declarations of the interface classes it implements. let inherited = match &declaration.base { @@ -401,12 +451,31 @@ pub(in crate::ast) fn specialize( }; let mut bases = Vec::new(); for id in inherited { - if let Some(base) = type_binding::procedural_type(id, native, tree, &env, &aliases)? + if let Some(base) = type_binding::procedural_type(id, native, tree, env, aliases)? .and_then(|ty| ty.class().map(str::to_owned)) { bases.push(base); } } + Ok(bases) +} + +#[inline(never)] +fn finish_specialization( + tree: &AnalysisContext<'_>, + generic: &str, + pending: Box, + bases: Vec, +) -> Converted { + let PendingSpecialization { + name, + mut parameters, + mut env, + mut aliases, + } = *pending; + let native = tree.declarations(); + let declaration = super::declaration(tree, generic) + .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The body sees the parameters and types of the bases, hidden by the // class's own, and the scope of the specialization (8.25.1). for base in &bases { @@ -1088,3 +1157,42 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } } } + +#[cfg(test)] +mod tests { + use std::path::Path; + + #[test] + fn inheritance_specialization_uses_the_default_thread_stack() { + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut source = String::from("module Top;"); + for index in 0..16 { + source.push_str(&format!( + "class Layer{index} #(int N = 0) extends Layer{}#(N + 1); endclass ", + index + 1, + )); + } + source.push_str( + "class Layer16 #(int N = 0); localparam int VALUE = N; endclass + Layer0#() object; initial $display(Layer0#()::VALUE); endmodule", + ); + crate::analyze_source(&source, Path::new("deep-class-inheritance.sv")).unwrap(); + + let error = crate::analyze_source( + "module Top; + class Recursive #(int N = 0) extends Recursive#(N + 1); endclass + Recursive object; endmodule", + Path::new("unbounded-class-inheritance.sv"), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("nested more than 64 deep"), "{error}"); + assert!(error.contains("class `Recursive`"), "{error}"); + }) + .unwrap() + .join() + .unwrap(); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index dfe0c33870b..4750eb0768f 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -679,6 +679,8 @@ struct InterfaceDecl { /// Whether the declaration refers to compilation-unit items of its file. uses_unit_items: bool, parameters: Vec, + /// Value parameters and localparams whose instance paths VPI can observe. + reflected_parameters: Vec, type_parameters: Vec, parameter_order: Vec, items: Vec, @@ -2423,6 +2425,7 @@ impl InterfaceDecl { uses_unit_items: false, uses_macros: has_directive(file.text(span)), parameters: Vec::new(), + reflected_parameters: Vec::new(), type_parameters: Vec::new(), parameter_order: Vec::new(), items: Vec::new(), @@ -2614,6 +2617,7 @@ impl InterfaceDecl { }); return Ok(()); }; + self.reflected_parameters.push(native_name(¶meter.name)); if local { self.declare(native_name(¶meter.name))?; self.items.push(Item::Constant { @@ -3506,11 +3510,17 @@ pub fn plan_interfaces_with_member_paths( let mut member_paths = HashMap::default(); for (handle_name, declarations) in &handles.by_name { for (_, handle) in declarations { - for member in &design.interfaces[&handle.interface].members { + let interface = &design.interfaces[&handle.interface]; + for member in interface + .members + .iter() + .map(|member| &member.name) + .chain(&interface.reflected_parameters) + { member_paths.insert( - format!("{handle_name}{SEPARATOR}{}", member.name), + format!("{handle_name}{SEPARATOR}{member}"), InterfaceMemberPath { - segments: vec![handle_name.clone(), member.name.clone()], + segments: vec![handle_name.clone(), member.clone()], arrayed: handle.arrayed, }, ); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 8f2971e3266..47c89a7fefd 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -76,6 +76,138 @@ fn systemverilog_parameters_are_typed_read_only_objects_at_o2() { clear_runtime(); } +#[cfg(feature = "systemverilog")] +#[test] +fn interface_parameters_keep_instance_paths_and_specialized_values() { + let _serial = lock_vpi(); + let source = r#" + package P; parameter PKG = 123; parameter axil_ctrl_bar$not_member = 99; endpackage + interface Bus #(parameter ADDR_W = 8, parameter extra$width = 3); + localparam HALF = ADDR_W / 2; + logic [ADDR_W-1:0] data; + endinterface + module Top #(parameter authored$width = 7)(output logic q); + import P::*; + Bus #(.ADDR_W(24)) axil_ctrl_bar(); + Bus #(.ADDR_W(12)) lanes[1:0](); + assign q = 1'b0; + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("interface_params.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + for (name, expected) in [ + (c"Top.axil_ctrl_bar.ADDR_W", 24), + (c"Top.axil_ctrl_bar.HALF", 12), + (c"Top.lanes[1].ADDR_W", 12), + (c"Top.lanes[0].HALF", 6), + (c"Top.lanes[0].extra$width", 3), + (c"Top.authored$width", 7), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TYPE, handle), VPI_PARAMETER); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?}"); + value.value.integer = 0; + vpi_put_value(handle, &value, ptr::null(), VPI_NO_DELAY); + vpi_get_value(handle, &mut value); + assert_eq!(value.value.integer, expected, "{name:?} is read-only"); + vpi_free_object(handle); + } + // Imported package constants do not acquire module-instance names. + assert!(vpi_handle_by_name(c"Top.PKG".as_ptr(), ptr::null_mut()).is_null()); + assert!( + vpi_handle_by_name(c"Top.axil_ctrl_bar$not_member".as_ptr(), ptr::null_mut()).is_null() + ); + } + clear_runtime(); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn generate_scopes_with_only_child_instances_are_iterable() { + let _serial = lock_vpi(); + let source = r#" + module Leaf #(parameter P = 0)(output logic q); + timeunit 1us; timeprecision 1ns; + assign q = P; + endmodule + module Top(output logic [1:0] q); + timeunit 1ns; timeprecision 1ps; + for (genvar n = 0; n < 2; n++) begin : bank + if (1) begin : shell + Leaf #(.P(n)) u(q[n]); + end + end + endmodule + "#; + let simulator = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("generate_scopes.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let image = simulator.shared_code().program_image().clone(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let _session = install_runtime(trusted_instance(image)).unwrap(); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let iterator = vpi_iterate(VPI_INTERNAL_SCOPE, top); + assert!(!iterator.is_null()); + let mut names = Vec::new(); + loop { + let bank = vpi_scan(iterator); + if bank.is_null() { + break; + } + names.push( + CStr::from_ptr(vpi_get_str(VPI_NAME, bank)) + .to_str() + .unwrap() + .to_string(), + ); + assert_eq!(vpi_get(VPI_TIME_UNIT, bank), -9); + let nested = vpi_iterate(VPI_INTERNAL_SCOPE, bank); + assert!(!nested.is_null()); + let shell = vpi_scan(nested); + assert!(!shell.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, shell)), c"shell"); + assert_eq!(vpi_get(VPI_TIME_UNIT, shell), -9); + assert!(vpi_scan(nested).is_null()); + let children = vpi_iterate(VPI_MODULE, shell); + let leaf = vpi_scan(children); + assert!(!leaf.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, leaf)), c"u"); + assert_eq!(vpi_get(VPI_TIME_UNIT, leaf), -6); + assert!(vpi_scan(children).is_null()); + vpi_free_object(leaf); + vpi_free_object(shell); + vpi_free_object(bank); + } + assert_eq!(names, ["bank[0]", "bank[1]"]); + vpi_free_object(top); + } + clear_runtime(); +} + unsafe extern "C" fn reschedule_long_callback(data: *mut VpiCbData) -> i32 { let count = LONG_CALLBACK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; let delay = LONG_CALLBACK_DELAY.load(Ordering::SeqCst); diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index af33388459f..51e4d6b5eb8 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -232,7 +232,7 @@ impl SharedNativeCode { } // Loading DPI-C libraries runs their initializers and keeps them // loaded, so it waits until the image is known to be usable. - let extern_functions = dpi.resolve(&program_image.runtime_schema.extern_functions)?; + let mut extern_functions = dpi.resolve(&program_image.runtime_schema.extern_functions)?; let symbols = program_image .symbols .iter() @@ -249,6 +249,13 @@ impl SharedNativeCode { program_image.options.perf_map, ) .map_err(|source| codegen_err(CodegenError::NativeMemory { source }))?; + let kernel_addresses = program_image + .runtime_schema + .native_kernel_offsets + .iter() + .map(|&offset| native_function_at(&jit_image, offset).map(|func| func as usize)) + .collect::, _>>()?; + extern_functions.append_native_kernels(kernel_addresses); let materialize = |event: NativeEventImageRef| -> Result { Ok(NativeEventRef { func: native_function_at(&jit_image, event.func_offset)?, @@ -399,6 +406,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) runtime_event_sites: Vec, /// Extern functions the code calls, resolved when the image is attached. pub(crate) extern_functions: Vec, + /// Image-local compiled callees appended to the DPI address table. + pub(crate) native_kernel_offsets: Vec, pub(crate) comb_observers: Vec>, pub(crate) testbench_read_roots: HashSet, pub(crate) rtl_writes: HashSet>, @@ -673,6 +682,11 @@ impl NativeProgramImage { if !entry_offsets.contains(&self.comb_offset) { return Err("eval_comb offset does not name an image entry".into()); } + for &offset in &self.runtime_schema.native_kernel_offsets { + if !entry_offsets.contains(&offset) { + return Err("native kernel offset does not name an image entry".into()); + } + } if self .comb_unit_offsets .iter() @@ -2163,6 +2177,16 @@ fn compile_program( options: &SimulatorOptions, capture_trace: bool, cancel: Option<&CompileCancel>, +) -> Result<(NativeProgramImage, Option), SimulatorError> { + compile_program_with_outlining_threshold(laid_out, options, capture_trace, cancel, 32_768) +} + +fn compile_program_with_outlining_threshold( + laid_out: &LaidOutProgram, + options: &SimulatorOptions, + capture_trace: bool, + cancel: Option<&CompileCancel>, + outline_threshold: usize, ) -> Result<(NativeProgramImage, Option), SimulatorError> { let sir = laid_out; let layout = laid_out.layout(); @@ -2175,42 +2199,40 @@ fn compile_program( .iter() .map(|unit| unit.blocks.len()) .sum::(); - let max_task_blocks = compile_tasks - .iter() - .map(|task| { - task.units - .iter() - .map(|unit| unit.blocks.len()) - .sum::() - }) - .max() - .unwrap_or(0); - let max_instructions = std::iter::once(sir.sir.eval_comb.iter().collect::>()) - .chain(compile_tasks.iter().map(|task| task.units.clone())) - .map(|units| { + let size = |units: &[&ExecutionUnit]| { + ( + units.iter().map(|unit| unit.blocks.len()).sum::(), units .iter() .flat_map(|unit| unit.blocks.values()) .map(|block| block.instructions.len()) - .sum::() - }) - .max() - .unwrap_or(0); + .sum::(), + ) + }; + let comb_size = size(&sir.sir.eval_comb.iter().collect::>()); + let task_sizes = compile_tasks + .iter() + .map(|task| size(&task.units)) + .collect::>(); + let max_task_blocks = task_sizes.iter().map(|size| size.0).max().unwrap_or(0); + let max_task_instructions = task_sizes.iter().map(|size| size.1).max().unwrap_or(0); + let max_instructions = comb_size.1.max(max_task_instructions); + let large = |size: (usize, usize)| size.0 >= 65_536 || size.1 >= 131_072; let release_pages = || { // Measure usable capacity after returning unused large-compiler pages. // Small single-worker builds must not trim unrelated process heaps. #[cfg(all(target_os = "linux", target_env = "gnu"))] - if comb_blocks.max(max_task_blocks) >= 65_536 { + if large(comb_size) || large((max_task_blocks, max_task_instructions)) { unsafe { libc::malloc_trim(0); } } }; release_pages(); - let workers = super::compile_resources::workers( - comb_blocks.max(max_task_blocks), - max_instructions, - compile_tasks.len() + 1, + let workers = super::compile_resources::workers_with_primary( + comb_size, + (max_task_blocks, max_task_instructions), + compile_tasks.len(), ); let serial = workers == 1; // Start expensive functions early so the final fused function does not @@ -2227,12 +2249,128 @@ fn compile_program( }); if options.x86_options.diagnostics.phase_timing { tracing::debug!( - "[native-timing] compile_program serial={serial} workers={workers} comb_blocks={comb_blocks} max_task_blocks={max_task_blocks} max_instructions={max_instructions} ff_tasks={}", - compile_tasks.len() + "[native-timing] compile_program serial={serial} workers={workers} comb_blocks={comb_blocks} max_task_blocks={max_task_blocks} max_instructions={max_instructions} ff_tasks={} settle_partitions={} settle_check={}", + compile_tasks.len(), + sir.runtime() + .runtime_schema + .settle_partitions + .as_ref() + .map_or(0, |s| s.partitions), + layout.settle_check(), ); } + // Execution units already communicate through state. Keep large units + // separate instead of rebuilding a single allocator problem, and dispatch + // them through the same bounded pool as the FF functions. + let split_comb = cfg!(any( + feature = "x86_64-codegen", + all(target_arch = "x86_64", not(feature = "arm64-codegen")) + )) && !capture_trace + && sir.sir.eval_comb.len() > 1 + && comb_size.1 >= outline_threshold; + let mut comb_chunk_jits = Vec::new(); let next_task = AtomicUsize::new(0); - let (comb_jit, compiled_ff_codes) = if serial { + let (comb_jit, compiled_ff_codes) = if split_comb { + let ff_count = compile_tasks.len(); + let sizes = task_sizes + .iter() + .copied() + .chain(sir.sir.eval_comb.iter().map(|unit| size(&[unit]))) + .collect::>(); + let mut order = (0..sizes.len()).collect::>(); + order.sort_by_key(|&index| std::cmp::Reverse(sizes[index])); + let workers = super::compile_resources::workers( + sizes.iter().map(|s| s.0).max().unwrap_or(0), + sizes.iter().map(|s| s.1).max().unwrap_or(0), + sizes.len(), + ); + if options.x86_options.diagnostics.phase_timing { + tracing::debug!( + "[native-timing] comb_chunks={} workers={workers}", + sir.sir.eval_comb.len() + ); + } + let codes = super::compile_resources::compile_tasks(&order, workers, |index| { + if cancelled(cancel) { + return Err(cancelled_error()); + } + if index < ff_count { + let task = &compile_tasks[index]; + compile_unit_refs( + &task.units, + layout, + options.four_state, + task.label, + task.merge_kind, + task.first_ff_unit, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + } else { + compile_unit_refs( + &[&sir.sir.eval_comb[index - ff_count]], + layout, + options.four_state, + "eval_comb_chunk", + NativeMergeKind::Partial, + None, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + } + }) + .map_err(|_| codegen_message("native compile worker panicked"))?; + let mut compiled = HashMap::default(); + for (index, code) in codes.into_iter().enumerate() { + let code = code?; + if index < ff_count { + compiled.insert(index, code); + } else { + comb_chunk_jits.push(code); + } + } + let first_slot = sir.runtime().runtime_schema.extern_functions.len() + 1; + let mut builder = celox_sir::SIRBuilder::new(); + for index in 0..comb_chunk_jits.len() { + let slot = u32::try_from(first_slot + index) + .ok() + .filter(|&slot| slot < 0x1000_0000) + .ok_or_else(|| codegen_message("too many native extern functions"))?; + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | slot, + args: Vec::new(), + }); + } + builder.seal_block(SIRTerminator::Return); + let caller_options = options + .x86_options + .clone() + .with_native_callees(comb_chunk_jits.iter().map(|code| code.required_state_size)); + let (blocks, register_map, _) = builder.drain(); + let comb = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + let root = compile_unit_refs( + &[&comb], + layout, + options.four_state, + "eval_comb", + NativeMergeKind::Complete, + None, + &caller_options, + false, + &options.optimize_options.diagnostics, + cancel, + )?; + (root, compiled) + } else if serial { let comb_jit = compile_units( &sir.sir.eval_comb, layout, @@ -2244,8 +2382,12 @@ fn compile_program( cancel, )?; let mut compiled = HashMap::default(); + let mut previous_large = large(comb_size); for (task_id, task) in compile_tasks.iter().enumerate() { - release_pages(); + if previous_large { + release_pages(); + } + previous_large = large(task_sizes[task_id]); let code = compile_unit_refs( &task.units, layout, @@ -2371,29 +2513,142 @@ fn compile_program( ) }) .collect::, _>>()?; - let process_jits = sir + // Return completed codegen's allocator pages before budgeting the process + // workers. Small designs leave unrelated process heaps alone. + release_pages(); + // Outlining amortizes the dominant circuit across all derived edges. + // Keep small circuits inline, where cross-boundary optimization is cheap. + let comb_instructions = sir + .sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .map(|block| block.instructions.len()) + .sum::(); + let outline_comb = cfg!(any( + feature = "x86_64-codegen", + all(target_arch = "x86_64", not(feature = "arm64-codegen")) + )) && !sir.deferred_derived_edges.is_empty() + && comb_instructions >= outline_threshold; + let outlined_comb = if outline_comb { + let slot = u32::try_from(sir.runtime().runtime_schema.extern_functions.len()) + .ok() + .filter(|&slot| slot < 0x1000_0000) + .ok_or_else(|| codegen_message("too many native extern functions"))?; + let mut builder = celox_sir::SIRBuilder::new(); + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | slot, + args: Vec::new(), + }); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + Some([ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }]) + } else { + None + }; + let mut process_options = options.x86_options.clone(); + if outline_comb { + // Nested functions must not overwrite the caller's spills, saved + // registers, scratch values, or extern call area. + process_options = process_options.with_native_callees([comb_jit.required_state_size]); + } + let derived_model = (!sir.deferred_derived_edges.is_empty()).then(|| { + celox_design::schedule::ScheduleModel::derive(&sir.design, &sir.runtime().runtime_schema) + }); + let process_sizes = sir .sir .processes .iter() .enumerate() .map(|(index, unit)| { - if cancelled(cancel) { - return Err(cancelled_error()); - } - compile_unit_refs( - &[unit], - layout, - options.four_state, - &format!("process[{index}]"), - NativeMergeKind::Complete, - None, - &options.x86_options, - false, - &options.optimize_options.diagnostics, - cancel, + sir.deferred_derived_edges.get(&index).map_or_else( + || { + ( + unit.blocks.len(), + unit.blocks + .values() + .map(|block| block.instructions.len()) + .sum(), + ) + }, + |edge| { + if outline_comb { + // The recipe estimate includes two complete comb + // copies. Both now use a single call; its fixed CFG + // allowance already covers those call instructions. + ( + edge.blocks.saturating_sub(comb_blocks.saturating_mul(2)), + edge.instructions + .saturating_sub(comb_instructions.saturating_mul(2)), + ) + } else { + (edge.blocks, edge.instructions) + } + }, ) }) - .collect::, _>>()?; + .collect::>(); + let max_process_blocks = process_sizes.iter().map(|size| size.0).max().unwrap_or(0); + let max_process_instructions = process_sizes.iter().map(|size| size.1).max().unwrap_or(0); + // The resource budget already includes overlapping SIR/MIR copies. + // Use the expanded size, rather than the tiny reserved process entry. + let process_workers = super::compile_resources::workers( + max_process_blocks, + max_process_instructions, + process_sizes.len(), + ); + let mut process_order = (0..process_sizes.len()).collect::>(); + process_order.sort_by_key(|&index| std::cmp::Reverse(process_sizes[index])); + if options.x86_options.diagnostics.phase_timing { + tracing::debug!( + "[native-timing] process_compile workers={process_workers} units={} max_blocks={max_process_blocks} max_instructions={max_process_instructions}", + process_sizes.len() + ); + } + let compile_process = |index| { + let unit = &sir.sir.processes[index]; + if cancelled(cancel) { + return Err(cancelled_error()); + } + // Expand, compile, then drop just this edge's SIR. Retaining every + // expansion makes memory scale with circuit size times edge count. + let generated = sir + .deferred_derived_edges + .get(&index) + .map(|edge| { + let model = derived_model.as_ref().expect("deferred edge model"); + if let Some(comb) = &outlined_comb { + edge.generate_with_comb(sir, model, comb) + } else { + edge.generate(sir, model) + } + .map_err(codegen_message) + }) + .transpose()?; + let unit = generated.as_ref().unwrap_or(unit); + compile_unit_refs( + &[unit], + layout, + options.four_state, + &format!("process[{index}]"), + NativeMergeKind::Complete, + None, + &process_options, + false, + &options.optimize_options.diagnostics, + cancel, + ) + }; + let process_jits = + super::compile_resources::compile_tasks(&process_order, process_workers, compile_process) + .map_err(|_| codegen_message("native process compile thread panicked"))? + .into_iter() + .collect::, _>>()?; let lane_kernels = super::lanes::compile_lane_kernels(sir, options, cancel)?; let codegen_trace = capture_trace .then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks)); @@ -2402,6 +2657,7 @@ fn compile_program( .checked_add(layout.triggered_bits_total_size) .expect("native semantic-memory size overflow"); let native_memory_size = std::iter::once(comb_jit.required_state_size) + .chain(comb_chunk_jits.iter().map(|code| code.required_state_size)) .chain( compiled_ff_codes .values() @@ -2421,6 +2677,11 @@ fn compile_program( ) .fold(semantic_memory_size, usize::max); let required_native_features = std::iter::once(comb_jit.required_native_features) + .chain( + comb_chunk_jits + .iter() + .map(|code| code.required_native_features), + ) .chain( compiled_ff_codes .values() @@ -2449,6 +2710,20 @@ fn compile_program( "eval_comb".into(), &comb_jit, )?; + let mut native_kernel_offsets = if outline_comb || split_comb { + vec![comb_offset] + } else { + Vec::new() + }; + for (index, code) in comb_chunk_jits.iter().enumerate() { + native_kernel_offsets.push(append_native_code( + &mut packed_image, + &mut code_entries, + &mut image_symbols, + format!("eval_comb_chunk[{index}]"), + code, + )?); + } let mut comb_unit_offsets = Vec::with_capacity(comb_unit_jits.len()); for (index, compiled) in comb_unit_jits.iter().enumerate() { comb_unit_offsets.push(append_native_code( @@ -2639,6 +2914,7 @@ fn compile_program( runtime_errors: sir.runtime().runtime_schema.runtime_errors.clone(), runtime_event_sites: sir.runtime().runtime_schema.runtime_event_sites.clone(), extern_functions: sir.runtime().runtime_schema.extern_functions.clone(), + native_kernel_offsets, comb_observers: sir.runtime().runtime_schema.comb_observers.clone(), testbench_read_roots: sir.runtime().runtime_schema.testbench_read_roots.clone(), rtl_writes: sir.runtime().runtime_schema.rtl_writes.clone(), @@ -2782,6 +3058,35 @@ fn write_initial_run_to_plane( } impl NativeBackend { + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + pub(crate) fn compile_outlined_image_for_test( + program: &LaidOutProgram, + options: &SimulatorOptions, + ) -> Result { + compile_program_with_outlining_threshold(program, options, false, None, 0) + .map(|(image, _)| image) + } + + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + pub(crate) fn split_comb_units_for_test(program: &mut LaidOutProgram) { + program.sir.eval_comb = program + .sir + .eval_comb + .iter() + .flat_map(split_comb_execution_unit) + .collect(); + } + pub(crate) fn eval_comb_units_with( &mut self, mut after_unit: impl FnMut(&mut Self), diff --git a/crates/celox/src/backend/native/compile_resources.rs b/crates/celox/src/backend/native/compile_resources.rs index 0144103c5a8..7d33da0e01a 100644 --- a/crates/celox/src/backend/native/compile_resources.rs +++ b/crates/celox/src/backend/native/compile_resources.rs @@ -2,6 +2,62 @@ const MAX_WORKERS: usize = 4; +/// Dispatch in priority order, but return results in stable task-index order. +/// Each worker owns at most one expanded process and its compilation state. +pub(super) fn compile_tasks( + order: &[usize], + workers: usize, + compile: impl Fn(usize) -> T + Sync, +) -> std::thread::Result> { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut results = if workers <= 1 || order.len() <= 1 { + order + .iter() + .map(|&index| (index, compile(index))) + .collect::>() + } else { + let next = AtomicUsize::new(0); + std::thread::scope(|scope| { + let handles = (0..workers.min(order.len())) + .map(|_| { + let next = &next; + let compile = &compile; + scope.spawn(move || { + let mut results = Vec::new(); + loop { + let position = next.fetch_add(1, Ordering::Relaxed); + let Some(&index) = order.get(position) else { + break; + }; + results.push((index, compile(index))); + } + results + }) + }) + .collect::>(); + let mut results = Vec::new(); + let mut panic = None; + for handle in handles { + match handle.join() { + Ok(completed) => results.extend(completed), + Err(error) => { + if panic.is_none() { + panic = Some(error); + } + } + } + } + if let Some(error) = panic { + Err(error) + } else { + Ok(results) + } + })? + }; + results.sort_unstable_by_key(|(index, _)| *index); + Ok(results.into_iter().map(|(_, result)| result).collect()) +} + pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize { choose_workers( blocks, @@ -12,6 +68,52 @@ pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize ) } +/// One primary circuit and a queue of smaller independent event functions. +/// Reserve the primary once, rather than charging its size to every worker. +pub(super) fn workers_with_primary( + primary: (usize, usize), + secondary: (usize, usize), + tasks: usize, +) -> usize { + choose_workers_with_primary( + primary, + secondary, + tasks, + std::thread::available_parallelism().map_or(1, usize::from), + available_memory(), + ) +} + +fn choose_workers_with_primary( + primary: (usize, usize), + secondary: (usize, usize), + tasks: usize, + cpus: usize, + available: Option, +) -> usize { + let maximum = MAX_WORKERS.min(cpus.max(1)).min(tasks.saturating_add(1)); + let Some(available) = available else { + return choose_workers( + primary.0.max(secondary.0), + primary.1.max(secondary.1), + tasks.saturating_add(1), + cpus, + None, + ); + }; + let budget = available - available / 5; + let remaining = budget.saturating_sub(estimated_memory(primary.0, primary.1)); + 1 + (remaining / estimated_memory(secondary.0, secondary.1)) + .min(maximum.saturating_sub(1) as u64) as usize +} + +fn estimated_memory(blocks: usize, instructions: usize) -> u64 { + (blocks as u64) + .saturating_mul(24 * 1024) + .max((instructions as u64).saturating_mul(4096)) + .max(128 * 1024 * 1024) +} + fn choose_workers( blocks: usize, instructions: usize, @@ -30,10 +132,7 @@ fn choose_workers( // eight-hart functions peaked at 6.54 GiB for the entire process tree. // Account for straight-line designs too, not only CFG size. // These are conservative estimates, not reservations or memory limits. - let per_function = (blocks as u64) - .saturating_mul(24 * 1024) - .max((instructions as u64).saturating_mul(4096)) - .max(128 * 1024 * 1024); + let per_function = estimated_memory(blocks, instructions); // Leave room for the running simulator and unrelated host activity. let budget = available - available / 5; (budget / per_function).min(maximum as u64).max(1) as usize @@ -154,6 +253,93 @@ mod tests { const GIB: u64 = 1024 * 1024 * 1024; + #[test] + fn primary_worker_budget_keeps_capacity_for_smaller_functions() { + let primary = (65_536, 1_000_000); + let small = (100, 1_000); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 16, Some(8 * GIB)), + 4 + ); + assert_eq!( + choose_workers_with_primary(primary, primary, 10, 16, Some(8 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 16, Some(4 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 0, 16, Some(8 * GIB)), + 1 + ); + assert_eq!( + choose_workers_with_primary(primary, small, 10, 2, Some(8 * GIB)), + 2 + ); + assert_eq!( + choose_workers_with_primary((120_000, 1), small, 10, 16, None), + 1 + ); + for available in [0, GIB, 4 * GIB, 5 * GIB, 8 * GIB, u64::MAX] { + for secondary in [small, primary, (usize::MAX, usize::MAX)] { + let workers = + choose_workers_with_primary(primary, secondary, 10, 16, Some(available)); + assert!((1..=MAX_WORKERS).contains(&workers)); + if workers > 1 { + let reserved = u128::from(estimated_memory(primary.0, primary.1)) + + (workers - 1) as u128 + * u128::from(estimated_memory(secondary.0, secondary.1)); + assert!(reserved <= u128::from(available - available / 5)); + } + } + } + } + + #[test] + fn indexed_tasks_keep_results_ordered_and_bound_active_work() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let order = (0..16).rev().collect::>(); + for workers in [1, 2, 4] { + let active = AtomicUsize::new(0); + let peak = AtomicUsize::new(0); + let seen = AtomicUsize::new(0); + let results = compile_tasks(&order, workers, |index| { + let count = active.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(count, Ordering::SeqCst); + seen.fetch_or(1 << index, Ordering::SeqCst); + std::thread::yield_now(); + active.fetch_sub(1, Ordering::SeqCst); + index * 3 + }) + .unwrap(); + assert_eq!(results, (0..16).map(|index| index * 3).collect::>()); + assert_eq!(seen.load(Ordering::SeqCst), (1 << 16) - 1); + assert_eq!(active.load(Ordering::SeqCst), 0); + assert!(peak.load(Ordering::SeqCst) <= workers); + } + } + + #[test] + fn indexed_tasks_preserve_errors_and_return_worker_panics() { + let results = compile_tasks(&[3, 2, 1, 0], 2, |index| { + if index == 1 || index == 3 { + Err(index) + } else { + Ok(index) + } + }) + .unwrap(); + assert_eq!(results.into_iter().collect::, _>>(), Err(1)); + assert!( + compile_tasks(&[0, 1, 2], 2, |index| { + assert_ne!(index, 1, "worker panic probe"); + index + }) + .is_err() + ); + } + #[cfg(target_os = "linux")] #[test] fn finite_process_limit_caps_the_worker_memory_budget() { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 3c1a322be44..f812ecbcff4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,8 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Compound event probes extend the fork activation image format. -const CONTAINER_VERSION: u16 = 47; +// Native kernel offsets and lexical reflection scopes extend the image metadata. +const CONTAINER_VERSION: u16 = 49; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 3ebc630ef97..183cb8cae95 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -788,6 +788,49 @@ impl EdgePlan { /// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit /// reads the scheduler's dirty flag to know whether to settle first. pub(crate) fn attach(program: &mut LaidOutProgram) { + attach_with_mode(program, false); +} + +/// Reserve native entry indices without retaining a copy of the full circuit +/// for both polarities of every derived-clock event. +pub(crate) fn attach_deferred(program: &mut LaidOutProgram) { + attach_with_mode(program, true); +} + +#[derive(Clone, Debug)] +pub(crate) struct DeferredEdge { + event: AbsoluteAddr, + rising: bool, + fires: bool, + flag: AbsoluteAddr, + pub(crate) blocks: usize, + pub(crate) instructions: usize, +} + +impl DeferredEdge { + pub(crate) fn generate( + &self, + program: &LaidOutProgram, + model: &ScheduleModel, + ) -> Result { + self.generate_with_comb(program, model, &program.sir.eval_comb) + } + + pub(crate) fn generate_with_comb( + &self, + program: &LaidOutProgram, + model: &ScheduleModel, + comb: &[Unit], + ) -> Result { + let plan = EdgePlan::new(program, model, self.event)? + .ok_or("deferred derived edge no longer has a plan")?; + let mut unit = plan.unit(comb, self.rising, self.fires, Settle::Flag(self.flag)); + crate::settle::instrument_unit(program, &mut unit); + Ok(unit) + } +} + +fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) { let schema = &program.runtime.runtime_schema; let Some(flag) = schema .scheduler @@ -815,14 +858,81 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { _ => true, }; let mut indices = [0usize; 2]; - for (index, rising) in [true, false].into_iter().enumerate() { - let unit = plan.unit( - &program.sir.eval_comb, - rising, - fires(rising), - Settle::Flag(flag), + // Include both settles and every possible FF path. The control-flow + // allowance also covers gate expressions and per-unit continuations. + let (estimated_blocks, estimated_instructions) = if deferred { + let units = program + .sir + .eval_comb + .iter() + .chain(&program.sir.eval_comb) + .chain(plan.entries().flat_map(|units| { + units + .eval_apply + .iter() + .chain(units.eval_only.as_ref().unwrap_or(&units.eval_apply)) + .chain(units.apply.iter().flatten()) + })); + let gate_ops = plan.gated.iter().map(|gate| gate.gate.len()).sum::(); + units.fold( + ( + 1024usize, + 8192usize.saturating_add(gate_ops.saturating_mul(16)), + ), + |(blocks, instructions), unit| { + ( + blocks.saturating_add(unit.blocks.len()).saturating_add(2), + instructions.saturating_add( + unit.blocks + .values() + .map(|b| b.instructions.len()) + .sum::(), + ), + ) + }, + ) + } else { + (0, 0) + }; + if deferred { + tracing::debug!( + "[derived-edge-size] event={} kind={:?} blocks={} instructions={}", + program.get_path(&event), + kind, + estimated_blocks, + estimated_instructions, ); + } + for (index, rising) in [true, false].into_iter().enumerate() { indices[index] = program.sir.processes.len(); + let unit = if deferred { + program.deferred_derived_edges.insert( + indices[index], + DeferredEdge { + event, + rising, + fires: fires(rising), + flag, + blocks: estimated_blocks, + instructions: estimated_instructions, + }, + ); + let mut builder = Builder::new(); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } else { + plan.unit( + &program.sir.eval_comb, + rising, + fires(rising), + Settle::Flag(flag), + ) + }; program.sir.processes.push(unit); } edges.push(celox_design::DerivedEdgeUnits { @@ -848,6 +958,7 @@ pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { .min(); if let Some(first) = first { program.sir.processes.truncate(first); + program.deferred_derived_edges.clear(); program.runtime.runtime_schema.derived_edges.clear(); } program diff --git a/crates/celox/src/dpi.rs b/crates/celox/src/dpi.rs index 06ab57898db..164b3cf4d12 100644 --- a/crates/celox/src/dpi.rs +++ b/crates/celox/src/dpi.rs @@ -176,6 +176,13 @@ impl Default for ExternFunctionTable { } impl ExternFunctionTable { + /// Append image-local compiled callees after the DPI imports. + pub(crate) fn append_native_kernels(&mut self, addresses: impl IntoIterator) { + let mut table = self.addresses.to_vec(); + table.extend(addresses); + self.addresses = table.into(); + } + /// The user table's address, which the state header holds. The internal /// floating-point helper occupies the immediately preceding slot, and the /// heap helper the one before it. diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index f226fc20aa6..23a062b2d34 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -93,6 +93,9 @@ pub struct RuntimeDesign { instance_ids: HashMap, variables: HashMap, package_instances: crate::HashSet, + /// Source-declared lexical scopes used only by reflection. Keep the + /// real-instance display path unchanged for lookup and VCD bookkeeping. + reflection_instance_paths: std::collections::BTreeMap>, } impl std::ops::Deref for RuntimeDesign { @@ -195,6 +198,7 @@ impl RuntimeDesign { instance_ids: frontend.instance_ids, variables, package_instances: frontend.package_instances, + reflection_instance_paths: Default::default(), }; design .validate() @@ -206,6 +210,14 @@ impl RuntimeDesign { &self.semantic } + #[cfg(feature = "systemverilog")] + pub(crate) fn set_reflection_instance_paths( + &mut self, + paths: std::collections::BTreeMap>, + ) { + self.reflection_instance_paths = paths; + } + pub fn instances(&self) -> impl Iterator { self.instances.values() } @@ -563,6 +575,10 @@ pub struct LaidOutProgram { pub sir: SirProgram, pub(crate) runtime: RuntimeProgram, layout: crate::backend::MemoryLayout, + /// Native-only generated process entries. Their SIR is expanded for one + /// compilation at a time; `sir.processes` reserves their stable indices. + #[cfg(feature = "host-runtime")] + pub(crate) deferred_derived_edges: HashMap, } impl LaidOutProgram { @@ -773,6 +789,8 @@ impl OptimizedSir { sir, runtime, layout, + #[cfg(feature = "host-runtime")] + deferred_derived_edges: HashMap::default(), }; crate::settle::instrument(&mut laid_out); laid_out @@ -894,7 +912,11 @@ impl RuntimeProgram { .design .instances() .map(|instance| { - let segments = &instance.display_path; + let segments = self + .design + .reflection_instance_paths + .get(&instance.id) + .unwrap_or(&instance.display_path); let name = segments .last() .cloned() @@ -926,9 +948,42 @@ impl RuntimeProgram { // instances. Retain their source path segments as navigable scopes. let real_scopes = scope_sources .iter() - .map(|scope| scope.full_name.clone()) - .collect::>(); + .map(|scope| (scope.full_name.clone(), scope.instance_id)) + .collect::>(); let mut member_scopes = HashMap::default(); + let root_instance = self + .design + .root_instance() + .expect("top-level instance exists") + .id; + // A generate block can contain only child instances, without a local + // variable to create its scope. Materialize every declared prefix and + // inherit its time scale from the nearest real enclosing instance. + for segments in self.design.reflection_instance_paths.values() { + let mut owner = root_instance; + for depth in 1..segments.len() { + let full_name = format!("{root_name}.{}", segments[..depth].join(".")); + if let Some(&instance) = real_scopes.get(&full_name) { + owner = instance; + continue; + } + let parent_name = if depth == 1 { + root_name.clone() + } else { + format!("{root_name}.{}", segments[..depth - 1].join(".")) + }; + member_scopes + .entry(full_name.clone()) + .or_insert_with(|| ScopeSource { + is_instance: false, + instance_id: owner, + name: segments[depth - 1].clone(), + full_name, + parent_name: Some(parent_name), + module_name: String::new(), + }); + } + } for scope in &scope_sources { let instance = self.design.instance(scope.instance_id).unwrap(); for address in instance.state_addresses() { @@ -939,7 +994,7 @@ impl RuntimeProgram { for depth in 1..variable.path.len() { let full_name = format!("{}.{}", scope.full_name, variable.path[..depth].join(".")); - if real_scopes.contains(&full_name) { + if real_scopes.contains_key(&full_name) { continue; } let parent_name = if depth == 1 { diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index fd3e655c203..646d3e33a05 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -630,7 +630,7 @@ pub fn parse_sv( if let Some(trace) = trace.as_deref_mut() { trace.absorb_frontend(frontend_trace); } - finalize_scheduled_rtl( + let mut program = finalize_scheduled_rtl( scheduled, None, four_state, @@ -642,7 +642,43 @@ pub fn parse_sv( testbench_random_seed, component_libraries, component_file_base, - ) + )?; + let paths = program + .runtime + .design + .instances() + .filter_map(|instance| { + let scopes = sv_reflection_scope_segments(&instance.display_path); + (scopes != instance.display_path).then_some((instance.id, scopes)) + }) + .collect(); + program.runtime.design.set_reflection_instance_paths(paths); + Ok(program) +} + +/// Split only SystemVerilog hierarchy separators. Escaped identifiers retain +/// their spelling and whitespace terminator (IEEE 1800-2023 5.6.1). +#[cfg(feature = "systemverilog")] +fn sv_reflection_scope_segments(segments: &[String]) -> Vec { + let mut result = Vec::new(); + for segment in segments { + let mut start = 0; + let mut escaped = false; + for (index, character) in segment.char_indices() { + if escaped { + if character.is_ascii_whitespace() { + escaped = false; + } + } else if character == '\\' { + escaped = true; + } else if character == '.' { + result.push(segment[start..index].to_string()); + start = index + 1; + } + } + result.push(segment[start..].to_string()); + } + result } /// An analyzer error as a parser error: a construct the analyzer does not @@ -1135,3 +1171,27 @@ mod fused_hint_tests { ); } } + +#[cfg(all(test, feature = "systemverilog"))] +mod sv_scope_tests { + use super::sv_reflection_scope_segments; + + #[test] + fn lexical_scopes_preserve_escaped_dots_and_instance_paths() { + let slash = char::from(92u8); + let generated = format!("bank[2].{slash}literal.with.dots .u"); + let leaf = format!("{slash}leaf.with.dots"); + let source = vec![generated.clone(), leaf.clone()]; + let scopes = sv_reflection_scope_segments(&source); + assert_eq!( + scopes, + vec![ + "bank[2]".to_string(), + format!("{slash}literal.with.dots "), + "u".to_string(), + leaf + ] + ); + assert_eq!(scopes.join("."), source.join(".")); + } +} diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs index 4358d762110..89b3591e54c 100644 --- a/crates/celox/src/settle.rs +++ b/crates/celox/src/settle.rs @@ -150,6 +150,18 @@ pub(crate) fn instrument_processes_from(program: &mut LaidOutProgram, first: usi } } +/// Apply the same process instrumentation after a deferred native kernel is +/// expanded. Its reserved process entry contained no stores to instrument. +#[cfg(feature = "host-runtime")] +pub(crate) fn instrument_unit( + program: &LaidOutProgram, + unit: &mut ExecutionUnit, +) { + if let Some(marker) = Marker::new(program.layout(), program.runtime()) { + marker.instrument(unit); + } +} + struct Marker<'a> { settle: &'a SettleLayout, layout: &'a crate::backend::MemoryLayout, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 8060be969e9..0e0992259c5 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2837,6 +2837,7 @@ mod host { fn into_laid_out_program( self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, + defer_derived_edges: bool, ) -> Result< ( crate::ir::LaidOutProgram, @@ -2847,13 +2848,14 @@ mod host { ), SimulatorError, > { - self.into_laid_out_program_with_trace(layout_mode, None) + self.into_laid_out_program_with_trace(layout_mode, None, defer_derived_edges) } fn into_laid_out_program_with_trace( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, trace: Option<&mut crate::debug::CompilationTrace>, + defer_derived_edges: bool, ) -> Result< ( crate::ir::LaidOutProgram, @@ -3013,7 +3015,11 @@ mod host { .optimize_options .is_enabled(crate::optimizer::SirPass::DerivedEdgeUnits) { - crate::derived_edge::attach(&mut laid_out); + if defer_derived_edges { + crate::derived_edge::attach_deferred(&mut laid_out); + } else { + crate::derived_edge::attach(&mut laid_out); + } } #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] if let Some(sink) = &self.options.derived_edge_units { @@ -3069,7 +3075,10 @@ mod host { let phase_start = phase_timing.then(crate::timing::now); let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { @@ -3139,7 +3148,10 @@ mod host { let phase_start = phase_timing.then(crate::timing::now); let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { @@ -3195,9 +3207,10 @@ mod host { let (laid_out, warnings, options, vcd_path, injected_components) = { let vcd_recording = self.vcd_path.is_some(); - self.into_laid_out_program(crate::backend::tiered::tiered_layout_mode( - vcd_recording, - ))? + self.into_laid_out_program( + crate::backend::tiered::tiered_layout_mode(vcd_recording), + false, + )? }; validate_untimed_processes(laid_out.runtime())?; @@ -3266,9 +3279,10 @@ mod host { let (laid_out, warnings, options, vcd_path, injected_components) = { let vcd_recording = self.vcd_path.is_some(); - self.into_laid_out_program(crate::backend::tiered::tiered_layout_mode( - vcd_recording, - ))? + self.into_laid_out_program( + crate::backend::tiered::tiered_layout_mode(vcd_recording), + false, + )? }; validate_untimed_processes(laid_out.runtime())?; @@ -3320,6 +3334,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, )?; validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { @@ -3365,6 +3380,7 @@ mod host { .into_laid_out_program_with_trace( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, Some(&mut trace), + true, )?; validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { @@ -3493,7 +3509,10 @@ mod host { self, ) -> Result, SimulatorError> { let (laid_out, mut warnings, options, vcd_path, injected_components) = self - .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + .into_laid_out_program( + crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, + )?; validate_untimed_processes(laid_out.runtime())?; let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; @@ -3870,6 +3889,7 @@ mod host { pub fn build_cranelift(self) -> Result, SimulatorError> { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, |program, options| { let mut trace = crate::debug::CompilationTrace::default(); let wants_trace = options.trace.pre_optimized_clif @@ -3896,6 +3916,7 @@ mod host { { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, crate::backend::native::NativeBackend::new, ) } @@ -3916,6 +3937,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, + true, )?; let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; @@ -3970,6 +3992,7 @@ mod host { { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, crate::backend::wasm_runtime::WasmBackend::new, ) } @@ -3980,6 +4003,7 @@ mod host { ) -> Result, SimulatorError> { self.build_with_backend( crate::backend::memory_layout::MemoryLayoutMode::Packed, + false, crate::backend::InterpBackend::new, ) } @@ -3990,7 +4014,7 @@ mod host { self, ) -> Result, SimulatorError> { let layout = crate::backend::tiered::tiered_layout_mode(self.vcd_path.is_some()); - self.build_with_backend(layout, |program, options| { + self.build_with_backend(layout, false, |program, options| { Ok(crate::backend::TieredBackend::new(program, options)) }) } @@ -3998,11 +4022,12 @@ mod host { fn build_with_backend( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, + defer_derived_edges: bool, compile: impl Fn(&crate::ir::LaidOutProgram, &SimulatorOptions) -> Result, ) -> Result, SimulatorError> { self.options.emit_triggers = true; let (laid_out, mut warnings, options, vcd_path, injected_components) = - self.into_laid_out_program(layout_mode)?; + self.into_laid_out_program(layout_mode, defer_derived_edges)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let shadow = Self::start_shadow( @@ -4211,6 +4236,217 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + target_arch = "x86_64", + target_arch = "aarch64", + feature = "arm64-codegen" + ) + ))] + #[test] + fn deferred_edges_preserve_expanded_ir_and_reserve_only_small_entries() { + let source = r#"module Top(input bit clk, input bit en, output bit [7:0] q); + bit [7:0] r = 0, a = 0, b = 0, c = 0; + wire gated = clk & en; + wire inverted = ~clk; + wire second = gated & r[0]; + always_ff @(posedge clk) r <= r + 1; + always_ff @(posedge gated) a <= a + r; + always_ff @(posedge inverted) b <= b + a; + always_ff @(posedge second) c <= c + b; + assign q = a + b + c; + endmodule"#; + for partitioned in [false, true] { + let builder = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("deferred_edges.sv"))], + "Top", + ) + .emit_triggers() + .opt_level(crate::OptLevel::O1) + .disable_pass(crate::SirPass::DerivedEdgeUnits); + let builder = if partitioned { + builder.settle_partition(crate::SettlePartition::Always) + } else { + builder + }; + let (base, _, options, _, _) = builder + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) + .unwrap(); + let first = base.sir.processes.len(); + let mut expanded = base.clone(); + crate::derived_edge::attach(&mut expanded); + crate::settle::instrument_processes_from(&mut expanded, first, false); + let mut deferred = base; + crate::derived_edge::attach_deferred(&mut deferred); + crate::settle::instrument_processes_from(&mut deferred, first, false); + assert!(deferred.deferred_derived_edges.len() >= 4); + assert_eq!(expanded.sir.processes.len(), deferred.sir.processes.len()); + assert_eq!( + expanded.runtime().runtime_schema.derived_edges, + deferred.runtime().runtime_schema.derived_edges, + ); + if partitioned { + assert!(deferred.layout().settle.is_some()); + } + let model = celox_design::schedule::ScheduleModel::derive( + &deferred.design, + &deferred.runtime().runtime_schema, + ); + for (&index, edge) in &deferred.deferred_derived_edges { + let reserved = &deferred.sir.processes[index]; + assert_eq!(reserved.blocks.len(), 1); + assert!(reserved.register_map.is_empty()); + assert!(reserved.blocks.values().all(|block| { + block.instructions.is_empty() + && matches!(block.terminator, crate::ir::SIRTerminator::Return) + })); + let generated = edge.generate(&deferred, &model).unwrap(); + generated.verify_result().unwrap(); + assert!(edge.blocks >= generated.blocks.len()); + assert!( + edge.instructions + >= generated + .blocks + .values() + .map(|block| block.instructions.len()) + .sum::() + ); + assert_eq!(generated.blocks, expanded.sir.processes[index].blocks); + assert_eq!( + generated.register_map, + expanded.sir.processes[index].register_map + ); + } + let expanded_image = + crate::backend::native::NativeBackend::compile_image(&expanded, &options).unwrap(); + let deferred_image = + crate::backend::native::NativeBackend::compile_image(&deferred, &options).unwrap(); + assert_eq!(expanded_image.code_image(), deferred_image.code_image()); + #[cfg(all(target_arch = "x86_64", not(feature = "arm64-codegen")))] + { + let outlined_image = + crate::backend::native::NativeBackend::compile_outlined_image_for_test( + &deferred, &options, + ) + .unwrap(); + // Exercise pointer-free serialization before relocating both + // images into independent executable mappings. + let bytes = outlined_image.to_container_bytes().unwrap(); + let outlined_image: crate::backend::native::NativeProgramImage = + crate::backend::native::NativeProgramImage::from_container_bytes(&bytes) + .unwrap(); + let mut simulations = [deferred_image, outlined_image].map(|image| { + let runtime = image.runtime_program(); + // SAFETY: these images were compiled from this fixture. + let backend = + unsafe { crate::backend::native::NativeBackend::from_image(image) } + .unwrap(); + let mut sim = crate::Simulator::with_backend_and_program_for_simulation( + backend, + runtime, + Vec::new(), + ); + sim.apply_initial_values(); + sim.modify(|_| {}).unwrap(); + sim + }); + for step in 0..80 { + for sim in &mut simulations { + let enable = sim.signal("en"); + sim.modify(|io| io.set(enable, u8::from(step % 3 != 0))) + .unwrap(); + let clk = sim.event("clk"); + if step % 5 == 0 { + sim.edge(clk, crate::Edge::Falling).unwrap(); + } else { + sim.tick(clk).unwrap(); + } + } + for name in ["q", "r", "a", "b", "c"] { + assert_eq!( + simulations[0].get(simulations[0].signal(name)), + simulations[1].get(simulations[1].signal(name)), + "partitioned={partitioned}, step={step}, signal={name}" + ); + } + } + } + let baseline = crate::derived_edge::without_units(&deferred); + assert!(baseline.deferred_derived_edges.is_empty()); + assert!(baseline.runtime().runtime_schema.derived_edges.is_empty()); + } + } + + #[cfg(all( + test, + feature = "systemverilog", + target_arch = "x86_64", + not(feature = "arm64-codegen") + ))] + #[test] + fn native_comb_chunks_preserve_cross_unit_state_through_image_roundtrip() { + let source = r#"module Top(input bit [7:0] a, + output bit [7:0] mid, out, mirror); + assign mid = a + 8'h11; + assign out = mid ^ 8'ha5; + assign mirror = out + mid; + endmodule"#; + let (mut program, _, options, _, _) = crate::Simulator::from_sv_sources( + vec![(source, std::path::Path::new("chunks.sv"))], + "Top", + ) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) + .unwrap(); + crate::backend::native::NativeBackend::split_comb_units_for_test(&mut program); + assert!(program.sir.eval_comb.len() > 1); + let merged = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let chunked = crate::backend::native::NativeBackend::compile_outlined_image_for_test( + &program, &options, + ) + .unwrap(); + assert!( + chunked + .code_entries() + .iter() + .filter(|entry| entry.name.starts_with("eval_comb_chunk[")) + .count() + > 1 + ); + for image in [merged, chunked] { + let image = crate::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + let runtime = image.runtime_program(); + // SAFETY: this image was compiled from this fixture. + let backend = unsafe { crate::NativeBackend::from_image(image) }.unwrap(); + let mut sim = crate::Simulator::with_backend_and_program_for_simulation( + backend, + runtime, + Vec::new(), + ); + sim.apply_initial_values(); + for step in 0..80u8 { + let value = step.wrapping_mul(17); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, value)).unwrap(); + let mid = value.wrapping_add(0x11); + let out = mid ^ 0xa5; + for (name, expected) in [ + ("mid", mid), + ("out", out), + ("mirror", out.wrapping_add(mid)), + ] { + let signal = sim.signal(name); + assert_eq!(sim.get(signal), num_bigint::BigUint::from(expected)); + } + } + } + } + #[cfg(all( test, feature = "systemverilog", @@ -4236,7 +4472,7 @@ endmodule"#; let (mut program, warnings, options, _, _) = crate::Simulation::from_sv_sources(sources, "Top") .emit_triggers() - .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) .unwrap(); let schema = &mut program.runtime.runtime_schema; let count = schema.processes.len(); @@ -4296,7 +4532,7 @@ endmodule"#; "Top", ) .emit_triggers() - .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); @@ -4346,7 +4582,7 @@ endmodule"#; vec![(&source, std::path::Path::new("native-vcd.sv"))], "Top", ) - .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); @@ -4408,7 +4644,7 @@ endmodule"#; "Top", ) .four_state(four_state) - .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) .unwrap(); let image = crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index a633fbf92b6..11c62aaa718 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -240,7 +240,7 @@ pub enum CodegenError { source: wasmtime::Error, }, - #[cfg(feature = "host-runtime")] + #[cfg(any(feature = "host-runtime", feature = "systemverilog"))] #[error("{message}")] Message { message: String }, @@ -250,7 +250,7 @@ pub enum CodegenError { Cancelled, } -#[cfg(feature = "host-runtime")] +#[cfg(any(feature = "host-runtime", feature = "systemverilog"))] impl CodegenError { pub(crate) fn message(message: impl Into) -> Self { Self::Message {