diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index dc586ef7f0e..b5734b32718 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -37,6 +37,7 @@ use celox_sv_analyzer as sv; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use num_bigint::BigUint; +mod case_equality; mod comb; mod comb_retention; mod ff; @@ -5048,6 +5049,17 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr { op: *op, expr: Box::new(expr_for_state_mode(expr, four_state)), }, + sv::ir::Expr::Binary { left, op, right } + if !four_state && matches!(op, sv::ir::BinaryOp::EqCase | sv::ir::BinaryOp::NeCase) => + { + // Storage remains two-state; exact comparison operands retain + // literal X/Z until value and mask are compared (11.4.5). + sv::ir::Expr::Binary { + left: Box::new(expr_for_state_mode(left, true)), + op: *op, + right: Box::new(expr_for_state_mode(right, true)), + } + } sv::ir::Expr::Binary { left, op, right } => sv::ir::Expr::Binary { left: Box::new(expr_for_state_mode(left, four_state)), op: *op, diff --git a/crates/celox-frontend-sv/src/lowering/case_equality.rs b/crates/celox-frontend-sv/src/lowering/case_equality.rs new file mode 100644 index 00000000000..4555d5cfe87 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/case_equality.rs @@ -0,0 +1,445 @@ +//! Exact comparisons retain literal X/Z even when runtime storage has one plane. +use super::procedural::{ConstCache, node_is_signed, slt_const4}; +use super::*; +use num_traits::Zero; + +type Planes = (NodeId, NodeId); + +pub(super) fn compare( + arena: &mut SLTNodeArena, + left: NodeId, + op: BinaryOp, + right: NodeId, +) -> Result { + let width = celox_slt::get_width(left, arena).max(celox_slt::get_width(right, arena)); + let signed = node_is_signed(arena, left) && node_is_signed(arena, right); + let left = coerce_node_width(arena, left, Some(width), signed)?; + let right = coerce_node_width(arena, right, Some(width), signed)?; + let mut builder = Builder { + arena, + values: HashMap::default(), + constants: ConstCache::default(), + }; + let l = builder.project(left)?; + let r = builder.project(right)?; + if builder.zero(l.1) && builder.zero(r.1) { + return builder.node(SLTNode::Binary(l.0, op, r.0)); + } + builder.exact(l, r, op == BinaryOp::NeCase) +} + +pub(super) fn is_known( + arena: &mut SLTNodeArena, + node: NodeId, +) -> Result { + let mut builder = Builder { + arena, + values: HashMap::default(), + constants: ConstCache::default(), + }; + let (_, mask) = builder.project(node)?; + Ok(builder.zero(mask)) +} + +struct Builder<'a, A: std::hash::Hash + Eq + Clone> { + arena: &'a mut SLTNodeArena, + values: HashMap, + constants: ConstCache, +} + +impl Builder<'_, A> { + fn node(&mut self, node: SLTNode) -> Result { + self.arena.alloc(node) + } + fn constant( + &mut self, + value: BigUint, + width: usize, + ) -> Result { + self.node(SLTNode::Constant(value, BigUint::default(), width, false)) + } + fn zeros(&mut self, width: usize) -> Result { + self.constant(BigUint::default(), width) + } + fn ones(&mut self, width: usize) -> Result { + self.constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( + &mut self, + a: NodeId, + op: BinaryOp, + b: NodeId, + ) -> Result { + self.node(SLTNode::Binary(a, op, b)) + } + fn unary(&mut self, op: UnaryOp, a: NodeId) -> Result { + self.node(SLTNode::Unary(op, a)) + } + fn mux( + &mut self, + cond: NodeId, + yes: NodeId, + no: NodeId, + ) -> Result { + self.node(SLTNode::Mux { + cond, + then_expr: yes, + else_expr: no, + }) + } + fn zero(&mut self, node: NodeId) -> bool { + slt_const4(self.arena, &mut self.constants, node) + .is_some_and(|(v, m, _)| v.is_zero() && m.is_zero()) + } + fn any(&mut self, node: NodeId) -> Result { + self.unary(UnaryOp::Or, node) + } + fn expanded( + &mut self, + flag: NodeId, + width: usize, + ) -> Result { + let one = self.ones(width)?; + let zero = self.zeros(width)?; + self.mux(flag, one, zero) + } + fn exact( + &mut self, + l: Planes, + r: Planes, + negate: bool, + ) -> Result { + let payload = self.binary(l.0, BinaryOp::Eq, r.0)?; + let mask = self.binary(l.1, BinaryOp::Eq, r.1)?; + let equal = self.binary(payload, BinaryOp::And, mask)?; + if negate { + self.unary(UnaryOp::LogicNot, equal) + } else { + Ok(equal) + } + } + fn truth(&mut self, p: Planes) -> Result { + let not_mask = self.unary(UnaryOp::BitNot, p.1)?; + let known = self.binary(p.0, BinaryOp::And, not_mask)?; + let known_one = self.any(known)?; + let unknown = self.any(p.1)?; + let no_one = self.unary(UnaryOp::LogicNot, known_one)?; + let unknown = self.binary(no_one, BinaryOp::And, unknown)?; + let value = self.binary(known_one, BinaryOp::Or, unknown)?; + Ok((value, unknown)) + } + fn arithmetic( + &mut self, + value: NodeId, + mask: NodeId, + width: usize, + ) -> Result { + let mask = self.expanded(mask, width)?; + let value = self.binary(value, BinaryOp::Or, mask)?; + Ok((value, mask)) + } + fn project(&mut self, root: NodeId) -> Result { + // Append-only node IDs let this worklist retain sharing without cloning + // the arena or using the native call stack for deeply nested operands. + let mut work = vec![(root, false)]; + while let Some((id, expanded)) = work.pop() { + if self.values.contains_key(&id) { + continue; + } + let node = self.arena.get(id).clone(); + let width = celox_slt::get_width(id, self.arena); + if let Some((value, mask, _)) = slt_const4(self.arena, &mut self.constants, id) { + let signed = node_is_signed(self.arena, id); + let value = + self.node(SLTNode::Constant(value, BigUint::default(), width, signed))?; + let mask = self.constant(mask, width)?; + self.values.insert(id, (value, mask)); + continue; + } + let children = match &node { + SLTNode::Unary(_, a) + | SLTNode::Slice { expr: a, .. } + | SLTNode::Capture { expr: a, .. } => vec![*a], + SLTNode::Binary(a, _, b) => vec![*a, *b], + SLTNode::Concat(parts) => parts.iter().map(|p| p.0).collect(), + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => vec![*cond, *then_expr, *else_expr], + // Calls/folds and inputs cross a runtime storage boundary. + // Their result is two-state; explicit literal operands remain + // visible in the structural and arithmetic nodes above. + _ => Vec::new(), + }; + if !expanded && !children.is_empty() { + work.push((id, true)); + for child in children.into_iter().rev() { + if !self.values.contains_key(&child) { + work.push((child, false)); + } + } + continue; + } + let result = match node { + SLTNode::Binary(a, op, b) => { + let l = self.values[&a]; + let r = self.values[&b]; + self.binary_planes(id, l, op, r, width)? + } + SLTNode::Unary(op, inner) => { + let p = self.values[&inner]; + if self.zero(p.1) { + (self.unary(op, p.0)?, self.zeros(width)?) + } else { + match op { + UnaryOp::Ident => p, + UnaryOp::ToTwoState => { + let not = self.unary(UnaryOp::BitNot, p.1)?; + (self.binary(p.0, BinaryOp::And, not)?, self.zeros(width)?) + } + UnaryOp::BitNot => { + let not = self.unary(op, p.0)?; + (self.binary(not, BinaryOp::Or, p.1)?, p.1) + } + UnaryOp::LogicNot => { + let truth = self.truth(p)?; + let not = self.unary(UnaryOp::LogicNot, truth.0)?; + (self.binary(not, BinaryOp::Or, truth.1)?, truth.1) + } + UnaryOp::Or => self.truth(p)?, + UnaryOp::And => { + let candidate = self.binary(p.0, BinaryOp::Or, p.1)?; + let value = self.unary(op, candidate)?; + let unknown = self.any(p.1)?; + (value, self.binary(value, BinaryOp::And, unknown)?) + } + UnaryOp::Xor | UnaryOp::Minus => { + let value = self.unary(op, p.0)?; + let unknown = self.any(p.1)?; + self.arithmetic(value, unknown, width)? + } + UnaryOp::PopCount => { + let not = self.unary(UnaryOp::BitNot, p.1)?; + let known = self.binary(p.0, BinaryOp::And, not)?; + (self.unary(op, known)?, self.zeros(width)?) + } + _ => { + let value = self.unary(op, p.0)?; + let unknown = self.any(p.1)?; + self.arithmetic(value, unknown, width)? + } + } + } + } + SLTNode::Slice { expr, access } => { + let p = self.values[&expr]; + ( + self.node(SLTNode::Slice { expr: p.0, access })?, + self.node(SLTNode::Slice { expr: p.1, access })?, + ) + } + SLTNode::Concat(parts) => { + let payload = parts.iter().map(|(p, w)| (self.values[p].0, *w)).collect(); + let mask = parts.iter().map(|(p, w)| (self.values[p].1, *w)).collect(); + ( + self.node(SLTNode::Concat(payload))?, + self.node(SLTNode::Concat(mask))?, + ) + } + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => { + let c = self.truth(self.values[&cond])?; + let t = self.values[&then_expr]; + let e = self.values[&else_expr]; + let value = self.mux(c.0, t.0, e.0)?; + let mask = self.mux(c.0, t.1, e.1)?; + if self.zero(c.1) { + (value, mask) + } else { + // An unknown condition merges equal bits and makes + // only differing bits X, retaining equal X/Z bits. + let dv = self.binary(t.0, BinaryOp::Xor, e.0)?; + let dm = self.binary(t.1, BinaryOp::Xor, e.1)?; + let diff = self.binary(dv, BinaryOp::Or, dm)?; + let merged_value = self.binary(t.0, BinaryOp::Or, diff)?; + let merged_mask = self.binary(t.1, BinaryOp::Or, diff)?; + ( + self.mux(c.1, merged_value, value)?, + self.mux(c.1, merged_mask, mask)?, + ) + } + } + SLTNode::Capture { expr, key } => { + let p = self.values[&expr]; + ( + self.node(SLTNode::Capture { expr: p.0, key })?, + self.node(SLTNode::Capture { expr: p.1, key })?, + ) + } + _ => (id, self.zeros(width)?), + }; + self.values.insert(id, result); + } + Ok(self.values[&root]) + } + fn binary_planes( + &mut self, + original: NodeId, + l: Planes, + op: BinaryOp, + r: Planes, + width: usize, + ) -> Result { + if self.zero(l.1) + && self.zero(r.1) + && !matches!( + op, + BinaryOp::DivU | BinaryOp::DivS | BinaryOp::RemU | BinaryOp::RemS + ) + { + return Ok((self.binary(l.0, op, r.0)?, self.zeros(width)?)); + } + match op { + BinaryOp::EqCase | BinaryOp::NeCase => { + Ok((self.exact(l, r, op == BinaryOp::NeCase)?, self.zeros(1)?)) + } + BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => { + let masks = self.binary(l.1, BinaryOp::Or, r.1)?; + let value = self.binary(l.0, op, r.0)?; + let mask = if op == BinaryOp::Xor { + masks + } else { + let (a, b) = if op == BinaryOp::And { + ( + self.unary(UnaryOp::BitNot, l.0)?, + self.unary(UnaryOp::BitNot, r.0)?, + ) + } else { + (l.0, r.0) + }; + let lm = self.unary(UnaryOp::BitNot, l.1)?; + let rm = self.unary(UnaryOp::BitNot, r.1)?; + let a = self.binary(a, BinaryOp::And, lm)?; + let b = self.binary(b, BinaryOp::And, rm)?; + let known = self.binary(a, BinaryOp::Or, b)?; + let not = self.unary(UnaryOp::BitNot, known)?; + self.binary(masks, BinaryOp::And, not)? + }; + Ok((self.binary(value, BinaryOp::Or, mask)?, mask)) + } + BinaryOp::LogicAnd | BinaryOp::LogicOr => { + let a = self.truth(l)?; + let b = self.truth(r)?; + self.binary_planes( + original, + a, + if op == BinaryOp::LogicAnd { + BinaryOp::And + } else { + BinaryOp::Or + }, + b, + 1, + ) + } + BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqWildcard | BinaryOp::NeWildcard => { + let masks = self.binary(l.1, BinaryOp::Or, r.1)?; + let not = self.unary(UnaryOp::BitNot, masks)?; + let diff = self.binary(l.0, BinaryOp::Xor, r.0)?; + let diff = self.binary(diff, BinaryOp::And, not)?; + let mismatch = self.any(diff)?; + let ambiguous = if matches!(op, BinaryOp::EqWildcard | BinaryOp::NeWildcard) { + let care = self.unary(UnaryOp::BitNot, r.1)?; + let lm = self.binary(l.1, BinaryOp::And, care)?; + self.any(lm)? + } else { + self.any(masks)? + }; + let no_diff = self.unary(UnaryOp::LogicNot, mismatch)?; + let mask = self.binary(no_diff, BinaryOp::And, ambiguous)?; + let value = if matches!(op, BinaryOp::Ne | BinaryOp::NeWildcard) { + self.binary(mismatch, BinaryOp::Or, mask)? + } else { + no_diff + }; + Ok((value, mask)) + } + BinaryOp::Shl | BinaryOp::Shr | BinaryOp::Sar => { + let value = self.binary(l.0, op, r.0)?; + let mask = self.binary(l.1, op, r.0)?; + let unknown = self.any(r.1)?; + let all = self.expanded(unknown, width)?; + Ok(( + self.binary(value, BinaryOp::Or, all)?, + self.binary(mask, BinaryOp::Or, all)?, + )) + } + BinaryOp::Float { .. } => Ok((original, self.zeros(width)?)), + _ => { + let lm = self.any(l.1)?; + let rm = self.any(r.1)?; + let mut unknown = self.binary(lm, BinaryOp::Or, rm)?; + if matches!( + op, + BinaryOp::DivU | BinaryOp::DivS | BinaryOp::RemU | BinaryOp::RemS + ) { + let zero = self.zeros(celox_slt::get_width(r.0, self.arena))?; + let zero = self.binary(r.0, BinaryOp::Eq, zero)?; + unknown = self.binary(unknown, BinaryOp::Or, zero)?; + } + let value = self.binary(l.0, op, r.0)?; + self.arithmetic(value, unknown, width) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deep_known_operands_reuse_the_original_comparison() { + let mut arena = SLTNodeArena::::new(); + let mut value = arena + .alloc(SLTNode::Input { + variable: SourceVarId::default(), + signed: false, + index: Vec::new(), + access: BitAccess::new(0, 31), + }) + .unwrap(); + for i in 0..512u32 { + let constant = arena + .alloc(SLTNode::Constant(i.into(), BigUint::default(), 32, false)) + .unwrap(); + value = arena + .alloc(SLTNode::Binary(value, BinaryOp::Xor, constant)) + .unwrap(); + } + let zero = arena + .alloc(SLTNode::Constant( + BigUint::default(), + BigUint::default(), + 32, + false, + )) + .unwrap(); + let expected = arena + .alloc(SLTNode::Binary(value, BinaryOp::EqCase, zero)) + .unwrap(); + let before = arena.len(); + assert_eq!( + compare(&mut arena, value, BinaryOp::EqCase, zero).unwrap(), + expected + ); + assert!( + arena.len() <= before + 1, + "known operands allocated shadow work for every node" + ); + } +} diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 246447ad5c8..0d066423299 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -583,7 +583,18 @@ impl<'p, 'a> Comb<'p, 'a> { expr: &sv::ir::Expr, context: Option<(usize, bool)>, ) -> Result { - let expr = expr_for_state_mode(expr, self.m.four_state); + self.eval_mode(store, frames, expr, context, false) + } + + fn eval_mode( + &mut self, + store: &mut Store, + frames: &[Frame], + expr: &sv::ir::Expr, + context: Option<(usize, bool)>, + preserve_literals: bool, + ) -> Result { + let expr = expr_for_state_mode(expr, self.m.four_state || preserve_literals); let expr = if self.m.calls(&expr) { self.hoist(store, frames, &expr)? } else { @@ -847,11 +858,14 @@ impl<'p, 'a> Comb<'p, 'a> { } } sources.extend(r_sources); - let rebuilt = if l == left && r == right { - node - } else { - self.alloc(SLTNode::Binary(l, op, r))? - }; + let rebuilt = + if !self.m.four_state && matches!(op, BinaryOp::EqCase | BinaryOp::NeCase) { + super::case_equality::compare(self.arena, l, op, r).map_err(slt_error)? + } else if l == left && r == right { + node + } else { + self.alloc(SLTNode::Binary(l, op, r))? + }; (rebuilt, sources) } SLTNode::Unary(op, inner) => { @@ -2285,7 +2299,13 @@ impl<'p, 'a> Comb<'p, 'a> { return Ok(conditions); } let selector_signed = self.expr_signed(selector); - let (selector_node, selector_sources) = self.eval(store, frames, selector, None)?; + let (selector_node, selector_sources) = self.eval_mode( + store, + frames, + selector, + None, + kind == sv::ir::CaseKind::Exact, + )?; let mut labels = Vec::with_capacity(items.len()); let mut width = self.width(selector_node); let mut all_signed = selector_signed; @@ -2296,7 +2316,8 @@ impl<'p, 'a> Comb<'p, 'a> { return Err(unsupported("range label outside case inside")); }; all_signed &= self.expr_signed(value); - let (node, sources) = self.eval(store, frames, value, None)?; + let (node, sources) = + self.eval_mode(store, frames, value, None, kind == sv::ir::CaseKind::Exact)?; width = width.max(self.width(node)); item_labels.push((node, sources)); } @@ -2307,8 +2328,14 @@ impl<'p, 'a> Comb<'p, 'a> { // equality: an unsigned operand also turns the others' operands // unsigned (11.8.2). let selector_node = if self.width(selector_node) < width || selector_signed != all_signed { - self.eval(store, frames, selector, Some((width, all_signed)))? - .0 + self.eval_mode( + store, + frames, + selector, + Some((width, all_signed)), + kind == sv::ir::CaseKind::Exact, + )? + .0 } else { selector_node }; @@ -2322,7 +2349,13 @@ impl<'p, 'a> Comb<'p, 'a> { && (self.width(*node) < width || self.expr_signed(value) != all_signed) { *node = self - .eval(store, frames, value, Some((width, all_signed)))? + .eval_mode( + store, + frames, + value, + Some((width, all_signed)), + kind == sv::ir::CaseKind::Exact, + )? .0; } } @@ -2337,7 +2370,12 @@ impl<'p, 'a> Comb<'p, 'a> { for (node, mut sources) in item_labels { let node = coerce_node_width(self.arena, node, Some(width), all_signed) .map_err(slt_error)?; - let matched = self.alloc(SLTNode::Binary(selector_node, op, node))?; + let matched = if !self.m.four_state && kind == sv::ir::CaseKind::Exact { + super::case_equality::compare(self.arena, selector_node, op, node) + .map_err(slt_error)? + } else { + self.alloc(SLTNode::Binary(selector_node, op, node))? + }; let matched = if kind == sv::ir::CaseKind::X { // A wildcard comparison returns X when only selector // unknowns prevent a definite match. casex ignores those @@ -2538,11 +2576,21 @@ impl<'p, 'a> Comb<'p, 'a> { ) -> Result, sv::AnalyzerError> { let none = vec![false; items.len()]; let mut probe = store.fork(); - let (selector_node, _) = self.eval(&mut probe, frames, selector, None)?; + let (selector_node, _) = self.eval_mode( + &mut probe, + frames, + selector, + None, + kind == sv::ir::CaseKind::Exact, + )?; let selector_width = self.width(selector_node); // A four-state selector also takes X and Z bits; only exact // comparisons of a narrow selector are enumerated. - let four_state_selector = !self.two_state(selector_node); + let four_state_selector = if self.m.four_state { + !self.two_state(selector_node) + } else { + !super::case_equality::is_known(self.arena, selector_node).map_err(slt_error)? + }; if four_state_selector && (kind != sv::ir::CaseKind::Exact || selector_width > 6) { return Ok(none); } @@ -2558,7 +2606,13 @@ impl<'p, 'a> Comb<'p, 'a> { sv::AnalyzerError, > { let signed = this.expr_signed(expr); - let (node, _) = this.eval(&mut probe, frames, expr, None)?; + let (node, _) = this.eval_mode( + &mut probe, + frames, + expr, + None, + kind == sv::ir::CaseKind::Exact, + )?; Ok(slt_const4(this.arena, &mut this.consts, node) .map(|(value, mask, width)| (value, mask, width, signed))) }; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6056876e786..06b4e932c0d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -969,6 +969,27 @@ impl<'p, 'a> Ff<'p, 'a> { stable(*id) } }; + if !self.m.four_state { + // Node IDs are topological. Cache exact comparisons before mapping + // their parents, reusing the existing graph/loop remapper. + for (index, expression) in arena.iter().enumerate() { + if let SLTNode::Binary(left, op @ (BinaryOp::EqCase | BinaryOp::NeCase), right) = + expression + { + let left = arena + .get(*left) + .map_addr(*left, arena, &mut mapped_arena, &mut cache, &map) + .map_err(slt_error)?; + let right = arena + .get(*right) + .map_addr(*right, arena, &mut mapped_arena, &mut cache, &map) + .map_err(slt_error)?; + let equal = super::case_equality::compare(&mut mapped_arena, left, *op, right) + .map_err(slt_error)?; + cache.insert(NodeId(index), equal); + } + } + } let mapped = arena .get(node) .map_addr(node, arena, &mut mapped_arena, &mut cache, &map) diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 1f445fb33a2..3b8390d9a8b 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2211,7 +2211,7 @@ pub(super) fn slt_unknown( ) -> Result { let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); arena - .alloc(SLTNode::Constant(BigUint::default(), mask, width, false)) + .alloc(SLTNode::Constant(mask.clone(), mask, width, false)) .map_err(slt_error) } diff --git a/crates/celox-slt/src/const_inline.rs b/crates/celox-slt/src/const_inline.rs index 172056809e7..720faf7836c 100644 --- a/crates/celox-slt/src/const_inline.rs +++ b/crates/celox-slt/src/const_inline.rs @@ -1,8 +1,9 @@ //! Constant variable inlining for combinational logic paths. //! //! Detects variables whose *every* LogicPath target is a constant expression -//! (no runtime inputs), then rewrites all `SLTNode::Input` references to those -//! variables with `SLTNode::Constant` nodes containing the precomputed value. +//! (no runtime inputs), whose reads are all covered by those drivers, then +//! rewrites their `SLTNode::Input` references to precomputed constants. +//! Variables with reads of undriven ranges retain their state dependencies. //! This eliminates the Store→Load memory roundtrip for compile-time constants //! such as genvar-expanded parity-check matrices. @@ -226,6 +227,17 @@ struct ConstVar { payload: BigUint, /// Combined 4-state mask. mask: BigUint, + /// Sorted, merged driven ranges. Bits outside them retain their state. + written: Vec, +} + +impl ConstVar { + fn covers(&self, access: BitAccess) -> bool { + let index = self.written.partition_point(|range| range.msb < access.lsb); + self.written + .get(index) + .is_some_and(|range| range.lsb <= access.lsb && range.msb >= access.msb) + } } /// Inline constant variables: rewrite Input references → Constant nodes. @@ -305,9 +317,42 @@ pub fn inline_constant_variables( if mask != BigUint::from(0u32) { continue; } - const_vars.insert(var.clone(), ConstVar { payload, mask }); + // Do not invent zeroes for undriven bits. Keep coverage as ranges, + // so a sparse driver does not allocate a mask up to its bit offset. + let mut written: Vec<_> = entries.iter().map(|(access, _)| *access).collect(); + written.sort_unstable_by_key(|access| access.lsb); + written.dedup_by(|next, previous| { + if next.lsb <= previous.msb.saturating_add(1) { + previous.msb = previous.msb.max(next.msb); + true + } else { + false + } + }); + const_vars.insert( + var.clone(), + ConstVar { + payload, + mask, + written, + }, + ); } + // All reads must be covered before removing a variable's dependency + // edges. A read can include undriven bits even above the highest driver, + // or a hole between drivers; those bits retain their initial state. + for node in arena.iter() { + if let SLTNode::Input { + variable, access, .. + } = node + && const_vars + .get(variable) + .is_some_and(|cv| !cv.covers(*access)) + { + const_vars.remove(variable); + } + } if const_vars.is_empty() { return Ok(false); } @@ -559,6 +604,99 @@ mod tests { use super::eval_const_expr; + #[test] + fn only_inlines_reads_covered_by_constant_drivers() { + use crate::{LogicPath, LogicPathTarget}; + use celox_design::{BitAccess, VarAtomBase}; + + for bridge_gap in [false, true] { + for access in [ + BitAccess::new(2, 3), + BitAccess::new(0, 3), + BitAccess::new(4, 7), + BitAccess::new(0, 7), + ] { + let mut arena = SLTNodeArena::::new(); + let one = arena + .alloc(SLTNode::Constant(1u8.into(), 0u8.into(), 1, false)) + .unwrap(); + let zero = arena + .alloc(SLTNode::Constant(0u8.into(), 0u8.into(), 1, false)) + .unwrap(); + let three = arena + .alloc(SLTNode::Constant(3u8.into(), 0u8.into(), 2, false)) + .unwrap(); + let make_path = |variable, access, expr, sources: crate::HashSet<_>| LogicPath { + transparent_copy: false, + target: LogicPathTarget::Var(VarAtomBase { + id: variable, + access, + }), + previous_sources: sources.clone(), + address_sources: sources.clone(), + sources, + local_inputs: vec![], + order_before: Default::default(), + comb_capture_enable_sites: vec![], + comb_capture_enable_always: false, + pre_lower_nodes: vec![], + expr, + }; + // Non-sorted fragments. Filling bit 1 makes 0..=3 contiguous, + // but never covers higher bits. Unobserved gaps do not stop + // reads confined to the driven bits from being inlined. + let mut paths = vec![ + make_path(1, BitAccess::new(2, 3), three, Default::default()), + make_path(1, BitAccess::new(0, 0), one, Default::default()), + ]; + if bridge_gap { + paths.push(make_path(1, BitAccess::new(1, 1), zero, Default::default())); + } + let input = arena + .alloc(SLTNode::Input { + variable: 1, + signed: false, + index: vec![], + access, + }) + .unwrap(); + let source = VarAtomBase { id: 1, access }; + paths.push(make_path( + 2, + BitAccess::new(0, access.msb - access.lsb), + input, + [source].into_iter().collect(), + )); + let inlined = access == BitAccess::new(2, 3) + || (access == BitAccess::new(0, 3) && bridge_gap); + assert_eq!( + super::inline_constant_variables(&mut paths, &mut arena).unwrap(), + inlined + ); + let path = paths.last().unwrap(); + if inlined { + let expected = if access.lsb == 2 { 3u8 } else { 13u8 }; + assert_eq!( + super::eval_const_expr(path.expr, &arena), + (expected.into(), 0u8.into(), access.msb - access.lsb + 1) + ); + } else { + assert_eq!( + path.expr, input, + "read of an undriven bit became a constant" + ); + } + for edges in [&path.sources, &path.previous_sources, &path.address_sources] { + assert_eq!( + edges.contains(&source), + !inlined, + "dependency of an unrewritten read was removed" + ); + } + } + } + } + #[test] fn floating_operations_fold_ieee_payloads_and_result_widths() { use celox_design::{BinaryOp, FloatBinaryOp, FloatPrecision, FloatUnaryOp}; diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index a523b192871..4057357db90 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -869,3 +869,15 @@ Verilator 5.052 records 2 passes, 3 mismatches, 3 compiler faults, and 1 unsupported four-state case; Icarus 13.0 records 9 compile errors. In the Reactive-wakeup case, xezim loses the matured Observed report, while Verilator also emits the Final report that the wait resumption must flush. + +### Z expressions inside exact comparisons in Verilator + +The `operators::two_state_case_equality_*` regressions keep runtime storage +two-state while testing literal X/Z in expressions (IEEE 1800-2023 11.4.5 +and 12.5; issue #2136). Icarus 13.0 passes all five cases. Verilator 5.052 +passes `keeps_call_effects_and_loaded_bytes`, but rejects the other four +with `Unsupported tristate construct` or `Unsupported: tristate in top-level IO`. +Their actual compile diagnostics are retained in +[the Verilator operators report](verification/sv/verilator/operators.json); +they remain executed cases rather than exclusions. Reproduce with +`verify-sv-verilator --filter two_state_case_equality --jobs 1`. diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index fceded314db..352e9b1e1dc 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1900,3 +1900,167 @@ endmodule (assert_eq a_count 1) (assert_eq b_count 1) (assert_eq y 0)) + +(case two_state_case_equality_preserves_unknown_literals + ; IEEE 1800-2023 11.4.5 and 12.5: X/Z participate in exact comparisons. + (source "two_state_case_literals.sv" #" + module Top(input bit clk, input bit [7:0] b, + output logic parity_x, reversed_x, exact_z, different_x, + output logic ordinary_case, output logic [3:0] registered, + output logic [7:0] guarded); + assign parity_x = ((^b) === 1'bx); + assign reversed_x = (1'bx === (^b)); + assign exact_z = (b === 8'b1001_011z); + assign different_x = (b !== 8'b1001_011x); + assign guarded = ((^b) === 1'bx) ? 8'b0 : b; + always_comb begin + case (b) + 8'b1001_011z: ordinary_case = 1; + default: ordinary_case = 0; + endcase + end + always_ff @(posedge clk) begin + registered[0] <= ((^b) === 1'bx); + registered[1] <= (b === 8'b1001_011x); + registered[2] <= (b !== 8'b1001_011z); + case (b) + 8'b1001_011x: registered[3] <= 1; + default: registered[3] <= 0; + endcase + end + endmodule + "#) + (top Top) + (set b 0x96) + (assert_eq parity_x 0) + (assert_eq reversed_x 0) + (assert_eq exact_z 0) + (assert_eq different_x 1) + (assert_eq ordinary_case 0) + (assert_eq guarded 0x96) + (tick clk) + (assert_eq registered 4) + (set b 0x97) + (assert_eq parity_x 0) + (assert_eq different_x 1) + (assert_eq guarded 0x97) + (tick clk) + (assert_eq registered 4) + (set b 0) + (assert_eq parity_x 0) + (assert_eq guarded 0)) + +(case two_state_case_equality_compares_literal_structure + (source "two_state_case_structure.sv" #" + module Top(input bit [7:0] b, input bit [128:0] wide, + output logic same_x, x_vs_z, mixed_equal, signed_x, signed_z, + output logic unsigned_x, wide_x, bit_cast); + function automatic bit to_bit(input logic value); return value; endfunction + assign same_x = ({b,1'bx} === {b,1'bx}); + assign x_vs_z = ({b,1'bx} === {b,1'bz}); + assign mixed_equal = ({b,1'bx} === {8'h96,1'bx}); + assign signed_x = (4'sbx001 === 8'sbxxxxx001); + assign signed_z = (4'sbz001 === 8'sbzzzzz001); + assign unsigned_x = (4'sbx001 === 8'bxxxxx001); + assign wide_x = (wide === {64'd0,1'bx,64'd0}); + assign bit_cast = (to_bit(1'bx) === 1'b0); + endmodule + "#) + (top Top) + (modify (set b 0x96) (set wide 0)) + (assert_eq same_x 1) + (assert_eq x_vs_z 0) + (assert_eq mixed_equal 1) + (assert_eq signed_x 1) + (assert_eq signed_z 1) + (assert_eq unsigned_x 0) + (assert_eq wide_x 0) + (assert_eq bit_cast 1) + (set b 0x97) + (assert_eq mixed_equal 0)) + +(case two_state_case_equality_preserves_conditional_unknowns + (source "two_state_case_mux.sv" #" + module Top(input bit s, output logic x_match, z_match, same_known, + output logic ordinary_case); + assign x_match = ((s ? 1'bx : 1'b0) === 1'bx); + assign z_match = ((s ? 1'bz : 1'b0) === 1'bz); + assign same_known = ((s ? 1'bx : 1'b0) === 1'b0); + always_comb begin + case (s ? 1'bz : 1'b0) + 1'bz: ordinary_case = 1; + default: ordinary_case = 0; + endcase + end + endmodule + "#) + (top Top) + (set s 0) + (assert_eq x_match 0) + (assert_eq z_match 0) + (assert_eq same_known 1) + (assert_eq ordinary_case 0) + (set s 1) + (assert_eq x_match 1) + (assert_eq z_match 1) + (assert_eq same_known 0) + (assert_eq ordinary_case 1)) + +(case two_state_case_equality_keeps_call_effects_and_loaded_bytes + (source "two_state_case_effects.sv" #" + module Top(input bit [7:0] b, output int calls, + output logic compared, selected, output logic [7:0] loaded); + function automatic logic [7:0] mark(); + calls = calls + 1; + return b; + endfunction + initial begin + calls = 0; + #1; + compared = (mark() === 8'b1001_011x); + case (mark()) + 8'b1001_011z: selected = 1; + default: selected = 0; + endcase + loaded = ((^b) === 1'bx) ? 8'b0 : b; + #1 $finish; + end + endmodule + "#) + (top Top) + (run_until 0) + (set b 0x96) + (run_until 1) + (assert_eq calls 2) + (assert_eq compared 0) + (assert_eq selected 0) + (assert_eq loaded 0x96) + (run_to_finish)) + +(case two_state_case_equality_keeps_unknown_expression_bits + (source "two_state_case_expression.sv" #" + module Top(input bit b, output logic [16:0] q); + assign q[0] = ((b & 1'bx) === 1'bx); + assign q[1] = ((b | 1'bx) === 1'bx); + assign q[2] = ((b ^ 1'bz) === 1'bx); + assign q[3] = ((b && 1'bx) === 1'bx); + assign q[4] = ((b || 1'bx) === 1'bx); + assign q[5] = (({b,b} + 2'b0x) === 2'bxx); + assign q[6] = (({b,b} >> 1'bx) === 2'bxx); + assign q[7] = ((^{b,1'bx}) === 1'bx); + assign q[8] = ((&{b,1'bx}) === 1'bx); + assign q[9] = ((|{b,1'bz}) === 1'bx); + assign q[10] = ((!{b,1'bz}) === 1'bx); + assign q[11] = ((~{b,1'bz}) === {~b,1'bx}); + assign q[12] = ((b == 1'bx) === 1'bx); + assign q[13] = (({b,1'b0} == {1'bx,1'b1}) === 1'b0); + assign q[14] = ((1'b1 / b) === 1'bx); + assign q[15] = ((1'bx ? {b,1'bz} : {b,1'bz}) === {b,1'bz}); + assign q[16] = ((1'bx ? b : ~b) === 1'bx); + endmodule + "#) + (top Top) + (set b 0) + (assert_eq q 0x1fef6) + (set b 1) + (assert_eq q 0x1b9ed)) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index fd791951f59..a99e9df55c4 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -322,6 +322,20 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { "compile", "packed array parameters are not supported yet", ), + ( + "verilator", + "operators::two_state_case_equality_compares_literal_structure" + | "operators::two_state_case_equality_preserves_conditional_unknowns" + | "operators::two_state_case_equality_keeps_unknown_expression_bits", + ) => ("compile_error", "compile", "Unsupported tristate construct"), + ( + "verilator", + "operators::two_state_case_equality_preserves_unknown_literals", + ) => ( + "compile_error", + "compile", + "Unsupported: tristate in top-level IO", + ), _ => panic!("unreviewed failure: {tool} {name}: {status}"), }; assert_eq!(status, expected_status, "{name}"); diff --git a/crates/celox-test-suite/verification/sv/verilator/operators.json b/crates/celox-test-suite/verification/sv/verilator/operators.json index a71785fcc6f..a9fd197737d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/operators.json +++ b/crates/celox-test-suite/verification/sv/verilator/operators.json @@ -386,6 +386,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHEXPAND: /source_0.sv:9:35: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbx001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 9 | assign signed_x = (4'sbx001 === 8'sbxxxxx001);\n | ^~~\n ... For warning description see https://verilator.org/warn/WIDTHEXPAND?v=5.052\n ... Use \"/* verilator lint_off WIDTHEXPAND */\" and lint_on around source to disable this message.\n%Warning-WIDTHEXPAND: /source_0.sv:10:35: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbz001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 10 | assign signed_z = (4'sbz001 === 8'sbzzzzz001);\n | ^~~\n%Warning-WIDTHEXPAND: /source_0.sv:11:37: Operator EQCASE expects 8 bits on the LHS, but LHS's CONST '4'sbx001' generates 4 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 11 | assign unsigned_x = (4'sbx001 === 8'bxxxxx001);\n | ^~~\n%Error-UNSUPPORTED: /source_0.sv:7:33: Unsupported tristate construct: EQCASE\n : ... note: In instance 'celox_suite_tb.dut'\n 7 | assign x_vs_z = ({b,1'bx} === {b,1'bz});\n | ^~~\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_compares_literal_structure", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:13:24: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's REPLICATE generates 2 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 13 | assign q[10] = ((!{b,1'bz}) === 1'bx);\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHTRUNC?v=5.052\n ... Use \"/* verilator lint_off WIDTHTRUNC */\" and lint_on around source to disable this message.\n%Error-UNSUPPORTED: /source_0.sv:5:25: Unsupported tristate construct: XOR\n : ... note: In instance 'celox_suite_tb.dut'\n 5 | assign q[2] = ((b ^ 1'bz) === 1'bx);\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error-UNSUPPORTED: /source_0.sv:14:24: Unsupported tristate construct: NOT\n : ... note: In instance 'celox_suite_tb.dut'\n 14 | assign q[11] = ((~{b,1'bz}) === {~b,1'bx});\n | ^\n%Error-UNSUPPORTED: /source_0.sv:18:52: Unsupported tristate construct: EQCASE\n : ... note: In instance 'celox_suite_tb.dut'\n 18 | assign q[15] = ((1'bx ? {b,1'bz} : {b,1'bz}) === {b,1'bz});\n | ^~~\n%Error: Exiting due to 3 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_keeps_unknown_expression_bits", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:5:28: Unsupported tristate construct: NOT\n : ... note: In instance 'celox_suite_tb.dut'\n 5 | assign z_match = ((s ? 1'bz : 1'b0) === 1'bz);\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error-UNSUPPORTED: /source_0.sv:8:17: Unsupported tristate construct (not in propagation graph): AND\n : ... note: In instance 'celox_suite_tb.dut'\n 8 | case (s ? 1'bz : 1'b0)\n | ^\n%Error-UNSUPPORTED: /source_0.sv:8:9: Unsupported tristate construct: CASE\n : ... note: In instance 'celox_suite_tb.dut'\n 8 | case (s ? 1'bz : 1'b0)\n | ^~~~\n%Error: Exiting due to 3 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_preserves_conditional_unknowns", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Operators", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /testbench.sv:14:26: Unsupported: tristate in top-level IO: 'b'\n : ... note: In instance 'celox_suite_tb'\n 14 | Top dut (.clk(i_clk), .b(i_b), .parity_x(), .reversed_x(), .exact_z(), .different_x(), .ordinary_case(), .registered(), .guarded());\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "operators::two_state_case_equality_preserves_unknown_literals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Operators", "detail": "four-state expectations", diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 7be6789e3d7..ce52b3583be 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -205,4 +205,19 @@ sv_backends! { fn wide_reduction_and_respects_partial_storage_words(sim) { @case "operators::wide_reduction_and_respects_partial_storage_words"; } + fn two_state_case_equality_preserves_unknown_literals(sim) { + @case "operators::two_state_case_equality_preserves_unknown_literals"; + } + fn two_state_case_equality_compares_literal_structure(sim) { + @case "operators::two_state_case_equality_compares_literal_structure"; + } + fn two_state_case_equality_preserves_conditional_unknowns(sim) { + @case "operators::two_state_case_equality_preserves_conditional_unknowns"; + } + fn two_state_case_equality_keeps_call_effects_and_loaded_bytes(sim) { + @case "operators::two_state_case_equality_keeps_call_effects_and_loaded_bytes"; + } + fn two_state_case_equality_keeps_unknown_expression_bits(sim) { + @case "operators::two_state_case_equality_keeps_unknown_expression_bits"; + } } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 5c9d4afab27..687fd7cea73 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -838,11 +838,20 @@ fn initializes_partially_driven_internal_nets_to_z() { assign undriven_bits_are_z = (w[7:1] === 7'bzzzzzzz); endmodule "#; - let mut sim = - Simulator::from_sv_sources(vec![(source, Path::new("partial_internal_net.sv"))], "Top") - .build_cranelift() - .unwrap(); - assert_eq!(sim.get(sim.signal("undriven_bits_are_z")), 1u8.into()); + // Runtime storage retains X/Z only in four-state mode. Literal X/Z + // in exact comparisons remain distinct from zero in both modes. + for four_state in [false, true] { + let mut sim = + Simulator::from_sv_sources(vec![(source, Path::new("partial_internal_net.sv"))], "Top") + .four_state(four_state) + .build_cranelift() + .unwrap(); + assert_eq!( + sim.get_four_state(sim.signal("undriven_bits_are_z")), + (u8::from(four_state).into(), BigUint::default()), + "four_state={four_state}", + ); + } } #[test] @@ -893,11 +902,22 @@ fn initializes_shadowing_function_locals_to_unknown() { assign local_is_unknown = (f() === 1'bx); endmodule "#; - let mut sim = - Simulator::from_sv_sources(vec![(source, Path::new("function_local_shadow.sv"))], "Top") - .build_cranelift() - .unwrap(); - assert_eq!(sim.get(sim.signal("local_is_unknown")), 1u8.into()); + // Runtime storage retains X/Z only in four-state mode. Literal X/Z + // in exact comparisons remain distinct from zero in both modes. + for four_state in [false, true] { + let mut sim = Simulator::from_sv_sources( + vec![(source, Path::new("function_local_shadow.sv"))], + "Top", + ) + .four_state(four_state) + .build_cranelift() + .unwrap(); + assert_eq!( + sim.get_four_state(sim.signal("local_is_unknown")), + (u8::from(four_state).into(), BigUint::default()), + "four_state={four_state}", + ); + } } #[test] diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index 7eb2f628a7a..80f5b766cf4 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -329,6 +329,10 @@ test("every retained baseline accepts only its existing failures", () => { "fork_deferred::reused_slot_cannot_flush_completed_reports", "fork_deferred::sibling_event_queues_are_independent", "fork_deferred::sibling_wait_queues_are_independent", + "operators::two_state_case_equality_compares_literal_structure", + "operators::two_state_case_equality_keeps_unknown_expression_bits", + "operators::two_state_case_equality_preserves_conditional_unknowns", + "operators::two_state_case_equality_preserves_unknown_literals", "tagged_unions::conditional_struct_payload", "tagged_unions::constructors_and_checked_members", "tagged_unions::default_arguments",