Skip to content
Merged
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
125 changes: 93 additions & 32 deletions crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,30 +351,20 @@ fn coalesce_static_stores<A: Clone + std::fmt::Debug + PartialEq + Ord + std::ha
let mut replaced_indices = HashSet::default();
let mut insertions: HashMap<usize, Vec<SIRInstruction<A>>> = HashMap::default();

// Pre-index loads by address for efficient safety checks.
// Each entry is (instruction_index, offset, width, is_dynamic).
let mut load_index: HashMap<A, Vec<(usize, Option<usize>, usize)>> = HashMap::default();
// Moving a store to the end of a merged run must cross neither a read
// nor a later overlapping write. In particular, a narrow overwrite can
// sit between two adjacent candidate ranges in instruction order.
let mut access_index: HashMap<A, Vec<(usize, Option<usize>, usize)>> = HashMap::default();
let mut barriers = Vec::new();
for (idx, inst) in instructions.iter().enumerate() {
match inst {
SIRInstruction::Load(_, addr, SIROffset::Static(off), w) => {
load_index
.entry(addr.clone())
.or_default()
.push((idx, Some(*off), *w));
}
SIRInstruction::Load(_, addr, SIROffset::PackedElements { bit_offset, .. }, w) => {
load_index
.entry(addr.clone())
.or_default()
.push((idx, Some(*bit_offset), *w));
}
SIRInstruction::Load(_, addr, SIROffset::Dynamic(_) | SIROffset::Element { .. }, w) => {
load_index
.entry(addr.clone())
.or_default()
.push((idx, None, *w));
}
_ => {}
if is_memory_barrier(inst) {
barriers.push(idx);
}
if let Some((addr, offset, width, _)) = mem_access_info(inst) {
access_index
.entry(addr.clone())
.or_default()
.push((idx, offset, width));
}
}

Expand Down Expand Up @@ -438,7 +428,7 @@ fn coalesce_static_stores<A: Clone + std::fmt::Debug + PartialEq + Ord + std::ha
}

// Get loads for this address once (empty slice if none)
let addr_loads = load_index.get(&addr);
let addr_accesses = access_index.get(&addr);

let mut segment_start = 0;
while segment_start < details.len() {
Expand Down Expand Up @@ -483,18 +473,22 @@ fn coalesce_static_stores<A: Clone + std::fmt::Debug + PartialEq + Ord + std::ha

let insert_at_index = segment.iter().map(|s| s.index).max().unwrap();

// Safety check: ensure no conflicting load between store and insert point.
// Use pre-indexed loads to avoid scanning all instructions.
let safe = if let Some(loads) = addr_loads {
// Preserve the ordering of every range moved to the anchor.
let safe = if let Some(accesses) = addr_accesses {
segment.iter().all(|s| {
if s.index == insert_at_index {
return true;
}
// Check loads to this address in range (s.index, insert_at_index]
!loads.iter().any(|&(load_idx, load_off, load_w)| {
if load_idx <= s.index || load_idx > insert_at_index {
return false;
}
let first_barrier = barriers.partition_point(|&idx| idx <= s.index);
if barriers
.get(first_barrier)
.is_some_and(|&idx| idx <= insert_at_index)
{
return false;
}
let first = accesses.partition_point(|&(idx, _, _)| idx <= s.index);
let end = accesses.partition_point(|&(idx, _, _)| idx <= insert_at_index);
!accesses[first..end].iter().any(|&(_, load_off, load_w)| {
match load_off {
None => true, // dynamic offset — conservatively unsafe
Some(lo) => {
Expand Down Expand Up @@ -1823,6 +1817,73 @@ mod tests {
assert_eq!(reg_counter, 1);
}

#[test]
fn store_coalescing_preserves_intervening_overlapping_writes() {
for intervening_offset in [
SIROffset::Static(3),
SIROffset::PackedElements {
bit_offset: 3,
element_width: 1,
},
SIROffset::Dynamic(RegisterId(2)),
SIROffset::Element {
index: RegisterId(2),
element_width: 2,
bit_offset: 1,
dynamic_bit_offset: None,
},
] {
let mut instructions = vec![
SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)),
SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)),
SIRInstruction::Imm(RegisterId(2), SIRValue::new(1u8)),
SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]),
SIRInstruction::Store(7, intervening_offset, 1, RegisterId(1), vec![], vec![]),
SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]),
];
let original = instructions.clone();
let mut registers = [
(RegisterId(0), logic(2)),
(RegisterId(1), logic(1)),
(RegisterId(2), logic(32)),
]
.into_iter()
.collect();
let mut counter = 2;
// Merging the writes at bits 1 and 2..3 would move the latter
// past the intervening write of bit 3, erasing its new value.
assert!(!coalesce_static_stores_with_types(
&mut instructions,
&mut registers,
&mut counter,
&HashMap::default()
));
assert_eq!(instructions, original);
}
}

#[test]
fn store_coalescing_keeps_disjoint_intervening_writes_optimizable() {
let mut instructions = vec![
SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)),
SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)),
SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]),
SIRInstruction::Store(7, SIROffset::Static(5), 1, RegisterId(1), vec![], vec![]),
SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]),
];
let mut registers = [(RegisterId(0), logic(2)), (RegisterId(1), logic(1))]
.into_iter()
.collect();
let mut counter = 1;
assert!(coalesce_static_stores_with_types(
&mut instructions,
&mut registers,
&mut counter,
&HashMap::default()
));
verify(instructions, registers);
}

