diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b5734b32718..b2398904802 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -10686,6 +10686,45 @@ fn inferred_clock( mod tests { use super::*; + #[test] + fn stateless_function_scratch_loops_do_not_become_runtime_loops() { + let source = r#"module Top(input wire [255:0] d, output wire [255:0] q); + function [15:0][15:0] pattern(); + logic [15:0] words [15:0]; + for (int i=0; i<16; i++) words[i] = 16'b1 << i; + for (int i=0; i<16; i++) for (int j=0; j<16; j++) pattern[i][j] = words[i][j]; + endfunction + assign q = d ^ pattern(); + endmodule"#; + for four_state in [false, true] { + let output = schedule_sources( + &[(source, Path::new("top.sv"))], + "Top", + &[], + &[], + &[], + four_state, + &celox_frontend_core::ParallelScheduleOptions::default(), + &FrontendTraceOptions::default(), + None, + &mut Vec::new(), + ) + .unwrap(); + let instructions: usize = output + .scheduled + .sir + .eval_comb + .iter() + .flat_map(|unit| unit.blocks.values()) + .map(|block| block.instructions.len()) + .sum(); + assert!( + instructions < 32, + "constant scratch loops produced {instructions} runtime instructions" + ); + } + } + #[test] fn bit_select_width_does_not_evaluate_a_runtime_zero_sample() { let index = sv::ir::ConstExpr::Ident("index".into()); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 0d066423299..e95c646270d 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3288,6 +3288,17 @@ impl<'p, 'a> Comb<'p, 'a> { args: &[Option], arg_order: &[usize], ) -> Result, sv::AnalyzerError> { + if args.is_empty() + && let Some(literal) = self.m.constant_functions.value(name) + { + let node = self.alloc(SLTNode::Constant( + literal.value, + literal.mask, + literal.width, + literal.signed, + ))?; + return Ok(Some((node, Sources::default()))); + } let subroutine = self .m .subroutine(name) diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 3b8390d9a8b..ef3830e1fc5 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -46,6 +46,7 @@ pub(super) struct ProcModule<'a> { pub constants: &'a HashMap, pub parameter_types: &'a HashMap, pub subroutines: HashMap, + pub constant_functions: sv::RuntimeConstantFunctions<'a>, /// DPI-C imports of the module, by SystemVerilog name. pub dpi_imports: HashMap, /// Extern functions the module calls, by local index. @@ -246,6 +247,7 @@ impl<'a> ProcModule<'a> { constants, parameter_types, subroutines, + constant_functions: sv::RuntimeConstantFunctions::new(module, constants, four_state), dpi_imports, extern_functions: Vec::new(), extern_calls: 0, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index ab30c9180e9..4897f5fdc04 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -9,6 +9,8 @@ mod value; use value::Value; +mod runtime; +pub use runtime::RuntimeConstantFunctions; use num_bigint::BigUint; use std::cell::{Cell, RefCell}; @@ -49,6 +51,8 @@ pub(crate) struct State { functions: RefCell, revision: generate::Revision, depth: Cell, + runtime_fuel: Cell>, + runtime_two_state: Cell>, argument_names: RefCell<( Arc, Arc>>, @@ -891,6 +895,7 @@ pub(super) fn eval_call_literal( fn call_value(name: &str, args: &[Value], constants: &dyn ConstantEnvironment) -> Option { let state = constants.function_state()?; + runtime::charge(state)?; let functions = state.functions.borrow().functions.clone(); let function = functions.get(name)?; let depth = state.depth.get(); @@ -944,7 +949,8 @@ fn call_in_frame( let (return_name, return_type) = function.return_var.as_ref()?; frame.declare(return_name, return_type)?; frame.return_width = Some(frame.type_of(return_name)?.0); - frame.set(return_name, Value::integer(0))?; + let initial = frame.initial_value(return_name)?; + frame.set(return_name, initial)?; match frame.block(&function.body)? { Flow::Return(Some(value)) => { frame.set(return_name, value)?; @@ -1034,15 +1040,49 @@ impl<'a> Frame<'a> { } fn declare(&mut self, name: &str, r#type: &crate::ir::Type) -> Option<()> { - if !r#type.unpacked_ranges().is_empty() { + if self + .constants + .function_state() + .is_some_and(|state| state.runtime_two_state.get().is_some()) + && matches!( + r#type.kind(), + crate::ir::TypeKind::Real + | crate::ir::TypeKind::Shortreal + | crate::ir::TypeKind::String + | crate::ir::TypeKind::Object + ) + { + return None; + } + if !r#type.unpacked_ranges().is_empty() + && self + .constants + .function_state()? + .runtime_two_state + .get() + .is_none() + { return None; } - let width = r#type - .resolved_width() - .or_else(|| { - crate::typecheck::resolve_packed_width_in_env(r#type.packed_ranges(), self) - })? - .max(1); + // Resolved runtime types already include unpacked dimensions. + // Elaboration types still need their dimensions evaluated here. + let width = if let Some(width) = r#type.resolved_width() { + width.max(1) + } else { + let mut width = + crate::typecheck::resolve_packed_width_in_env(r#type.packed_ranges(), self)?.max(1); + for range in r#type.unpacked_ranges() { + let (left, right) = range.resolved_bounds().or_else(|| { + Some(( + self.eval_lowered(range.left())?, + self.eval_lowered(range.right())?, + )) + })?; + let count = usize::try_from(left.abs_diff(right)).ok()?.checked_add(1)?; + width = width.checked_mul(count)?; + } + width + }; if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; } @@ -1054,12 +1094,29 @@ impl<'a> Frame<'a> { Some(()) } + fn initial_value(&self, name: &str) -> Option { + let runtime = self + .constants + .function_state() + .and_then(|state| state.runtime_two_state.get()); + if runtime == Some(true) || self.two_state.contains(name) { + return Some(Value::integer(0)); + } + let (width, _) = self.type_of(name)?; + typecheck::parse_integral_literal(&format!("{width}'bx")).map(Value::from_literal) + } + fn set(&mut self, name: &str, value: Value) -> Option<()> { let value = match self.type_of(name) { Some((width, signed)) => value.resize(width, signed)?, None => value, }; - let value = if self.two_state.contains(name) { + let value = if self.two_state.contains(name) + || self + .constants + .function_state() + .is_some_and(|state| state.runtime_two_state.get() == Some(true)) + { value.into_two_state() } else { value @@ -1069,6 +1126,9 @@ impl<'a> Frame<'a> { } fn tick(&mut self) -> Option<()> { + if let Some(state) = self.constants.function_state() { + runtime::charge(state)?; + } self.iterations += 1; (self.iterations <= MAX_ITERATIONS).then_some(()) } @@ -1107,6 +1167,112 @@ impl<'a> Frame<'a> { self.eval_lowered(&lowered).map(Value::integer) } + fn case_operand(&mut self, expr: &Expr, context: ExprType) -> Option { + if context.width > constant_folding::MAX_CONSTANT_CONCAT_BITS { + return None; + } + let lowered = self.lower(expr)?.into(); + typecheck::eval_case_operand_in_env( + &lowered, + self, + &|name| self.type_of(name), + context.width, + context.signed, + ) + .map(Value::from_literal) + } + + /// Type queries must not execute a case label or select a conditional arm. + fn expression_type(&self, expr: &Expr) -> Option { + let ty = |(width, signed)| ExprType { width, signed }; + let placeholder = |ty: ExprType| ConstExpr::Resize { + expr: Box::new(ConstExpr::Literal("0".into())), + width: ty.width, + signed: ty.signed, + }; + let expression = match expr { + Expr::Ident(name) => { + return self.type_of(name).map(ty).or_else(|| { + self.constants + .literal(name) + .map(|value| ty((value.width, value.signed))) + }); + } + Expr::Literal(text) => { + // An unbased unsized fill is one bit in a self-determined + // type query; its value fills the eventual case context. + if matches!( + text.trim().to_ascii_lowercase().as_str(), + "'0" | "'1" | "'x" | "'z" | "'?" + ) { + return Some(ty((1, false))); + } + return typecheck::integral_literal_type_metadata(text).map(ty); + } + Expr::Resize { width, signed, .. } => return Some(ty((*width, *signed))), + Expr::Inside { .. } => return Some(ty((1, false))), + Expr::Select { + msb, lsb, signed, .. + } => { + let msb = self.eval_lowered(&msb.clone().into())?; + let lsb = self.eval_lowered(&lsb.clone().into())?; + return Some(ty(( + usize::try_from(msb.abs_diff(lsb)).ok()?.checked_add(1)?, + *signed, + ))); + } + Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => { + let width = parts.iter().try_fold(0usize, |width, part| { + width.checked_add(self.expression_type(part)?.width) + })?; + let count = if let Expr::RepeatConcat { count, .. } = expr { + usize::try_from(self.eval_lowered(&count.clone().into())?).ok()? + } else { + 1 + }; + return Some(ty((width.checked_mul(count)?, false))); + } + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => { + let functions = self.constants.function_state()?.functions.borrow(); + let (_, result) = functions.functions.get(name)?.return_var.as_ref()?; + let width = result.resolved_width().or_else(|| { + typecheck::resolve_packed_width_in_env(result.packed_ranges(), self) + })?; + return Some(ty((width, result.is_signed()))); + } + Expr::Call { callee, args, .. } => ConstExpr::Function { + callee: callee.clone(), + args: args + .iter() + .map(|arg| Some(placeholder(self.expression_type(arg.as_ref()?)?))) + .collect::>()?, + site: None, + }, + Expr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: Box::new(placeholder(self.expression_type(expr)?)), + }, + Expr::Binary { left, op, right } => ConstExpr::Binary { + left: Box::new(placeholder(self.expression_type(left)?)), + op: *op, + right: Box::new(placeholder(self.expression_type(right)?)), + }, + Expr::Mux { + then_expr, + else_expr, + .. + } => ConstExpr::Mux { + condition: Box::new(ConstExpr::Literal("0".into())), + then_expr: Box::new(placeholder(self.expression_type(then_expr)?)), + else_expr: Box::new(placeholder(self.expression_type(else_expr)?)), + }, + }; + infer_const_expr_type(&expression, &HashMap::default()) + } + fn truth(&mut self, expr: &Expr) -> Option { // An unknown procedural condition does not select the then branch. Some(self.eval(expr)?.truth() == Some(true)) @@ -1124,7 +1290,7 @@ impl<'a> Frame<'a> { /// `expr` as a constant expression, with the parts the constant /// evaluator does not model replaced by typed temporaries. fn lower(&mut self, expr: &Expr) -> Option { - Some(match expr { + let lowered = match expr { Expr::Ident(name) => ConstExpr::Ident(name.clone()), Expr::Literal(value) => ConstExpr::Literal(value.clone()), Expr::Unary { op, expr } => ConstExpr::Unary { @@ -1215,30 +1381,8 @@ impl<'a> Frame<'a> { width: *width, signed: *signed, }, - Expr::Inside { expr, items } => { - let mut found = false; - for item in items { - found |= match item { - InsideItem::Value(item) => self.truth(&Expr::Binary { - left: expr.clone(), - op: BinaryOp::EqWildcard, - right: Box::new(item.clone()), - })?, - InsideItem::Range { low, high } => { - self.truth(&Expr::Binary { - left: Box::new(low.clone()), - op: BinaryOp::Le, - right: expr.clone(), - })? && self.truth(&Expr::Binary { - left: expr.clone(), - op: BinaryOp::Le, - right: Box::new(high.clone()), - })? - } - }; - } - ConstExpr::Literal(format!("1'b{}", u8::from(found))) - } + Expr::Inside { expr, items } => self.lower_inside(expr, items)?, + Expr::Concat(_) | Expr::RepeatConcat { .. } => { let literal = self.concat_literal(expr)?; if literal.width == 0 { @@ -1246,7 +1390,73 @@ impl<'a> Frame<'a> { } self.temporary(Value::from_literal(literal))? } - }) + }; + // Runtime two-state evaluation discards X/Z at operation boundaries. + // This interpreter uses four-state expression rules. Only reuse a + // result when every intermediate is known; otherwise runtime lowering + // supplies the state-mode semantics (including out-of-range selects). + if self + .constants + .function_state() + .is_some_and(|state| state.runtime_two_state.get() == Some(true)) + { + let literal = typecheck::eval_const_integral_literal_in_env( + &lowered.clone().into(), + self, + &|name| self.type_of(name), + )?; + if literal.mask != BigUint::default() { + return None; + } + } + Some(lowered) + } + + #[inline(never)] + fn lower_inside(&mut self, expr: &Expr, items: &[InsideItem]) -> Option { + // Keep comparisons as four-state expressions. Procedural truth + // would turn an unknown membership result into a known zero. + let selector = self.lower(expr)?; + let mut result = Some(false); + for item in items { + let comparison = match item { + InsideItem::Value(item) => ConstExpr::Binary { + left: Box::new(selector.clone()), + op: BinaryOp::EqWildcard, + right: Box::new(self.lower(item)?), + }, + InsideItem::Range { low, high } => ConstExpr::Binary { + left: Box::new(ConstExpr::Binary { + left: Box::new(self.lower(low)?), + op: BinaryOp::Le, + right: Box::new(selector.clone()), + }), + op: BinaryOp::LogicAnd, + right: Box::new(ConstExpr::Binary { + left: Box::new(selector.clone()), + op: BinaryOp::Le, + right: Box::new(self.lower(high)?), + }), + }, + }; + let comparison = + typecheck::eval_const_integral_literal_in_env(&comparison.into(), self, &|name| { + self.type_of(name) + })?; + result = match (result, typecheck::integral_literal_truth(&comparison)) { + (Some(true), _) | (_, Some(true)) => Some(true), + (Some(false), Some(false)) => Some(false), + _ => None, + }; + } + Some(ConstExpr::Literal( + match result { + Some(true) => "1'b1", + Some(false) => "1'b0", + None => "1'bx", + } + .into(), + )) } /// Fold concatenations with each operand's own width before the surrounding @@ -1325,7 +1535,19 @@ impl<'a> Frame<'a> { } self.set(name, value)?; } - LValue::Select { name, msb, lsb, .. } => { + LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + .. + } => { + // Aggregate slice ordering needs element-aware assignment; + // leave that call to the ordinary runtime lowering. + if array_slice_width.is_some() || *array_slice_reversed { + return None; + } let msb = self.eval_lowered(&msb.clone().into())?; let lsb = self.eval_lowered(&lsb.clone().into())?; let old = self.values.get(name)?.clone(); @@ -1336,7 +1558,82 @@ impl<'a> Frame<'a> { Some(()) } + #[inline(never)] + fn case_statement( + &mut self, + kind: CaseKind, + selector: &Expr, + items: &[crate::procedural::CaseItemBase], + default: Option<&[Stmt]>, + ) -> Option { + if matches!(kind, CaseKind::Z | CaseKind::X) { + return None; + } + // All labels contribute to the common type, including labels + // after the first match (12.5). Query their types without + // executing them; labels are evaluated only in source order. + let mut context = self.expression_type(selector)?; + if kind == CaseKind::Exact { + for item in items { + for label in &item.labels { + let CaseLabel::Value(value) = label else { + return None; + }; + let ty = self.expression_type(value)?; + context.width = context.width.max(ty.width); + context.signed &= ty.signed; + } + } + } + let selector = if kind == CaseKind::Exact { + self.case_operand(selector, context)? + } else { + self.eval(selector)? + }; + let ConstExpr::Ident(selector) = self.temporary(selector)? else { + return None; + }; + for item in items { + for label in &item.labels { + let comparison = match (&kind, label) { + (CaseKind::Inside, label) => Expr::Inside { + expr: Box::new(Expr::Ident(selector.clone())), + items: vec![match label { + CaseLabel::Value(value) => InsideItem::Value(value.clone()), + CaseLabel::Range { low, high } => InsideItem::Range { + low: low.clone(), + high: high.clone(), + }, + }], + }, + (_, CaseLabel::Value(value)) => { + let value = self.case_operand(value, context)?; + let ConstExpr::Ident(value) = self.temporary(value)? else { + return None; + }; + Expr::Binary { + left: Box::new(Expr::Ident(selector.clone())), + op: BinaryOp::EqCase, + right: Box::new(Expr::Ident(value)), + } + } + (_, CaseLabel::Range { .. }) => return None, + }; + if self.truth(&comparison)? { + return self.block(&item.body); + } + } + } + if let Some(default) = default { + return self.block(default); + } + Some(Flow::Next) + } + fn stmt(&mut self, stmt: &Stmt) -> Option { + if let Some(state) = self.constants.function_state() { + runtime::charge(state)?; + } match stmt { Stmt::Assign { lhs, rhs, .. } => { let width = match lhs { @@ -1363,7 +1660,7 @@ impl<'a> Frame<'a> { self.declare(name, &r#type)?; let value = match init { Some(init) => self.assignment_value(init, self.type_of(name)?.0)?, - None => Value::integer(0), + None => self.initial_value(name)?, }; self.set(name, value)?; } @@ -1384,41 +1681,9 @@ impl<'a> Frame<'a> { items, default, } => { - if matches!(kind, CaseKind::Z | CaseKind::X) { - return None; - } - // Each label compares as an equality with the selector, at - // their common width (IEEE 1800-2023 12.5). - for item in items { - for label in &item.labels { - let comparison = match (kind, label) { - (CaseKind::Inside, label) => Expr::Inside { - expr: Box::new(selector.clone()), - items: vec![match label { - CaseLabel::Value(value) => InsideItem::Value(value.clone()), - CaseLabel::Range { low, high } => InsideItem::Range { - low: low.clone(), - high: high.clone(), - }, - }], - }, - (_, CaseLabel::Value(value)) => Expr::Binary { - left: Box::new(selector.clone()), - op: BinaryOp::Eq, - right: Box::new(value.clone()), - }, - (_, CaseLabel::Range { .. }) => return None, - }; - let matched = self.truth(&comparison)?; - if matched { - return self.block(&item.body); - } - } - } - if let Some(default) = default { - return self.block(default); - } + return self.case_statement(*kind, selector, items, default.as_deref()); } + Stmt::Loop { kind, init, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs b/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs new file mode 100644 index 00000000000..c88859d0e49 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs @@ -0,0 +1,520 @@ +//! Constant evaluation of stateless, effect-free calls in ordinary expressions. +use super::*; + +fn lvalue(value: crate::ir::LValue) -> LValue { + match value { + crate::ir::LValue::Ident(name) => LValue::Ident(name), + crate::ir::LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } => LValue::Select { + name, + msb: msb.into(), + lsb: lsb.into(), + array_slice_width: array_slice_width.map(Into::into), + array_slice_reversed, + signed: false, + is_2state: false, + }, + } +} + +/// A module's stateless zero-argument functions, evaluated at most once each. +/// This reuses the constant interpreter only after runtime lifetime and effect +/// checks; functions with persistent storage or observable effects stay calls. +pub struct RuntimeConstantFunctions<'a> { + state: State, + constants: &'a HashMap, + cache: RefCell>>, + two_state: bool, +} + +pub(super) fn charge(state: &State) -> Option<()> { + if let Some(fuel) = state.runtime_fuel.get() { + state.runtime_fuel.set(Some(fuel.checked_sub(1)?)); + } + Some(()) +} + +impl<'a> RuntimeConstantFunctions<'a> { + pub fn new( + module: &crate::ir::Module, + constants: &'a HashMap, + four_state: bool, + ) -> Self { + let subroutines = module + .subroutines() + .iter() + .cloned() + .map(|subroutine| { + subroutine.map(&mut Into::into, &mut lvalue, &mut std::convert::identity) + }) + .collect::>(); + let readers = simulation_state_readers(&subroutines); + let mut functions = ConstantFunctionTable::default(); + for subroutine in &subroutines { + if subroutine.is_task + || !subroutine.persistent_locals.is_empty() + || readers.contains_key(&subroutine.name) + || subroutine + .params + .iter() + .any(|param| param.direction != crate::procedural::ParamDirection::Input) + { + continue; + } + let Some(return_var) = subroutine + .return_var + .clone() + .zip(subroutine.return_type.clone()) + else { + continue; + }; + let mut owned = subroutine + .params + .iter() + .map(|param| param.name.clone()) + .collect::>(); + owned.insert(return_var.0.clone()); + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| { + if let Stmt::Local { name, .. } = stmt { + owned.insert(name.clone()); + } + }); + } + let mut impure = false; + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| match stmt { + Stmt::Assign { lhs, .. } => impure |= !owned.contains(lhs.name()), + Stmt::AssignConcat { parts, .. } => { + impure |= parts.iter().any(|lhs| !owned.contains(lhs.name())) + } + Stmt::SystemTask { .. } + | Stmt::Call { .. } + | Stmt::Delay { .. } + | Stmt::WaitEvent(_) + | Stmt::WaitImplicit(_) + | Stmt::Wait(_) + | Stmt::Fork { .. } + | Stmt::WaitFork + | Stmt::DisableFork => impure = true, + _ => {} + }); + } + if impure { + continue; + } + functions.insert( + subroutine.name.clone(), + ConstantFunction { + params: subroutine + .params + .iter() + .map(|param| (param.name.clone(), param.r#type.clone())) + .collect(), + argument_names: subroutine + .params + .iter() + .map(|param| param.source_name.clone()) + .collect(), + argument_defaults: subroutine + .params + .iter() + .map(|param| param.default.clone()) + .collect(), + return_var: Some(return_var), + body: subroutine.body.clone(), + }, + ); + } + // A rejected callee cannot become pure merely because its caller has + // no direct effect. Include default expressions and discarded branches. + loop { + let mut rejected = Vec::new(); + for (name, function) in &functions { + let mut missing = false; + let mut check = |callee: &Callee, _: CallArguments<'_>| { + if let Callee::Subroutine(name) = callee { + missing |= !functions.contains_key(name); + } + }; + for expression in function.argument_defaults.iter().flatten() { + visit_expr_calls(expression, &mut check); + } + for stmt in &function.body { + stmt.walk(&mut |stmt| { + for expression in lifetimes::stmt_exprs(stmt) { + visit_expr_calls(expression, &mut check); + } + }); + } + if missing { + rejected.push(name.clone()); + } + } + if rejected.is_empty() { + break; + } + for name in rejected { + functions.remove(&name); + } + } + let state = State::default(); + *state.functions.borrow_mut() = ConstantFunctions { + functions: Arc::new(functions), + locals: Arc::new( + module + .locals() + .iter() + .map(|local| (local.name.clone(), local.r#type.clone())) + .collect(), + ), + errors: Arc::default(), + }; + Self { + state, + constants, + cache: RefCell::default(), + two_state: !four_state, + } + } + + /// A call with no actual or formal arguments, or `None` when it cannot be + /// evaluated without runtime state, effects, or exceeding the shared budget. + pub fn value(&self, name: &str) -> Option { + if let Some(value) = self.cache.borrow().get(name) { + return value.clone(); + } + if !self + .state + .functions + .borrow() + .functions + .get(name)? + .params + .is_empty() + { + return None; + } + self.state.runtime_fuel.set(Some(MAX_ITERATIONS)); + self.state.runtime_two_state.set(Some(self.two_state)); + let env = Environment { + constants: self.constants, + functions: &self.state, + }; + let value = call_value(name, &[], &env).map(Value::into_literal); + self.state.runtime_fuel.set(None); + self.state.runtime_two_state.set(None); + self.cache.borrow_mut().insert(name.into(), value.clone()); + value + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn module(source: &str) -> crate::ir::Module { + let parsed = + crate::ParsedSource::parse(source, std::path::Path::new("constant-call.sv")).unwrap(); + let packages = crate::ParsedSource::analyze_packages(&[&parsed]).unwrap(); + parsed + .analyze_module( + "Top", + &HashMap::default(), + &[], + &[], + &crate::ModuleInterfaces::default(), + &packages, + ) + .unwrap() + .modules()[0] + .clone() + } + + #[test] + fn case_uses_the_types_of_all_labels() { + let module = module( + r#"module Top(output int q); + function automatic int mixed(); + logic signed [7:0] x = 8'hff; + case (x) + 16'shffff: return 1; + 16'h0000: return 2; + default: return 0; + endcase + endfunction + assign q = mixed(); + endmodule"#, + ); + let constants = HashMap::default(); + for four_state in [false, true] { + let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + assert_eq!(evaluator.value("mixed").unwrap().value, BigUint::default()); + } + } + + #[test] + fn inside_preserves_unknown_comparisons() { + let module = module( + r#"module Top(output logic q); + function automatic logic unknown_match(); + logic x; + return x inside {1'b1}; + endfunction + assign q = unknown_match(); + endmodule"#, + ); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let value = evaluator.value("unknown_match").unwrap(); + assert_eq!(value.mask, BigUint::from(1u8)); + assert_eq!(value.value, BigUint::from(1u8)); + } + + #[test] + fn case_context_reaches_arithmetic_and_skips_unselected_labels() { + let module = module( + r#"module Top(output int q); + function automatic logic [15:0] unreachable_label(); + while (1) begin end + return 0; + endfunction + function automatic int arithmetic(); + case (8'hff + 8'h01) + 8'h00: return 0; + 16'h100: return 1; + default: return 2; + endcase + endfunction + function automatic int signed_case(); + logic signed [7:0] x = -1; + case (x) + 16'shffff: return 1; + 16'sh0000: return 2; + default: return 0; + endcase + endfunction + function automatic int skip_label(); + case (8'hff + 8'h01) + 16'h100: return 1; + unreachable_label(): return 2; + default: return 0; + endcase + endfunction + function automatic logic fill_case(); + case ('1) + 8'hff: return 1; + default: return 0; + endcase + endfunction + function automatic int exact_unknown(); + case (1'bx) + 1'bz: return 0; + 1'bx: return 1; + default: return 2; + endcase + endfunction + assign q=0; + endmodule"#, + ); + let constants = HashMap::default(); + for four_state in [false, true] { + let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + for name in ["arithmetic", "signed_case", "skip_label", "fill_case"] { + assert_eq!( + evaluator.value(name).unwrap().value, + BigUint::from(1u8), + "{name}" + ); + } + if four_state { + assert_eq!( + evaluator.value("exact_unknown").unwrap().value, + BigUint::from(1u8) + ); + } + } + } + + #[test] + fn inside_combines_unknown_matches_and_ranges() { + let module = module( + r#"module Top(output logic q); + function automatic logic definite_match(); return 1'bx inside {1'b0, 1'b?}; endfunction + function automatic logic definite_mismatch(); return 2'bx0 inside {2'b11}; endfunction + function automatic logic unknown_range(); return 1'bx inside {[1'b0:1'b1]}; endfunction + function automatic logic empty_range(); return 2'b11 inside {[2'bxx:2'b01]}; endfunction + assign q=0; + endmodule"#, + ); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + for (name, expected, mask) in [ + ("definite_match", 1u8, 0u8), + ("definite_mismatch", 0, 0), + ("unknown_range", 1, 1), + ("empty_range", 0, 0), + ] { + let value = evaluator.value(name).unwrap(); + assert_eq!(value.value, BigUint::from(expected), "{name}"); + assert_eq!(value.mask, BigUint::from(mask), "{name}"); + } + } + + #[test] + fn stateless_matrix_function_with_unpacked_scratch_is_a_constant() { + let module = module( + r#"module Top(output wire [15:0] q); + function [3:0][3:0] pattern(); + logic [3:0] words [3:0]; + for (int i=0; i<4; i++) words[i] = 4'b1 << i; + for (int i=0; i<4; i++) for (int j=0; j<4; j++) pattern[i][j] = words[i][j]; + endfunction + assign q = pattern(); + endmodule"#, + ); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let result = evaluator.value("pattern").unwrap(); + assert_eq!(result.width, 16); + assert_eq!(result.value, BigUint::from(0x8421u32)); + assert_eq!(result.mask, BigUint::default()); + assert_eq!(evaluator.value("pattern"), Some(result)); + } + + #[test] + fn wide_matrix_value_is_evaluated_once() { + let module = module( + r#"module Top(output wire [8099:0] q); + function [89:0][89:0] pattern(); + logic [89:0] words [89:0]; + for (int i=0; i<90; i++) words[i] = 90'b1 << i; + for (int i=0; i<90; i++) pattern[i] = words[i]; + endfunction + assign q = pattern(); + endmodule"#, + ); + assert!(module.subroutines()[0].persistent_locals.is_empty()); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + FUNCTION_CALLS.with(|calls| calls.set(0)); + let value = evaluator.value("pattern").unwrap(); + let mut expected = BigUint::default(); + for i in 0..90 { + expected.set_bit(i * 91, true); + } + assert_eq!(value.width, 8100); + assert_eq!(value.value, expected); + assert_eq!(value.mask, BigUint::default()); + assert_eq!(evaluator.value("pattern"), Some(value)); + assert_eq!(FUNCTION_CALLS.with(Cell::get), 1); + } + + #[test] + fn runtime_state_and_observable_effects_remain_calls() { + let module = module( + r#"module Top(output int q); + int global_value; + function int stateful(); static int count=0; count++; return count; endfunction + function int writes_global(); global_value=7; return 7; endfunction + function int reads_global(); return global_value; endfunction + function int message(); $display("keep this effect"); return 3; endfunction + function int indirect(); return message(); endfunction + assign q = 0; + endmodule"#, + ); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + for name in [ + "stateful", + "writes_global", + "reads_global", + "message", + "indirect", + ] { + assert!( + evaluator.value(name).is_none(), + "{name} was treated as a constant" + ); + } + } + + #[test] + fn unknown_intermediates_in_two_state_mode_stay_runtime_calls() { + let module = module( + r#"module Top(output int q); + function automatic int explicit_unknown(); return 1'bx === 1'b0; endfunction + function automatic int outside_select(); logic [3:0] x=0; return x[8] === 1'b0; endfunction + function automatic int non_integral_local(); real x=1.5; return x * 2; endfunction + assign q=0; + endmodule"#, + ); + let constants = HashMap::default(); + let two_state = RuntimeConstantFunctions::new(&module, &constants, false); + for name in ["explicit_unknown", "outside_select", "non_integral_local"] { + assert!( + two_state.value(name).is_none(), + "{name} must retain runtime semantics" + ); + } + let four_state = RuntimeConstantFunctions::new(&module, &constants, true); + for name in ["explicit_unknown", "outside_select"] { + assert_eq!(four_state.value(name).unwrap().value, BigUint::default()); + } + assert!(four_state.value("non_integral_local").is_none()); + } + + #[test] + fn aggregate_slice_assignment_stays_with_runtime_lowering() { + let module = module( + r#"module Top(output wire [31:0] q); + function automatic logic [31:0] slices(); + logic [7:0] words [0:3]; + words[0]=8'h11; words[1]=8'h22; words[2]=8'h33; words[3]=8'h44; + words[0+:2] = words[2+:2]; + return {words[0], words[1], words[2], words[3]}; + endfunction + assign q = slices(); + endmodule"#, + ); + let constants = HashMap::default(); + let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + assert!( + evaluator + .state + .functions + .borrow() + .functions + .contains_key("slices") + ); + assert!(evaluator.value("slices").is_none()); + } + + #[test] + fn automatic_initial_values_follow_the_runtime_state_mode() { + let module = module( + r#"module Top(output int q); + function automatic int unknown_local(); logic [7:0] x; return x === 8'b0; endfunction + function automatic int bit_local(); bit [7:0] x; return x == 8'b0; endfunction + assign q = 0; + endmodule"#, + ); + let constants = HashMap::default(); + for four_state in [false, true] { + let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + assert_eq!( + evaluator.value("unknown_local").unwrap().value, + BigUint::from(u8::from(!four_state)) + ); + assert_eq!( + evaluator.value("bit_local").unwrap().value, + BigUint::from(1u8) + ); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs index b132c5348b5..557162da722 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs @@ -527,6 +527,11 @@ fn partial_return_assignments_reach_the_127_and_128_bit_boundaries() { "wide", vec![], vec![ + Stmt::Assign { + lhs: LValue::Ident("wide".into()), + rhs: literal("'0"), + nonblocking: false, + }, Stmt::Assign { lhs: select(7, 0), rhs: literal("8'ha5"), @@ -548,6 +553,34 @@ fn partial_return_assignments_reach_the_127_and_128_bit_boundaries() { } } +#[test] +fn partial_returns_preserve_unwritten_unknown_bits() { + let constants = HashMap::default(); + let mut function = function( + "partial", + vec![], + vec![Stmt::Assign { + lhs: LValue::Select { + name: "partial".into(), + msb: ConstExpr::Literal("1".into()), + lsb: ConstExpr::Literal("0".into()), + signed: false, + array_slice_width: None, + array_slice_reversed: false, + is_2state: false, + }, + rhs: literal("2'b01"), + nonblocking: false, + }], + ); + function.return_var = Some(("partial".into(), fixed_ty(8, false))); + let value = call_in_frame(&function, &[], Frame::new(&constants)) + .unwrap() + .into_literal(); + assert_eq!(value.value, BigUint::from(0xfdu8)); + assert_eq!(value.mask, BigUint::from(0xfcu8)); +} + #[test] fn full_width_return_assignments_keep_all_128_bits() { let constants = HashMap::default(); diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 53a7d6d08f1..9e3edd6b822 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -27,6 +27,7 @@ pub mod syntax; pub mod system_functions; pub mod typecheck; +pub use ast::const_functions::RuntimeConstantFunctions; pub use ast::interfaces::{ InterfaceMemberPath, InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, plan_interfaces_with_member_paths, diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index f795cfb1994..d825bc8d1ea 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -505,7 +505,23 @@ pub(crate) fn eval_generate_case_operand( width: usize, signed: bool, ) -> Option { - let expr = substitute_typed_constants(expr.clone(), constants, types); + eval_case_operand_in_env( + expr, + constants, + &|name| types.get(name).copied(), + width, + signed, + ) +} + +pub(crate) fn eval_case_operand_in_env( + expr: &ConstExpr, + constants: &dyn ConstantEnvironment, + types: &impl Fn(&str) -> Option<(usize, bool)>, + width: usize, + signed: bool, +) -> Option { + let expr = substitute_typed_constants_with_lookup(expr.clone(), constants, types); eval_integral_in_context(&expr, width, signed) } diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index 352e9b1e1dc..8af43ed30f7 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -2064,3 +2064,67 @@ endmodule (assert_eq q 0x1fef6) (set b 1) (assert_eq q 0x1b9ed)) + +(case constant_function_case_context + ; Explicit local assignments avoid an Icarus 13.0 automatic-initializer abort. + (source "constant_case.sv" #" + module Top(output logic [3:0] q, output logic [3:0] p); + function automatic logic mixed(); + logic signed [7:0] x; + x = 8'hff; + case (x) + 16'shffff: return 0; + 16'h0000: return 0; + default: return 1; + endcase + endfunction + function automatic logic arithmetic(); + case (8'hff + 8'h01) + 8'h00: return 0; + 16'h100: return 1; + default: return 0; + endcase + endfunction + function automatic logic all_signed(); + logic signed [7:0] x; + x = -1; + case (x) + 16'shffff: return 1; + 16'sh0000: return 0; + default: return 0; + endcase + endfunction + function automatic logic fill(); + case ('1) + 8'hff: return 1; + default: return 0; + endcase + endfunction + localparam logic [3:0] P = {fill(), all_signed(), arithmetic(), mixed()}; + assign p = P; + assign q = {fill(), all_signed(), arithmetic(), mixed()}; + endmodule + "#) + (top Top) + (assert_eq q 15) + (assert_eq p 15)) + +(case constant_function_case_unknowns + (four_state) + (source "constant_case_unknown.sv" #" + module Top(output logic q, output logic p); + function automatic logic exact_unknown(); + case (1'bx) + 1'bz: return 0; + 1'bx: return 1; + default: return 0; + endcase + endfunction + localparam logic P = exact_unknown(); + assign p = P; + assign q = exact_unknown(); + endmodule + "#) + (top Top) + (assert_eq q 1) + (assert_eq p 1)) diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index ce52b3583be..198d6baaf98 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,32 @@ +use super::*; + sv_backends! { + // Compare cached runtime calls with elaboration-time constants through + // Celox's four-state API, including the payload and mask of unknown bits. + fn constant_function_inside_unknowns(sim) { + @setup { let source = r#" + module Top(output logic [4:0] q, output logic [4:0] p); + function automatic logic unknown_match(); + logic x; + return x inside {1'b1}; + endfunction + function automatic logic definite_match(); return 1'bx inside {1'b0, 1'b?}; endfunction + function automatic logic definite_mismatch(); return 2'bx0 inside {2'b11}; endfunction + function automatic logic unknown_range(); return 1'bx inside {[1'b0:1'b1]}; endfunction + function automatic logic empty_range(); return 2'b11 inside {[2'bxx:2'b01]}; endfunction + localparam logic [4:0] P = {empty_range(), unknown_range(), definite_mismatch(), definite_match(), unknown_match()}; + assign p = P; + assign q = {empty_range(), unknown_range(), definite_mismatch(), definite_match(), unknown_match()}; + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("constant_inside.sv"))], "Top").four_state(true); + for name in ["q", "p"] { + assert_eq!(sim.get_four_state(sim.signal(name)), (BigUint::from(0x0bu8), BigUint::from(0x09u8)), "{name}"); + } + } + + fn constant_function_case_context(sim) { @case "operators::constant_function_case_context"; } + fn constant_function_case_unknowns(sim) { @case "operators::constant_function_case_unknowns"; } fn logical_equivalence(sim) { @case "operators::logical_equivalence"; } fn logical_equivalence_unknown(sim) { @case "operators::logical_equivalence_unknown"; } fn logical_equivalence_evaluates_operands_once(sim) { @case "operators::logical_equivalence_evaluates_operands_once"; }