diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f53a2af7176..c42896d21be 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -936,85 +936,126 @@ pub fn schedule_symbolic_rtl_reporting_loops( // working state is seeded with the stable value first, so a store // compares with the value its update replaces. let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); - for (source, counter) in probes { - let width = source.access.msb - source.access.lsb + 1; - let four_state = four_state && variables[&source.id].1; - let offset = match unpacked_element_widths.get(&source.id) { - Some(&element_width) - if width > element_width - && source.access.lsb.is_multiple_of(element_width) - && width.is_multiple_of(element_width) => - { - celox_sir::SIROffset::PackedElements { - bit_offset: source.access.lsb, - element_width, + // Each unit is instrumented once for all probes. Probe `p` is pass + // `2p` over the stable state and pass `2p + 1` over a flip-flop + // evaluation's working state, the order of instrumenting probe by + // probe. + let probe_codes: Vec<_> = probes + .iter() + .map(|&(source, counter)| { + let width = source.access.msb - source.access.lsb + 1; + let four_state = four_state && variables[&source.id].1; + let offset = match unpacked_element_widths.get(&source.id) { + Some(&element_width) + if width > element_width + && source.access.lsb.is_multiple_of(element_width) + && width.is_multiple_of(element_width) => + { + celox_sir::SIROffset::PackedElements { + bit_offset: source.access.lsb, + element_width, + } } - } - _ => celox_sir::SIROffset::Static(source.access.lsb), - }; - let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == STABLE_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: stable(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for process in &mut processes { - crate::watch::instrument_unit(&mut process.kernel, code); + _ => celox_sir::SIROffset::Static(source.access.lsb), + }; + (counter, width, four_state, offset) + }) + .collect(); + let mut probes_of: HashMap> = HashMap::default(); + for (index, (source, _)) in probes.iter().enumerate() { + probes_of.entry(source.id).or_default().push(index); + } + // The first probe of `signal` whose `pass` is `after` or later. + let first_probe = |signal: AbsoluteAddr, pass: fn(usize) -> usize, after: usize| { + let indices = probes_of.get(&signal)?; + indices + .get(indices.partition_point(|&index| pass(index) < after)) + .copied() + }; + fn probe_code( + probe: &(AbsoluteAddr, usize, bool, celox_sir::SIROffset), + signal: A, + counter: A, + ) -> crate::watch::WatchCode { + let &(_, width, four_state, ref offset) = probe; + crate::watch::WatchCode { + signal, + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, counter)], } - for units in eval_apply_ffs - .values_mut() - .chain(eval_only_ffs.values_mut()) - .chain(apply_ffs.values_mut()) + } + let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); + let working = |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let stable_code = |instruction: &SIRInstruction, after: usize| { + let address = crate::watch::write_destination(instruction)?; + if address.region != STABLE_REGION { + return None; + } + let index = first_probe(address.absolute_addr(), |index| 2 * index, after)?; + Some(( + 2 * index, + probe_code( + &probe_codes[index], + stable(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )) + }; + // A flip-flop evaluation's stores to a signal of `ff_multi_stored`; + // the commits that seed its working state are not writes of the + // process. + let evaluation_code = |instruction: &SIRInstruction, after: usize| { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && ff_multi_stored.contains(&address.absolute_addr()) + && let Some(index) = + first_probe(address.absolute_addr(), |index| 2 * index + 1, after) { - for unit in units { - crate::watch::instrument_unit(unit, code); - } + return Some(( + 2 * index + 1, + probe_code( + &probe_codes[index], + working(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )); } - for parts in parallel_ff_units.values_mut() { - for (_, part) in parts { - crate::watch::instrument_unit(&mut part.evaluate, code); - crate::watch::instrument_unit(&mut part.apply, code); - } + stable_code(instruction, after) + }; + for process in &mut processes { + crate::watch::instrument_writes_in_passes(&mut process.kernel, stable_code); + } + for units in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, evaluation_code); } - if ff_multi_stored.contains(&source.id) { - let working = - |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: working(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for_each_ff_evaluation( - &mut eval_apply_ffs, - &mut eval_only_ffs, - &mut parallel_ff_units, - |unit| instrument_stores(unit, code), - ); + } + for units in apply_ffs.values_mut() { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, stable_code); } - for path in &mut comb_blocks { - if let LogicPathTarget::Process { unit, .. } = &mut path.target { - crate::watch::instrument_unit(unit, |address| { - (*address == source.id).then(|| crate::watch::WatchCode { - signal: source.id, - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, counter)], - }) - }); - } + } + for parts in parallel_ff_units.values_mut() { + for (_, part) in parts { + crate::watch::instrument_writes_in_passes(&mut part.evaluate, evaluation_code); + crate::watch::instrument_writes_in_passes(&mut part.apply, stable_code); + } + } + for path in &mut comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let &address = crate::watch::write_destination(instruction)?; + let index = first_probe(address, |index| index, after)?; + Some(( + index, + probe_code(&probe_codes[index], address, probe_codes[index].0), + )) + }); } } let ff_units = eval_apply_ffs @@ -1052,31 +1093,45 @@ pub fn schedule_symbolic_rtl_reporting_loops( .iter() .map(|slots| slots.signal) .collect(); - for (signal, slots) in &counted { - if !ff_multi_stored.contains(signal) || pending.contains(signal) { - continue; - } - let (width, is_4state) = variables[signal]; - let regioned = RegionedAbsoluteAddr::from_absolute_addr; - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( - || crate::watch::WatchCode { - signal: regioned(WORKING_REGION, *signal), - offset: celox_sir::SIROffset::Static(0), - width, - four_state: four_state && is_4state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) - .collect(), - }, - ) - }; + // One pass per signal, in signal order; each pass watches only its + // own signal. + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let multi_stored: HashMap)> = counted + .iter() + .filter(|(signal, _)| ff_multi_stored.contains(signal) && !pending.contains(signal)) + .enumerate() + .map(|(pass, (&signal, slots))| { + let (width, is_4state) = variables[&signal]; + let code = crate::watch::WatchCode { + signal: regioned(WORKING_REGION, signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }; + (signal, (pass, code)) + }) + .collect(); + if !multi_stored.is_empty() { for_each_ff_evaluation( &mut eval_apply_ffs, &mut eval_only_ffs, &mut parallel_ff_units, - |unit| instrument_stores(unit, code), + |unit| { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let SIRInstruction::Store(address, ..) = instruction else { + return None; + }; + if address.region != WORKING_REGION { + return None; + } + let (pass, code) = multi_stored.get(&address.absolute_addr())?; + (*pass >= after).then(|| (*pass, code.clone())) + }) + }, ); } counted @@ -4012,19 +4067,6 @@ fn ff_multi_stored( .collect() } -/// [`crate::watch::instrument_unit`] for the stores alone: the commits that -/// seed a flip-flop evaluation's working state are not writes of the -/// process. -fn instrument_stores( - unit: &mut ExecutionUnit, - watch_for: impl Fn(&RegionedAbsoluteAddr) -> Option>, -) { - crate::watch::instrument_writes(unit, |instruction| match instruction { - SIRInstruction::Store(address, ..) => watch_for(address), - _ => None, - }); -} - /// Run `f` on every flip-flop evaluation. fn for_each_ff_evaluation( eval_apply_ffs: &mut FfUnits, diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 40a2bdbbc5c..b29ce3188b5 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -641,6 +641,113 @@ pub fn instrument_writes( } } +/// The result of [`instrument_writes`] once per pass, in pass order, in one +/// walk over `unit`. `watch_for(instruction, after)` gives the first pass +/// from `after` on that watches `instruction`, and its code. +/// +/// A later pass also sees the code an earlier one added, and wraps the write +/// inside it, so a write watched by several passes is surrounded by their +/// code from the first pass outward in. The new registers are numbered as +/// the passes one after another would number them. +pub fn instrument_writes_in_passes( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&SIRInstruction, usize) -> Option<(usize, WatchCode)>, +) { + let ExecutionUnit { + blocks, + register_map, + .. + } = unit; + let first_new = register_map.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let mut next_register = first_new; + // The pass, block and first register of every piece of code added, in + // the order the walk adds them. + let mut added: Vec<(usize, usize, usize)> = Vec::new(); + let mut instrumented = Vec::new(); + for (order, block) in blocks.values_mut().enumerate() { + if !block + .instructions + .iter() + .any(|instruction| watch_for(instruction, 0).is_some()) + { + continue; + } + let mut instructions = Vec::with_capacity(block.instructions.len()); + let mut work: Vec<(SIRInstruction, usize)> = Vec::new(); + for instruction in std::mem::take(&mut block.instructions) { + work.push((instruction, 0)); + while let Some((instruction, after)) = work.pop() { + let Some((pass, watch)) = watch_for(&instruction, after) else { + instructions.push(instruction); + continue; + }; + let value_type = match &instruction { + SIRInstruction::Store(_, _, _, value, ..) => register_map.get(value).cloned(), + _ => None, + }; + let mut b = SIRBuilder::new_with(next_register); + emit_watched(&mut b, &watch, instruction, value_type.as_ref()); + b.seal_block(SIRTerminator::Return); + let (mut emitted, registers, next) = b.drain(); + added.push((pass, order, next_register)); + next_register = next; + register_map.extend(registers); + let emitted = emitted + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions; + work.extend(emitted.into_iter().rev().map(|emitted| (emitted, pass + 1))); + } + } + block.instructions = instructions; + instrumented.push(block.id); + } + if added.is_empty() { + return; + } + + // Renumber the new registers pass by pass, then block by block in the + // order a pass visits them; within a block the walk already added each + // pass's code in order. + let mut ends: Vec = added.iter().skip(1).map(|&(.., first)| first).collect(); + ends.push(next_register); + let mut pieces: Vec<(usize, usize, usize, usize)> = added + .iter() + .zip(ends) + .map(|(&(pass, order, first), end)| (pass, order, first, end)) + .collect(); + pieces.sort_by_key(|&(pass, order, ..)| (pass, order)); + let mut renumbered = vec![0; next_register - first_new]; + let mut next = first_new; + for (.., first, end) in pieces { + for register in first..end { + renumbered[register - first_new] = next; + next += 1; + } + } + let renumber = |register: &mut RegisterId| { + if register.0 >= first_new { + register.0 = renumbered[register.0 - first_new]; + } + }; + for id in instrumented { + let block = blocks.get_mut(&id).expect("an instrumented block"); + for instruction in &mut block.instructions { + if let Some(register) = instruction.defined_register_mut() { + renumber(register); + } + instruction.for_each_use_mut(renumber); + } + } + let new_registers: Vec<_> = (first_new..next_register) + .filter_map(|id| register_map.remove_entry(&RegisterId(id))) + .collect(); + register_map.extend(new_registers.into_iter().map(|(mut id, ty)| { + renumber(&mut id); + (id, ty) + })); +} + /// Objects that hold back the occurrences of one flip-flop evaluation's /// writes to a signal until the commit that publishes them. /// @@ -1281,7 +1388,10 @@ pub fn declare_pending_slots( mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; - use super::{multi_store_candidates, multi_write_candidates, successors, write_destination}; + use super::{ + WatchCode, instrument_writes, instrument_writes_in_passes, multi_store_candidates, + multi_write_candidates, successors, write_destination, + }; /// Store a constant to `address` at the open block. fn store(b: &mut SIRBuilder, address: u32) { @@ -1556,4 +1666,118 @@ mod tests { let found = multi_store_candidates(&unit, |address| Some(*address)); assert_eq!(found, (0..10000).step_by(2).collect::>()); } + + /// One pass of the equivalence test: the writes it watches and the + /// code it adds. + struct Pass { + address: u32, + stores_only: bool, + code: WatchCode, + } + + impl Pass { + fn watches(&self, instruction: &SIRInstruction) -> bool { + match instruction { + SIRInstruction::Store(address, ..) => *address == self.address, + _ => !self.stores_only && write_destination(instruction) == Some(&self.address), + } + } + } + + /// A random unit of a few blocks writing a few addresses, and random + /// passes over the same addresses; a pass's counters may be written + /// by another pass's code. + fn random_instrumentation(seed: u64) -> (celox_sir::ExecutionUnit, Vec) { + use celox_design::CounterKind; + let state = std::cell::Cell::new(seed); + let next = |bound: u64| { + state.set( + state + .get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + (state.get() >> 33) % bound + }; + let addresses = 1 + next(6) as u32; + let widths = [1, 4, 8]; + let mut b = SIRBuilder::new(); + let blocks = 1 + next(4); + for block in 0..blocks { + for _ in 0..next(6) { + let width = widths[next(3) as usize]; + let value = if next(2) == 0 { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Imm(value, SIRValue::new(next(256) as u8))); + let address = next(addresses as u64) as u32; + b.emit(match next(3) { + 0 => SIRInstruction::Commit( + address, + address, + SIROffset::Static(0), + width, + Vec::new(), + ), + _ => SIRInstruction::Store( + address, + SIROffset::Static(next(2) as usize * 2), + width, + value, + Vec::new(), + Vec::new(), + ), + }); + } + if block + 1 < blocks { + let following = b.new_block(); + b.seal_block(SIRTerminator::Jump(following, Vec::new())); + b.switch_to_block(following); + } + } + let value = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(0u8))); + let unit = b.flush_eu().unwrap(); + let passes = (0..1 + next(8)) + .map(|_| Pass { + address: next(addresses as u64) as u32, + stores_only: next(2) == 0, + code: WatchCode { + signal: next(addresses as u64) as u32, + width: widths[next(3) as usize], + offset: SIROffset::Static(next(2) as usize * 2), + four_state: next(2) == 0, + counters: CounterKind::ALL + .into_iter() + .filter(|_| next(2) == 0) + .map(|kind| (kind, next(addresses as u64 + 2) as u32)) + .collect(), + }, + }) + .collect(); + (unit, passes) + } + + #[test] + fn instrumenting_in_passes_matches_one_pass_after_another() { + for seed in 0..3000 { + let (unit, passes) = random_instrumentation(seed); + let mut one_by_one = unit.clone(); + for pass in &passes { + instrument_writes(&mut one_by_one, |instruction| { + pass.watches(instruction).then(|| pass.code.clone()) + }); + } + let mut at_once = unit; + instrument_writes_in_passes(&mut at_once, |instruction, after| { + let found = passes[after.min(passes.len())..] + .iter() + .position(|pass| pass.watches(instruction))?; + Some((after + found, passes[after + found].code.clone())) + }); + assert_eq!(at_once, one_by_one, "seed {seed}"); + } + } }