#[test]
fn store_coalescing_marks_cross_element_transfer_explicitly() {
let mut instructions = (0..4)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::HashMap;
use crate::HashSet;
use crate::PassOptions;
use crate::ir::*;
use std::collections::BTreeMap;
use std::sync::Arc;

use super::block_opt::aggregate_static_offset;
Expand Down Expand Up @@ -51,6 +52,14 @@ struct StoreCandidate {
comb_capture_sites: Vec<u32>,
}

#[derive(Default)]
struct StoreGroup {
candidates: Vec<StoreCandidate>,
// Open groups have disjoint ranges. The predecessor of a new range's
// end suffices to detect overlap without quadratic scans of large blocks.
ranges: BTreeMap<usize, usize>,
}

fn coalesce_block(
block: &mut BasicBlock<RegionedAbsoluteAddr>,
register_map: &mut HashMap<RegisterId, RegisterType>,
Expand All @@ -62,15 +71,38 @@ fn coalesce_block(
//
// groups: addr -> vec of candidates (current open group)
// sealed_groups: completed groups ready for coalescing analysis
let mut groups: HashMap<RegionedAbsoluteAddr, Vec<StoreCandidate>> = HashMap::default();
let mut groups: HashMap<RegionedAbsoluteAddr, StoreGroup> = HashMap::default();
let mut sealed_groups: Vec<Vec<StoreCandidate>> = Vec::new();

for (i, inst) in block.instructions.iter().enumerate() {
if inst.is_host_interaction() {
for (_, group) in groups.drain() {
if group.candidates.len() >= 2 {
sealed_groups.push(group.candidates);
}
}
}
match inst {
SIRInstruction::Store(addr, SIROffset::Static(off), width, src, triggers, sites)
if triggers.is_empty() && sites.is_empty() =>
{
groups.entry(*addr).or_default().push(StoreCandidate {
let Some(end) = off.checked_add(*width) else {
seal_group(&mut groups, addr, &mut sealed_groups);
continue;
};
let overlaps = groups.get(addr).is_some_and(|group| {
group
.ranges
.range(..end)
.next_back()
.is_some_and(|(_, &previous_end)| previous_end > *off)
});
if overlaps {
seal_group(&mut groups, addr, &mut sealed_groups);
}
let group = groups.entry(*addr).or_default();
group.ranges.insert(*off, end);
group.candidates.push(StoreCandidate {
addr: *addr,
inst_index: i,
offset: *off,
Expand All @@ -82,31 +114,22 @@ fn coalesce_block(
SIRInstruction::Load(_, addr, _, _) => {
seal_group(&mut groups, addr, &mut sealed_groups);
}
SIRInstruction::Commit(src, _, _, _, _) => {
// Commit reads from src region
SIRInstruction::Commit(src, dst, _, _, _) => {
seal_group(&mut groups, src, &mut sealed_groups);
seal_group(&mut groups, dst, &mut sealed_groups);
}
// A Store with Dynamic offset could alias any static offset
SIRInstruction::Store(
addr,
SIROffset::Dynamic(_)
| SIROffset::Element { .. }
| SIROffset::PackedElements { .. },
_,
_,
_,
_,
) => {
// Noncandidate writes can overlap an open run or expose its state.
SIRInstruction::Store(addr, ..) => {
seal_group(&mut groups, addr, &mut sealed_groups);
}
_ => {}
}
}

// Flush remaining open groups
for (_, candidates) in groups.drain() {
if candidates.len() >= 2 {
sealed_groups.push(candidates);
for (_, group) in groups.drain() {
if group.candidates.len() >= 2 {
sealed_groups.push(group.candidates);
}
}

Expand Down Expand Up @@ -273,13 +296,13 @@ fn coalesce_block(
}

fn seal_group(
groups: &mut HashMap<RegionedAbsoluteAddr, Vec<StoreCandidate>>,
groups: &mut HashMap<RegionedAbsoluteAddr, StoreGroup>,
addr: &RegionedAbsoluteAddr,
sealed_groups: &mut Vec<Vec<StoreCandidate>>,
) {
if let Some(candidates) = groups.remove(addr) {
if candidates.len() >= 2 {
sealed_groups.push(candidates);
if let Some(group) = groups.remove(addr) {
if group.candidates.len() >= 2 {
sealed_groups.push(group.candidates);
}
}
}
Expand Down Expand Up @@ -321,6 +344,33 @@ mod tests {
}
}

#[test]
fn overlapping_store_seals_the_open_run() {
let addr = make_addr(0);
for middle in [
SIRInstruction::Store(addr, SIROffset::Static(3), 1, RegisterId(1), vec![], vec![]),
SIRInstruction::Commit(make_addr(1), addr, SIROffset::Static(3), 1, vec![]),
] {
let instructions = vec![
SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)),
SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)),
SIRInstruction::Store(addr, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]),
middle,
SIRInstruction::Store(addr, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]),
];
let registers = [
(RegisterId(0), RegisterType::Logic { width: 2 }),
(RegisterId(1), RegisterType::Logic { width: 1 }),
]
.into_iter()
.collect();
let mut eu = make_eu(instructions.clone(), registers);
CoalesceStoresPass::default().run(&mut eu, &PassOptions::default());
assert_eq!(eu.blocks[&BlockId(0)].instructions, instructions);
eu.verify();
}
}

#[test]
fn test_basic_contiguous_coalescing() {
// 3 contiguous 1-bit stores to bits 0, 1, 2 of the same variable
Expand Down
41 changes: 41 additions & 0 deletions crates/celox-test-suite/src/sv/cases/procedural.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,47 @@
(eval)
(assert_eq y 2))

(case static_function_unpacked_scratch_bits_at_element_boundaries
(source "scratch_bits.sv" #"
module Top(input logic [5:0] index, output logic [57:0] y);
function [58:0] identity(input logic [5:0] selected);
logic [57:0] words[57:0];
for (integer i=0; i<58; i=i+1) begin
words[i]='0;
words[i][i]=1'b1;
end
// The high result bit retains its value, so the function executes
// through the procedural path rather than symbolic substitution.
identity[57:0]=words[selected];
endfunction
assign y=identity(index);
endmodule
"#)
(top Top)
(for bit (range 0 58)
(modify (set index bit))
(assert_eq y (<< 1 bit))))

(case static_function_partial_writes_preserve_last_write
(source "partial_writes.sv" #"
module Top(input logic d, output wire [2:0] y);
function [4:0] update(input logic value);
update[3:2]='0;
update[3]=value;
update[1]=1'b1;
endfunction
wire [4:0] result=update(d);
assign y=result[3:1];
endmodule
"#)
(top Top)
(modify (set d 1))
(assert_eq y 5)
(modify (set d 0))
(assert_eq y 1)
(modify (set d 1))
(assert_eq y 5))

(case constant_functions_preserve_concat_operand_widths
(source "constant_concat.sv" #"
module Top(output logic [15:0] a,b, output logic [7:0] zero_part);
Expand Down
7 changes: 4 additions & 3 deletions crates/celox/src/optimizer/sir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,10 @@ pub(crate) fn optimize_native_merged_chain(
.unpacked_arrays
.iter()
.filter(|(_, array)| {
(1..=64).contains(&array.element_width)
&& array.element_stride * 8 != array.element_width
&& array.plane_size <= 256
// Element boundaries are a storage contract, including for
// large arrays and wide elements. Omitting them lets merged
// block optimization coalesce writes across padding gaps.
array.element_width != 0 && array.element_stride * 8 != array.element_width
})
.flat_map(|(&address, array)| {
[STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION].map(move |region| {
Expand Down
Loading
Loading