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
16 changes: 16 additions & 0 deletions conformance/sv-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,22 @@ method changes above changed only these twelve verdicts, with no passing case
regressing: 1,208 cases pass in 2state and 1,219 in 4state. Shared tests also cover short-circuiting and
unknown operands (IEEE 1800-2023 11.4.7).

Integral array reductions (7.12.3) support `sum`, `product`, `and`, `or` and
`xor`, with or without empty parentheses. The five unmodified
`chapter-7/arrays/unpacked/reduction-methods` simulation cases pass the
official runner in both state modes at the pinned revision. Only those ten
reviewed expectations change from `fail` to `pass`; this is a focused run,
not a new full-corpus measurement. Shared regressions also exercise fixed
arrays, queues, integral- and string-indexed associative arrays, element-width
overflow, signed results, packed type queries and four-state propagation.
Empty reductions use the operation identity (`product`: one, `and`: all ones,
`sum` / `or` / `xor`: zero). An explicit `legacy_empty_reductions` build option
selects zero for all empty reductions. These empty-input cases are covered by
shared and simulator API regressions; the five upstream cases use nonempty
arrays and do not distinguish these modes.
`with` expressions, iterator arguments and
multidimensional unpacked receivers remain unsupported.

## Running locally

Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment.
Expand Down
20 changes: 10 additions & 10 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1383,16 +1383,16 @@ chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 2state fail
chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 4state fail
chapter-7/arrays/unpacked/ordering-methods/sort.sv 2state fail
chapter-7/arrays/unpacked/ordering-methods/sort.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/and.sv 2state fail
chapter-7/arrays/unpacked/reduction-methods/and.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/or.sv 2state fail
chapter-7/arrays/unpacked/reduction-methods/or.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/product.sv 2state fail
chapter-7/arrays/unpacked/reduction-methods/product.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state fail
chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state fail
chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state fail
chapter-7/arrays/unpacked/reduction-methods/and.sv 2state pass
chapter-7/arrays/unpacked/reduction-methods/and.sv 4state pass
chapter-7/arrays/unpacked/reduction-methods/or.sv 2state pass
chapter-7/arrays/unpacked/reduction-methods/or.sv 4state pass
chapter-7/arrays/unpacked/reduction-methods/product.sv 2state pass
chapter-7/arrays/unpacked/reduction-methods/product.sv 4state pass
chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state pass
chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state pass
chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state pass
chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state pass
chapter-7/arrays/unpacked/slice-equality.sv 2state pass
chapter-7/arrays/unpacked/slice-equality.sv 4state pass
chapter-7/arrays/unpacked/slice.sv 2state pass
Expand Down
118 changes: 118 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ impl Ff<'_, '_> {
string_key,
);
let code = |opcode| encode(opcode, parameter);
if op.reduction().is_some() {
return self.container_reduction(op, layout, &args[0], parameter);
}
let zero = self.constant64(0);
let (width, signed) = op.result_type(layout);
let element_result = matches!(op, Get | PopFront | PopBack);
Expand Down Expand Up @@ -298,6 +301,121 @@ impl Ff<'_, '_> {
Ok(sv::ir::Expr::Ident(name))
}

