Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,15 @@ fn optimize_bit_extracts(
| SIRInstruction::Load(dst, _, _, _) => *dst,
_ => continue,
};
if use_count.get(&def_reg).copied().unwrap_or(0) == 0 {
// Also decrement use counts for operands of this dead instruction
if use_count.get(&def_reg).copied().unwrap_or(0) == 0 && dead_set.insert(dead_idx) {
// Multiple replacements may share this definition. Removing
// it consumes its operands once, not once per replacement.
if let SIRInstruction::Binary(_, lhs, _, rhs) = &instructions[dead_idx] {
*use_count.entry(*lhs).or_default() =
use_count.get(lhs).copied().unwrap_or(0).saturating_sub(1);
*use_count.entry(*rhs).or_default() =
use_count.get(rhs).copied().unwrap_or(0).saturating_sub(1);
}
dead_set.insert(dead_idx);
}
}
}
Expand Down Expand Up @@ -399,6 +399,69 @@ mod tests {
}
}

#[test]
fn preserves_ssa_when_replacements_share_a_shift() {
let addr = test_addr();
let other = RegionedAbsoluteAddr {
instance_id: InstanceId(1),
..addr
};
let mut unit = ExecutionUnit {
entry_block_id: BlockId(0),
blocks: [(
BlockId(0),
BasicBlock {
id: BlockId(0),
params: vec![],
instructions: vec![
SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), 8),
SIRInstruction::Load(RegisterId(8), other, SIROffset::Static(0), 8),
SIRInstruction::Imm(RegisterId(1), SIRValue::new(2u64)),
SIRInstruction::Binary(
RegisterId(2),
RegisterId(0),
BinaryOp::Shr,
RegisterId(1),
),
SIRInstruction::Imm(RegisterId(3), SIRValue::new(3u64)),
SIRInstruction::Binary(
RegisterId(4),
RegisterId(2),
BinaryOp::And,
RegisterId(3),
),
SIRInstruction::Imm(RegisterId(5), SIRValue::new(15u64)),
SIRInstruction::Binary(
RegisterId(6),
RegisterId(2),
BinaryOp::And,
RegisterId(5),
),
SIRInstruction::Binary(
RegisterId(7),
RegisterId(8),
BinaryOp::Shr,
RegisterId(1),
),
SIRInstruction::RuntimeEvent {
site_id: 0,
args: vec![RegisterId(4), RegisterId(6), RegisterId(7)],
},
],
terminator: SIRTerminator::Return,
},
)]
.into_iter()
.collect(),
register_map: (0..9)
.map(|id| (RegisterId(id), RegisterType::Logic { width: 8 }))
.collect(),
};
unit.verify_result().unwrap();
BitExtractPeepholePass.run(&mut unit, &PassOptions::default());
unit.verify_result().unwrap();
}

