diff --git a/CLAUDE.md b/CLAUDE.md index 4b006d7bd54..40fa5b29d36 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,6 +101,7 @@ GCC-style optimization level presets with per-pass overrides. | `IdentityStoreBypass` | Detects identity copies and registers address aliases | | `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) | | `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) | +| `PartitionedSettle` | Splits the combinational settle into partitions that run only when state they read changed (not a SIR transform; off unless enabled, `+sir:partitioned_settle`; `SimulatorBuilder::settle_check` cross-checks it) | ### Cranelift Backend Optimization diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 3456a2c8be1..92e7fc934be 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -16,6 +16,7 @@ fn layout_for(address: AbsoluteAddr, width: usize, four_state: bool) -> MemoryLa let total_size = plane_size * if four_state { 2 } else { 1 }; MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index 5b146b76b5a..cc010904637 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -6488,6 +6488,7 @@ mod bit_count_tests { MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests.rs b/crates/celox-backend-x86/src/backend/native/isel/tests.rs index 19b3c5d844b..8d513fecf0b 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests.rs @@ -16,6 +16,7 @@ use num_bigint::BigUint; fn empty_layout() -> MemoryLayout { MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs index 7ed5e929daa..db8fe2abd3f 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs @@ -196,6 +196,7 @@ fn compile_bit_count(op: UnaryOp, source_width: usize, four_state: bool) -> Comp let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs index aed958745c1..97a0c5cf9e5 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs @@ -800,6 +800,7 @@ fn narrowed_wide_binary_store_does_not_write_source_width() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1130,6 +1131,7 @@ fn execute_unaligned_64_bit_load(dynamic: bool) -> u64 { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1295,6 +1297,7 @@ fn verify_scalar_alignment_matrix(dynamic: bool, four_state: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1511,6 +1514,7 @@ fn verify_wide_alignment_matrix(dynamic: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs index ddce616c2bb..37503198e34 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs @@ -511,6 +511,7 @@ fn lowers_shared_selector_roots_to_cached_indexed_table_loads() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 51d1ae82584..3f94d1bda99 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -660,6 +660,7 @@ fn narrow_wide_shift_uses_only_chunks_covered_by_the_result() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -836,6 +837,7 @@ fn wide_shift_result_is_canonical_before_mux_condition() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs index fd1e45ec7e1..e0b20af1d78 100644 --- a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs +++ b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs @@ -1426,6 +1426,7 @@ mod tests { .collect(); MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs index 437eff6db62..0c82cb95455 100644 --- a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs +++ b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs @@ -145,6 +145,7 @@ pub fn compile(recover: bool) -> CompiledUpdate { )]; let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: celox_state_layout::MemoryLayoutMode::Packed, offsets: [ diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7294c286a4e..c2a6d1ce08c 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1053,6 +1053,27 @@ pub struct RuntimeSchema { /// Generated units that run an edge of an event with every derived /// clock domain it reaches, for the events that have them. pub derived_edges: Vec>, + /// The partitions of a partitioned combinational settle, when it is + /// partitioned. + pub settle_partitions: Option>, +} + +/// A combinational settle split into partitions that run only when state +/// they read changed since they last ran. +/// +/// Byte `p` of `flags` is partition `p`'s dirty flag; the byte after the +/// last partition's is the untracked byte, set once state may change +/// without anyone setting flags (a retained raw view), after which every +/// partition always runs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartitions { + pub flags: A, + pub partitions: u32, + /// State the settle reads or writes, with the partitions to mark when + /// something other than the settle writes it. A written object lists + /// its writers as well, so that, as in a single pass, the settle + /// recomputes it. + pub marks: Vec<(A, Vec)>, } /// The process units that run the edges of one event together with its @@ -1279,6 +1300,7 @@ impl Default for RuntimeSchema { time_slots: Vec::new(), scheduler: None, derived_edges: Vec::new(), + settle_partitions: None, } } } diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs index 05e833c6575..5a208e3e8c1 100644 --- a/crates/celox-frontend-core/src/lib.rs +++ b/crates/celox-frontend-core/src/lib.rs @@ -18,7 +18,7 @@ pub use shared::{ pub use trace::{FrontendTrace, FrontendTraceOptions, TraceSimModule}; pub use symbolic::flattening; -pub use symbolic::parallel::ParallelScheduleOptions; +pub use symbolic::parallel::{ParallelScheduleOptions, SettlePartitionMode}; pub(crate) type HashMap = fxhash::FxHashMap; pub(crate) type HashSet = fxhash::FxHashSet; diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 1b720f15176..11f7925b198 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -8,7 +8,7 @@ use crate::symbolic::artifact::{ use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, HashSet, InstancePath, ParallelScheduleOptions, ParserError, ScheduledRtl, ScheduledRtlOutput, - SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, + SettlePartitionMode, SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, }; use celox_design::{ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, @@ -1507,6 +1507,29 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } let parallel_comb_blocks = parallel.enabled().then(|| comb_blocks.clone()); + // The flag object of a partitioned settle is declared once the + // partitions are known; reserve its address now. + let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_flags = + settle_partitioning(parallel, &comb_blocks, &global_arena, eval_apply_ffs.len()).map( + |target_cost| { + let var_id = SourceVarId( + modules[&root_id] + .variables + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0), + ); + scheduler::SettlePartitioning { + flags: AbsoluteAddr { + instance_id: root_instance, + var_id, + }, + target_cost, + } + }, + ); let sched_start = flatten_timing.then(std::time::Instant::now); let schedule = match scheduler::sort_with_unpacked_element_widths( comb_blocks, @@ -1517,6 +1540,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( &var_widths, &unpacked_element_widths, next_runtime_error_code, + settle_flags, ) { Ok(schedule) => schedule, Err(error) => { @@ -1557,6 +1581,19 @@ pub fn schedule_symbolic_rtl_reporting_loops( }); } }; + let settle_partitions = schedule.partitions.clone(); + + let settle_flags = settle_flags.filter(|_| !settle_partitions.is_empty()); + if let Some(settle) = &settle_flags { + // The flags carry what changed from one settle to the next. + persistent_comb_state.insert(settle.flags); + declare_settle_flags( + &mut modules, + root_id, + settle.flags.var_id, + settle_partitions.len(), + ); + } let object_sizes = super::parallel::ObjectSizes { widths: &var_widths, element_widths: &unpacked_element_widths, @@ -1677,7 +1714,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( // events; that copy lets the FF part use comb values in registers. // Beyond that the copies would multiply the design by its event count, // so the ticks share the one `eval_comb` program instead. - let merge_comb_apply = eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS; + // A merged program drops comb stores the next full settle would redo; + // a partitioned settle keeps what its skipped partitions stored. + let merge_comb_apply = + eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS && settle_flags.is_none(); let mut eval_comb_apply_ffs = HashMap::default(); let mut fused_direct_ff_writes = HashMap::default(); if let ( @@ -1920,6 +1960,21 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain(bound_initials) .map(|(_, init)| init) .collect(); + if let Some(settle) = &settle_flags { + // Every partition runs at the first settle. + let partitions = settle_partitions.len(); + let value = (0..partitions).fold(BigUint::default(), |value, partition| { + value | (BigUint::from(1u8) << (partition * 8)) + }); + initial_memory_values.push(InitialStateValue { + address: settle.flags, + data: InitialStateData::Packed { + value, + mask: BigUint::default(), + written_mask: (BigUint::from(1u8) << ((partitions + 1) * 8)) - 1u8, + }, + }); + } let state_objects: HashMap = instance_modules .iter() .flat_map(|(&instance_id, module_id)| { @@ -2326,6 +2381,32 @@ pub fn schedule_symbolic_rtl_reporting_loops( let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_partitions = settle_flags.map(|settle| { + let mut marks: HashMap> = HashMap::default(); + for (index, partition) in settle_partitions.iter().enumerate() { + let index = index as u32; + for addr in &partition.reads { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + for addr in &partition.writes { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + } + let mut marks = marks + .into_iter() + .map(|(state, partitions)| (state, partitions.into_iter().collect())) + .collect::>(); + marks.sort_unstable(); + celox_design::SettlePartitions { + flags: project(settle.flags), + partitions: settle_partitions.len() as u32, + marks, + } + }); let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema { slots: slots.map(|var_id| { project(AbsoluteAddr { @@ -2468,6 +2549,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( time_slots, scheduler, derived_edges: Vec::new(), + settle_partitions, }, }; @@ -2485,6 +2567,77 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) } +/// Smallest combinational program, in expression nodes, whose settle +/// [`SettlePartitionMode::Estimated`] partitions. +const MIN_PARTITIONED_SETTLE_COST: usize = 20_000; +/// Expression nodes per partition of an estimated partitioned settle. +const SETTLE_PARTITION_COST: usize = 2_000; + +/// The cost per partition of a partitioned settle of `comb_blocks`, or +/// `None` to keep one pass. +/// +/// A partition costs a flag test per settle and flag stores in every writer +/// of what it reads, and pays off when most of the program is idle in most +/// settles. A design with few event domains drives most of its logic from +/// one clock, so it keeps the single pass, as does a small program. +fn settle_partitioning( + parallel: &ParallelScheduleOptions, + comb_blocks: &[LogicPath], + arena: &SLTNodeArena, + events: usize, +) -> Option { + // Lane-partitioned kernels run the comb program as lane tasks. + if parallel.enabled() { + return None; + } + match parallel.settle { + SettlePartitionMode::Off => None, + SettlePartitionMode::Always => Some(1), + SettlePartitionMode::Estimated => { + if events <= MERGED_COMB_APPLY_EVENTS { + return None; + } + let cost: usize = comb_blocks + .iter() + .map(|path| scheduler::path_cost(arena, path)) + .sum(); + (cost >= MIN_PARTITIONED_SETTLE_COST).then_some(SETTLE_PARTITION_COST) + } + } +} + +/// Declare the flags of a settle of `partitions` partitions, one byte each +/// plus the untracked byte, as a hidden variable of the top module. +fn declare_settle_flags( + modules: &mut HashMap, + root: ModuleId, + var_id: SourceVarId, + partitions: usize, +) { + let width = (partitions + 1) * 8; + let variables = &mut modules.get_mut(&root).expect("top module").variables; + variables.insert( + var_id, + crate::symbolic::artifact::SymbolicVariable { + path: vec!["$settle".to_string(), "flags".to_string()], + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: false, + kind: DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: Vec::new(), + value_kind: Default::default(), + }, + packed_dims: vec![width], + unpacked_ranges: Vec::new(), + source: None, + module_affiliated: false, + }, + ); +} + /// Declare the hidden objects a compiled scheduler exchanges with the /// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for /// a design with `process_count` process kernels. A design without kernels diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs index dccfada3730..f0824ef3d88 100644 --- a/crates/celox-frontend-core/src/symbolic/parallel.rs +++ b/crates/celox-frontend-core/src/symbolic/parallel.rs @@ -27,6 +27,22 @@ pub struct ParallelScheduleOptions { /// Smallest accepted estimated speedup of a partitioned phase, in /// percent of its single-lane cost. pub minimum_speedup_percent: u64, + /// Whether the combinational settle may be split into partitions that + /// run only when what they read changed. Only a host that reports its + /// writes and instruments the units it generates may request it. + pub settle: SettlePartitionMode, +} + +/// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SettlePartitionMode { + /// One pass over the whole combinational program. + #[default] + Off, + /// Partition designs with many event domains and a large program. + Estimated, + /// Partition every program into the smallest partitions. For tests. + Always, } impl ParallelScheduleOptions { @@ -35,6 +51,7 @@ impl ParallelScheduleOptions { lanes: 1, synchronization_cost: 400, minimum_speedup_percent: 125, + settle: SettlePartitionMode::Off, }; /// Request `lanes` simulation lanes with the default cost model. diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 94ba20cf12e..05bb918ca1e 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -119,6 +119,27 @@ pub trait SimBackend { assert!(offset + bytes.len() <= len, "write past the memory image"); // Safety: the backend exposes `len` writable bytes at `ptr`. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()) }; + self.mark_settle_range(offset, bytes.len()); + } + + /// Set the flags of the settle partitions reading `offset..offset + len`, + /// which the host wrote. + fn mark_settle_range(&mut self, offset: usize, len: usize) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_range(ptr.cast_mut(), offset, len) }; + } + } + + /// From now on run every settle partition on every settle: a raw view + /// of the state can change it without reporting. + fn mark_settle_untracked(&mut self) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_untracked(ptr.cast_mut()) }; + } } /// Return an opaque owner that keeps the memory allocation alive. @@ -200,17 +221,18 @@ pub trait SimBackend { /// Called by host setters, which share the generated-store notification ABI. fn mark_vcd_signal(&mut self, signal: SignalRef) { + let len = signal.array_layout.map_or_else( + || celox_state_layout::get_byte_size(signal.width), + |array| array.element_count * array.element_stride, + ); if let Some(trace) = self.layout().trace.as_ref() { - let len = signal.array_layout.map_or_else( - || celox_state_layout::get_byte_size(signal.width), - |array| array.element_count * array.element_stride, - ); let (ptr, _) = self.memory_as_ptr(); // SAFETY: layout homes and metadata fit in the writable state image. unsafe { trace.mark_range(ptr.cast_mut(), signal.offset, len); } } + self.mark_settle_range(signal.offset, len); } } diff --git a/crates/celox-sir-opt/src/lib.rs b/crates/celox-sir-opt/src/lib.rs index 352f3cbc005..57d173ca032 100644 --- a/crates/celox-sir-opt/src/lib.rs +++ b/crates/celox-sir-opt/src/lib.rs @@ -102,5 +102,6 @@ pub fn optimize( mod policy; pub use policy::{ - OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SirDiagnostics, SirPass, + OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SettlePartition, SirDiagnostics, + SirPass, }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs index 7ec294253c5..8d6b6973002 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs @@ -44,6 +44,14 @@ struct StoreCandidate { struct GlobalIdentityFacts { accesses: HashMap, stores: Vec, + /// In a partitioned settle, where each address is loaded and the + /// immediate dominators of every unit (see [`reads_follow_store`]). + settle_loads: Option, +} + +struct SettleLoads { + sites: HashMap>, + immediate_dominators: Vec>, } /// Analyze all combinational units before selecting any whole-program address @@ -69,15 +77,27 @@ pub(in crate::optimizer) fn optimize_program_identity_stores( ); blocked_aliases.extend(program.design.initial_state.iter().map(|init| init.address)); + let settle_flags = settle_flags(program); optimize_eval_comb_identity_stores( &mut program.sir.eval_comb, &metadata, &blocked_aliases, program.layout_requirements.state_aliases(), four_state, + settle_flags, ) } +/// The flags of a partitioned settle, whose guards skip a partition only +/// when it would store what memory already holds. +fn settle_flags(program: &OptimizationContext) -> Option { + program + .runtime_schema + .settle_partitions + .as_ref() + .map(|settle| settle.flags) +} + fn address_metadata(program: &OptimizationContext) -> HashMap { program .design @@ -101,8 +121,9 @@ fn optimize_eval_comb_identity_stores( blocked_aliases: &HashSet, existing_aliases: &HashMap, four_state: bool, + settle_flags: Option, ) -> HashMap { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let aliases = select_aliases( &facts, metadata, @@ -129,20 +150,36 @@ pub(crate) fn retain_final_identity_aliases(program: &mut OptimizationContext, f let aliases = program.layout_requirements.state_aliases().clone(); let mut valid = aliases.keys().copied().collect::>(); + let settle_flags = settle_flags(program); retain_aliases_valid_for_units( &program.sir.eval_comb, &aliases, &metadata, four_state, + settle_flags, &mut valid, ); for units in program.sir.eval_comb_apply_ffs.values() { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); } // The lane-partitioned combinational kernel is one more projection of the // same comb logic, lowered and optimized independently. with_parallel_comb_units(program, |units| { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); }); program .layout_requirements @@ -190,17 +227,31 @@ pub(crate) fn remove_final_identity_alias_stores( return; } let metadata = address_metadata(program); + let settle_flags = settle_flags(program); remove_proven_alias_stores( &mut program.sir.eval_comb, validated_aliases, &metadata, four_state, + settle_flags, ); for units in program.sir.eval_comb_apply_ffs.values_mut() { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); } with_parallel_comb_units(program, |units| { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); }); } @@ -263,9 +314,10 @@ fn retain_aliases_valid_for_units( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, valid: &mut HashSet, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); valid.retain(|alias| { aliases .get(alias) @@ -316,8 +368,9 @@ fn remove_proven_alias_stores( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let mut sites = aliases .iter() .filter_map(|(&alias, &canonical)| proven_alias_store(&facts, alias, canonical).flatten()) @@ -373,7 +426,7 @@ fn analyze_eval_comb_aliases( ) -> HashMap { // Phase 1: collect every read/write and every syntactic store candidate. // No alias decision is made while the scan is incomplete. - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, None); // Phase 2: require the completed global facts for both identity and // duplicate-store proofs. @@ -390,9 +443,14 @@ fn collect_global_facts( units: &[ExecutionUnit], metadata: &HashMap, four_state: bool, + settle_flags: Option, ) -> GlobalIdentityFacts { let mut accesses = HashMap::::default(); let mut stores = Vec::new(); + let mut settle_loads = settle_flags.map(|_| SettleLoads { + sites: HashMap::default(), + immediate_dominators: units.iter().map(immediate_dominators).collect(), + }); for (eu_index, eu) in units.iter().enumerate() { let mut defs = HashMap::default(); @@ -408,7 +466,7 @@ fn collect_global_facts( // each candidate applies a sparse decrement map rather than cloning // this whole table. let use_counts = register_use_counts(eu); - let must_execute = must_execute_blocks(eu); + let must_execute = must_execute_blocks(eu, settle_flags); for block in eu.blocks.values() { for (instruction_index, inst) in block.instructions.iter().enumerate() { @@ -417,6 +475,13 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(address.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + loads + .sites + .entry(address.absolute_addr()) + .or_default() + .push((eu_index, block.id, instruction_index)); + } } SIRInstruction::Store( address, @@ -477,6 +542,14 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(source.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + // A commit reads its source outside any proof here. + loads + .sites + .entry(source.absolute_addr()) + .or_default() + .push((usize::MAX, block.id, instruction_index)); + } increment_saturating( &mut accesses .entry(destination.absolute_addr()) @@ -498,7 +571,108 @@ fn collect_global_facts( store.address, ) }); - GlobalIdentityFacts { accesses, stores } + GlobalIdentityFacts { + accesses, + stores, + settle_loads, + } +} + +/// Whether every read of `store`'s address comes after the store: later in +/// its block, in a block it dominates, or in a later unit, which the +/// topological order runs after it. Then an alias reads what the store +/// would have written. +/// +/// Only a partitioned settle relaxes the unread rule this way: there a +/// reader in a later partition loads a copy's target from memory, where the +/// single pass forwards the stored register. +fn reads_follow_store(facts: &GlobalIdentityFacts, store: &StoreCandidate) -> bool { + let Some(loads) = &facts.settle_loads else { + return false; + }; + let address = store.address.absolute_addr(); + let Some(sites) = loads.sites.get(&address) else { + return true; + }; + sites.iter().all(|&(eu_index, block, instruction_index)| { + if eu_index == usize::MAX { + return false; + } + if eu_index != store.eu_index { + return eu_index > store.eu_index; + } + if block == store.block { + return instruction_index > store.instruction_index; + } + let dominators = &loads.immediate_dominators[eu_index]; + let mut current = block; + while let Some(&parent) = dominators.get(¤t) { + if parent == store.block { + return true; + } + if parent == current { + return false; + } + current = parent; + } + false + }) +} + +/// The immediate dominator of every block of `eu` reachable from its entry; +/// the entry is its own. +fn immediate_dominators(eu: &ExecutionUnit) -> HashMap { + let blocks = reverse_postorder_with(eu, &terminator_successors); + let indices = blocks + .iter() + .copied() + .enumerate() + .map(|(index, block)| (block, index)) + .collect::>(); + let mut predecessors = vec![Vec::new(); blocks.len()]; + for (index, block_id) in blocks.iter().enumerate() { + if let Some(block) = eu.blocks.get(block_id) { + for successor in terminator_successors(&block.terminator) { + if let Some(&successor_index) = indices.get(&successor) { + predecessors[successor_index].push(index); + } + } + } + } + let mut immediate_dominator = vec![None; blocks.len()]; + if blocks.is_empty() { + return HashMap::default(); + } + immediate_dominator[0] = Some(0); + let mut changed = true; + while changed { + changed = false; + for block in 1..blocks.len() { + let mut defined = predecessors[block] + .iter() + .copied() + .filter(|&predecessor| immediate_dominator[predecessor].is_some()); + let Some(mut new_dominator) = defined.next() else { + continue; + }; + for predecessor in defined { + if let Some(intersection) = + intersect_dominators(predecessor, new_dominator, &immediate_dominator) + { + new_dominator = intersection; + } + } + if immediate_dominator[block] != Some(new_dominator) { + immediate_dominator[block] = Some(new_dominator); + changed = true; + } + } + } + immediate_dominator + .into_iter() + .enumerate() + .filter_map(|(index, dominator)| Some((blocks[index], blocks[dominator?]))) + .collect() } fn identity_commit_is_profitable( @@ -645,7 +819,12 @@ fn select_aliases( || !store.effects_are_removable || blocked_aliases.contains(&alias) || existing_aliases.contains_key(&alias) - || !is_unique_unread_alias(alias, &facts.accesses) + || !(is_unique_unread_alias(alias, &facts.accesses) + || (facts + .accesses + .get(&alias) + .is_some_and(|access| access.writes == 1) + && reads_follow_store(facts, store))) || facts .accesses .get(&canonical) @@ -910,8 +1089,35 @@ fn ff_referenced_addresses(program: &OptimizationContext) -> HashSet) -> HashSet { - let blocks = reverse_postorder(eu); +/// +/// A partitioned settle skips a partition only when its stores would write +/// what memory already holds, so for an identity copy the partition counts +/// as executed: its guard (a branch into a block that stores to +/// `settle_flags`) is treated as always taken. +fn must_execute_blocks( + eu: &ExecutionUnit, + settle_flags: Option, +) -> HashSet { + let successors = |terminator: &SIRTerminator| { + if let ( + Some(flags), + SIRTerminator::Branch { + true_block: (body, _), + .. + }, + ) = (settle_flags, terminator) + && eu.blocks.get(body).is_some_and(|block| { + block.instructions.iter().any(|instruction| { + matches!(instruction, SIRInstruction::Store(address, ..) + if address.region == STABLE_REGION && address.absolute_addr() == flags) + }) + }) + { + return vec![*body]; + } + terminator_successors(terminator) + }; + let blocks = reverse_postorder_with(eu, &successors); if blocks.is_empty() { return HashSet::default(); } @@ -927,7 +1133,7 @@ fn must_execute_blocks(eu: &ExecutionUnit) -> HashSet) -> Vec { +fn reverse_postorder_with( + eu: &ExecutionUnit, + successors_of: &dyn Fn(&SIRTerminator) -> Vec, +) -> Vec { if !eu.blocks.contains_key(&eu.entry_block_id) { return Vec::new(); } @@ -1029,7 +1238,7 @@ fn reverse_postorder(eu: &ExecutionUnit) -> Vec { return Vec::new(); }; stack.push((block_id, true)); - let mut successors = terminator_successors(&block.terminator); + let mut successors = successors_of(&block.terminator); successors.reverse(); stack.extend(successors.into_iter().map(|successor| (successor, false))); } @@ -1429,6 +1638,7 @@ mod tests { &HashSet::default(), existing_aliases, four_state, + None, ) } @@ -2349,7 +2559,7 @@ mod tests { .collect(); let metadata = metadata(&[(source, 8), (destination, 8)]); - remove_proven_alias_stores(&mut units, &aliases, &metadata, false); + remove_proven_alias_stores(&mut units, &aliases, &metadata, false, None); assert_eq!( units[0].blocks[&BlockId(0)].instructions, @@ -2374,7 +2584,7 @@ mod tests { &[(0, 8)], )]; let metadata = metadata(&[(source, 8), (destination, 8)]); - let facts = collect_global_facts(&units, &metadata, false); + let facts = collect_global_facts(&units, &metadata, false, None); assert!( proven_alias_store(&facts, destination.absolute_addr(), source.absolute_addr()) diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs index 90c1664ed84..caa5fca0305 100644 --- a/crates/celox-sir-opt/src/policy.rs +++ b/crates/celox-sir-opt/src/policy.rs @@ -30,7 +30,8 @@ impl OptLevel { pub fn default_enabled(self, pass: SirPass) -> bool { match self { OptLevel::O0 => matches!(pass, SirPass::TailCallSplit), - OptLevel::O1 | OptLevel::O2 => true, + // Opt-in until it pays off on its own (#2013). + OptLevel::O1 | OptLevel::O2 => !matches!(pass, SirPass::PartitionedSettle), } } @@ -122,6 +123,10 @@ define_sir_passes! { /// clock's domain once more, so disabling it trades tick speed for build /// time. DerivedEdgeUnits => "derived_edge_units", + /// Split the combinational settle of designs with many event domains + /// into partitions that run only when state they read changed. Not a + /// SIR transform: the frontend consumes it. Off unless enabled. + PartitionedSettle => "partitioned_settle", } /// Diagnostics and additional verification for the SIR optimizer. /// @@ -167,9 +172,21 @@ pub struct OptimizeOptions { max_native_memory_width: usize, parallel_lanes: u32, parallel_partition: ParallelPartition, + settle_partition: SettlePartition, pub diagnostics: SirDiagnostics, } +/// How the compiler decides whether to partition the combinational settle +/// ([`SirPass::PartitionedSettle`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SettlePartition { + /// Partition designs with many event domains and a large program. + #[default] + Estimated, + /// Partition every program as finely as possible. For tests. + Always, +} + /// How the compiler decides whether a phase gets a lane-partitioned kernel. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ParallelPartition { @@ -202,6 +219,7 @@ impl OptimizeOptions { }, parallel_lanes: 1, parallel_partition: ParallelPartition::Estimated, + settle_partition: SettlePartition::Estimated, diagnostics: SirDiagnostics::default(), } } @@ -273,6 +291,15 @@ impl OptimizeOptions { self.parallel_partition } + pub fn with_settle_partition(mut self, partition: SettlePartition) -> Self { + self.settle_partition = partition; + self + } + + pub fn settle_partition(&self) -> SettlePartition { + self.settle_partition + } + /// Query whether a specific pass is active. pub fn is_enabled(&self, pass: SirPass) -> bool { if self.enabled.contains(&pass) { @@ -285,10 +312,13 @@ impl OptimizeOptions { } /// Returns true if any SIR transform is enabled: any pass other than - /// the TailCallSplit and DerivedEdgeUnits selectors. + /// the TailCallSplit, DerivedEdgeUnits and PartitionedSettle selectors. pub fn any_enabled(&self) -> bool { SirPass::ALL.iter().any(|&p| { - !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p) + !matches!( + p, + SirPass::TailCallSplit | SirPass::DerivedEdgeUnits | SirPass::PartitionedSettle + ) && self.is_enabled(p) }) } diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index c0aa948bae2..4f2f1390dd8 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -2420,6 +2420,37 @@ pub struct ScheduleResult { /// comb/FF schedule. These Stores are semantic state updates rather than /// disposable comb publications. pub direct_ff_writes: Vec>, + /// The partitions of a partitioned settle, in schedule order; empty when + /// the schedule runs as one pass. + pub partitions: Vec>, +} + +/// Request to split a combinational schedule into partitions that run only +/// when state they read changed since they last ran. +/// +/// Byte `p` of `flags`, a two-state object, is partition `p`'s dirty flag: +/// the settle runs the partition only when it is not zero, and clears it. +/// A partition that runs sets the flags of the partitions reading what it +/// writes; every other writer of state a partition reads must set its flag +/// too ([`SettlePartition::reads`]). +#[derive(Clone, Copy, Debug)] +pub struct SettlePartitioning { + pub flags: Addr, + /// Approximate expression nodes per partition. + pub target_cost: usize, +} + +/// One partition of a partitioned settle. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartition { + /// The state objects the partition reads. A change to any of them must + /// set the partition's flag before the next settle. + pub reads: Vec, + /// The state objects the partition writes. + pub writes: Vec, + /// Whether the partition runs on every settle, because it has effects + /// beyond its stores. + pub pinned: bool, } pub trait ClockFfLowering { @@ -3464,6 +3495,333 @@ const UNROLL_THRESHOLD: usize = 32; /// compatibility matrix for a long run of independent roots. const MAX_JOINT_FOLD_ROOTS: usize = 16; +/// One partition of a settle plan. +struct PlannedPartition { + reads: Vec, + writes: Vec, + /// The partitions whose flags it sets when it runs: those reading what + /// it writes, itself included when it reads the previous value of its + /// own writes. + marks: Vec, + pinned: bool, +} + +/// The partitions of a settle, each a contiguous run of scheduled work. +struct PartitionPlan { + /// The first scheduled work of each partition. + first_work: Vec, + partitions: Vec>, +} + +/// The paths of one piece of scheduled combinational work. +fn work_paths(work: &ScheduledWork) -> &[usize] { + match work { + ScheduledWork::CombPath(path) => std::slice::from_ref(path), + ScheduledWork::CombScc(paths) | ScheduledWork::GuardedComb { paths, .. } => paths, + ScheduledWork::Ff(_) => &[], + } +} + +/// The approximate lowering cost of a path: its distinct expression nodes, +/// or a process unit's instructions. +pub fn path_cost( + arena: &SLTNodeArena, + path: &LogicPath, +) -> usize { + if let LogicPathTarget::Process { unit, .. } = &path.target { + return unit + .blocks + .values() + .map(|block| block.instructions.len() + 1) + .sum(); + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + let mut cost = 0; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + cost += 1; + match arena.get(node) { + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) + | SLTNode::Slice { expr: operand, .. } + | SLTNode::Capture { expr: operand, .. } => stack.push(*operand), + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + // A loop's cost scales with its trip count; count it as large. + SLTNode::ForFold { .. } | SLTNode::ForFoldGroup { .. } => cost += 64, + SLTNode::Input { .. } | SLTNode::Constant(..) => {} + } + } + cost +} + +/// Whether a path's expression captures a value at an evaluation position. +fn path_has_capture( + arena: &SLTNodeArena, + path: &LogicPath, +) -> bool { + if matches!(path.target, LogicPathTarget::CombCaptureEvent { .. }) { + return true; + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + match arena.get(node) { + SLTNode::Capture { .. } => return true, + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) | SLTNode::Slice { expr: operand, .. } => { + stack.push(*operand) + } + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + _ => {} + } + } + false +} + +/// Whether a path does more than store its value: comb capture events, +/// activation of capture sites, and process units with runtime events or +/// extern calls. A partition holding one runs on every settle. +fn path_has_effects(path: &LogicPath) -> bool { + if !path.comb_capture_enable_sites.is_empty() || path.comb_capture_enable_always { + return true; + } + match &path.target { + LogicPathTarget::CombCaptureEvent { .. } => true, + LogicPathTarget::Process { unit, .. } => unit.blocks.values().any(|block| { + block + .instructions + .iter() + .any(|instruction| match instruction { + SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + | SIRInstruction::ExternCall { .. } => true, + SIRInstruction::Store(.., capture_sites) => !capture_sites.is_empty(), + _ => false, + }) + }), + LogicPathTarget::Var(_) => false, + } +} + +/// Cut a combinational schedule into partitions of about +/// `partitioning.target_cost`, or `None` when it would be one. +fn plan_settle_partitions( + prepared: &PreparedSchedule, + arena: &SLTNodeArena, + var_widths: &HashMap, + partitioning: SettlePartitioning, +) -> Option<(PartitionPlan, Addr)> { + let input = &prepared.input; + // A captured value or a pre-lowered node is materialized at one place + // and reused at a later one through the lowering cache, which a + // partition boundary between them would clear. + if input + .iter() + .any(|path| !path.pre_lower_nodes.is_empty() || path_has_capture(arena, path)) + { + return None; + } + // Whole-variable copies, by target. + let mut copy_source: HashMap = HashMap::default(); + for work in &prepared.scheduled_work { + if let ScheduledWork::CombPath(path) = work + && let Some((target, source)) = whole_variable_copy(arena, &input[*path], var_widths) + { + copy_source.insert(target, source); + } + } + let mut first_work = Vec::new(); + let mut cost = 0; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if first_work.is_empty() || cost >= partitioning.target_cost { + first_work.push(index); + cost = 0; + } + cost += work_paths(work) + .iter() + .map(|&path| path_cost(arena, &input[path])) + .sum::(); + } + if first_work.len() < 2 { + return None; + } + let mut partition_of_work = vec![0; prepared.scheduled_work.len()]; + for (partition, &first) in first_work.iter().enumerate() { + let end = first_work + .get(partition + 1) + .copied() + .unwrap_or(prepared.scheduled_work.len()); + partition_of_work[first..end].fill(partition); + } + let count = first_work.len(); + let mut reads = vec![BTreeSet::new(); count]; + let mut writes = vec![BTreeSet::new(); count]; + let mut previous = vec![BTreeSet::new(); count]; + let mut pinned = vec![false; count]; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + let partition = partition_of_work[index]; + for &path_index in work_paths(work) { + let path = &input[path_index]; + pinned[partition] |= path_has_effects(path); + let atoms = path + .sources + .iter() + .chain(&path.address_sources) + .chain(&path.previous_sources); + reads[partition].extend(atoms.map(|atom| atom.id)); + // A process's activation guard reads its occurrence counters and + // startup slots as well. + if let LogicPathTarget::Process { + sensitivity_counters, + startup, + unit, + .. + } = &path.target + { + // The unit may read more than its listed sources, such as + // force controls. It runs at its process's first projection + // and writes every output there. + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, address, ..) => { + reads[partition].insert(*address); + } + SIRInstruction::Store(address, ..) => { + writes[partition].insert(*address); + } + SIRInstruction::Commit(source, target, ..) => { + reads[partition].insert(*source); + writes[partition].insert(*target); + } + _ => {} + } + } + } + for (atom, counter) in sensitivity_counters { + reads[partition].extend([atom.id, *counter]); + } + if let Some(startup) = startup { + reads[partition].insert(startup.initialized); + for (atom, slot) in &startup.inputs { + reads[partition].extend([atom.id, *slot]); + } + for (counter, slot) in &startup.counters { + reads[partition].extend([*counter, *slot]); + } + } + } + previous[partition].extend(path.previous_sources.iter().map(|atom| atom.id)); + if let Some(target) = path.target.var() { + writes[partition].insert(target.id); + } + } + } + // Reading a copy's target reads its source: the copy may become an + // alias of its source, whose changes then reach the target without the + // copy running. + for read in &mut reads { + let mut sources = Vec::new(); + for &addr in read.iter() { + let mut current = addr; + let mut steps = 0; + while let Some(&source) = copy_source.get(¤t) { + sources.push(source); + current = source; + steps += 1; + if steps > copy_source.len() { + break; + } + } + } + read.extend(sources); + } + let mut readers: HashMap> = HashMap::default(); + for (partition, read) in reads.iter().enumerate() { + for &addr in read { + readers.entry(addr).or_default().push(partition); + } + } + let partitions = (0..count) + .map(|partition| { + let mut marks = BTreeSet::new(); + for addr in &writes[partition] { + for &reader in readers.get(addr).into_iter().flatten() { + if reader != partition || previous[partition].contains(addr) { + marks.insert(reader); + } + } + } + PlannedPartition { + reads: reads[partition].iter().copied().collect(), + writes: writes[partition].iter().copied().collect(), + marks: marks.into_iter().collect(), + pinned: pinned[partition], + } + }) + .collect(); + Some(( + PartitionPlan { + first_work, + partitions, + }, + partitioning.flags, + )) +} + +/// The `(target, source)` of a path that copies one whole variable into +/// another of the same width. +fn whole_variable_copy( + arena: &SLTNodeArena, + path: &LogicPath, + var_widths: &HashMap, +) -> Option<(Addr, Addr)> { + if !path.transparent_copy || !path.previous_sources.is_empty() { + return None; + } + let target = match &path.target { + LogicPathTarget::Var(target) => target, + _ => return None, + }; + let width = *var_widths.get(&target.id)?; + if target.access.lsb != 0 || target.access.msb + 1 != width { + return None; + } + match arena.get(path.expr) { + SLTNode::Input { + variable, + index, + access, + .. + } if index.is_empty() + && access.lsb == 0 + && access.msb + 1 == width + && var_widths.get(variable) == Some(&width) + && *variable != target.id => + { + Some((target.id, *variable)) + } + _ => None, + } +} + /// Lowering state for one sequence of scheduled work emitted through one SIR /// builder. Register numbers and the expression cache are local to it. struct WorkLowering<'a, Addr: Clone + Eq + Hash> { @@ -3478,6 +3836,11 @@ struct WorkLowering<'a, Addr: Clone + Eq + Hash> { /// The processes whose unit an acyclic projection has run (see /// [`Self::lower`]). run_processes: HashSet, + /// Inside a partition of a partitioned settle, which units must not + /// split. + in_partition: bool, + /// Where a guarded partition continues when it is skipped. + partition_merge: Option, } impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a, Addr> { @@ -3492,9 +3855,102 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a pending_fold_indices: Vec::new(), pending_fold_roots: HashSet::default(), run_processes: HashSet::default(), + in_partition: false, + partition_merge: None, } } + /// Open partition `index`: run it only when its flag or the untracked + /// byte (`untracked`) is set, and clear its flag. Values computed before + /// it may be reused inside, but not the other way round, so the + /// expression cache starts over. + fn begin_partition( + &mut self, + flags: Addr, + index: usize, + untracked: usize, + partition: &PlannedPartition, + ) { + self.flush_pending_folds(); + if self.context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if let Some(eu) = self.builder.flush_eu() { + self.execution_units.push(eu); + } + } + self.lower_cache.clear(); + self.in_partition = true; + let offset = SIROffset::Static(index * 8); + if !partition.pinned { + let own = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Load(own, flags, offset.clone(), 8)); + let all = self.builder.alloc_bit(8, false); + self.builder.emit(SIRInstruction::Load( + all, + flags, + SIROffset::Static(untracked * 8), + 8, + )); + let flag = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Binary(flag, own, BinaryOp::Or, all)); + let zero = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let dirty = self.builder.alloc_bit(1, false); + self.builder + .emit(SIRInstruction::Binary(dirty, flag, BinaryOp::Ne, zero)); + let body = self.builder.new_block(); + let merge = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: dirty, + true_block: (body, Vec::new()), + false_block: (merge, Vec::new()), + }); + self.builder.switch_to_block(body); + self.partition_merge = Some(merge); + } + let clean = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(clean, SIRValue::new(0u64))); + self.builder.emit(SIRInstruction::Store( + flags, + offset, + 8, + clean, + Vec::new(), + Vec::new(), + )); + } + + /// Close a partition: set the flags of the partitions reading what it + /// wrote, then join the path that skipped it. + fn end_partition(&mut self, flags: Addr, partition: &PlannedPartition) { + self.flush_pending_folds(); + if !partition.marks.is_empty() { + let one = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + for &reader in &partition.marks { + self.builder.emit(SIRInstruction::Store( + flags, + SIROffset::Static(reader * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + if let Some(merge) = self.partition_merge.take() { + self.builder + .seal_block(SIRTerminator::Jump(merge, Vec::new())); + self.builder.switch_to_block(merge); + } + self.lower_cache.clear(); + self.in_partition = false; + } + /// Lower the buffered run of exact grouped-fold paths. fn flush_pending_folds(&mut self) { let context = self.context; @@ -3854,7 +4310,10 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a } } else { // DAG Part — flush before emitting if the EU has grown too large - if context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if context.split_large_units + && !self.in_partition + && self.builder.block_count() >= EU_BLOCK_LIMIT + { self.flush_pending_folds(); if let Some(eu) = self.builder.flush_eu() { self.execution_units.push(eu); @@ -3932,6 +4391,7 @@ fn sort_impl( unpacked_element_widths: &HashMap, first_runtime_error_code: i64, mut ff: Option<&mut dyn ClockFfLowering>, + partitioning: Option>, ) -> Result, ClockSortError> { let prepared = prepare_schedule( input, @@ -3972,7 +4432,25 @@ fn sort_impl( } let mut runtime_errors: HashMap> = HashMap::default(); let mut next_runtime_error_code = first_runtime_error_code; - for work in &prepared.scheduled_work { + let plan = partitioning + .filter(|_| ff.is_none()) + .and_then(|partitioning| { + plan_settle_partitions(&prepared, arena, var_widths, partitioning) + }); + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if let Some((plan, flags)) = &plan { + if let Some(partition) = plan.first_work.iter().position(|&first| first == index) { + if partition > 0 { + lowering.end_partition(*flags, &plan.partitions[partition - 1]); + } + lowering.begin_partition( + *flags, + partition, + plan.partitions.len(), + &plan.partitions[partition], + ); + } + } lowering.lower( work, ff.as_deref_mut(), @@ -3980,6 +4458,11 @@ fn sort_impl( &mut next_runtime_error_code, )?; } + if let Some((plan, flags)) = &plan + && let Some(last) = plan.partitions.last() + { + lowering.end_partition(*flags, last); + } // Flush the final exact grouped-fold run after the SCC loop. lowering.flush_pending_folds(); if let Some(ff_lowering) = ff { @@ -3991,6 +4474,18 @@ fn sort_impl( execution_units: lowering.finish(), runtime_errors, direct_ff_writes, + partitions: plan + .map(|(plan, _)| { + plan.partitions + .into_iter() + .map(|partition| SettlePartition { + reads: partition.reads, + writes: partition.writes, + pinned: partition.pinned, + }) + .collect() + }) + .unwrap_or_default(), }) } @@ -4013,6 +4508,7 @@ pub fn sort( var_widths, &HashMap::default(), first_runtime_error_code, + None, ) } @@ -4025,6 +4521,7 @@ pub fn sort_with_unpacked_element_widths, unpacked_element_widths: &HashMap, first_runtime_error_code: i64, + partitioning: Option>, ) -> Result, SchedulerError> { match sort_impl::( input, @@ -4036,6 +4533,7 @@ pub fn sort_with_unpacked_element_widths Ok(result), Err(ClockSortError::Scheduler(error)) => Err(error), @@ -4066,6 +4564,7 @@ pub fn sort_clock( unpacked_element_widths, first_runtime_error_code, Some(ff), + None, ) } @@ -4085,7 +4584,7 @@ mod tests { LogicPath, LogicPathTarget, SLTForFoldGroupState, SLTNode, SLTNodeArena, SLTToSIRLowerer, }; use celox_design::{BinaryOp, BitAccess, VarAtomBase}; - use celox_sir::{SIRBuilder, SIRInstruction, SIRTerminator}; + use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator}; #[test] fn deep_input_dependencies_use_heap_and_preserve_inverse_index() { @@ -4629,6 +5128,105 @@ mod tests { assert_eq!(adj, vec![vec![1], vec![2], Vec::new()]); } + fn partitioned_sort( + paths: Vec>, + arena: &SLTNodeArena, + ) -> super::ScheduleResult { + let widths = (10..14).map(|id| (id, 8)).collect(); + super::sort_with_unpacked_element_widths( + paths, + arena, + &crate::HashSet::default(), + &crate::HashMap::default(), + false, + &widths, + &crate::HashMap::default(), + 1, + Some(super::SettlePartitioning { + flags: 99, + target_cost: 1, + }), + ) + .unwrap() + } + + #[test] + fn settle_partitions_follow_schedule_and_guard_on_their_flags() { + let mut arena = SLTNodeArena::new(); + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + simple_path(&mut arena, 12, Some(11)), + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![12], vec![13]), + ] + ); + assert!(result.partitions.iter().all(|partition| !partition.pinned)); + // Each partition loads its own flag and the untracked-writes flag + // after them; a partition sets its reader's. + let mut loaded = Vec::new(); + let mut stored = Vec::new(); + for unit in &result.execution_units { + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, 99, SIROffset::Static(byte), 8) => { + loaded.push(*byte) + } + SIRInstruction::Store(99, SIROffset::Static(byte), 8, ..) => { + stored.push(*byte) + } + _ => {} + } + } + } + } + loaded.sort_unstable(); + stored.sort_unstable(); + assert_eq!(loaded, vec![0, 8, 16, 24, 24, 24]); + // The clears of all three flags, and the marks of partitions 1 and 2. + assert_eq!(stored, vec![0, 8, 8, 16, 16]); + } + + #[test] + fn settle_copy_readers_read_the_copied_source() { + let mut arena = SLTNodeArena::new(); + let mut copy = simple_path(&mut arena, 12, Some(11)); + copy.transparent_copy = true; + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + copy, + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + // The copy is guarded like other work, and its reader reads the + // copied source too. + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![11, 12], vec![13]), + ] + ); + } + #[test] fn memory_ssa_scheduler_lowers_independent_single_use_chains_contiguously() { let mut arena = SLTNodeArena::new(); diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index ff2fbef6463..f296da09d27 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -11,7 +11,9 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use serde::{Deserialize, Serialize}; use std::hash::Hash; +mod settle; mod trace; +pub use settle::{SettleLayout, SettleObject}; pub use trace::{TRACE_GROUP_BYTES, TraceLayout}; pub const RUNTIME_EVENT_CAPACITY: usize = 1024; @@ -191,6 +193,9 @@ pub trait LayoutSource { pub struct MemoryLayout { /// Present only in builds that record waveforms. pub trace: Option, + /// Present when the combinational settle is partitioned. + #[serde(default)] + pub settle: Option, pub four_state: bool, pub mode: MemoryLayoutMode, /// Stable region offsets. Includes all declared state objects. @@ -338,6 +343,15 @@ fn place_region( align_up(current + LANE_SEGMENT_GUARD, LANE_SEGMENT_ALIGN) } +impl MemoryLayout { + /// Whether each settle runs a second time to cross-check its partitions + /// ([`SettleLayout::check`]). + #[inline] + pub fn settle_check(&self) -> bool { + self.settle.as_ref().is_some_and(|settle| settle.check) + } +} + impl MemoryLayout where A: Copy + Eq + Hash + Ord, @@ -553,6 +567,7 @@ where Self { trace: None, + settle: None, four_state, mode, offsets, diff --git a/crates/celox-state-layout/src/settle.rs b/crates/celox-state-layout/src/settle.rs new file mode 100644 index 00000000000..652d5009930 --- /dev/null +++ b/crates/celox-state-layout/src/settle.rs @@ -0,0 +1,74 @@ +//! Dirty flags of a partitioned combinational settle. +//! +//! Generated code sets the flags of the partitions reading the state it +//! writes; host writes go through [`SettleLayout::mark_range`]. Writes no +//! one reports, through a retained raw view of the state, set the untracked +//! byte, after which every partition runs on every settle. +use serde::{Deserialize, Serialize}; + +/// State written outside generated code and the partitions reading it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleObject { + /// Byte range of the object, both planes. + pub start: usize, + pub end: usize, + pub partitions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleLayout { + /// One byte per partition, then the untracked byte. + pub flags_offset: usize, + pub partitions: usize, + /// Sorted by `start`, disjoint. + pub objects: Vec, + /// Debug cross-check: the backends run each settle again with every + /// partition flagged and panic where the results differ. + #[serde(default)] + pub check: bool, +} + +impl SettleLayout { + pub fn new(flags_offset: usize, partitions: usize, mut objects: Vec) -> Self { + objects.sort_unstable_by_key(|object| object.start); + Self { + flags_offset, + partitions, + objects, + check: false, + } + } + + /// Set the flags of the partitions reading state in `offset..offset + len`. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_range(&self, memory: *mut u8, offset: usize, len: usize) { + let end = offset + len.max(1); + let first = self.objects.partition_point(|object| object.end <= offset); + for object in self.objects[first..] + .iter() + .take_while(|object| object.start < end) + { + for &partition in &object.partitions { + // SAFETY: flags lie inside the image (caller contract). + unsafe { *memory.add(self.flags_offset + partition as usize) = 1 }; + } + } + } + + /// The bytes of the flags, the untracked byte included. + pub fn flags(&self) -> std::ops::Range { + self.flags_offset..self.flags_offset + self.partitions + 1 + } + + /// Run every partition on every settle from now on: a raw view of the + /// state can change it without reporting. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_untracked(&self, memory: *mut u8) { + // SAFETY: the untracked byte follows the flags (caller contract). + unsafe { *memory.add(self.flags_offset + self.partitions) = 1 }; + } +} diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 6a7c6a613bd..2a17b1cf19a 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1983,10 +1983,12 @@ impl SimBackend for InterpBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr() as *mut u8, self.layout.merged_total_size, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -1995,6 +1997,10 @@ impl SimBackend for InterpBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/memory_image.rs b/crates/celox/src/backend/memory_image.rs index d24445e881b..aa1abc8e54a 100644 --- a/crates/celox/src/backend/memory_image.rs +++ b/crates/celox/src/backend/memory_image.rs @@ -134,6 +134,12 @@ impl MemoryImage { unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.logical_words) } } + pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8] { + let words = self.as_mut_slice(); + // SAFETY: the words are initialized, and bytes have no alignment. + unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast(), words.len() * 8) } + } + pub(crate) fn len_words(&self) -> usize { self.logical_words } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 020fc779b31..f1bca202fb7 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -536,6 +536,7 @@ impl NativeProgramImage { time_slots: self.runtime_schema.time_slots.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), + settle_partitions: None, }, testbench: self.testbench.clone(), } @@ -2589,6 +2590,9 @@ pub struct NativeBackend { /// Boxed so the address in the state header survives moves. heap: Box, execution_timing: Option, + /// Whether generated calls go through [`Self::call_func_slow`]: timing + /// is on, or settles are cross-checked. + slow_calls: bool, /// Worker threads for lane-partitioned kernels, started on first use. lane_pool: Option, /// Per-kernel choice between partitioned and sequential code. @@ -2807,6 +2811,7 @@ impl NativeBackend { } } + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2814,6 +2819,7 @@ impl NativeBackend { comb_capture_enabled, heap: Default::default(), execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2836,6 +2842,7 @@ impl NativeBackend { comb_capture_enabled: Vec, heap: Box, ) -> Self { + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2843,6 +2850,7 @@ impl NativeBackend { comb_capture_enabled, heap, execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2948,6 +2956,7 @@ impl NativeBackend { /// Start a fresh opt-in measurement of generated native function calls. pub fn start_execution_timing(&mut self) { self.execution_timing = Some(NativeExecutionTiming::default()); + self.slow_calls = true; } /// Total capacity of the live image in `u64` words. @@ -2967,10 +2976,12 @@ impl NativeBackend { self.memory.resize_zeroed_within_capacity(mem_size_words); } self.compiled = shared; + self.slow_calls = self.execution_timing.is_some() || self.compiled.layout.settle_check(); } /// Stop timing and return the accumulated generated-code interval. pub fn finish_execution_timing(&mut self) -> Option { + self.slow_calls = self.compiled.layout.settle_check(); self.execution_timing.take() } @@ -3145,6 +3156,29 @@ impl NativeBackend { } fn call_func_timed(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if !self.slow_calls { + return Self::call_func(self.memory.as_mut_slice(), func); + } + self.call_func_slow(func) + } + + #[cold] + fn call_func_slow(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if func as usize == self.compiled.comb_func as usize && self.compiled.layout.settle_check() + { + let compiled = Arc::clone(&self.compiled); + return crate::settle::run_checked( + self, + compiled.layout.settle.as_ref().expect("checked settle"), + compiled.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.call_func_measured(func), + ); + } + self.call_func_measured(func) + } + + fn call_func_measured(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { let Some(_) = self.execution_timing else { return Self::call_func(self.memory.as_mut_slice(), func); }; @@ -3514,10 +3548,12 @@ impl super::super::SimBackend for NativeBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr().cast(), self.memory.len_words() * 8, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -3526,6 +3562,10 @@ impl super::super::SimBackend for NativeBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 984c26ba14a..ae25f64d4a2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 38; +const CONTAINER_VERSION: u16 = 39; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index 49e879915c7..ebc6e902a1c 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -912,7 +912,18 @@ impl JitBackend { |backend| backend.run_sim_func(comb_func), ); } - self.run_sim_func(self.comb_func) + let comb_func = self.comb_func; + if self.shared.layout.settle_check() { + let shared = Arc::clone(&self.shared); + return crate::settle::run_checked( + self, + shared.layout.settle.as_ref().expect("checked settle"), + shared.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.run_sim_func(comb_func), + ); + } + self.run_sim_func(comb_func) } /// Resolves an `AbsoluteAddr` into a performance-optimized [`SignalRef`]. @@ -1230,7 +1241,9 @@ impl JitBackend { /// Returns a mutable raw pointer to the JIT memory and its total size in bytes. pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { let size = self.shared.layout.merged_total_size; - (self.memory.expose_mut_ptr() as *mut u8, size) + let view = (self.memory.expose_mut_ptr() as *mut u8, size); + celox_runtime::backend::SimBackend::mark_settle_untracked(self); + view } pub fn runtime_event_buffer_as_ptr(&self) -> (*const u8, usize) { @@ -1415,6 +1428,10 @@ impl super::SimBackend for JitBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 45cbdac4913..506bbabcaa3 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -111,6 +111,10 @@ impl super::traits::SimBackend for WasmBackend { } fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.data_mut(&mut self.store)[offset..offset + bytes.len()].copy_from_slice(bytes); + self.mark_settle_range(offset, bytes.len()); + if self.raw_view_exposed { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { !self.raw_view_exposed @@ -683,6 +687,7 @@ impl WasmBackend { pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { self.raw_view_exposed = true; + celox_runtime::backend::SimBackend::mark_settle_untracked(self); let data = self.memory.data_mut(&mut self.store); (data.as_mut_ptr(), self.layout.merged_total_size) } diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 5b45f5b093e..3ebc630ef97 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -1077,8 +1077,24 @@ mod tests { generated_dirty = stale(generated_dirty, outcome); assert_eq!(generated_dirty, walked_dirty, "step {step}"); let (left, right) = (state(&generated.backend), state(&walked.backend)); - if let Some(offset) = left.iter().zip(&right).position(|(a, b)| a != b) { - let offset = offset + celox_state_layout::STATE_HEADER_SIZE; + // The settle's partition flags hold only what is left to + // recompute. + let flags = walked + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()); + if let Some(offset) = left + .iter() + .zip(&right) + .enumerate() + .map(|(offset, pair)| (offset + celox_state_layout::STATE_HEADER_SIZE, pair)) + .find(|(offset, (a, b))| { + a != b && !flags.as_ref().is_some_and(|flags| flags.contains(offset)) + }) + .map(|(offset, _)| offset) + { let name = walked .named_signals() .into_iter() diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 718e9675d66..f226fc20aa6 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -566,6 +566,18 @@ pub struct LaidOutProgram { } impl LaidOutProgram { + /// The units, with the layout and runtime metadata they are checked + /// against, borrowed apart. + pub(crate) fn split_mut( + &mut self, + ) -> ( + &mut SirProgram, + &crate::backend::MemoryLayout, + &RuntimeProgram, + ) { + (&mut self.sir, &self.layout, &self.runtime) + } + #[cfg(feature = "host-runtime")] pub(crate) fn enable_vcd_tracking(&mut self) { self.layout.enable_trace(); @@ -575,6 +587,15 @@ impl LaidOutProgram { &self.layout } + /// Cross-check every partitioned settle (see + /// [`celox_state_layout::SettleLayout::check`]). + #[cfg(feature = "host-runtime")] + pub(crate) fn set_settle_check(&mut self, check: bool) { + if let Some(settle) = self.layout.settle.as_mut() { + settle.check = check; + } + } + pub fn runtime(&self) -> &RuntimeProgram { &self.runtime } @@ -701,7 +722,8 @@ impl OptimizedSir { }); } crate::optimizer::sir::retain_final_identity_aliases(&mut program, four_state); - let layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + let mut layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + layout.settle = crate::settle::layout(&program, &layout); // Classify before alias stores disappear: an identity alias is a // combinational copy even once it only shares its source's storage. collect_comb_writes(&mut program); @@ -747,11 +769,13 @@ impl OptimizedSir { layout_requirements, } = program; debug_assert!(layout_requirements.is_empty()); - LaidOutProgram { + let mut laid_out = LaidOutProgram { sir, runtime, layout, - } + }; + crate::settle::instrument(&mut laid_out); + laid_out } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 474221fabfc..79ebb562df4 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -37,6 +37,7 @@ pub(crate) mod portable; // Builds without the host runtime run every slot in the reference loop. #[cfg(feature = "host-runtime")] mod scheduler; +mod settle; #[cfg(feature = "host-runtime")] mod simulation; mod simulator; @@ -90,6 +91,7 @@ pub use num_bigint::BigUint; pub use optimizer::OptLevel; pub use optimizer::OptimizeOptions; pub use optimizer::ParallelPartition; +pub use optimizer::SettlePartition; pub use optimizer::SirDiagnostics; pub use optimizer::SirPass; pub use simulator::render_diagnostic; diff --git a/crates/celox/src/optimizer.rs b/crates/celox/src/optimizer.rs index ed23d101223..97b35bfc831 100644 --- a/crates/celox/src/optimizer.rs +++ b/crates/celox/src/optimizer.rs @@ -1,4 +1,6 @@ -pub use celox_sir_opt::{OptLevel, OptimizeOptions, ParallelPartition, SirDiagnostics, SirPass}; +pub use celox_sir_opt::{ + OptLevel, OptimizeOptions, ParallelPartition, SettlePartition, SirDiagnostics, SirPass, +}; pub mod sir; @@ -98,5 +100,12 @@ pub(crate) fn parallel_schedule_options( parallel.synchronization_cost = 0; parallel.minimum_speedup_percent = 0; } + parallel.settle = if !options.is_enabled(SirPass::PartitionedSettle) { + celox_frontend_core::SettlePartitionMode::Off + } else if options.settle_partition() == SettlePartition::Always { + celox_frontend_core::SettlePartitionMode::Always + } else { + celox_frontend_core::SettlePartitionMode::Estimated + }; parallel } diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 94da9e00dc9..cad4dd76b4c 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -600,6 +600,12 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); + let mut schedule_options = crate::optimizer::parallel_schedule_options(optimize_options); + if !force_signals.is_empty() { + // Native code applies explicit forces to reads the SLT has already + // folded, outside any partition's dependencies. + schedule_options.settle = celox_frontend_core::SettlePartitionMode::Off; + } let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions_and_latch_policy( sources, @@ -608,7 +614,7 @@ pub fn parse_sv( ignored_loops, true_loops, four_state, - &crate::optimizer::parallel_schedule_options(optimize_options), + &schedule_options, &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), config.allow_inferred_latches, diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs new file mode 100644 index 00000000000..24a5bf6bde5 --- /dev/null +++ b/crates/celox/src/settle.rs @@ -0,0 +1,238 @@ +//! Partitioned combinational settle (`RuntimeSchema::settle_partitions`): +//! the flag layout, and the flag stores of the units outside the settle. +//! +//! A partition of the settle runs only when its flag is set. The settle's +//! own partitions set the flags of their readers; every other writer of +//! state the settle reads or writes sets them here, at each store or commit +//! to the state, and host writes set them through +//! [`celox_state_layout::SettleLayout`]. +use crate::ir::{ + ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, RegisterType, SIRInstruction, + SIROffset, STABLE_REGION, +}; +use celox_sir::SIRValue; +use celox_state_layout::{SettleLayout, SettleObject}; + +/// The flag layout of `program`'s partitioned settle, if it has one. +pub(crate) fn layout( + program: &crate::ir::OptimizedSir, + layout: &crate::backend::MemoryLayout, +) -> Option { + let settle = program.runtime.runtime_schema.settle_partitions.as_ref()?; + let planes = |address| { + if layout.four_state && layout.is_4states.get(address).copied().unwrap_or(false) { + 2 + } else { + 1 + } + }; + let mut objects: Vec = Vec::new(); + for (address, partitions) in &settle.marks { + let Some(&start) = layout.offsets.get(address) else { + continue; + }; + let end = start + layout.plane_size(address) * planes(address); + objects.push(SettleObject { + start, + end, + partitions: partitions.clone(), + }); + } + // Aliases share storage: one entry per home, with every reader. + objects.sort_unstable_by_key(|object| (object.start, object.end)); + let mut merged: Vec = Vec::new(); + for object in objects { + match merged.last_mut() { + Some(last) if last.start == object.start => { + last.end = last.end.max(object.end); + last.partitions.extend(object.partitions); + last.partitions.sort_unstable(); + last.partitions.dedup(); + } + _ => merged.push(object), + } + } + Some(SettleLayout::new( + layout.offsets[&settle.flags], + settle.partitions as usize, + merged, + )) +} + +/// Run a settle through `run` and cross-check it ([`SettleLayout::check`]): +/// run it again from the same state with every partition flagged, and panic +/// at the first byte of design state (below `state_end`) the two runs leave +/// differently. The state continues from the first run. +// The backends that cross-check: native and Cranelift. +#[cfg(any( + feature = "cranelift", + all( + feature = "host-runtime", + any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ) + ) +))] +#[cold] +pub(crate) fn run_checked( + backend: &mut B, + settle: &SettleLayout, + state_end: usize, + memory: impl Fn(&mut B) -> &mut [u8], + mut run: impl FnMut(&mut B) -> Result<(), E>, +) -> Result<(), E> { + let flags = settle.flags(); + let before = memory(backend).to_vec(); + run(backend)?; + let partial = memory(backend).to_vec(); + let state = memory(backend); + state.copy_from_slice(&before); + state[flags.start..flags.end - 1].fill(1); + run(backend)?; + let full = memory(backend); + if let Some(offset) = (celox_state_layout::STATE_HEADER_SIZE..state_end) + .find(|offset| full[*offset] != partial[*offset] && !flags.contains(offset)) + { + let object = settle + .objects + .iter() + .find(|object| (object.start..object.end).contains(&offset)); + let dirty: Vec = (0..settle.partitions) + .filter(|&partition| before[flags.start + partition] != 0) + .collect(); + panic!( + "partitioned settle: state byte {offset} is {} after the partitions that ran, {} \ + after all ({}; flagged at entry: {dirty:?} of {})", + partial[offset], + full[offset], + object.map_or_else( + || "not read or written by the settle".to_string(), + |object| format!( + "object {}..{} of partitions {:?}", + object.start, object.end, object.partitions + ) + ), + settle.partitions + ); + } + full.copy_from_slice(&partial); + Ok(()) +} + +/// Add the flag stores to every unit outside the settle. +pub(crate) fn instrument(program: &mut LaidOutProgram) { + instrument_processes_from(program, 0, true); +} + +/// Add the flag stores to the processes from index `first` on, and to the +/// other units outside the settle when `all`. +pub(crate) fn instrument_processes_from(program: &mut LaidOutProgram, first: usize, all: bool) { + let (sir, layout, runtime) = program.split_mut(); + let Some(marker) = Marker::new(layout, runtime) else { + return; + }; + if all { + for unit in sir + .eval_apply_ffs + .values_mut() + .chain(sir.eval_comb_apply_ffs.values_mut()) + .chain(sir.eval_only_ffs.values_mut()) + .chain(sir.apply_ffs.values_mut()) + .flatten() + { + marker.instrument(unit); + } + } + for unit in sir.processes.iter_mut().skip(first) { + marker.instrument(unit); + } +} + +struct Marker<'a> { + settle: &'a SettleLayout, + layout: &'a crate::backend::MemoryLayout, + flags: RegionedAbsoluteAddr, +} + +impl<'a> Marker<'a> { + fn new( + layout: &'a crate::backend::MemoryLayout, + runtime: &'a crate::ir::RuntimeProgram, + ) -> Option { + let settle = layout.settle.as_ref()?; + let schema = runtime.runtime_schema.settle_partitions.as_ref()?; + Some(Self { + settle, + layout, + flags: RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, schema.flags), + }) + } + + /// The partitions reading the stable state `address` names. + fn readers(&self, address: &RegionedAbsoluteAddr) -> Vec { + if address.region != STABLE_REGION { + return Vec::new(); + } + let Some(&start) = self.layout.offsets.get(&address.absolute_addr()) else { + return Vec::new(); + }; + let index = self + .settle + .objects + .partition_point(|object| object.start < start); + match self.settle.objects.get(index) { + Some(object) if object.start == start => object.partitions.clone(), + _ => Vec::new(), + } + } + + fn instrument(&self, unit: &mut ExecutionUnit) { + let mut next_register = unit + .register_map + .keys() + .map(|register| register.0 + 1) + .max() + .unwrap_or(0); + for block in unit.blocks.values_mut() { + let mut one = None; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in std::mem::take(&mut block.instructions) { + let readers = match &instruction { + SIRInstruction::Store(address, ..) => self.readers(address), + SIRInstruction::Commit(_, address, ..) => self.readers(address), + _ => Vec::new(), + }; + instructions.push(instruction); + if readers.is_empty() { + continue; + } + let one = *one.get_or_insert_with(|| { + let register = RegisterId(next_register); + next_register += 1; + unit.register_map.insert( + register, + RegisterType::Bit { + width: 8, + signed: false, + }, + ); + instructions.push(SIRInstruction::Imm(register, SIRValue::new(1u64))); + register + }); + for partition in readers { + instructions.push(SIRInstruction::Store( + self.flags, + SIROffset::Static(partition as usize * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + block.instructions = instructions; + } + } +} diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ceb3ba86f99..d736149742d 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -163,8 +163,9 @@ fn difference( "scheduling state {key:?}, the reference {reference:?}" )); } - // The compiled scheduler's slots hold nothing between runs. - let scheduler: Vec<_> = primary + // The compiled scheduler's slots hold nothing between runs, and the + // settle's partition flags only what is left to recompute. + let excluded: Vec<_> = primary .program .runtime_schema .scheduler @@ -174,9 +175,16 @@ fn difference( let signal = primary.backend.resolve_signal(address); signal.offset..signal.offset + celox_state_layout::get_byte_size(signal.width) }) + .chain( + primary + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()), + ) .collect(); - if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &scheduler) - { + if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &excluded) { let signal = primary .named_signals() .into_iter() diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 6e1d6ae5327..e07b3fd7954 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1288,6 +1288,7 @@ mod host { ); } } + self.backend.mark_settle_range(signal.offset, 1); } /// Drain runtime events, lazily evaluating dirty combinational logic. diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 75e1a4f61a5..caf6d58953f 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1686,6 +1686,9 @@ mod host { /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. pub native_force_support: bool, + /// Cross-check every partitioned settle against one that runs every + /// partition (see [`SimulatorBuilder::settle_check`]). + pub settle_check: bool, /// Explicit hierarchical observation and native force targets. pub signal_access: crate::SignalAccessOptions, /// Dead store elimination policy. @@ -1991,6 +1994,7 @@ mod host { emit_triggers: false, #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] derived_edge_units: None, + settle_check: false, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), dead_store_policy: DeadStorePolicy::Off, @@ -2221,9 +2225,11 @@ mod host { pub fn opt_level(mut self, level: crate::optimizer::OptLevel) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = crate::optimizer::OptimizeOptions::new(level) .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self.options.cranelift_options = crate::backend::CraneliftOptions::for_speed_optimization( level != crate::optimizer::OptLevel::O0, @@ -2258,13 +2264,15 @@ mod host { pub fn optimize(mut self, enable: bool) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = if enable { crate::optimizer::OptimizeOptions::all() } else { crate::optimizer::OptimizeOptions::none() } .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2284,9 +2292,15 @@ mod host { } else { self.options.optimize_options.parallel_partition() }; + let settle = if options.settle_partition() == crate::SettlePartition::Always { + crate::SettlePartition::Always + } else { + self.options.optimize_options.settle_partition() + }; self.options.optimize_options = options .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2328,6 +2342,34 @@ mod host { self } + /// Debug cross-check of a partitioned settle: the native and + /// Cranelift backends run each settle a second time from the same + /// state with every partition flagged, and panic at the first state + /// byte the two runs leave differently. Slow; for testing the + /// partitioning. Effects of the partitions that run in both passes, + /// such as runtime events, happen twice. + pub fn settle_check(mut self, enable: bool) -> Self { + self.options.settle_check = enable; + self + } + + /// Cut the combinational settle into partitions that run only when + /// state they read changed ([`crate::SirPass::PartitionedSettle`]). + /// + /// [`crate::SettlePartition::Estimated`] partitions a large settle of + /// a design with several clock events; + /// [`crate::SettlePartition::Always`] partitions every settle it can, + /// for testing. + pub fn settle_partition(mut self, partition: crate::SettlePartition) -> Self { + self.options.optimize_options = self + .options + .optimize_options + .clone() + .enable(crate::optimizer::SirPass::PartitionedSettle) + .with_settle_partition(partition); + self + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -2902,6 +2944,8 @@ mod host { } } + // Units generated from here on write state the settle may read. + let first_generated_process = laid_out.sir.processes.len(); // A timed simulation runs the slots of kernels that only delay // in a compiled scheduler, generated from the final units. #[cfg(feature = "host-runtime")] @@ -2922,6 +2966,8 @@ mod host { if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); } + crate::settle::instrument_processes_from(&mut laid_out, first_generated_process, false); + laid_out.set_settle_check(self.options.settle_check); // Link DPI-C imports before code generation, so a missing C // function fails the build early; the backends reuse the result. diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..66576f565f2 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -376,7 +376,9 @@ impl Simulator { let comb_writes = &self.program.runtime_schema.comb_writes; // A timed simulation stores its time into the time slots, and a state // file keeps the time in its schedule; an untimed one reads zero. - // A compiled scheduler's slots hold nothing between runs. + // A compiled scheduler's slots hold nothing between runs, and the + // flags of a partitioned settle describe how this build settles, + // not the design: loading state sets them. let time_slots: crate::HashSet<_> = self .program .runtime_schema @@ -390,12 +392,19 @@ impl Simulator { .flat_map(|scheduler| scheduler.slots.iter()), ) .collect(); + let settle_flags = self + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags_offset); let mut objects: Vec<_> = self .backend .layout() .offsets .keys() .filter(|address| !time_slots.contains(address)) + .filter(|address| Some(self.backend.layout().offsets[*address]) != settle_flags) .map(|&address| (self.program.get_path(&address), address)) .collect(); objects.sort_unstable(); diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index b01452f8fc2..0d5c205b104 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -116,7 +116,7 @@ pub(crate) fn eval_backend_expr( |offset, len| writes.push((offset, len)), ); if let Some(trace) = backend.layout().trace.as_ref() { - for (offset, len) in writes { + for &(offset, len) in &writes { // SAFETY: bound bytecode writes valid locations in this image, and // the simulator cannot execute concurrently with this evaluation. unsafe { @@ -124,6 +124,9 @@ pub(crate) fn eval_backend_expr( } } } + for (offset, len) in writes { + backend.mark_settle_range(offset, len); + } value } diff --git a/crates/celox/tests/settle_partitions.rs b/crates/celox/tests/settle_partitions.rs new file mode 100644 index 00000000000..3e9fa3dba0f --- /dev/null +++ b/crates/celox/tests/settle_partitions.rs @@ -0,0 +1,297 @@ +//! A partitioned settle runs a partition only when state it reads changed +//! (#2013). Forced on every settle it can cut, it must match the single-pass +//! settle on every backend, whatever wrote the state: a register update, a +//! host write, a loaded state file. +use celox::{BigUint, SettlePartition, Simulator, SirPass}; + +/// Two clock domains feeding a combinational network deep enough to cut into +/// many partitions, with a memory read through a run-time index and a +/// combinational output depending on a host input only. +const DESIGN: &str = r#" +module Top ( + clk_a: input 'a clock, + clk_b: input 'b clock, + rst: input 'a reset, + din: input 'a logic<8>, + sel: input 'a logic<2>, + bypass: input 'a logic<8>, + sum: output 'a logic<8>, + mixed: output 'a logic<8>, + picked: output 'a logic<8>, + direct: output 'a logic<8>, + slow: output 'b logic<8>, +) { + var ra: 'a logic<8>; + var mem: 'a logic<8> [4]; + var rb: 'b logic<8>; + var s1: 'a logic<8>; + var s2: 'a logic<8>; + var s3: 'a logic<8>; + var s4: 'a logic<8>; + always_ff (clk_a, rst) { + if_reset { + ra = 0; + } else { + ra = ra + din; + mem[ra[1:0]] = ra ^ din; + } + } + unsafe (cdc) { + always_ff (clk_b) { + rb = rb + s4; + } + assign s2 = s1 ^ rb; + assign slow = rb; + } + assign s1 = ra + 8'd1; + assign s3 = {s2[3:0], s1[7:4]}; + assign s4 = s3 + bypass; + assign sum = s4 + s1; + assign mixed = s3 ^ s2; + assign picked = mem[sel]; + assign direct = bypass + 8'd3; +} +"#; + +const OUTPUTS: [&str; 5] = ["sum", "mixed", "picked", "direct", "slow"]; + +fn partitioned() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top") + .settle_partition(SettlePartition::Always) + .settle_check(true) +} + +fn single_pass() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top").disable_pass(SirPass::PartitionedSettle) +} + +/// Drive both clocks and the inputs with a fixed pseudo-random sequence, +/// reading every output after each host write and each tick. +macro_rules! trace { + ($sim:expr) => {{ + let sim = &mut $sim; + let clk_a = sim.event("clk_a"); + let clk_b = sim.event("clk_b"); + let rst = sim.signal("rst"); + let din = sim.signal("din"); + let sel = sim.signal("sel"); + let bypass = sim.signal("bypass"); + let outputs = OUTPUTS.map(|name| sim.signal(name)); + let mut trace = Vec::new(); + macro_rules! read { + () => { + outputs + .iter() + .map(|&signal| sim.get(signal)) + .collect::>() + }; + } + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + sim.tick(clk_a).unwrap(); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + let mut seed = 0x2013u32; + for _ in 0..64 { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let bits = seed >> 8; + // A host write alone must reach the combinational outputs. + sim.modify(|io| { + io.set(din, bits as u8); + io.set(sel, (bits >> 8) as u8 & 3); + io.set(bypass, (bits >> 10) as u8); + }) + .unwrap(); + trace.push(read!()); + match bits >> 18 & 3 { + 0 => sim.tick(clk_a).unwrap(), + 1 => sim.tick(clk_b).unwrap(), + 2 => sim.tick_events(&[clk_a, clk_b]).unwrap(), + _ => {} + } + trace.push(read!()); + } + trace + }}; +} + +fn reference() -> Vec> { + trace!(single_pass().build().unwrap()) +} + +#[test] +fn partitioned_interpreter_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_interpreter().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_cranelift_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_cranelift().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_wasm_matches_single_pass() { + assert_eq!(trace!(partitioned().build_wasm().unwrap()), reference()); +} + +#[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) +))] +#[test] +fn partitioned_native_matches_single_pass() { + assert_eq!(trace!(partitioned().build_native().unwrap()), reference()); +} + +/// Loading a state file writes every object, so every partition reading one +/// must run again; the settle's flags themselves are not state. +#[test] +fn loaded_state_reaches_partitions() { + let mut source = partitioned().build().unwrap(); + trace!(source); + let file = source.save_state().unwrap(); + assert!( + file.objects + .iter() + .all(|object| !object.path.contains("$settle")), + "the settle flags are saved as state" + ); + let mut target = partitioned().build().unwrap(); + // Settle once before the load, so no partition is pending. + trace!(target); + target.load_state(&file).unwrap(); + let mut plain = single_pass().build().unwrap(); + plain.load_state(&file).unwrap(); + assert_eq!(trace!(target), trace!(plain)); +} + +#[cfg(feature = "systemverilog")] +mod systemverilog { + use std::path::Path; + + use celox::{BigUint, SettlePartition, Simulation, SirPass}; + + /// A clock gated through a latch (Xilinx BUFGCE): the latch is a process + /// of the settle, and the gated clock's edge runs another domain. + const GATED: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] fast, + output logic [7:0] gated, + output logic [7:0] view +); + logic clk = 0; + logic en = 0; + logic en_l; + logic [7:0] din = 0; + always #5 clk = ~clk; + always #7 en = ~en; + always #3 din = din + 8'd29; + always_latch begin + if (!clk) en_l = en; + end + wire gclk = clk & en_l; + initial begin fast = 0; gated = 0; end + always_ff @(posedge clk) fast <= fast + din; + always_ff @(posedge gclk) gated <= gated ^ fast; + assign view = gated + fast; +endmodule +"#; + + /// A process writing two outputs runs at its first output's place in + /// the schedule, so the second output changes there too. + const SPLIT: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [3:0] y, + output logic [3:0] b, + output logic [1:0] w, + output int n +); + logic [3:0] a = 4'b0101; + logic c = 0; + always_comb begin y = 4'b0; if (c) y = a; b = a; end + assign w = y[1:0]; + initial begin n = 0; #1 forever begin @(y); n++; end end + initial begin + #2 c = 1; + #1 a = 4'b0110; + #1 a = 4'b0111; + #2 c = 0; + #1 a = 4'b1001; + end +endmodule +"#; + + /// A whole-variable copy of a process output, read by another process. + const COPY: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] r, + output logic [7:0] q +); + logic [7:0] a = 8'd3; + logic s = 0; + logic [7:0] p; + logic [7:0] pc; + always_comb begin p = 8'd0; q = 8'd0; if (s) begin p = a; q = ~a; end end + assign pc = p; + always_comb r = pc + 8'd1; + always #2 a = a + 8'd5; + always #3 s = ~s; +endmodule +"#; + + fn trace( + source: &str, + outputs: &[&str], + end: u64, + settle: Option, + ) -> Vec> { + let builder = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let builder = match settle { + Some(settle) => builder.settle_partition(settle).settle_check(true), + None => builder.disable_pass(SirPass::PartitionedSettle), + }; + let mut sim = builder.build().unwrap(); + let outputs: Vec<_> = outputs.iter().map(|name| sim.signal(name)).collect(); + let mut trace = Vec::new(); + for time in 0..end { + sim.run_until(time).unwrap(); + trace.push(outputs.iter().map(|&signal| sim.get(signal)).collect()); + } + trace + } + + fn matches_single_pass(source: &str, outputs: &[&str], end: u64) -> Vec> { + let single = trace(source, outputs, end, None); + assert_eq!( + trace(source, outputs, end, Some(SettlePartition::Always)), + single + ); + single + } + + #[test] + fn latch_gated_clock_matches_single_pass() { + let single = matches_single_pass(GATED, &["fast", "gated", "view"], 200); + // The gated domain must have run. + assert_ne!(single.last().unwrap()[1], BigUint::from(0u8)); + } + + #[test] + fn multi_output_process_matches_single_pass() { + let single = matches_single_pass(SPLIT, &["y", "b", "w", "n"], 10); + // At 5, y and w follow a through the intermediate 0. + assert_eq!(single[5][2], BigUint::from(3u8)); + } + + #[test] + fn copy_of_a_process_output_matches_single_pass() { + matches_single_pass(COPY, &["r", "q"], 40); + } +} diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index a10c48ca3b5..fc8608038ba 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -101,6 +101,15 @@ unnecessary: compile the clock's domain once more; the `derived_edge_units` selector (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to trade tick speed for build time. +- the combinational settle can be cut into partitions, contiguous ranges of + its schedule, that run only when their dirty flag is set + (`partitioned_settle`, off unless enabled). A partition that runs sets the + flags of the partitions reading what it writes; every other writer sets them + too: generated stores and commits of state a partition reads or writes, host + writes, state loads, and a retained raw view of the state, after which every + partition runs. `SimulatorBuilder::settle_check` runs each settle a second + time with every partition flagged and panics where the two differ; effects + of partitions that run twice, such as runtime events, then happen twice. - in the time slots a compiled scheduler runs, a combinational settle waits until its results are read: it runs, where the reference loop last settled, before a process kernel or domain that reads combinational outputs diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index b358062dc33..466b8f0b6ae 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -394,7 +394,9 @@ export interface SimulatorOptions { * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split, * derived_edge_units (generated units for the edges of gated and divided * clocks; "-sir:derived_edge_units" walks their plans instead, which - * builds faster and ticks slower) + * builds faster and ticks slower), partitioned_settle (settle only the + * partitions of the combinational logic whose inputs changed; off unless + * enabled with "+sir:partitioned_settle") * * @example ["-sir:reschedule", "+sir:gvn"] */