fn container_reduction(
&mut self,
op: ContainerOp,
layout: ContainerLayout,
receiver: &sv::ir::Expr,
parameter: u64,
) -> Result<sv::ir::Expr, sv::AnalyzerError> {
let width = layout.width as usize;
let four_state = !layout.two_state && self.m.four_state;
let alloc = |b: &mut SIRBuilder<Addr>| {
if four_state {
b.alloc_logic(width)
} else {
b.alloc_bit(width, layout.signed)
}
};
let code = |opcode| encode(opcode, parameter);
// Keep one immutable snapshot of the receiver throughout the traversal.
let handle = self.handle(receiver)?;
let zero = self.constant64(0);
let one = self.constant64(1);
let length = self.heap_call(code(heap::LEN), &[handle]);
let associative = matches!(layout.kind, ContainerKind::Associative { .. });
let first = if associative {
self.heap_call(code(heap::FIRST), &[handle, zero])
} else {
zero
};
let seed = alloc(&mut self.b);
let identity = match op {
ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => BigUint::from(1u8),
ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => {
(BigUint::from(1u8) << width) - BigUint::from(1u8)
}
_ => BigUint::zero(),
};
self.b
.emit(SIRInstruction::Imm(seed, SIRValue::new(identity)));
let remaining = self.b.alloc_bit(64, false);
let key = self.b.alloc_bit(64, false);
let accumulator = alloc(&mut self.b);
let header = self.b.new_block_with(vec![remaining, key, accumulator]);
let body = self.b.new_block();
let result = alloc(&mut self.b);
let exit = self.b.new_block_with(vec![result]);
self.b
.seal_block(SIRTerminator::Jump(header, vec![length, first, seed]));
self.b.switch_to_block(header);
let more = self.b.alloc_bit(1, false);
self.b
.emit(SIRInstruction::Binary(more, remaining, BinaryOp::Ne, zero));
self.b.seal_block(SIRTerminator::Branch {
cond: more,
true_block: (body, Vec::new()),
false_block: (exit, vec![accumulator]),
});
self.b.switch_to_block(body);
let raw = self.heap_call(code(heap::GET), &[handle, key, zero]);
let mask = self.heap_call(code(heap::GET_MASK), &[handle, key, zero]);
let element = self.container_join(raw, mask, width, four_state);
let combined = alloc(&mut self.b);
let binary = match op {
ContainerOp::ReduceSum => BinaryOp::Add,
ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => BinaryOp::Mul,
ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => BinaryOp::And,
ContainerOp::ReduceOr => BinaryOp::Or,
ContainerOp::ReduceXor => BinaryOp::Xor,
_ => unreachable!("reduction method"),
};
self.b.emit(SIRInstruction::Binary(
combined,
accumulator,
binary,
element,
));
let next = if associative {
self.heap_call(code(heap::NEXT), &[handle, key])
} else {
let next = self.b.alloc_bit(64, false);
self.b
.emit(SIRInstruction::Binary(next, key, BinaryOp::Add, one));
next
};
let fewer = self.b.alloc_bit(64, false);
self.b
.emit(SIRInstruction::Binary(fewer, remaining, BinaryOp::Sub, one));
self.b
.seal_block(SIRTerminator::Jump(header, vec![fewer, next, combined]));
self.b.switch_to_block(exit);
// The accumulator starts at the operation's identity. Only explicit
// legacy compatibility replaces an empty product/AND with zero.
let value = if matches!(
op,
ContainerOp::LegacyReduceProduct | ContainerOp::LegacyReduceAnd
) {
let empty = self.b.alloc_bit(1, false);
self.b
.emit(SIRInstruction::Binary(empty, length, BinaryOp::Eq, zero));
let empty_value = alloc(&mut self.b);
self.b
.emit(SIRInstruction::Imm(empty_value, SIRValue::new(0u8)));
let value = alloc(&mut self.b);
self.b
.emit(SIRInstruction::Mux(value, empty, empty_value, result));
value
} else {
result
};
let (temp, name) = self
.m
.temp("array_reduction", width, layout.signed, four_state);
self.store(temp, SIROffset::Static(0), width, value);
Ok(sv::ir::Expr::Ident(name))
}