#[test]
fn keeps_shift_result_used_by_runtime_event() {
let addr = test_addr();
Expand Down
109 changes: 109 additions & 0 deletions crates/celox-sir-opt/src/optimizer/passes/memory/commit_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,35 @@ struct PendingSegments {

impl PendingSegments {
fn build(eu: &ExecutionUnit<RegionedAbsoluteAddr>) -> Self {
Self::build_with_working_inputs(eu, false)
}

fn build_with_working_inputs(eu: &ExecutionUnit<RegionedAbsoluteAddr>, inputs: bool) -> Self {
let mut endpoints: HashMap<AbsoluteAddr, Vec<usize>> = HashMap::default();
for block in eu.blocks.values() {
for instruction in &block.instructions {
match instruction {
SIRInstruction::Load(_, addr, offset, bits)
if inputs && addr.region == WORKING_REGION =>
{
let (start, end) = instruction_range(&eu.register_map, offset, *bits);
endpoints
.entry(addr.absolute_addr())
.or_default()
.extend([start, end]);
}
SIRInstruction::Commit(src, dst, offset, bits, _)
if inputs
&& src.region == STABLE_REGION
&& dst.region == WORKING_REGION
&& src.absolute_addr() == dst.absolute_addr() =>
{
let (start, end) = instruction_range(&eu.register_map, offset, *bits);
endpoints
.entry(dst.absolute_addr())
.or_default()
.extend([start, end]);
}
SIRInstruction::Store(addr, offset, bits, _, _, _)
if addr.region == WORKING_REGION
|| addr.region == SPARSE_WORKING_REGION =>
Expand Down Expand Up @@ -348,6 +373,90 @@ fn update_segments(bits: &mut [u64], range: std::ops::Range<usize>, set: bool) {
}
}

/// A partial event can read pending values produced by another task. Such
/// values cannot be redirected to STABLE or have their publication removed.
/// Track possibly uninitialized access fragments, rather than bits of the
/// declared object, so large arrays with sparse accesses remain sparse.
pub(crate) fn uninitialized_working_observations(
eu: &ExecutionUnit<RegionedAbsoluteAddr>,
) -> DirectStableStoreHazards {
use std::collections::VecDeque;
let segments = PendingSegments::build_with_working_inputs(eu, true);
let mut hazards = DirectStableStoreHazards::default();
if segments.count == 0 {
return hazards;
}
let words = segments.count.div_ceil(64);
let mut incoming = HashMap::default();
incoming.insert(eu.entry_block_id, vec![u64::MAX; words]);
let mut queue = VecDeque::from([eu.entry_block_id]);
while let Some(id) = queue.pop_front() {
let block = &eu.blocks[&id];
let mut undefined = incoming[&id].clone();
for instruction in &block.instructions {
let observed = match instruction {
SIRInstruction::Load(_, address, offset, width)
if address.region == WORKING_REGION =>
{
Some((*address, offset, *width))
}
SIRInstruction::Commit(source, _, offset, width, _)
if source.region == WORKING_REGION =>
{
Some((*source, offset, *width))
}
_ => None,
};
if let Some((address, offset, width)) = observed {
let (start, end) = instruction_range(&eu.register_map, offset, width);
segments.record_observation(
&mut hazards,
&undefined,
address.absolute_addr(),
start,
end,
);
}
let defined = match instruction {
SIRInstruction::Store(address, offset, width, ..)
if address.region == WORKING_REGION =>
{
Some((*address, offset, *width))
}
SIRInstruction::Commit(source, destination, offset, width, _)
if source.region == STABLE_REGION
&& destination.region == WORKING_REGION
&& source.absolute_addr() == destination.absolute_addr() =>
{
Some((*destination, offset, *width))
}
_ => None,
};
if let Some((address, offset, width)) = defined
&& let Some(start) = offset.constant_bit_offset()
&& let Some(end) = start.checked_add(width)
&& let Some(range) = segments.segment_range(address.absolute_addr(), start, end)
{
update_segments(&mut undefined, range, false);
}
}
for successor in crate::ir::cfg::terminator_successors(&block.terminator) {
let is_new = !incoming.contains_key(&successor);
let entry = incoming.entry(successor).or_insert_with(|| vec![0; words]);
let mut changed = is_new;
for (destination, source) in entry.iter_mut().zip(&undefined) {
let merged = *destination | *source;
changed |= merged != *destination;
*destination = merged;
}
if changed {
queue.push_back(successor);
}
}
}
hazards
}

/// Bit ranges for which replacing a WORKING/SPARSE write with an immediate
/// STABLE write could change an observation in this complete event CFG.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ pub fn eliminate_working_round_trip(
eu: &mut ExecutionUnit<RegionedAbsoluteAddr>,
_eu_boundary_blocks: &[BlockId],
) {
eliminate_working_round_trip_impl(eu, false);
}

/// Optimize one partial event task. Pending values can have producers outside
/// this function, so publication requires proof of a local definition on every
/// path. Sparse publication can also consume dirty entries from other tasks.
pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit<RegionedAbsoluteAddr>) {
eliminate_working_round_trip_impl(eu, true);
}

fn eliminate_working_round_trip_impl(eu: &mut ExecutionUnit<RegionedAbsoluteAddr>, partial: bool) {
use crate::HashMap;

// Phase 1: Scan — collect info about each WORKING variable
Expand Down Expand Up @@ -140,9 +151,16 @@ pub fn eliminate_working_round_trip(
.collect();

let unsafe_after_store = super::commit_ops::direct_stable_store_hazards(eu);
let uninitialized = (partial && !eligible.is_empty())
.then(|| super::commit_ops::uninitialized_working_observations(eu));
let eligible: crate::HashSet<AbsoluteAddr> = eligible
.into_iter()
.filter(|addr| !unsafe_after_store.contains_addr(*addr))
.filter(|addr| {
!unsafe_after_store.contains_addr(*addr)
&& !uninitialized
.as_ref()
.is_some_and(|undefined| undefined.contains_addr(*addr))
})
.collect();

// Sparse state has no per-EU seed: every producer writes the same pending
Expand All @@ -151,7 +169,8 @@ pub fn eliminate_working_round_trip(
let sparse_eligible: crate::HashSet<AbsoluteAddr> = sparse_vars
.iter()
.filter(|(addr, info)| {
info.has_store
!partial
&& info.has_store
&& info.stable_addr.is_some()
&& !info.invalid_apply
&& !unsafe_after_store.contains_addr(**addr)
Expand Down Expand Up @@ -627,4 +646,122 @@ mod tests {
SIRInstruction::Commit(..)
));
}
#[test]
fn partial_event_keeps_publication_of_another_producers_fragment() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(24), 8),
SIRInstruction::Store(
addr(WORKING_REGION),
SIROffset::Static(24),
8,
RegisterId(1),
Vec::new(),
Vec::new(),
),
working_apply(SIROffset::Static(16), 8),
working_apply(SIROffset::Static(24), 8),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}

#[test]
fn partial_event_requires_a_definition_on_every_branch() {
for both_paths in [false, true] {
let store = || {
SIRInstruction::Store(
addr(WORKING_REGION),
SIROffset::Static(0),
8,
RegisterId(1),
Vec::new(),
Vec::new(),
)
};
let mut unit = eu(vec![
block(
0,
vec![],
SIRTerminator::Branch {
cond: RegisterId(3),
true_block: (BlockId(1), vec![]),
false_block: (BlockId(2), vec![]),
},
),
block(1, vec![store()], SIRTerminator::Jump(BlockId(3), vec![])),
block(
2,
if both_paths { vec![store()] } else { vec![] },
SIRTerminator::Jump(BlockId(3), vec![]),
),
block(
3,
vec![working_apply(SIROffset::Static(0), 8)],
SIRTerminator::Return,
),
]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
if both_paths {
assert!(unit.blocks[&BlockId(3)].instructions.is_empty());
assert!(
matches!(unit.blocks[&BlockId(1)].instructions[0],SIRInstruction::Store(address,..) if address.region==STABLE_REGION)
);
} else {
assert_eq!(unit, before);
}
}
}

#[test]
fn partial_event_keeps_unseeded_dynamic_pending_values() {
let mut unit = eu(vec![block(
0,
vec![
indexed_working_store(),
working_apply(SIROffset::Static(0), 64),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}

#[test]
fn partial_event_can_redirect_a_locally_seeded_dynamic_update() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(0), 64),
indexed_working_store(),
working_apply(SIROffset::Static(0), 64),
],
SIRTerminator::Return,
)]);
eliminate_partial_working_round_trip(&mut unit);
assert!(
matches!(unit.blocks[&BlockId(0)].instructions.as_slice(),[SIRInstruction::Store(address,SIROffset::Element {..},..)] if address.region==STABLE_REGION)
);
}
#[test]
fn partial_event_keeps_reads_of_another_producers_pending_fragment() {
let mut unit = eu(vec![block(
0,
vec![
working_seed(SIROffset::Static(0), 8),
SIRInstruction::Load(RegisterId(2), addr(WORKING_REGION), SIROffset::Static(8), 8),
working_apply(SIROffset::Static(0), 8),
],
SIRTerminator::Return,
)]);
let before = unit.clone();
eliminate_partial_working_round_trip(&mut unit);
assert_eq!(unit, before);
}
}
Loading
Loading