diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index 2f439a631e1..5910e061df0 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -4343,8 +4343,12 @@ mod tests { } #[test] - fn native_handle_edges_of_clocks_comb_logic_does_not_read_stay_settled() { - for (seen, comb_read) in [("1'b1", false), ("clk", true)] { + fn native_handle_edges_preserve_settledness_for_unused_clocks_and_wiring() { + for (seen, settled, value) in [ + ("1'b1", true, Some(1)), + ("clk", true, Some(0)), + ("~clk", false, None), + ] { let source = format!( "module Top (clk: input clock, count: output logic<8>, seen: output logic) {{ always_ff (clk) {{ count += 1; }} @@ -4356,13 +4360,22 @@ mod tests { let events: HashMap = serde_json::from_str(&handle.events_json()).unwrap(); let clk = events["clk"]; assert!(handle.edges(vec![clk], vec![true], None).unwrap()); - // Moving `clk` without running a domain leaves combinational - // logic stale only when it reads `clk`, or already was. + // Unused clocks and direct wiring remain settled after an + // inactive edge. Other clock-dependent logic still needs a settle. assert_eq!( handle.edges(vec![clk], vec![false], Some(false)).unwrap(), - !comb_read, + settled, "{seen}" ); + if let Some(value) = value { + let layout: serde_json::Value = + serde_json::from_str(&handle.layout_json()).unwrap(); + let offset = layout["seen"]["offset"].as_u64().unwrap() as usize; + let (memory, len) = handle.backend.as_mut().unwrap().memory_as_mut_ptr(); + assert!(offset < len); + // Read the stored result without implicitly evaluating comb. + assert_eq!(unsafe { *memory.add(offset) }, value, "{seen}"); + } assert!(handle.edges(vec![clk], vec![true], Some(true)).unwrap()); assert!(!handle.edges(vec![clk], vec![false], Some(true)).unwrap()); handle.dispose().unwrap(); diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 05bb918ca1e..2cef0230087 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -47,6 +47,14 @@ pub trait SimBackend { // ── evaluation ────────────────────────────────────────────── fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode>; + /// Publish all combinational effects of a single clock-level change when + /// its cone is proven to contain only wiring. Called only from a settled + /// state, immediately after the host writes the clock. `false` must leave + /// state unchanged and requests the normal full settle. + fn eval_clock_aliases(&mut self, _event: Self::Event) -> Result { + Ok(false) + } + /// Evaluate and apply a flip-flop domain for the given event. fn eval_apply_ff_at(&mut self, event: Self::Event) -> Result<(), SimulatorErrorCode>; diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index be49d6dc281..44b22c6a96e 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -358,7 +358,9 @@ where }; let new = edge.level(); let fires = info.fires(known(from), edge); - let settle = dirty || info.comb_read; + let comb_read = + info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?); + let settle = dirty || comb_read; if let Some(plan) = plan { // A gated clock is judged from the lever's real level before the // edge, x and z included. @@ -381,11 +383,11 @@ where return Ok(if settled { EdgeOutcome::Settled } else { - moved_only(info.comb_read) + moved_only(comb_read) }); } if !fires { - return Ok(moved_only(info.comb_read)); + return Ok(moved_only(comb_read)); } if settle { executor.eval_comb_apply_ff_at(event)?; @@ -552,7 +554,8 @@ where any_moved = true; write.write(executor.backend_mut(), info.signal, new); transitions.push((info.signal, (old, new))); - comb_read |= info.comb_read; + comb_read |= + info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?); let fires = info.fires(known(old), edge); if cached { changed.push((event, fires)); diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 7e13bd35dba..ae3d4b70502 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -166,6 +166,7 @@ impl super::super::EventHandle for NativeEventRef { /// that share the same compiled machine code. pub struct SharedNativeCode { comb_func: NativeSimFunc, + clock_alias_funcs: Vec>, comb_unit_funcs: Vec, /// One function per process kernel. process_funcs: Vec, @@ -308,8 +309,25 @@ impl SharedNativeCode { .map(materialize) .collect::, _>>()?; + // Optional named exports keep older images usable: absence requests a + // full settle. Export names are part of the native runtime contract. + let mut clock_alias_funcs = vec![None; id_to_event.len()]; + for entry in &program_image.code_entries { + if let Some(id) = entry.name.strip_prefix(super::clock_aliases::EXPORT_PREFIX) { + let id = id + .strip_suffix(']') + .and_then(|id| id.parse::().ok()) + .filter(|&id| id < clock_alias_funcs.len()) + .ok_or_else(|| codegen_message("invalid clock alias export"))?; + if clock_alias_funcs[id].is_some() { + return Err(codegen_message("duplicate clock alias export")); + } + clock_alias_funcs[id] = Some(native_function_at(&jit_image, entry.offset)?); + } + } Ok(Self { comb_func, + clock_alias_funcs, comb_unit_funcs, process_funcs, lane_kernels, @@ -359,7 +377,8 @@ impl SharedNativeCode { /// One callable function in a packed native code image. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NativeCodeEntry { - /// Stable diagnostic name for the emitted function. + /// Stable name for the emitted function. `clock_alias_update[N]` names + /// an optional clock-wiring update entry for event N; other names are diagnostic. pub name: String, /// Byte offset from the start of the native image. pub offset: usize, @@ -2656,6 +2675,26 @@ fn compile_program_with_outlining_threshold( .into_iter() .collect::, _>>()?; let lane_kernels = super::lanes::compile_lane_kernels(sir, options, cancel)?; + let mut clock_alias_jits = Vec::new(); + if !options.four_state && !options.native_force_support && force_bindings.is_empty() { + let (_, clocks) = crate::backend::event_ids(sir); + for (id, clock) in clocks.into_iter().enumerate() { + if let Some(units) = super::clock_aliases::extract(sir, clock) { + let name = format!("{}{}]", super::clock_aliases::EXPORT_PREFIX, id); + let compiled = compile_units( + &units, + layout, + false, + &name, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + )?; + clock_alias_jits.push((name, compiled)); + } + } + } let codegen_trace = capture_trace .then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks)); let semantic_memory_size = layout @@ -2663,6 +2702,11 @@ fn compile_program_with_outlining_threshold( .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( + clock_alias_jits + .iter() + .map(|(_, code)| code.required_state_size), + ) .chain(comb_chunk_jits.iter().map(|code| code.required_state_size)) .chain( compiled_ff_codes @@ -2683,6 +2727,11 @@ fn compile_program_with_outlining_threshold( ) .fold(semantic_memory_size, usize::max); let required_native_features = std::iter::once(comb_jit.required_native_features) + .chain( + clock_alias_jits + .iter() + .map(|(_, code)| code.required_native_features), + ) .chain( comb_chunk_jits .iter() @@ -2768,6 +2817,15 @@ fn compile_program_with_outlining_threshold( )?; task_offsets.insert(task_id, offset); } + for (name, compiled) in &clock_alias_jits { + append_native_code( + &mut packed_image, + &mut code_entries, + &mut image_symbols, + name.clone(), + compiled, + )?; + } let lane_image = lane_kernels .map(|kernels| kernels.pack(&mut packed_image, &mut code_entries, &mut image_symbols)) .transpose()?; @@ -3695,6 +3753,14 @@ impl super::super::SimBackend for NativeBackend { self.call_func_timed(func) } + fn eval_clock_aliases(&mut self, event: NativeEventRef) -> Result { + let Some(func) = self.compiled.clock_alias_funcs[event.id] else { + return Ok(false); + }; + self.call_func_timed(func)?; + Ok(true) + } + fn eval_apply_ff_at(&mut self, event: NativeEventRef) -> Result<(), SimulatorErrorCode> { if self.lane_event_kernel(event) { let compiled = Arc::clone(&self.compiled); @@ -4085,6 +4151,45 @@ mod tests { BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, }; + #[test] + fn image_without_clock_alias_exports_uses_full_settle() { + let source = r#" + module Child (clk: input clock, d: input bit<8>, q: output bit<8>) { + always_ff (clk) { q = d; } + } + module Top (clk: input clock, d: input bit<8>, q: output bit<8>) { + inst child: Child (clk, d, q); + } + "#; + let mut image = crate::Simulator::builder(source, "Top") + .four_state(false) + .compile_native() + .unwrap() + .into_program_image(); + let previous = image.code_entries.len(); + image.code_entries.retain(|entry| { + !entry + .name + .starts_with(super::super::clock_aliases::EXPORT_PREFIX) + }); + assert_eq!(previous, image.code_entries.len() + 1); + let image = + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap(); + let mut sim = crate::Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + let event = sim.event("clk"); + let d = sim.signal("d"); + sim.set(d, 42u8); + sim.active_edge(event).unwrap(); + sim.inactive_edge(event).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 42u8.into()); + assert_eq!( + sim.get(sim.child_signal(&[("child", 0)], "clk")), + 0u8.into() + ); + } + /// A unit of `blocks` blocks loading `value`, with its maps filled in /// forward or reverse order. fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit { diff --git a/crates/celox/src/backend/native/clock_aliases.rs b/crates/celox/src/backend/native/clock_aliases.rs new file mode 100644 index 00000000000..8478e3a50b1 --- /dev/null +++ b/crates/celox/src/backend/native/clock_aliases.rs @@ -0,0 +1,146 @@ +//! A clock move whose entire combinational cone is wiring needs only these +//! stores, not another evaluation of the datapath. Keep the original stores +//! (including trigger bookkeeping) and leave the full comb function unchanged. + +use crate::HashMap; +use crate::ir::{ + AbsoluteAddr, BlockId, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, + SIRInstruction, SIROffset, SIRTerminator, +}; +use celox_sir::BasicBlock; + +pub(super) const EXPORT_PREFIX: &str = "clock_alias_update["; + +pub(super) fn extract( + program: &LaidOutProgram, + clock: AbsoluteAddr, +) -> Option>> { + let events = &program.design.events; + if events.reset_clocks.contains_key(&clock) + || !events.combinationally_read.contains(&clock) + || !program + .runtime() + .runtime_schema + .persistent_comb_state + .is_empty() + || !program.runtime().runtime_schema.comb_observers.is_empty() + { + return None; + } + let is_alias = + |address: RegionedAbsoluteAddr| events.canonical(address.absolute_addr()) == clock; + let mut result = Vec::new(); + for unit in &program.sir.eval_comb { + let cfg = celox_sir::cfg::SirCfg::analyze_forward(unit).ok()?; + // A copy must execute exactly once on every successful evaluation. + // Exclude error exits rather than hoisting through them. Other logic + // may contain loops; only the copied stores must be outside cycles. + if unit + .blocks + .values() + .any(|block| matches!(block.terminator, SIRTerminator::Error(_))) + { + return None; + } + let exits: Vec<_> = unit + .blocks + .values() + .filter(|block| matches!(block.terminator, SIRTerminator::Return)) + .map(|block| cfg.index[&block.id]) + .collect(); + let mut loads = HashMap::default(); + for block in unit.blocks.values() { + for instruction in &block.instructions { + if matches!( + instruction, + SIRInstruction::ExternCall { .. } + | SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + ) { + return None; + } + if let Some(read) = instruction.memory_read() { + if is_alias(*read.addr) { + // Only direct root loads: alias chains and working-state + // loads require a more general dependency proof. + match instruction { + SIRInstruction::Load(reg, addr, SIROffset::Static(0), 1) + if addr.region == 0 && addr.absolute_addr() == clock => + { + loads.insert(*reg, instruction.clone()); + } + _ => return None, + } + } + } + } + } + let mut stores = Vec::new(); + for id in &cfg.block_ids { + let block = &unit.blocks[id]; + let mut used = false; + block + .terminator + .for_each_use(|reg| used |= loads.contains_key(®)); + if used { + return None; + } + for instruction in &block.instructions { + let mut uses_clock = false; + instruction.for_each_use(|reg| uses_clock |= loads.contains_key(®)); + let writes_alias = instruction + .memory_write() + .is_some_and(|write| is_alias(*write.addr)); + if !uses_clock && !writes_alias { + continue; + } + match instruction { + SIRInstruction::Store(addr, SIROffset::Static(0), 1, source, _, captures) + if addr.region == 0 + && addr.absolute_addr() != clock + && is_alias(*addr) + && loads.contains_key(source) + && captures.is_empty() + && !cfg.sccs[cfg.scc_for_block[cfg.index[id]]].cyclic + && exits + .iter() + .all(|&exit| cfg.dominators.dominates(cfg.index[id], exit)) => + { + stores.push(instruction.clone()); + } + _ => return None, + } + } + } + if stores.is_empty() { + continue; + } + let mut registers: Vec = loads.keys().copied().collect(); + registers.sort_unstable(); + let register_map = registers + .iter() + .map(|reg| (*reg, unit.register_map[reg].clone())) + .collect(); + let mut instructions: Vec<_> = registers.iter().map(|reg| loads[reg].clone()).collect(); + instructions.extend(stores); + let id = BlockId(0); + result.push(ExecutionUnit { + entry_block_id: id, + blocks: [( + id, + BasicBlock { + id, + params: Vec::new(), + instructions, + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map, + }); + } + // No exports for unused clocks: their ordinary topology already avoids settling. + (!result.is_empty()).then_some(result) +} diff --git a/crates/celox/src/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index 3a41492b801..0b0e613dca3 100644 --- a/crates/celox/src/backend/native/mod.rs +++ b/crates/celox/src/backend/native/mod.rs @@ -1,4 +1,5 @@ pub mod backend; +mod clock_aliases; mod compile_resources; mod image_file; mod lanes; diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index bf76d552d4c..fdb70cbee83 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -1391,6 +1391,23 @@ impl SimBackend for TieredBackend { } } + fn eval_clock_aliases(&mut self, event: TieredEventRef) -> Result { + // Do not promote during a partial settle: normal evaluation boundaries + // continue to own tier changes and their accounting. + match &mut self.phase { + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => { + let event = native.id_to_event_slice()[event.id()]; + native.eval_clock_aliases(event) + } + _ => Ok(false), + } + } + fn eval_apply_ff_at(&mut self, event: TieredEventRef) -> Result<(), SimulatorErrorCode> { self.maybe_promote(); self.maybe_upgrade(); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 1e4653b2e21..ca90b98db52 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2394,7 +2394,7 @@ mod host { celox_runtime::set_level, ); if let Some(old) = moved { - if info.comb_read { + if self.clock_move_needs_settle(event, info.comb_read)? { self.dirty = true; } if info.fires(old, active) { @@ -2402,7 +2402,7 @@ mod host { } } self.backend.set(info.signal, inactive.level()); - if info.comb_read || observers { + if self.clock_move_needs_settle(event, info.comb_read)? || observers { self.dirty = true; } Ok(()) @@ -2421,12 +2421,24 @@ mod host { } self.backend .set(info.signal, info.active_edge().opposite().level()); - if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + if self.clock_move_needs_settle(event, info.comb_read)? + || !self.program.runtime_schema.comb_observers.is_empty() + { self.dirty = true; } Ok(()) } + /// Publish wiring immediately when the previous state was settled; + /// otherwise leave the entire pending evaluation to the normal path. + fn clock_move_needs_settle( + &mut self, + event: B::Event, + comb_read: bool, + ) -> Result { + Ok(comb_read && (self.dirty || !self.backend.eval_clock_aliases(event)?)) + } + /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2522,7 +2534,9 @@ mod host { // wait behind the kernel's stores (4 KiB aliasing), // which made a period cost almost two domain runs. self.backend.set(info.signal, edge.level()); - if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + if self.clock_move_needs_settle(event, info.comb_read)? + || !self.program.runtime_schema.comb_observers.is_empty() + { self.dirty = true; } return Ok(()); @@ -2539,7 +2553,7 @@ mod host { else { return Ok(()); }; - if info.comb_read { + if self.clock_move_needs_settle(event, info.comb_read)? { self.dirty = true; } if info.fires(old, edge) { @@ -2559,7 +2573,7 @@ mod host { && !self.finish_sites && self.backend.runs_derived_edge_units() { - return self.edge_unit(info, edge, unit); + return self.edge_unit(event, info, edge, unit); } let plans = std::sync::Arc::clone(&self.derived_ticks); let plan = plans.get(event.id()).and_then(Option::as_ref); @@ -2581,6 +2595,7 @@ mod host { #[inline(never)] fn edge_unit( &mut self, + event: B::Event, info: celox_runtime::EventEdge, edge: celox_runtime::Edge, unit: DerivedEdgeUnit, @@ -2597,9 +2612,9 @@ mod host { return Ok(()); }; let fires = info.fires(old, edge); + let comb_read = self.clock_move_needs_settle(event, info.comb_read)?; if let Some(flag) = self.derived_settle { - self.backend - .set(flag, u8::from(self.dirty || info.comb_read)); + self.backend.set(flag, u8::from(self.dirty || comb_read)); } let index = match edge { celox_runtime::Edge::Rising => unit.rising, @@ -2613,7 +2628,7 @@ mod host { // in the plan walk. let outcome = if unit.gated || fires { celox_runtime::EdgeOutcome::Settled - } else if info.comb_read { + } else if comb_read { celox_runtime::EdgeOutcome::Moved } else { celox_runtime::EdgeOutcome::Stored @@ -3930,7 +3945,11 @@ mod host { assign seen = {seen}; }}" ); - let mut sim = Simulator::builder(&source, "Top").build().unwrap(); + // The interpreter requests the generic full-settle fallback. + // Native wiring-only cones are checked in native_clock_aliases. + let mut sim = Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); let clk = sim.event("clk"); sim.posedge(clk).unwrap(); assert!(!sim.dirty); diff --git a/crates/celox/tests/native_clock_aliases.rs b/crates/celox/tests/native_clock_aliases.rs new file mode 100644 index 00000000000..5135b786858 --- /dev/null +++ b/crates/celox/tests/native_clock_aliases.rs @@ -0,0 +1,170 @@ +//! Native clock-cone specialization, including its optional image exports. +#![cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + +use celox::{NativeBackend, SharedNativeCode}; +use celox::{NativeProgramImage, SimBackend, Simulator}; +use std::sync::Arc; + +const SOURCE: &str = r#" +module Child (clk: input clock, d: input bit<8>, q: output bit<8>) { + always_ff (clk) { q = d; } +} +module Top (clk: input clock, d: input bit<8>, q: output bit<8>) { + inst child: Child (clk, d, q); +} +"#; + +fn image(source: &str, four_state: bool) -> NativeProgramImage { + Simulator::builder(source, "Top") + .four_state(four_state) + .compile_native() + .unwrap() + .into_program_image() +} + +fn exports(image: &NativeProgramImage) -> usize { + image + .code_entries() + .iter() + .filter(|entry| entry.name.starts_with("clock_alias_update[")) + .count() +} + +#[test] +fn clock_wiring_projection_matches_full_settle_after_image_roundtrip() { + let image = image(SOURCE, false); + assert_eq!(exports(&image), 1); + let image = + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap(); + // SAFETY: this test just compiled and serialized the image. + let shared = Arc::new(unsafe { SharedNativeCode::from_image(image) }.unwrap()); + let mut fast = NativeBackend::from_shared(shared.clone()); + let mut full = NativeBackend::from_shared(shared); + let event = fast.id_to_event_slice()[0]; + use celox::EventHandle; + let clock = fast.resolve_signal(&event.addr()); + fast.eval_comb().unwrap(); + full.eval_comb().unwrap(); + for value in [1u8, 0, 1, 0] { + fast.clear_triggered_bits(); + full.clear_triggered_bits(); + fast.set(clock, value); + full.set(clock, value); + assert!(fast.eval_clock_aliases(event).unwrap()); + full.eval_comb().unwrap(); + assert_eq!(fast.get_triggered_bits(), full.get_triggered_bits()); + for (addr, &offset) in &fast.layout().offsets { + let width = fast.layout().plane_size(addr); + let bytes = |backend: &NativeBackend| { + let (ptr, _) = backend.memory_as_ptr(); + // SAFETY: layout ranges describe live signal storage. Exclude + // host pointers and scratch memory, which differ per instance. + unsafe { std::slice::from_raw_parts(ptr.add(offset), width) }.to_vec() + }; + assert_eq!(bytes(&fast), bytes(&full), "{addr:?}"); + } + } +} + +#[test] +fn falling_edges_publish_aliases_and_dirty_inputs_still_settle() { + let mut sim = Simulator::builder(SOURCE, "Top") + .four_state(false) + .build_native() + .unwrap(); + let clk = sim.event("clk"); + let d = sim.signal("d"); + let q = sim.signal("q"); + let child_clk = sim.child_signal(&[("child", 0)], "clk"); + for value in [17u8, 29, 255] { + // Leave this data write dirty: the projection must not suppress it. + sim.set(d, value); + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(q), value.into()); + assert_eq!(sim.get(child_clk), 1u8.into()); + sim.inactive_edge(clk).unwrap(); + // Inspect the backend directly so this assertion cannot cause a + // deferred full settle and hide a missing alias publication. + assert_eq!(sim.backend_ref().get(child_clk), 0u8.into()); + // Already settled rising edge takes the specialized path. + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(q), value.into()); + sim.inactive_edge(clk).unwrap(); + } +} + +#[test] +fn clock_data_dependencies_and_four_state_keep_full_settle() { + assert_eq!(exports(&image(SOURCE, true)), 0); + let source = SOURCE.replace( + "inst child: Child (clk, d, q);", + "var data: bit<8>; assign data = if (clk as u8) != 0 ? d : 0; inst child: Child (clk, d: data, q);" + ); + assert_eq!(exports(&image(&source, false)), 0); +} + +#[test] +fn coincident_clock_moves_publish_both_wiring_cones() { + let source = r#" + module Counter (clk: input clock, q: output bit<8>) { + always_ff (clk) { q += 1; } + } + module Top ( + clk_a: input 'fast clock, clk_b: input 'slow clock, + a: output 'fast bit<8>, b: output 'slow bit<8>, + ) { + inst first: Counter (clk: clk_a, q: a); + inst second: Counter (clk: clk_b, q: b); + } + "#; + let compiled = Simulator::builder(source, "Top") + .four_state(false) + .compile_native() + .unwrap(); + assert_eq!(exports(compiled.program_image()), 2); + let mut sim = compiled.initialize().unwrap(); + let a = sim.event("clk_a"); + let b = sim.event("clk_b"); + use celox_runtime::Edge::{Falling, Rising}; + for expected in 1..=4u8 { + sim.edges(&[(a, Rising), (b, Rising)]).unwrap(); + assert_eq!(sim.get(sim.signal("a")), expected.into()); + assert_eq!(sim.get(sim.signal("b")), expected.into()); + sim.edges(&[(b, Falling), (a, Falling)]).unwrap(); + for child in ["first", "second"] { + let clk = sim.child_signal(&[(child, 0)], "clk"); + assert_eq!(sim.backend_ref().get(clk), 0u8.into()); + } + } +} + +#[test] +fn unrelated_combinational_loop_does_not_prevent_clock_specialization() { + let source = SOURCE.replace( + "always_ff (clk) { q = d; }", + r#" + var sum: bit<8>; + always_comb { + sum = 0; + for i in 0..1024 { + if i <: (d as u32) { sum += 1; } + } + } + always_ff (clk) { q = sum; } + "#, + ); + let compiled = Simulator::builder(&source, "Top") + .four_state(false) + .compile_native() + .unwrap(); + assert_eq!(exports(compiled.program_image()), 1); + let mut sim = compiled.initialize().unwrap(); + let clk = sim.event("clk"); + let d = sim.signal("d"); + for expected in [3u8, 99, 255] { + sim.modify(|io| io.set(d, expected)).unwrap(); + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(sim.signal("q")), expected.into()); + sim.inactive_edge(clk).unwrap(); + } +}