fn container_element(
&mut self,
expr: &sv::ir::Expr,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ mod port_owners;
mod timing;
mod type_binding;
pub(crate) use parameters::unbounded_parameter_marker;
mod array_reductions;
mod containers;
mod patterns;
mod procedural;
Expand Down
142 changes: 142 additions & 0 deletions crates/celox-sv-analyzer/src/ast/array_reductions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//! Integral unpacked array reductions (IEEE 1800-2023 7.12.3).
use super::*;
use celox_sv_syntax::{Declarations, ExprId, ExprKind};
use system_functions::ContainerOp;

pub(super) fn bind(
id: ExprId,
native: &Declarations,
tree: &AnalysisContext<'_>,
dims: &PackedDimensions,
) -> Converted<Option<(Expr, VariableDimensions)>> {
let callee = match &native.expression(id).kind {
ExprKind::Call { expression, .. } => *expression,
_ => id,
};
let ExprKind::Member {
expression: base,
separator,
name,
} = &native.expression(callee).kind
else {
return Ok(None);
};
if separator != "." {
return Ok(None);
}
let mut op = match name.spelling.as_str() {
"sum" => ContainerOp::ReduceSum,
"product" => ContainerOp::ReduceProduct,
"and" => ContainerOp::ReduceAnd,
"or" => ContainerOp::ReduceOr,
"xor" => ContainerOp::ReduceXor,
_ => return Ok(None),
};
if timescales::analysis_options(&tree.state.timescales).legacy_empty_reductions {
op = match op {
ContainerOp::ReduceProduct => ContainerOp::LegacyReduceProduct,
ContainerOp::ReduceAnd => ContainerOp::LegacyReduceAnd,
_ => op,
};
}
let ExprKind::Name(receiver) = &native
.expression(expression_binding::ungroup(*base, native))
.kind
else {
return Ok(None);
};
let receiver = instances::normalize_identifier(&receiver.spelling);
let Some(shape) = dims.get(&receiver) else {
return Ok(None);
};
if shape.container.is_none() && shape.unpacked.is_empty() {
return Ok(None);
}
if let ExprKind::Call { arguments, .. } = &native.expression(id).kind
&& !arguments.is_empty()
{
return Err(unsupported(
"array reduction arguments require a with expression",
));
}
if let Some(container) = shape.container.as_deref() {
if container.layout.handle.is_some() {
return Err(unsupported("array reduction requires integral elements"));
}
return Ok(Some((
containers::call(op, container.layout, vec![Expr::Ident(receiver)]),
procedural::dimensions_from_type(&container.element),
)));
}
if shape.unpacked.len() != 1 || shape.real || shape.string || shape.class.is_some() {
return Err(unsupported(
"array reduction requires one-dimensional integral elements",
));
}
let width = shape
.packed
.iter()
.try_fold(1usize, |width, dim| {
width.checked_mul(
usize::try_from(eval_ast_const_expr(
&tree.state,
&dim.width,
&dims.const_env,
)?)
.ok()?,
)
})
.ok_or_else(|| unsupported("array reduction element width"))?;
let count = usize::try_from(
eval_ast_const_expr(&tree.state, &shape.unpacked[0].width, &dims.const_env)
.ok_or_else(|| unsupported("array reduction length"))?,
)
.map_err(|_| unsupported("array reduction length"))?;
let elements = (0..count).map(|index| Expr::Select {
expr: Box::new(Expr::Ident(receiver.clone())),
msb: ConstExpr::Literal(((index + 1) * width - 1).to_string()),
lsb: ConstExpr::Literal((index * width).to_string()),
signed: shape.signed,
});
let identity = match op {
ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => format!("{width}'d1"),
ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => {
format!("{width}'b{}", "1".repeat(width))
}
_ => format!("{width}'d0"),
};
let mut level = std::iter::once(Expr::Literal(identity))
.chain(elements)
.collect::<Vec<_>>();
// A balanced tree keeps large fixed arrays from making expression depth
// proportional to the number of elements.
while level.len() > 1 {
let mut next = Vec::with_capacity(level.len().div_ceil(2));
let mut values = level.into_iter();
while let Some(left) = values.next() {
next.push(if let Some(right) = values.next() {
Expr::Binary {
left: Box::new(left),
op: op.reduction().expect("reduction method").into(),
right: Box::new(right),
}
} else {
left
});
}
level = next;
}
let result = level.pop().expect("reduction identity");
// A method result is self-determined: assignment context must not widen
// intermediate additions or products past the element type.
let mut result_shape = shape.clone();
result_shape.unpacked.clear();
Ok(Some((
Expr::Resize {
expr: Box::new(result),
width,
signed: shape.signed,
},
result_shape,
)))
}
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub(super) fn expr_is_two_state(
callee: Callee::Object(op),
..
} => {
!matches!(**op, ObjectOp::Container { op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal, layout } if !layout.two_state)
!matches!(**op, ObjectOp::Container { op, layout } if !layout.two_state && (op.reduction().is_some() || matches!(op, ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal)))
}
Expr::Call {
callee: Callee::Subroutine(name),
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,10 @@ pub(in crate::ast) fn shape(
while let Some(job) = jobs.pop() {
match job {
Job::Enter(id) => {
if let Some((_, shape)) = array_reductions::bind(id, native, tree, context)? {
values.push(shape);
continue;
}
let callee = match native.expression(id).kind {
ExprKind::Call { expression, .. } => expression,
_ => id,
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ pub(in crate::ast) fn bind_value(
));
}
}
if let Some((value, _)) = array_reductions::bind(id, native, tree, dimensions)? {
values.push(value);
continue;
}
if let Some(value) = containers::value(id, native, tree, dimensions, false)? {
values.push(value);
continue;
Expand Down
11 changes: 11 additions & 0 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,6 +1199,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
root: celox_sv_syntax::ExprId,
) -> Result<Vec<Stmt>, AnalyzerError> {
let native = self.tree.declarations();
if let Some((mut value, _)) = array_reductions::bind(root, native, self.tree, &self.dims)? {
self.rename_expr(&mut value);
return Ok(vec![Stmt::Eval(value)]);
}
if let Some(mut value) = containers::value(root, native, self.tree, &self.dims, true)? {
self.rename_expr(&mut value);
return Ok(vec![Stmt::Eval(value)]);
Expand Down Expand Up @@ -1236,6 +1240,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
{
let query_root =
expression_binding::call_statement_root(root, discarded, self.tree.declarations())?;
if discarded
&& let Some((mut value, _)) =
array_reductions::bind(query_root, native, self.tree, &self.dims)?
{
self.rename_expr(&mut value);
return Ok(vec![Stmt::Eval(value)]);
}
if discarded
&& let Some(mut value) =
containers::value(query_root, native, self.tree, &self.dims, true)?
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast/timescales.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ pub(super) fn revision(state: &State) -> &generate::Revision {
&state.revision
}

pub(super) fn analysis_options(state: &State) -> crate::AnalysisOptions {
state.design.borrow().design.options
}

pub(super) fn with_interface_instance<T>(
state: &State,
name: &str,
Expand Down
Loading
Loading