diff --git a/crates/celox-frontend-core/src/symbolic/flattening.rs b/crates/celox-frontend-core/src/symbolic/flattening.rs index b31cfe65896..8d0f7c79af9 100644 --- a/crates/celox-frontend-core/src/symbolic/flattening.rs +++ b/crates/celox-frontend-core/src/symbolic/flattening.rs @@ -518,6 +518,12 @@ fn collect_inputs_with_window( set: &mut crate::HashSet>, visited: &mut HashMap>, ) { + // IEEE 1800-2023 11.4.12.1: a zero-count replication contributes no + // bits to its enclosing concatenation. There is no dependency window + // to visit, and constructing one would underflow its inclusive MSB. + if get_width(expr, arena) == 0 { + return; + } let requested = window.unwrap_or_else(|| BitAccess::new(0, get_width(expr, arena) - 1)); let uncovered = claim_uncovered_window(visited.entry(expr).or_default(), requested); @@ -596,6 +602,9 @@ fn collect_inputs_with_window( // Walk from LSB side to map the requested window to each part. let mut part_lsb = 0usize; for (part, width) in parts.iter().rev() { + if *width == 0 { + continue; + } let part_msb = part_lsb + width - 1; if win.overlaps(&BitAccess::new(part_lsb, part_msb)) { let ov_lsb = std::cmp::max(win.lsb, part_lsb); diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index bc6ad7f6c91..0d655719cf8 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -54,4 +54,6 @@ pub use lowering::{ prepare_external_hierarchy_with_foreign_resolver_with_options, schedule_sources_with_options, }; -pub use lowering::schedule_sources_with_force_signals; +pub use lowering::{ + schedule_sources_with_force_signals, schedule_sources_with_parameter_expressions, +}; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b065fabd633..7b440f50b12 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -128,7 +128,7 @@ pub(crate) struct LoweredSvModule { #[derive(Clone)] struct AnalyzedSvModule { name: String, - interface_member_paths: HashMap>, + interface_member_paths: HashMap, source: std::rc::Rc, implicit_nets_allowed: bool, /// The positional interface of every module in all sources, used to bind @@ -1788,6 +1788,49 @@ pub fn schedule_sources_with_force_signals( warnings: &mut Vec, analysis_options: sv::AnalysisOptions, force_signals: &[String], +) -> Result { + let parameters = parameter_overrides + .iter() + .map(|(name, value)| (name.clone(), sv::ir::ConstExpr::Literal(value.to_string()))) + .collect::>(); + schedule_sources_with_parameter_expressions( + sources, + top, + ¶meters, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + warnings, + analysis_options, + force_signals, + ) +} + +/// Schedule a design with typed SV constant expressions as top parameters. +#[allow(clippy::too_many_arguments)] +pub fn schedule_sources_with_parameter_expressions( + sources: &[(&str, &Path)], + top: &str, + parameter_overrides: &[(String, sv::ir::ConstExpr)], + ignored_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + )], + true_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + usize, + )], + four_state: bool, + parallel: &celox_frontend_core::ParallelScheduleOptions, + trace_options: &FrontendTraceOptions, + trace: Option<&mut FrontendTrace>, + warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, + force_signals: &[String], ) -> Result { let mut found = Vec::new(); let scheduled = schedule_sources_collecting( @@ -1813,7 +1856,7 @@ pub fn schedule_sources_with_force_signals( fn schedule_sources_collecting( sources: &[(&str, &Path)], top: &str, - parameter_overrides: &[(String, u64)], + parameter_overrides: &[(String, sv::ir::ConstExpr)], ignored_loops: &[( (Vec<(String, usize)>, Vec), (Vec<(String, usize)>, Vec), @@ -1845,7 +1888,7 @@ fn schedule_sources_collecting( .iter() .map(|(name, value)| LoweredSvParameterOverride { name: name.clone(), - value: Some(sv::ir::ConstExpr::Literal(value.to_string())), + value: Some(value.clone()), bound_type: None, bound_pattern: None, }) @@ -1990,7 +2033,13 @@ fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvMod source .interface_member_paths .get(segment) - .cloned() + .and_then(|path| path.restore(segment)) + .or_else(|| { + source + .interface_member_paths + .values() + .find_map(|path| path.restore(segment)) + }) .unwrap_or_else(|| vec![segment.clone()]) }) .collect(); @@ -2091,7 +2140,7 @@ fn specialize_module( module .interface_member_paths .iter() - .find(|(_, segments)| segments.join(".") == *path) + .find(|(_, segments)| segments.segments.join(".") == *path) .map_or_else(|| path.clone(), |(flat, _)| flat.clone()) }) .collect::>(); @@ -2313,7 +2362,38 @@ fn lower_module_with_overrides( }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); - if port.is_net() || type_info.is_4state { + if let Some(default) = port.default() { + if !variable.array_dims.is_empty() { + warnings.push(( + crate::FrontendWarningKind::UnpackedPortDefault { + module: name.clone(), + port: port.name().to_string(), + }, + None, + )); + } + let literal = sv::typecheck::context_size_const_integral_literal( + default, + &constants, + ¶meter_types, + type_info.width, + type_info.signed, + ) + .ok_or_else(|| { + sv::AnalyzerError::Unsupported(format!( + "nonconstant input port default `{}`", + port.name() + )) + })?; + initial_memory_values.push(InitialStateValue { + address: id, + data: InitialStateData::Packed { + value: literal.value, + mask: literal.mask, + written_mask: (BigUint::from(1u8) << type_info.width) - BigUint::from(1u8), + }, + }); + } else if port.is_net() || type_info.is_4state { let written_mask = (BigUint::from(1u8) << type_info.width) - BigUint::from(1u8); let value = if port.is_net() { BigUint::default() @@ -2381,9 +2461,66 @@ fn lower_module_with_overrides( variables.insert(id, variable); } + // Retain integral parameters for external observation, without adding them + // to name_to_id: HDL expressions must still fold parameter references as + // constants rather than introduce runtime loads. + for parameter in module.parameters() { + let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else { + continue; + }; + let signed = parameter.resolved_signed().unwrap_or(false); + let expr = parameter.value().cloned().or_else(|| { + constants + .get(parameter.name()) + .copied() + .map(const_expr_from_i128) + }); + let Some(literal) = expr.and_then(|expr| { + sv::typecheck::context_size_const_integral_literal( + &expr, + &constants, + ¶meter_types, + width, + signed, + ) + }) else { + continue; + }; + let id = next_var_id(&mut next_id); + let written_mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + initial_memory_values.push(InitialStateValue { + address: id, + data: InitialStateData::Packed { + value: literal.value, + mask: literal.mask, + written_mask, + }, + }); + variables.insert( + id, + SvVariable { + path: vec![parameter.name().to_string()], + width, + signed, + is_4state: true, + packed_ranges: vec![(width as i128 - 1, 0)], + array_dims: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Parameter, + type_kind: PortTypeKind::Logic, + source: None, + hidden: false, + force_control: None, + }, + ); + } + let forceable = variables .iter() .filter_map(|(&id, var)| { + if var.kind == VariableKind::Parameter { + return None; + } let name = &var.path[0]; force_signals.iter().any(|path| name == path).then_some(id) }) @@ -3914,6 +4051,39 @@ fn build_instance_glue( ), )?; (expr, sources, source_ids) + } else if let Some(default) = child + .source + .ports() + .iter() + .find(|port| port.name() == formal) + .and_then(|port| port.default()) + { + // IEEE 1800-2023 23.2.2.4: defaults belong to the child's + // parameter scope, and apply only to omitted connections. + let literal = sv::typecheck::context_size_const_integral_literal( + default, + &child.constants, + &child.parameter_types, + width, + child_var.signed, + ) + .ok_or_else(|| { + ParserError::illegal_context( + "systemverilog input port default", + formal.clone(), + None, + ) + })?; + ( + arena.alloc(SLTNode::Constant( + literal.value, + literal.mask, + width, + child_var.signed, + ))?, + HashSet::default(), + Vec::new(), + ) } else { let unknown_mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); ( @@ -4387,7 +4557,9 @@ fn lower_glue_parent_expr( )? }; let width = celox_slt::get_width(node, arena); - nodes.push((node, width)); + if width != 0 { + nodes.push((node, width)); + } sources.extend(part_sources); source_ids.extend(part_source_ids); } @@ -5574,7 +5746,9 @@ fn lower_expr_with_context( None, )?; let width = celox_slt::get_width(node, arena); - nodes.push((node, width)); + if width != 0 { + nodes.push((node, width)); + } sources.extend(part_sources); } Some((arena.alloc(SLTNode::Concat(nodes)).ok()?, sources)) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 3ae40680a8f..5024c2dc46d 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -38,6 +38,9 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations. #[error("mixed explicit and default time units or precisions across design elements")] MixedTimescale, + /// Aggregate defaults are a compatibility extension to IEEE 1800-2023 23.2.2.4. + #[error("default value on unpacked input port `{module}.{port}` is a language extension")] + UnpackedPortDefault { module: String, port: String }, /// A memory file without address directives holds a different number of /// words than the address range of `$readmemh`/`$readmemb` /// (IEEE 1800-2023 21.4). @@ -141,6 +144,7 @@ impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", + FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", })) @@ -155,6 +159,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } + FrontendWarningKind::UnpackedPortDefault { .. } => { + "IEEE 1800-2023 23.2.2.4 permits defaults on singular input ports; use unpacked_port_default=warn or allow to enable aggregate defaults" + } FrontendWarningKind::MemoryFileWordCount { .. } => { "give one word per address of the range, or place the words with `@address` directives" } diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index 272f81c49b3..1ea8cfb1cf1 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -32,6 +32,8 @@ pub struct ReflectionScope { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ReflectionSignal { + /// An elaboration constant exposed as a read-only VPI parameter. + pub is_parameter: bool, pub name: String, pub full_name: String, pub parent: ReflectionScopeId, diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index f31aefea4d5..f574291b4e3 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -108,18 +108,21 @@ fn analyze_source_impl(source: ast::Source) -> Result { let mut ports = Vec::new(); for port in module.ports() { port_table.insert(module, port)?; - ports.push(ir::Port::new( - port.name().to_string(), - port.direction().into(), - ir::Type::from_ast( - port.r#type().clone(), - &ast::const_functions::Environment { - constants: &constants, - functions: &state.const_functions, - }, - ), - port.is_net(), - )); + ports.push( + ir::Port::new( + port.name().to_string(), + port.direction().into(), + ir::Type::from_ast( + port.r#type().clone(), + &ast::const_functions::Environment { + constants: &constants, + functions: &state.const_functions, + }, + ), + port.is_net(), + ) + .with_default(port.default().cloned().map(Into::into)), + ); } let signals = module .signals() diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 09423e4e817..220496f725f 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1613,6 +1613,7 @@ pub struct Port { direction: PortDirection, r#type: Type, is_net: bool, + default: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -1671,6 +1672,7 @@ impl Port { direction, r#type, is_net, + default: None, } } @@ -1689,6 +1691,15 @@ impl Port { pub fn is_net(&self) -> bool { self.is_net } + + pub(crate) fn with_default(mut self, default: Option) -> Self { + self.default = default; + self + } + + pub fn default(&self) -> Option<&ConstExpr> { + self.default.as_ref() + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index ed034a5723d..940dd8a3d0c 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -73,24 +73,8 @@ pub(super) fn runtime_cast_target_expr( two_state, } => (target, numeric_size, two_state), }; - let operand_signed = expr_signedness_with_return_types( - &expr, - &packed_dimensions.expression_signedness, - &packed_dimensions.functions, - &packed_dimensions.function_return_types, - ) - .or_else(|| { - // A genvar or an untyped constant is an `int`. - let Expr::Ident(name) = &expr else { - return None; - }; - const_env.contains_key(name).then(|| { - parameter_types_from_const_env(const_env) - .get(name) - .is_none_or(|r#type| r#type.signed) - }) - }) - .ok_or_else(|| unsupported("cast of an operand whose signedness is unknown"))?; + let operand_signed = dimensions::expression_signedness(&expr, packed_dimensions, const_env) + .ok_or_else(|| unsupported("cast of an operand whose signedness is unknown"))?; let expr = if two_state { Expr::Unary { op: UnaryOp::ToTwoState, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 51f69c82a0a..9216fbbc5d2 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -7,6 +7,7 @@ //! calls that are not system functions. Bodies are interpreted from their //! procedural statements. +use num_bigint::BigUint; use std::cell::{Cell, RefCell}; use super::*; @@ -1101,7 +1102,64 @@ impl Frame<'_> { } ConstExpr::Literal(format!("1'b{}", u8::from(found))) } - Expr::Concat(_) | Expr::RepeatConcat { .. } => return None, + Expr::Concat(_) | Expr::RepeatConcat { .. } => { + let literal = self.concat_literal(expr)?; + if literal.width == 0 { + return None; + } + let value = crate::typecheck::integral_literal_as_i128(&literal, false)?; + self.temporary(value, literal.width, false) + } + }) + } + + /// Fold concatenations with each operand's own width before the surrounding + /// assignment can resize the value. This interpreter stores at most 128 bits. + fn concat_literal(&mut self, expr: &Expr) -> Option { + self.tick()?; + let (parts, count) = match expr { + Expr::Concat(parts) => (parts, 1), + Expr::RepeatConcat { count, parts } => { + let count = usize::try_from(self.eval_lowered(&count.clone().into())?).ok()?; + (parts, count) + } + _ => { + let lowered: crate::ir::ConstExpr = self.lower(expr)?.into(); + return crate::typecheck::eval_const_integral_literal_in_env( + &lowered, + self, + &|name| self.type_of(name), + ); + } + }; + let mut width = 0usize; + let mut value = BigUint::default(); + let mut mask = BigUint::default(); + for part in parts { + let literal = self.concat_literal(part)?; + width = width.checked_add(literal.width)?; + if width > 128 { + return None; + } + value = (value << literal.width) | literal.value; + mask = (mask << literal.width) | literal.mask; + } + let total = width.checked_mul(count)?; + if total > 128 { + return None; + } + let mut result_value = BigUint::default(); + let mut result_mask = BigUint::default(); + // A zero-width group remains empty for any count, without iterating. + for _ in 0..if width == 0 { 0 } else { count } { + result_value = (result_value << width) | &value; + result_mask = (result_mask << width) | &mask; + } + Some(crate::typecheck::IntegralLiteral { + width: total, + signed: false, + value: result_value, + mask: result_mask, }) } diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 79213285077..74a629b0e14 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -28,7 +28,7 @@ pub(super) fn value_expression( let mut context = dimensions.clone(); context.const_env = HashMap::default().into(); context.type_aliases = HashMap::default(); - bind_in_context(root, native, tree, &context, dimensions, true) + bind_in_context(root, native, tree, &context, dimensions) } pub(super) fn bind( root: ExprId, @@ -55,7 +55,7 @@ fn bind_in( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted> { - bind_in_context(root, native, tree, dimensions, dimensions, false) + bind_in_context(root, native, tree, dimensions, dimensions) } fn bind_in_context( root: ExprId, @@ -63,7 +63,6 @@ fn bind_in_context( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, query_dimensions: &PackedDimensions, - value_actual: bool, ) -> Converted> { enum Job { Enter(ExprId), @@ -123,7 +122,6 @@ fn bind_in_context( jobs.push(Job::Enter(*right)); jobs.push(Job::Enter(*left)); } - ExprKind::Conditional { .. } if value_actual => return Ok(None), ExprKind::Conditional { condition, then_expression, @@ -140,7 +138,7 @@ fn bind_in_context( *expression, native, tree, - dimensions, + query_dimensions, ) { Ok(target) => target, Err(AnalyzerError::Unsupported(_)) => return Ok(None), @@ -149,6 +147,20 @@ fn bind_in_context( jobs.push(Job::Cast(target)); jobs.push(Job::Enter(*expression)); } + ExprKind::Concatenation(_) | ExprKind::Replication { .. } => { + // Actual values retain the parent's specialization context. + // The symbolic context deliberately omits its numeric env, + // but a concat must be folded to a typed literal here. + let expr = + expression_binding::bind_value(id, native, tree, query_dimensions, None)?; + let Some(value) = + selects::indexed_expression_value(&tree.state, expr, query_dimensions) + else { + return Ok(None); + }; + values.push(value); + } + ExprKind::Call { expression, arguments, @@ -242,14 +254,14 @@ fn bind_in_context( )); jobs.extend(indices.into_iter().rev().map(Job::Enter)); } else { - let value = match expression_binding::bind_value( - id, native, tree, dimensions, None, - ) { + let value = match indexed_expression(id, native, tree, query_dimensions) { Ok(value) => value, Err(AnalyzerError::Unsupported(_)) => return Ok(None), Err(error) => return Err(error), }; - let Some(value) = expr_to_const(&tree.state, value) else { + let Some(value) = + selects::indexed_expression_value(&tree.state, value, query_dimensions) + else { return Ok(None); }; values.push(value); @@ -294,9 +306,12 @@ fn bind_in_context( }, Job::Cast(target) => { let value = values.pop().ok_or_else(disagreement)?; - let Some(value) = - casts::cast_constant_target(&tree.state, value, target, &dimensions.const_env) - else { + let Some(value) = casts::cast_constant_target( + &tree.state, + value, + target, + &query_dimensions.const_env, + ) else { return Ok(None); }; values.push(value); diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index aaf8f2d27e8..7246b76e780 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -407,13 +407,24 @@ fn constant_with_folded_selections_with_lookup( then_expr: Box::new(convert(then_expr)?), else_expr: Box::new(convert(else_expr)?), }), - Expr::Call { callee, args, .. } => Some(ConstExpr::call( - state, - callee.clone(), - args.iter() - .map(|arg| convert(arg.as_ref()?)) - .collect::>>()?, - )), + Expr::Call { callee, args, .. } => { + // Materialize a constant function's self-determined return type + // before the enclosing selection/arithmetic receives its context. + if let Some(literal) = + const_functions::eval_expression_literal(&state.const_functions, expr, const_env) + { + return Some(ConstExpr::Literal( + typecheck::format_integral_literal_binary(&literal), + )); + } + Some(ConstExpr::call( + state, + callee.clone(), + args.iter() + .map(|arg| convert(arg.as_ref()?)) + .collect::>>()?, + )) + } _ => expr_to_const(state, expr.clone()), } } diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index bba54816cd4..b6d9aebd366 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -33,12 +33,51 @@ pub(super) fn ports_from_scope( type_aliases, )?, ); - ports.push(Port::new( - native_port_name(native)?, - direction, - ty, - !explicit && !native.variable, - )); + let default = native + .default + .map(|value| { + if direction != PortDirection::Input { + return Err(unsupported("default value on a non-input port")); + } + if !ty.unpacked_ranges().is_empty() { + let name = native_port_name(native)?; + let mut dimensions = + PackedDimensions::new(HashMap::default(), const_env, type_aliases); + dimensions.insert(name.clone(), procedural::dimensions_from_type(&ty)); + let expression = expression_binding::expression( + value, + syntax_tree.declarations(), + &LValue::Ident(name), + syntax_tree, + &dimensions, + )?; + let value = fold_const_integral_expr_preserving_mask( + &syntax_tree.state, + expression, + const_env, + ); + return expr_to_const(&syntax_tree.state, value) + .ok_or_else(|| unsupported("nonconstant unpacked input port default")); + } + constant_binding::expression( + value, + syntax_tree.declarations(), + syntax_tree, + const_env, + type_aliases, + )? + .ok_or_else(|| unsupported("nonconstant input port default")) + }) + .transpose()?; + ports.push( + Port::new( + native_port_name(native)?, + direction, + ty, + !explicit && !native.variable, + ) + .with_default(default), + ); } Ok(ports) } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 0c04886874a..f62510932aa 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -52,21 +52,30 @@ fn bound_query_type( packed_dimensions: &PackedDimensions, const_env: &HashMap, ) -> Option { - let signed = expr_signedness_with_return_types( - expression, - &SizeQuerySignedness { - dimensions: packed_dimensions, - const_env, - }, - &HashMap::default(), - &packed_dimensions.function_return_types, - )?; + let signed = expression_signedness(expression, packed_dimensions, const_env)?; Some(ExprType { width: width.max(1), signed, }) } +/// Resolve signedness recursively from lexical declarations and parameter types. +pub(super) fn expression_signedness( + expression: &Expr, + dimensions: &PackedDimensions, + const_env: &HashMap, +) -> Option { + expr_signedness_with_return_types( + expression, + &SizeQuerySignedness { + dimensions, + const_env, + }, + &dimensions.functions, + &dimensions.function_return_types, + ) +} + /// The same precedence as the former eagerly collected signedness table, /// looking up only the identifiers used by the query operand. struct SizeQuerySignedness<'a> { @@ -82,7 +91,9 @@ impl Signedness for SizeQuerySignedness<'_> { if let Some(signed) = self.const_env.get(&variable_signed_marker(name)) { return Some(*signed != 0); } - parameter_type_from_const_env(self.const_env, name).map(|ty| ty.signed) + parameter_type_from_const_env(self.const_env, name) + .map(|ty| ty.signed) + .or_else(|| self.const_env.contains_key(name).then_some(true)) } } diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 0020b69d294..d2ebefd8a09 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -60,6 +60,7 @@ pub(super) struct Item { pub env: SharedMap, pub literals: SharedMap, parameter_dimensions: Arc, + qualified_types: SharedMap, names: SharedMap, imports: SharedMap, shadowed: Arc>, @@ -189,7 +190,16 @@ impl Item { &self, aliases: &'m HashMap, ) -> Cow<'m, HashMap> { - self.block_imports().type_aliases(aliases) + if self.qualified_types.is_empty() { + return self.block_imports().type_aliases(aliases); + } + let mut all = aliases.clone(); + all.extend( + self.qualified_types + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + Cow::Owned(self.block_imports().type_aliases(&all).into_owned()) } /// Make the constant functions this item sees the installed ones, until @@ -503,12 +513,29 @@ struct Scope { literals: SharedMap, parameters: Vec, parameter_dimensions: Arc, + qualified_types: SharedMap, names: SharedMap, imports: SharedMap, shadowed: Arc>, } impl Scope { + fn type_aliases<'m>( + &self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + if self.qualified_types.is_empty() { + return self.block_imports().type_aliases(aliases); + } + let mut all = aliases.clone(); + all.extend( + self.qualified_types + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + Cow::Owned(self.block_imports().type_aliases(&all).into_owned()) + } + fn block_imports(&self) -> BlockImports<'_> { BlockImports { state: &self.state, @@ -817,6 +844,7 @@ impl<'a> Elaborator<'a, '_> { env: scope.env.clone(), literals: scope.literals.clone(), parameter_dimensions: scope.parameter_dimensions.clone(), + qualified_types: scope.qualified_types.clone(), names: scope.names.clone(), imports: scope.imports.clone(), shadowed: scope.shadowed.clone(), @@ -1147,15 +1175,106 @@ impl<'a> Elaborator<'a, '_> { Expr::Literal(format_typed_parameter_literal(value, 32, true)), ); } - // Reject unsupported local types before signal precollection tries to - // resolve their uses. Native membership owns the declaration class. - if children.iter().any(|id| { - matches!( - self.tree.declarations().body_item(*id).kind, - celox_sv_syntax::BodyItemKind::TypeAlias(_) - ) - }) { - return Err(unsupported("type declaration inside generate scope")); + // Native declarations remain in their owning scope. Carry qualified + // bindings with every item rather than leaking a sibling's typedefs. + let type_names = children + .iter() + .filter_map(|id| { + if let celox_sv_syntax::BodyItemKind::TypeAlias(alias) = + self.tree.declarations().body_item(*id).kind + { + Some(instances::normalize_identifier( + &self.tree.declarations().type_alias(alias).name.spelling, + )) + } else { + None + } + }) + .collect::>(); + if !type_names.is_empty() { + let mut enum_names = HashSet::default(); + for id in children { + if let celox_sv_syntax::BodyItemKind::TypeAlias(alias) = + self.tree.declarations().body_item(*id).kind + && let celox_sv_syntax::TypeAliasTarget::DataType(ty) = + self.tree.declarations().type_alias(alias).target + && let celox_sv_syntax::DataTypeKind::Enum { items, .. } = + &self.tree.declarations().data_type(ty).kind + { + for item in items { + let name = instances::normalize_identifier(&item.name.spelling); + if !enum_names.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + } + } + } + let mut aliases = types::type_aliases_from_body_with_env( + self.tree, + children, + &scope.env, + &self.aliases, + )?; + let enums = parameters::enum_member_constants_from_items( + self.tree, + children, + &scope.env, + &aliases, + &HashMap::default(), + )?; + for name in type_names { + if !declared.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + let ty = aliases + .get(&name) + .ok_or_else(|| { + unsupported(format!("unresolved generate-local typedef `{name}`")) + })? + .clone(); + // Freeze definition-site dimensions before a nested block or + // another loop iteration shadows the names in their bounds. + let ty = procedural::scoped_type(ty, &scope.env); + if ty.packed_ranges().iter().any(|range| { + eval_ast_const_expr(&self.tree.state, range.left(), &scope.env).is_none() + || eval_ast_const_expr(&self.tree.state, range.right(), &scope.env) + .is_none() + }) { + return Err(unsupported(format!( + "unresolved generate-local typedef bounds `{name}`" + ))); + } + let qualified = format!("{}.{}", scope.path, scope_component(&name)); + scope.qualified_types.insert(qualified.clone(), ty.clone()); + scope.names.insert(name.clone(), qualified.clone()); + scope.imports.insert(name.clone(), qualified.clone()); + Arc::make_mut(&mut scope.shadowed).insert(name.clone()); + aliases.insert(qualified, ty.clone()); + aliases.insert(name, ty); + } + for (name, number) in enums.numbers { + if !declared.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + scope.env.insert(name.clone(), number); + insert_parameter_type_markers(&mut scope.env, &name, enums.types[&name]); + scope.env.insert(enum_marker(&name), 1); + scope + .literals + .insert(name.clone(), enums.exprs[&name].clone()); + scope.names.insert( + name.clone(), + format!("{}.{}", scope.path, scope_component(&name)), + ); + Arc::make_mut(&mut scope.shadowed).insert(name); + } + self.aliases = Cow::Owned(aliases); } self.constants_and_signal_types(children, &mut scope, &mut declared)?; for id in children { @@ -1309,6 +1428,7 @@ fn module_constant_functions( env: env.clone().into(), literals: literals.clone().into(), parameter_dimensions: Arc::default(), + qualified_types: SharedMap::default(), names: SharedMap::default(), imports: SharedMap::default(), shadowed: Arc::default(), @@ -2217,8 +2337,24 @@ mod tests { "duplicate case-generate default", ), ( - "if (1) begin typedef logic T; T tmp; end", - "type declaration inside generate scope", + "if (1) begin typedef logic T; typedef bit T; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef enum logic { A,B } T; typedef enum logic { A,C } U; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef logic T; logic T; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef enum logic { A,B } T; localparam A=1; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin parameter type T=logic; end", + "generate-local type parameter", ), ( "for (genvar i=0; i<1; i++) begin function automatic logic f(); return 0; endfunction end", @@ -2543,7 +2679,7 @@ mod tests { fn subroutine_projection_preserves_generate_diagnostics() { for body in [ "if (UNKNOWN) begin : g logic x; end", - "if (1) begin : g typedef logic T; T x; end", + "if (1) begin : g parameter type T=logic; end", "for (genvar i=0; i<1; i++) begin : g function logic f(); return 0; endfunction end", "if (1) begin : g localparam P=Q; localparam Q=P; end", ] { diff --git a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs index 879408cbefe..70a2e2f20e9 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs @@ -393,7 +393,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { } let index_ref = index.as_ref().map(|(name, value)| (name.as_str(), *value)); let functions = scope.block_imports().install_constant_functions(); - let aliases = scope.block_imports().type_aliases(self.module_aliases); + let aliases = scope.type_aliases(self.module_aliases); let outer = std::mem::replace(&mut self.aliases, aliases); contexts.0.push(Context { outer, diff --git a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs index 83b64247e90..bbe7e925066 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs @@ -2,7 +2,7 @@ use super::*; -type Key = [usize; 5]; +type Key = [usize; 6]; pub(in crate::ast) struct ScopeViews<'a> { dimensions: &'a PackedDimensions, @@ -60,6 +60,7 @@ fn key(item: &Item) -> Key { item.names.identity(), Arc::as_ptr(&item.shadowed) as usize, Arc::as_ptr(&item.parameter_dimensions) as usize, + item.qualified_types.identity(), ] } @@ -109,7 +110,7 @@ mod tests { ); let inherited = HashMap::from_iter([("P".into(), Expr::Literal("99".into()))]); let original = &active[0]; - let mut changed: Vec<_> = (0..5).map(|_| original.clone()).collect(); + let mut changed: Vec<_> = (0..6).map(|_| original.clone()).collect(); changed[0].env.insert("P".into(), 8); changed[1] .literals @@ -117,14 +118,24 @@ mod tests { changed[2].names.insert("alias".into(), "g.x".into()); Arc::make_mut(&mut changed[3].shadowed).insert("extra".into()); Arc::make_mut(&mut changed[4].parameter_dimensions).clear(); + changed[5] + .qualified_types + .insert("g.T".into(), Type::implicit()); let mut views = ScopeViews::with_literals(&dimensions, &inherited); for item in active.iter().chain(&changed) { let (cached_dimensions, cached_literals) = views.get(item); assert_eq!(cached_dimensions, &item.dimensions(&dimensions)); assert_eq!(&**cached_literals, &item.parameter_literals(&inherited)); } - assert_eq!(views.views.len(), 8); - assert_eq!(views.literal_views.len(), 8); + assert!(!views.dimensions(original).type_aliases.contains_key("g.T")); + assert!( + views + .dimensions(&changed[5]) + .type_aliases + .contains_key("g.T") + ); + assert_eq!(views.views.len(), 9); + assert_eq!(views.literal_views.len(), 9); // Collector inputs also bound the cache: a different inherited context // must never see the materialization from the preceding collector. let other = HashMap::from_iter([("P".into(), Expr::Literal("7".into()))]); diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 945f9e1528d..a57b12356e5 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -3073,7 +3073,41 @@ pub fn plan_interfaces( } /// Original paths of flattened interface fields, indexed by bound module name. -pub type InterfaceMemberPaths = HashMap>>; +pub type InterfaceMemberPaths = HashMap>; + +/// Provenance for a field flattened from an interface instance or instance array. +#[derive(Clone, Debug)] +pub struct InterfaceMemberPath { + pub segments: Vec, + pub arrayed: bool, +} + +impl InterfaceMemberPath { + /// Recover element indices only for a source-declared interface array. + pub fn restore(&self, flattened: &str) -> Option> { + let [handle, member] = self.segments.as_slice() else { + return None; + }; + if flattened == format!("{handle}{SEPARATOR}{member}") { + return Some(self.segments.clone()); + } + if !self.arrayed { + return None; + } + let indexed = flattened.strip_suffix(&format!("{SEPARATOR}{member}"))?; + let mut indices = indexed.strip_prefix(handle)?; + if indices.is_empty() { + return None; + } + while !indices.is_empty() { + let rest = indices.strip_prefix('[')?; + let (index, tail) = rest.split_once(']')?; + index.parse::().ok()?; + indices = tail; + } + Some(vec![indexed.to_string(), member.clone()]) + } +} /// Build the interface plan and retain source member paths for reflection. pub fn plan_interfaces_with_member_paths( @@ -3420,7 +3454,10 @@ pub fn plan_interfaces_with_member_paths( for member in &design.interfaces[&handle.interface].members { member_paths.insert( format!("{handle_name}{SEPARATOR}{}", member.name), - vec![handle_name.clone(), member.name.clone()], + InterfaceMemberPath { + segments: vec![handle_name.clone(), member.name.clone()], + arrayed: handle.arrayed, + }, ); } } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index a1fc0113ff7..1ed46598ace 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -11,6 +11,7 @@ //! locals of subroutines that keep their value are not supported. use super::*; +mod bit_result; /// The argument directions of each subroutine, by the names calls use. pub(super) type Directions = HashMap>; @@ -129,6 +130,8 @@ fn keep_in( pub(super) fn check_subroutine_statics( state: &AnalysisState, subroutine: &Subroutine, + constants: &HashMap, + locals: &[LocalVariable], statics: &HashSet, directions: &Directions, ) -> Result<(), AnalyzerError> { @@ -153,6 +156,18 @@ pub(super) fn check_subroutine_statics( ) .and_then(|entry| match entry { Entry::Unobserved => Ok(()), + Entry::Observed + if init.is_none() + && bit_result::proves_local( + state, + name, + &stmts[index + 1..], + constants, + locals, + ) => + { + Ok(()) + } Entry::Observed => Err(AnalyzerError::Unsupported(format!( "static variable `{}` of subroutine `{}` that keeps its value \ between calls (declare it `automatic`)", @@ -199,6 +214,9 @@ pub(super) fn check_subroutine_statics( /// a static function the variable named after it is static too, so a call /// that does not assign it returns the result of an earlier call. pub(super) fn check_static_result( + state: &AnalysisState, + constants: &HashMap, + locals: &[LocalVariable], subroutine: &Subroutine, directions: &Directions, ) -> Result<(), AnalyzerError> { @@ -214,6 +232,7 @@ pub(super) fn check_static_result( // `return value;` assigns the result as it leaves. match flow.block(&subroutine.body, false) { Ok(exits) if exits.next != Some(false) => Ok(()), + _ if bit_result::proves(state, subroutine, constants, locals) => Ok(()), _ => Err(AnalyzerError::Unsupported(format!( "static function `{}` whose result keeps its value between calls (assign it on \ every path, or declare the function `automatic`)", diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs new file mode 100644 index 00000000000..b0458e14acd --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs @@ -0,0 +1,344 @@ +//! Bounded bit coverage for static results and scratch locals filled by constant loops. +use super::*; +use num_bigint::BigUint; + +const MAX_BITS: usize = 65536; +const MAX_STEPS: usize = 65536; + +pub(super) fn proves( + state: &AnalysisState, + subroutine: &Subroutine, + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + let Some(name) = subroutine.return_var.as_deref() else { + return false; + }; + let Some(width) = subroutine + .return_type + .as_ref() + .and_then(|ty| ty.resolved_width()) + .filter(|width| (1..=MAX_BITS).contains(width)) + else { + return false; + }; + proves_variable(state, name, width, &subroutine.body, constants, locals) +} + +pub(super) fn proves_local( + state: &AnalysisState, + name: &str, + body: &[Stmt], + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + let Some(local) = locals.iter().find(|local| local.name == name) else { + return false; + }; + // The lowered local type's width already includes unpacked dimensions. + let Some(width) = local.r#type.resolved_width() else { + return false; + }; + proves_variable(state, name, width, body, constants, locals) +} + +pub(super) fn proves_variable( + state: &AnalysisState, + name: &str, + width: usize, + body: &[Stmt], + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + if !(1..=MAX_BITS).contains(&width) { + return false; + } + let mut env = constants.clone(); + let mut types = HashMap::default(); + for local in locals { + env.remove(&local.name); + if local.r#type.unpacked_ranges().is_empty() + && let Some(width) = local + .r#type + .resolved_width() + .filter(|width| (1..=64).contains(width)) + { + let signed = local.r#type.is_signed(); + types.insert(local.name.clone(), (width, signed)); + env.insert( + dimensions::parameter_width_marker(&local.name), + width as i128, + ); + env.insert( + dimensions::parameter_signed_marker(&local.name), + i128::from(signed), + ); + } + } + let mut proof = Proof { + state, + name, + width, + written: BigUint::default(), + full: (BigUint::from(1u8) << width) - BigUint::from(1u8), + env, + types, + remaining: MAX_STEPS, + }; + proof.block(body) == Some(true) +} + +struct Proof<'a> { + state: &'a AnalysisState, + name: &'a str, + width: usize, + written: BigUint, + full: BigUint, + env: HashMap, + types: HashMap, + remaining: usize, +} + +impl Proof<'_> { + fn readable(&self, expression: &Expr) -> bool { + pure(expression) && (self.written == self.full || !expr_reads(expression, self.name)) + } + + fn value(&self, expression: &Expr) -> Option { + if !self.readable(expression) { + return None; + } + let dims = PackedDimensions::new(HashMap::default(), &self.env, &HashMap::default()); + let value = expr_to_index_const(self.state, expression.clone(), &dims)?; + eval_ast_const_expr(self.state, &value, &self.env) + } + + fn store(&mut self, name: &str, value: Option) -> Option<()> { + self.env.remove(name); + if let Some(value) = value { + let (width, signed) = *self.types.get(name)?; + let low = if signed { -(1i128 << (width - 1)) } else { 0 }; + let high = if signed { + (1i128 << (width - 1)) - 1 + } else { + (1i128 << width) - 1 + }; + // Refuse to prove through assignment truncation. This keeps the + // abstract loop's iteration sequence equal to the declared type's. + if !(low..=high).contains(&value) { + return None; + } + self.env.insert(name.to_string(), value); + } + Some(()) + } + + /// `true` means no entry bit can subsequently be observed. Unknown control + /// flow or calls give no proof; the ordinary lifetime check still rejects. + fn block(&mut self, statements: &[Stmt]) -> Option { + for statement in statements { + self.remaining = self.remaining.checked_sub(1)?; + match statement { + Stmt::Local { name, init } if name != self.name => { + let value = init.as_ref().and_then(|value| self.value(value)); + if let Some(init) = init { + if !self.readable(init) { + return None; + } + } + self.store(name, value)?; + } + Stmt::Assign { + lhs, + rhs, + nonblocking: false, + } => { + if !self.readable(rhs) { + return None; + } + if lhs.name() == self.name { + match lhs { + LValue::Ident(_) => self.written = self.full.clone(), + LValue::Select { msb, lsb, .. } => { + if !pure_constant(msb) || !pure_constant(lsb) { + return None; + } + let left = eval_ast_const_expr(self.state, msb, &self.env)?; + let right = eval_ast_const_expr(self.state, lsb, &self.env)?; + let low = usize::try_from(left.min(right)).ok()?; + let high = usize::try_from(left.max(right)).ok()?; + if high >= self.width { + return None; + } + for bit in low..=high { + self.written.set_bit(bit as u64, true); + } + } + } + } else if let LValue::Ident(name) = lhs { + let value = self.value(rhs); + self.store(name, value)?; + } else if let LValue::Select { name, msb, lsb, .. } = lhs { + // A partial store loses our numeric value for this + // other local, but does not read its previous bits. + if !pure_constant(msb) + || !pure_constant(lsb) + || const_expr_reads(msb, self.name) + || const_expr_reads(lsb, self.name) + { + return None; + } + self.env.remove(name); + } + } + Stmt::Loop { + kind: crate::procedural::LoopKind::For, + init, + condition: Some(condition), + step, + body, + } => { + if self.block(init)? { + return Some(true); + } + while self.value(condition)? != 0 { + self.remaining = self.remaining.checked_sub(1)?; + if self.block(body)? || self.block(step)? { + return Some(true); + } + } + } + Stmt::If { + condition, + then_body, + else_body, + } => { + let branch = if self.value(condition)? != 0 { + then_body + } else { + else_body + }; + if self.block(branch)? { + return Some(true); + } + } + Stmt::Return(Some(value)) if self.readable(value) => return Some(true), + _ => return None, + } + if self.written == self.full { + return Some(true); + } + } + Some(self.written == self.full) + } +} + +fn pure_constant(expression: &ConstExpr) -> bool { + match expression { + ConstExpr::Ident(_) | ConstExpr::Literal(_) => true, + ConstExpr::Function { .. } => false, + ConstExpr::Select { expr, bit } => pure_constant(expr) && pure_constant(bit), + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + pure_constant(expr) && pure_constant(msb) && pure_constant(lsb) + } + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => pure_constant(expr), + ConstExpr::Binary { left, right, .. } => pure_constant(left) && pure_constant(right), + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => pure_constant(condition) && pure_constant(then_expr) && pure_constant(else_expr), + } +} + +fn pure(expression: &Expr) -> bool { + match expression { + Expr::Ident(_) | Expr::Literal(_) => true, + Expr::Call { .. } => false, + Expr::Select { expr, msb, lsb, .. } => { + pure(expr) && pure_constant(msb) && pure_constant(lsb) + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => pure(expr), + Expr::Binary { left, right, .. } => pure(left) && pure(right), + Expr::Mux { + condition, + then_expr, + else_expr, + } => pure(condition) && pure(then_expr) && pure(else_expr), + Expr::Concat(parts) => parts.iter().all(pure), + Expr::RepeatConcat { count, parts } => pure_constant(count) && parts.iter().all(pure), + Expr::Inside { expr, items } => { + pure(expr) && items.iter().all(|item| item.exprs().into_iter().all(pure)) + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn incomplete_or_entry_dependent_scratch_arrays_stay_rejected() { + for body in [ + "for(integer i=0;i<1;i=i+1) words[i]=a;", + "for(integer i=0;i<2;i=i+1) words[0]=a;", + "for(integer i=0;i<2;i=i+1) words[i]=words[i]^a;", + "if(a[0]) for(integer i=0;i<2;i=i+1) words[i]=a;", + "other[words[0]]=0; for(integer i=0;i<2;i=i+1) words[i]=a;", + ] { + let source = format!( + "module Top(input logic[7:0] a, output logic[7:0] y); \ + function [7:0] f(input logic[7:0] a); \ + logic[7:0] words[1:0]; logic[7:0] other; {body} \ + f=words[0]+words[1]; endfunction assign y=f(a); endmodule" + ); + let error = crate::analyze_source(&source, std::path::Path::new("partial-scratch.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("static variable `words`"), "{body}: {error}"); + } + } + + #[test] + fn incomplete_or_entry_dependent_results_stay_rejected() { + for body in [ + "for(integer i=0;i<3;i=i+1) f[i]=a[i];", + "for(integer i=0;i<4;i=i+1) f[0]=a[i];", + "for(integer i=0;i<0;i=i+1) f[i]=a[i];", + "if(a[0]) for(integer i=0;i<4;i=i+1) f[i]=a[i];", + "for(integer i=0;i<4;i=i+1) begin if(i==2) break; f[i]=a[i]; end", + "for(integer i=0;i<4;i=i+1) f[i]=f[i]^a[i];", + "for(byte i=127;i<129;i=i+1) f[i%4]=a[i%4];", + ] { + let source = format!( + "module Top(input logic[3:0] a, output logic[3:0] y); \ + function [3:0] f(input logic[3:0] a); {body} endfunction \ + assign y=f(a); endmodule" + ); + let error = crate::analyze_source(&source, std::path::Path::new("partial-result.sv")) + .unwrap_err() + .to_string(); + assert!( + error.contains("whose result keeps its value"), + "{body}: {error}" + ); + } + } + + #[test] + fn index_calls_do_not_prove_bit_coverage() { + let source = r#" + module Top(input logic[3:0] a, output logic[3:0] y); + function automatic integer mutate(inout integer index); + index=3; return 0; + endfunction + function [3:0] f(input logic[3:0] a); + for(integer i=0;i<4;i=i+1) f[mutate(i)]=a[i]; + endfunction + assign y=f(a); + endmodule + "#; + let error = crate::analyze_source(source, std::path::Path::new("index-call.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("whose result keeps its value"), "{error}"); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 4445dcde46d..8bd0afb46cf 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -806,7 +806,7 @@ pub(super) fn parameter_element_literal( }; let element_width = width_from(indices.len())?; let total_width = width_from(0)?; - if total_width > 127 { + if total_width > 128 { return None; } let signed = env @@ -826,8 +826,15 @@ pub(super) fn parameter_element_literal( let from_right = usize::try_from(index.abs_diff(right)).ok()?; offset = offset.checked_add(from_right.checked_mul(width_from(position + 1)?)?)?; } - let value = *env.get(name)? as u128 & ((1u128 << total_width) - 1); - let element = (value >> offset) & ((1u128 << element_width) - 1); + let mask = |width| { + if width == 128 { + u128::MAX + } else { + (1u128 << width) - 1 + } + }; + let value = *env.get(name)? as u128 & mask(total_width); + let element = (value >> offset) & mask(element_width); Some(format!( "{element_width}'{signing}b{element:0element_width$b}" )) @@ -878,10 +885,26 @@ pub(super) fn enum_member_constants_from_scope( base_const_env: &HashMap, type_aliases: &HashMap, parameter_overrides: &HashMap, +) -> Result { + let items = syntax_tree.body_membership()?; + enum_member_constants_from_items( + syntax_tree, + &items, + base_const_env, + type_aliases, + parameter_overrides, + ) +} + +pub(super) fn enum_member_constants_from_items( + syntax_tree: &AnalysisContext<'_>, + declarations: &[celox_sv_syntax::BodyItemId], + base_const_env: &HashMap, + type_aliases: &HashMap, + parameter_overrides: &HashMap, ) -> Result { use celox_sv_syntax::{BodyItemKind, DataTypeKind, TypeAliasTarget}; let native = syntax_tree.declarations(); - let declarations = syntax_tree.body_membership()?; let enum_type = |id| { let BodyItemKind::TypeAlias(alias) = native.body_item(id).kind else { return None; @@ -899,7 +922,7 @@ pub(super) fn enum_member_constants_from_scope( let mut resolved_type_aliases = type_aliases.clone(); let mut parameters = Vec::new(); let no_overrides = HashMap::default(); - for id in declarations { + for &id in declarations { if let BodyItemKind::Parameter(_) = native.body_item(id).kind { let authored = ownership::body(id, syntax_tree)?; let local = authored.first().is_some_and(|parameter| parameter.local); @@ -917,7 +940,12 @@ pub(super) fn enum_member_constants_from_scope( }, )?; extend_const_env_with_parameters(&syntax_tree.state, &mut eval_env, ¶meters); - resolved_type_aliases = type_aliases_from_scope_with_env(syntax_tree, &eval_env)?; + resolved_type_aliases = types::type_aliases_from_body_with_env( + syntax_tree, + declarations, + &eval_env, + &resolved_type_aliases, + )?; continue; } let Some(id) = enum_type(id) else { @@ -1006,7 +1034,12 @@ pub(super) fn enum_member_constants_from_scope( // A later typedef may use a cast or range that depends on this // enum's members. Rebuild aliases from the enriched environment // before resolving a subsequent enum base through that typedef. - resolved_type_aliases = type_aliases_from_scope_with_env(syntax_tree, &eval_env)?; + resolved_type_aliases = types::type_aliases_from_body_with_env( + syntax_tree, + declarations, + &eval_env, + &resolved_type_aliases, + )?; } Ok(constants) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 1ce0ac90e77..3d5af5962cc 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1458,11 +1458,19 @@ pub(super) fn lower_subroutine( lifetimes::check_subroutine_statics( &tree.state, &subroutine, + &builder.dims.const_env, + builder.state.locals, &statics, builder.state.subroutine_directions, )?; if !builder.automatic { - lifetimes::check_static_result(&subroutine, builder.state.subroutine_directions)?; + lifetimes::check_static_result( + &tree.state, + &builder.dims.const_env, + builder.state.locals, + &subroutine, + builder.state.subroutine_directions, + )?; } Ok(subroutine) } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 30dea33af77..7bce362fd3d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -524,6 +524,7 @@ impl ScopeSymbols { rename.r#type(port.r#type.clone()), port.is_net, ) + .with_default(port.default.clone().map(|value| rename.const_expr(value))) }) .collect(), signals: self diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 505cbca70f9..09b1184363f 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -979,8 +979,45 @@ pub(super) fn indexed_select_bounds_values( .unwrap_or(false); // The base is self-determined; endpoint arithmetic must not inherit its // unsigned type or truncate a carry across the base expression's width. - let base = eval_ast_const_expr(state, &base, &dimensions.const_env) - .ok_or_else(|| unsupported("indexed part-select start"))?; + let Some(base_value) = eval_ast_const_expr(state, &base, &dimensions.const_env) else { + // A procedural loop index is not constant while its body is bound. + // Keep the endpoints in declared coordinates so normal memory range + // flattening retains the element offset. Lowering can then unroll the + // loop before requiring a constant selection inside each memory word. + let memory_word = name + .and_then(|name| dimensions.get(name)) + .is_some_and(|shape| { + !shape.unpacked.is_empty() + && index_count == shape.unpacked.len() + && shape.packed.len() == 1 + }); + let ty = self_determined_type(state, &base, dimensions).filter(|ty| ty.0 <= 32); + let Some(ty) = ty.filter(|_| memory_word) else { + return Err(unsupported("indexed part-select start")); + }; + let base = ConstExpr::Resize { + expr: Box::new(self_determined_index(state, base, dimensions)), + width: 64, + signed: ty.1, + }; + // Zero-extend unsigned indices before using signed endpoint arithmetic. + let base = ConstExpr::Resize { + expr: Box::new(base), + width: 64, + signed: true, + }; + let other = ConstExpr::Binary { + left: Box::new(base.clone()), + op: if plus { BinaryOp::Add } else { BinaryOp::Sub }, + right: Box::new(ConstExpr::Literal(format!("64'sd{}", width - 1))), + }; + return Ok(if plus == ascending { + (base, other) + } else { + (other, base) + }); + }; + let base = base_value; let overflow = || unsupported("indexed part-select bounds"); let offset = width - 1; let other = if plus { @@ -1315,7 +1352,11 @@ fn self_determined_type( Some((literal.width, literal.signed)) } ConstExpr::Ident(name) => { - let variable = dimensions.get(name)?; + let Some(variable) = dimensions.get(name) else { + return dimensions::parameter_type_from_const_env(const_env, name) + .map(|ty| (ty.width, ty.signed)) + .or_else(|| const_env.contains_key(name).then_some((32, true))); + }; if !variable.unpacked.is_empty() { return None; } diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 48811337dad..fa20c7e6cb5 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -10,9 +10,35 @@ pub(super) fn type_aliases_from_scope( pub(super) fn type_aliases_from_scope_with_env( syntax_tree: &AnalysisContext<'_>, const_env: &HashMap, +) -> Converted> { + type_aliases_in_scope(syntax_tree, const_env, &HashMap::default(), true, None) +} + +/// Resolve a selected body while retaining its enclosing lexical type bindings. +pub(super) fn type_aliases_from_body_with_env( + syntax_tree: &AnalysisContext<'_>, + items: &[celox_sv_syntax::BodyItemId], + const_env: &HashMap, + inherited: &HashMap, +) -> Converted> { + type_aliases_in_scope(syntax_tree, const_env, inherited, false, Some(items)) +} + +fn type_aliases_in_scope( + syntax_tree: &AnalysisContext<'_>, + const_env: &HashMap, + inherited: &HashMap, + include_header: bool, + items: Option<&[celox_sv_syntax::BodyItemId]>, ) -> Converted> { let mut aliases = scope::imported(&syntax_tree.state).type_aliases.clone(); - if syntax_tree.scope_handle() != crate::source_tree::ScopeHandle::Compilation { + aliases.extend( + inherited + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + if include_header && syntax_tree.scope_handle() != crate::source_tree::ScopeHandle::Compilation + { for parameter in syntax_tree.root_unit()?.parameters.iter().flatten() { add_type_parameter( parameter, @@ -23,11 +49,11 @@ pub(super) fn type_aliases_from_scope_with_env( )?; } } - let mut pending = syntax_tree - .body_membership()? - .into_iter() - .rev() - .collect::>(); + let members = match items { + Some(items) => items.to_vec(), + None => syntax_tree.body_membership()?, + }; + let mut pending = members.into_iter().rev().collect::>(); while let Some(id) = pending.pop() { match &syntax_tree.declarations().body_item(id).kind { BodyItemKind::Region(items) => pending.extend(items.iter().rev()), diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index ec2eab0ac6c..c68a5d34ca4 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -305,9 +305,6 @@ fn validate_scope( if !selected(port.tokens) { continue; } - if port.default.is_some() { - return Err(unsupported("ANSI port default value")); - } if port .data_type .is_some_and(|id| matches!(native.data_type(id).kind, DataTypeKind::Enum { .. })) diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 9f2f486daba..8043ee03782 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -328,6 +328,7 @@ pub struct Port { direction: PortDirection, r#type: Type, is_net: bool, + default: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -384,6 +385,7 @@ impl Port { direction, r#type, is_net, + default: None, } } @@ -402,6 +404,15 @@ impl Port { pub fn is_net(&self) -> bool { self.is_net } + + pub(crate) fn with_default(mut self, default: Option) -> Self { + self.default = default; + self + } + + pub fn default(&self) -> Option<&ConstExpr> { + self.default.as_ref() + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 4f8fa0b85bb..a9deafc2c07 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -28,7 +28,8 @@ pub mod system_functions; pub mod typecheck; pub use ast::interfaces::{ - InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, plan_interfaces_with_member_paths, + InterfaceMemberPath, InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, + plan_interfaces_with_member_paths, }; pub use ast::interfaces::{ InterfacePrototype, interface_prototypes, interface_prototypes_for, diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs b/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs index 3ac913da8ec..cb6fad3d153 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs @@ -423,7 +423,6 @@ mod parameter_tests { #[test] fn native_override_special_forms_preserve_existing_diagnostics() { for (value, diagnostic) in [ - ("1?2:3", "parameter override expression"), ("1:2:3", "mintypmax expression"), ("1 inside {1,2}", "parameter override expression"), ] { diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 5c157f76050..5eb7cb7aa24 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -1481,6 +1481,9 @@ fn literal_as_i128(value: &str) -> Option { /// Static type of a syntax-validated literal, without expanding a sized value. /// Type queries need only the size/sign prefix, including for huge operands. pub(crate) fn integral_literal_type_metadata(value: &str) -> Option<(usize, bool)> { + if value.trim().starts_with('"') { + return parse_string_literal(value.trim()).map(|literal| (literal.width, false)); + } let normalized = value.trim().replace('_', ""); if let Some((size, based)) = normalized.split_once('\'') && !size.is_empty() @@ -1498,6 +1501,9 @@ pub(crate) fn integral_literal_type_metadata(value: &str) -> Option<(usize, bool } pub fn parse_integral_literal(value: &str) -> Option { + if value.trim().starts_with('"') { + return parse_string_literal(value.trim()); + } let normalized = value.trim().replace('_', ""); if let Some(literal) = parse_unbased_unsized_literal(&normalized) { return Some(literal); @@ -1509,6 +1515,107 @@ pub fn parse_integral_literal(value: &str) -> Option { } } +/// Parse a single SV literal, optionally preceded by a unary sign. +/// Parameter overrides use this instead of accepting arbitrary source text. +pub fn parse_parameter_literal(text: &str) -> Option { + let text = text.trim(); + let (op, literal) = if let Some(value) = text.strip_prefix('-') { + (Some(UnaryOp::Minus), value.trim()) + } else if let Some(value) = text.strip_prefix('+') { + (Some(UnaryOp::Plus), value.trim()) + } else { + (None, text) + }; + let mut sources = celox_sv_syntax::SourceMap::default(); + let file = sources.add("", literal); + let tokens = celox_sv_syntax::lex(&sources, file).ok()?; + let [token] = tokens.as_slice() else { + return None; + }; + if !matches!( + token.kind, + celox_sv_syntax::TokenKind::Number | celox_sv_syntax::TokenKind::String + ) { + return None; + } + parse_integral_literal(literal)?; + let value = ConstExpr::Literal(literal.to_string()); + Some(match op { + Some(op) => ConstExpr::Unary { + op, + expr: Box::new(value), + }, + None => value, + }) +} + +// IEEE 1800-2023 5.9 and 5.9.1: in integral expressions a string +// literal is an unsigned packed sequence of bytes, including decoded escapes. +fn parse_string_literal(text: &str) -> Option { + let body = text.strip_prefix('"')?.strip_suffix('"')?; + let mut input = body.bytes().peekable(); + let mut bytes = Vec::new(); + while let Some(byte) = input.next() { + let byte = match byte { + b'\\' => match input.next()? { + b'\n' => continue, + b'\r' if input.peek() == Some(&b'\n') => { + input.next(); + continue; + } + b'n' => b'\n', + b't' => b'\t', + b'v' => 11, + b'f' => 12, + b'a' => 7, + first @ b'0'..=b'7' => { + let mut value = u16::from(first - b'0'); + for _ in 0..2 { + let Some(next @ b'0'..=b'7') = input.peek().copied() else { + break; + }; + input.next(); + value = value * 8 + u16::from(next - b'0'); + } + value as u8 + } + b'x' => { + let mut value = 0; + let mut count = 0; + for _ in 0..2 { + let Some(next) = input + .peek() + .copied() + .and_then(|b| char::from(b).to_digit(16)) + else { + break; + }; + input.next(); + value = value * 16 + next as u8; + count += 1; + } + if count == 0 { + return None; + } + value + } + escaped if escaped.is_ascii() => escaped, + _ => return None, + }, + b'"' | b'\n' | b'\r' => return None, + byte if byte.is_ascii() => byte, + _ => return None, + }; + bytes.push(byte); + } + Some(IntegralLiteral { + width: bytes.len().max(1).checked_mul(8)?, + signed: false, + value: BigUint::from_bytes_be(&bytes), + mask: BigUint::default(), + }) +} + fn parse_unbased_unsized_literal(value: &str) -> Option { let mut chars = value.chars(); (chars.next()? == '\'' && chars.clone().count() == 1).then_some(())?; diff --git a/crates/celox-test-suite/src/sv/cases/generate.vtest b/crates/celox-test-suite/src/sv/cases/generate.vtest index 07807734aaa..db206a46a8b 100644 --- a/crates/celox-test-suite/src/sv/cases/generate.vtest +++ b/crates/celox-test-suite/src/sv/cases/generate.vtest @@ -871,3 +871,58 @@ (top Top) (eval) (assert_eq y 4)) + +(case generate_local_typedefs_keep_lexical_scope + (source "generate_types.sv" #" + module Top(input logic[7:0] a, output logic[7:0] y,z,widths, + output logic[3:0] root_value, output logic[7:0] parent_value); + typedef logic[3:0] T; + T root; + assign root=a[3:0]; + assign root_value=root; + if(1) begin:left + typedef logic[7:0] T; + typedef logic[1:0] state_t; localparam LEFT_ON=3; + T temp; + state_t state; + assign state=LEFT_ON; + assign temp=a; + assign y=(state==3) ? temp : 0; + T after_inner; + if(1) begin:inner + typedef logic[1:0] inner_t; + inner_t tiny; + assign tiny=a[1:0]; + end + assign after_inner=a; + assign parent_value=after_inner; + end + if(1) begin:right + typedef logic[3:0] T; + typedef logic[1:0] state_t; localparam RIGHT_ON=2; + T temp; + state_t state; + assign state=RIGHT_ON; + assign temp=a[3:0]; + assign z=(state==2) ? {4'hc,temp} : 0; + end + for(genvar i=0;i<2;i=i+1) begin:lanes + typedef logic[i+2:0] lane_t; + lane_t temp; + assign temp=a; + assign widths[4*i+:4]=$bits(temp); + end + endmodule + "#) + (top Top) + (modify (set a 0xa7)) + (assert_eq y 0xa7) + (assert_eq z 0xc7) + (assert_eq root_value 7) + (assert_eq parent_value 0xa7) + (assert_eq widths 0x43) + (modify (set a 0x5c)) + (assert_eq y 0x5c) + (assert_eq z 0xcc) + (assert_eq root_value 0xc) + (assert_eq parent_value 0x5c)) diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index b9e4bb1b180..ef8a2439d0c 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1,5 +1,34 @@ (group hierarchy (category hierarchy)) +(case input_port_defaults_use_child_scope_and_only_omitted_connections + (source "default_input.sv" #" + module Child #(parameter D=8'ha5)(output logic [7:0] y, + input logic [7:0] a=D); + assign y=a; + endmodule + module Fill(output logic [7:0] y, input logic [7:0] a='1); + assign y=a; + endmodule + module Top #(parameter D=0)(input logic [7:0] a, + output logic [7:0] omitted, open, connected, positional, fill); + Child #(.D(8'h96)) c0(.y(omitted)); + Child c1(.a(),.y(open)); + Child c2(.a(a),.y(connected)); + Child c3(positional); + Fill c4(.y(fill)); + endmodule + "#) + (top Top) + (modify (set a 0)) + (assert_eq omitted 0x96) + (assert_eq open 0xa5) + (assert_eq connected 0) + (assert_eq positional 0xa5) + (assert_eq fill 0xff) + (modify (set a 0x5a)) + (assert_eq connected 0x5a) + (assert_eq omitted 0x96)) + (case drives_omitted_and_open_child_inputs_with_z (four_state) (source "open_input.sv" #" @@ -558,3 +587,80 @@ (assert_eq override_var 5) (assert_eq override_type 15) (assert_eq override_array 15)) + +(case concatenated_parameter_actuals_use_each_parent_specialization + (source "concat_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=1, parameter logic[7:0] V=8'ha5)( + output logic[31:0] repeated, combined); + Child #(.P({N{V}})) c0(repeated); + Child #(.P({V,8'(N)})) c1(combined); + endmodule + module Top(output logic[31:0] a, b, c, d); + Parent #(.N(1),.V(8'h12)) p0(a,b); + Parent #(.N(3),.V(8'hc3)) p1(c,d); + endmodule + "#) + (top Top) + (assert_eq a 0x12) + (assert_eq b 0x1201) + (assert_eq c 0xc3c3c3) + (assert_eq d 0xc303)) + +(case conditional_parameter_actuals_follow_parent_specialization + (source "conditional_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=1)(output logic [31:0] y, z); + Child #(.P(N > 2 ? N+10 : 3)) c0(y); + Child #(.P(N > 2 ? (N > 4 ? 8 : 7) : 6)) c1(z); + endmodule + module Top(output logic [31:0] a,b,c,d); + Parent p0(a,b); + Parent #(.N(4)) p1(c,d); + endmodule + "#) + (top Top) + (assert_eq a 3) + (assert_eq b 6) + (assert_eq c 14) + (assert_eq d 7)) + +(case generated_parameter_part_select_actuals + (source "selected_actual.sv" #" + module Child #(parameter P=0)(output logic [1:0] y); + assign y=P; + endmodule + module Parent #(parameter logic [7:0] P=8'he4)(output logic [7:0] y); + for(genvar i=0;i<4;i=i+1) begin:g + Child #(.P(P[i*2 +: 2])) c(y[i*2 +: 2]); + end + endmodule + module Top(output logic [7:0] a,b); + Parent p0(a); + Parent #(.P(8'h1b)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 0xe4) + (assert_eq b 0x1b)) + +(case sized_parameter_actuals_follow_parent_specialization + (source "sized_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=8)(output logic [31:0] y); + Child #(.P(N'(16'hfedc))) c(y); + endmodule + module Top(output logic [31:0] a,b); + Parent p0(a); + Parent #(.N(12)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 0xdc) + (assert_eq b 0xedc)) diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 06570bc4e76..34f641f537e 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1667,3 +1667,72 @@ (assert_eq wrapped (& (>> by_index (* next 8)) 255)) (tick clk) (assert_eq registered value))) + +(case procedural_loop_writes_memory_word_part_selects + (source "memory_byte_enables.sv" #" + module Top #(parameter BYTE_W=8)(input logic clk, rst, input logic [1:0] addr, strobe, + input logic [15:0] data, output logic [15:0] q, ascending_q); + logic [15:0] mem[0:3]; + logic [0:15] ascending_mem[3:0]; + always_ff @(posedge clk) begin + if (rst) begin + for (integer i=0; i<4; i=i+1) begin + mem[i] <= 0; + ascending_mem[i] <= 0; + end + end else begin + for (integer i=0; i<2; i=i+1) begin + if (strobe[i]) begin + mem[addr][BYTE_W*i +: BYTE_W] <= data[BYTE_W*i +: BYTE_W]; + ascending_mem[addr][2*BYTE_W-1-BYTE_W*i -: BYTE_W] <= data[BYTE_W*i +: BYTE_W]; + end + end + end + end + assign q=mem[addr]; + assign ascending_q=ascending_mem[addr]; + endmodule + "#) + (top Top) + (modify (set rst 1) (set addr 0) (set strobe 0) (set data 0)) + (tick clk) + (assert_eq q 0) + (assert_eq ascending_q 0) + (modify (set rst 0) (set strobe 3) (set data 0x1234)) + (tick clk) + (assert_eq q 0x1234) + (assert_eq ascending_q 0x1234) + (modify (set addr 1) (set strobe 1) (set data 0xabcd)) + (tick clk) + (assert_eq q 0x00cd) + (assert_eq ascending_q 0x00cd) + (modify (set strobe 2) (set data 0x5678)) + (tick clk) + (assert_eq q 0x56cd) + (assert_eq ascending_q 0x56cd) + (modify (set strobe 0) (set data 0xffff)) + (tick clk) + (assert_eq q 0x56cd) + (assert_eq ascending_q 0x56cd) + (modify (set addr 0)) + (assert_eq q 0x1234) + (assert_eq ascending_q 0x1234) + (modify (set addr 2)) + (assert_eq q 0) + (assert_eq ascending_q 0)) + +(case indexed_selections_in_constant_declaration_contexts + (source "declaration_select.sv" #" + module Top(output logic [3:0] enumeration, output logic [31:0] width); + localparam logic [7:0] P=8'hab; + logic [P[4 +: 4]-1:0] y; + typedef enum logic [3:0] { E=P[4 +: 4] } nibble; + nibble state; + assign state=E; + assign enumeration=state; + assign width=$bits(y); + endmodule + "#) + (top Top) + (assert_eq enumeration 10) + (assert_eq width 10)) diff --git a/crates/celox-test-suite/src/sv/cases/literals.vtest b/crates/celox-test-suite/src/sv/cases/literals.vtest index b5164bc0b56..9c90d6c3820 100644 --- a/crates/celox-test-suite/src/sv/cases/literals.vtest +++ b/crates/celox-test-suite/src/sv/cases/literals.vtest @@ -47,3 +47,30 @@ (let mask (xmask (get y))) (assert (== value 0b1011)) (assert (== mask 0b0011))) + +(case string_literals_are_unsigned_packed_bytes + (source "string_literals.sv" #" + module Child #(parameter P="fallback")(output logic [63:0] y); + assign y=P; + endmodule + module Top #(parameter VENDOR="XILINX")( + output logic matched, output logic [63:0] forwarded, + output logic [47:0] escaped, output logic [23:0] underscore, + output logic [7:0] empty_width, output logic [15:0] extended); + localparam TEXT="A_B"; + localparam COPY=TEXT; + assign matched=(VENDOR == "XILINX") && (COPY == "A_B"); + Child #(.P(VENDOR)) child(forwarded); + assign escaped={"\101", "\x42", "\n", "\t", "\\", "\""}; + assign underscore=COPY; + assign empty_width=$bits(""); + assign extended="\200"; + endmodule + "#) + (top Top) + (assert_eq matched 1) + (assert_eq forwarded 0x58494c494e58) + (assert_eq escaped 0x41420a095c22) + (assert_eq underscore 0x415f42) + (assert_eq empty_width 8) + (assert_eq extended 0x80)) diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index be1e0c90737..8af35d60f9a 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -937,6 +937,105 @@ (modify (set a 0b10)) (assert_eq y 0xaa)) +(case forwards_replicated_parameter_values + (source "replicated_parameter.sv" #" + module Child #(parameter P=0)(output logic [63:0] y); + assign y=P; + endmodule + module Top #(parameter N=2, parameter P={N{32'h12345678}})( + output logic [63:0] y); + Child #(.P(P)) child(.y(y)); + endmodule + "#) + (top Top) + (assert_eq y 0x1234567812345678)) + +(case size_casts_resolve_generated_locals_and_parameter_expressions + (source "scoped_cast.sv" #" + module Child #(parameter N=2, parameter signed S=-3)(input logic [7:0] bus_data, + input logic select, input logic [7:0] data, + output logic [15:0] y, signed_value, unsigned_value); + if (N>1) begin : g + logic [7:0] saved; + assign saved=data; + assign y=16'(select ? saved : bus_data); + assign signed_value=16'(S+1); + assign unsigned_value=16'(8'(8'(N)-8'd3)); + end + endmodule + module Top(input logic select, input logic [7:0] data, + output logic [15:0] y, signed_value, unsigned_value); + Child child(8'h80, select, data, y, signed_value, unsigned_value); + endmodule + "#) + (top Top) + (modify (set select 0) (set data 0xf1)) + (assert_eq y 0x80) + (assert_eq signed_value 0xfffe) + (assert_eq unsigned_value 0xff) + (modify (set select 1)) + (assert_eq y 0xf1)) + +(case parameter_size_casts_in_generate_conditions + (source "generate_cast.sv" #" + module Top #(parameter W=3, parameter MASK=3'b100)( + output logic [7:0] y, output logic signed_test, output logic guard); + if ((W'(MASK) & {W{1'b1}}) == 0) assign y=8'h11; + else assign y=8'hab; + if (W'(-1) < 0) assign signed_test=1'b1; + else assign signed_test=1'b0; + if ((0 || 0) && (W'(MASK) & {W{1'b1}}) == 0) assign guard=1'b0; + else assign guard=1'b1; + endmodule + "#) + (top Top) + (assert_eq y 0xab) + (assert_eq signed_test 1) + (assert_eq guard 1)) + +(case zero_count_replications_preserve_concat_bits + (source "zero_replication.sv" #" + module Top #(parameter PAD=0)(input logic [3:0] a, + output logic [7:0] front, middle, back); + assign front = {{PAD{1'bx}}, a, 4'h5}; + assign middle = {4'ha, {PAD{1'bz}}, a}; + assign back = {a, 4'hc, {PAD{1'b1}}}; + endmodule + "#) + (top Top) + (modify (set a 9)) + (assert_eq front 0x95) + (assert_eq middle 0xa9) + (assert_eq back 0x9c) + (modify (set a 3)) + (assert_eq front 0x35) + (assert_eq middle 0xa3) + (assert_eq back 0x3c)) + +(case zero_count_replications_preserve_unknown_bits + (four_state) + (source "zero_replication.sv" #" + module Top #(parameter PAD=0)(input logic [3:0] a, + output logic [7:0] front, middle, back); + assign front = {{PAD{1'bx}}, a, 4'h5}; + assign middle = {4'ha, {PAD{1'bz}}, a}; + assign back = {a, 4'hc, {PAD{1'b1}}}; + endmodule + "#) + (top Top) + (modify (set a 9)) + (assert_eq front 0x95) + (assert_eq middle 0xa9) + (assert_eq back 0x9c) + (modify (set a 3)) + (assert_eq front 0x35) + (assert_eq middle 0xa3) + (assert_eq back 0x3c) + (modify (set a (fourstate 0xa 0x5))) + (assert_eq front (fourstate 0xa5 0x50)) + (assert_eq middle (fourstate 0xaa 0x05)) + (assert_eq back (fourstate 0xac 0x50))) + (case preserves_unknown_complement_and_converts_bit_function_arguments (four_state) (source "four_state_unary.sv" #" diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 12890845ac2..3b571e71fee 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -705,3 +705,99 @@ "#) (top Top) (assert_eq partial (fourstate 0xd 0x5))) + +(case static_function_result_filled_by_constant_loops + (source "static_result.sv" #" + module Top #(parameter W=5)(input logic [W-1:0] gray, + output logic [W-1:0] binary, reversed); + function [W-1:0] gray_to_binary(input logic [W-1:0] g); + for (integer i=0; i> i); + endfunction + function [W-1:0] reverse_bits(input logic [W-1:0] g); + for (integer i=W-1; i>=0; i=i-1) + reverse_bits[W-1-i]=g[i]; + endfunction + assign binary=gray_to_binary(gray); + assign reversed=reverse_bits(gray); + endmodule + "#) + (top Top) + (modify (set gray 0x00)) + (assert_eq binary 0x00) + (assert_eq reversed 0x00) + (modify (set gray 0x10)) + (assert_eq binary 0x1f) + (assert_eq reversed 0x01) + (modify (set gray 0x04)) + (assert_eq binary 0x07) + (assert_eq reversed 0x04) + (modify (set gray 0x1b)) + (assert_eq binary 0x12) + (assert_eq reversed 0x1b)) + +(case static_function_scratch_arrays_are_filled_before_reads + (source "scratch_array.sv" #" + module Top(input logic [7:0] a, output logic [7:0] y); + function [7:0] transform(input logic [7:0] value); + logic [7:0] words [1:0]; + for(integer i=0;i<2;i=i+1) begin + words[i]='0; + words[i][i]=value[i]; + end + transform=words[0]+words[1]; + endfunction + assign y=transform(a); + endmodule + "#) + (top Top) + (set a 3) + (eval) + (assert_eq y 3) + (set a 0) + (eval) + (assert_eq y 0) + (set a 2) + (eval) + (assert_eq y 2)) + +(case constant_functions_preserve_concat_operand_widths + (source "constant_concat.sv" #" + module Top(output logic [15:0] a,b, output logic [7:0] zero_part); + function automatic [15:0] expand(input logic [3:0] value); + expand={{2{value}},value,4'h5}; + endfunction + function automatic [7:0] trim(input logic [3:0] value); + trim={4'hd,{0{value}},value}; + endfunction + localparam A=expand(4'h2), B=expand(4'ha), Z=trim(4'h3); + assign a=A; + assign b=B; + assign zero_part=Z; + endmodule + "#) + (top Top) + (assert_eq a 0x2225) + (assert_eq b 0xaaa5) + (assert_eq zero_part 0xd3)) + +(case constant_functions_inside_selected_parameter_initializers + (source "selected_constant_function.sv" #" + module Parent #(parameter W=8)(output logic [31:0] y); + localparam logic [31:0] WIDTHS=W; + function automatic [31:0] make_mask(input integer unused); + integer width; + width=WIDTHS[0 +: 8]; + make_mask={32{1'b1}}>>(32-width); + endfunction + localparam logic [31:0] MASK=(W==0) ? 32'(0) : make_mask(0); + assign y=MASK; + endmodule + module Top(output logic [31:0] a,b); + Parent p0(a); + Parent #(.W(4)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 255) + (assert_eq b 15)) diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index d92de3fbb29..0088f8a35a7 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -292,7 +292,10 @@ pub(super) fn run() -> bool { } iterations += 1; if iterations > 1_000_000 { - fail("VPI callback scheduler exceeded 1000000 iterations".to_string()); + fail( + "VPI callback scheduler exceeded 1000000 iterations without advancing time" + .to_string(), + ); break; } @@ -362,7 +365,14 @@ pub(super) fn run() -> bool { let Some(next_time) = next_time else { break; }; - with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.time = next_time)); + with_host(|host| { + borrow_cell_mut(&host.callbacks, |state| { + if next_time > state.time { + iterations = 0; + } + state.time = next_time; + }) + }); fire_all(CB_NEXT_SIM_TIME); if !finish_requested() { super::flush_pending_writes(); diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 4d31bbed865..7b72d33a241 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -50,6 +50,9 @@ pub const VPI_X: i32 = 3; pub const VPI_ITERATOR: i32 = 27; pub const VPI_CONSTANT: i32 = 7; pub const VPI_MODULE: i32 = 32; +pub const VPI_PARAMETER: i32 = 41; +pub const VPI_CONST_TYPE: i32 = 40; +pub const VPI_BINARY_CONST: i32 = 3; pub const VPI_NET: i32 = 36; pub const VPI_PORT: i32 = 44; pub const VPI_REG: i32 = 48; @@ -723,29 +726,33 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand .collect() }) .unwrap_or_default(), - (VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES, Some(ObjectRef::Scope(id))) => { - reflection - .scope(id) - .map(|scope| { - scope - .signals - .iter() - .copied() - .filter(|signal_id| { - let signal = reflection.signal(*signal_id).unwrap(); - match kind { - VPI_PORT => signal.direction != SignalDirection::Internal, - VPI_REG => true, - VPI_VARIABLES => signal.direction == SignalDirection::Internal, - VPI_NET => false, - _ => false, - } - }) - .map(ObjectRef::Signal) - .collect() - }) - .unwrap_or_default() - } + ( + VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, + Some(ObjectRef::Scope(id)), + ) => reflection + .scope(id) + .map(|scope| { + scope + .signals + .iter() + .copied() + .filter(|signal_id| { + let signal = reflection.signal(*signal_id).unwrap(); + if signal.is_parameter { + return kind == VPI_PARAMETER; + } + match kind { + VPI_PORT => signal.direction != SignalDirection::Internal, + VPI_REG => true, + VPI_VARIABLES => signal.direction == SignalDirection::Internal, + VPI_NET => false, + _ => false, + } + }) + .map(ObjectRef::Signal) + .collect() + }) + .unwrap_or_default(), _ => Vec::new(), } }) @@ -784,7 +791,18 @@ pub unsafe extern "C" fn vpi_scan(iterator: VpiHandle) -> VpiHandle { fn object_type(object: ObjectRef) -> i32 { match object { ObjectRef::Scope(_) => VPI_MODULE, - ObjectRef::Signal(_) => VPI_REG, + ObjectRef::Signal(id) => with_runtime(|runtime| { + if runtime + .reflection() + .signal(id) + .is_some_and(|signal| signal.is_parameter) + { + VPI_PARAMETER + } else { + VPI_REG + } + }) + .unwrap_or(VPI_REG), } } @@ -836,6 +854,13 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { }) .unwrap_or(0), VPI_TYPE => object_type(object), + VPI_CONST_TYPE => { + if object_type(object) == VPI_PARAMETER { + VPI_BINARY_CONST + } else { + 0 + } + } VPI_TOP_MODULE => i32::from(object == ObjectRef::Scope(ReflectionScopeId(0))), VPI_SIZE | VPI_SCALAR | VPI_VECTOR | VPI_DIRECTION | VPI_SIGNED => { with_runtime(|runtime| { @@ -1220,6 +1245,16 @@ pub unsafe extern "C" fn vpi_put_value( let Some(ObjectRef::Signal(id)) = (unsafe { object_ref(reference) }) else { return ptr::null_mut(); }; + if with_runtime(|runtime| { + runtime + .reflection() + .signal(id) + .is_some_and(|signal| signal.is_parameter) + }) + .unwrap_or(false) + { + return ptr::null_mut(); + } let identity = with_runtime(|runtime| runtime.signal_identity(id)).flatten(); let Some(identity) = identity else { return ptr::null_mut(); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 4fa69954160..fe2ef1926b0 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -8,6 +8,143 @@ use celox::{NativeProgramInstance, SimBackend, Simulator}; use celox_vpi::*; static VPI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +static LONG_CALLBACK_COUNT: AtomicUsize = AtomicUsize::new(0); +static LONG_CALLBACK_DELAY: AtomicUsize = AtomicUsize::new(1); + +#[cfg(feature = "systemverilog")] +#[test] +fn systemverilog_parameters_are_typed_read_only_objects_at_o2() { + let _serial = lock_vpi(); + let source = "module Top #(parameter WIDTH=8, parameter signed NEG=-3, + parameter logic [64:0] WIDE=65'h10000000000000001, + parameter logic [3:0] FOUR=4'b10xz)(output logic [7:0] y); + assign y=WIDTH; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("params.sv"))], "Top") + .param("WIDTH", 9) + .four_state(true) + .opt_level(celox::OptLevel::O2) + .build() + .unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + unsafe { + for (name, expected) in [ + (c"Top.WIDTH", "00000000000000000000000000001001"), + (c"Top.NEG", "11111111111111111111111111111101"), + ( + c"Top.WIDE", + "10000000000000000000000000000000000000000000000000000000000000001", + ), + (c"Top.FOUR", "10xz"), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TYPE, handle), VPI_PARAMETER); + assert_eq!(vpi_get(VPI_CONST_TYPE, handle), VPI_BINARY_CONST); + let mut value = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + assert_eq!(CStr::from_ptr(value.value.str_).to_str().unwrap(), expected); + let replacement = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_put_value(handle, &replacement, ptr::null(), VPI_NO_DELAY); + vpi_get_value(handle, &mut value); + assert_eq!(CStr::from_ptr(value.value.str_).to_str().unwrap(), expected); + vpi_free_object(handle); + } + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let iterator = vpi_iterate(VPI_PARAMETER, top); + let mut count = 0; + loop { + let parameter = vpi_scan(iterator); + if parameter.is_null() { + break; + } + count += 1; + vpi_free_object(parameter); + } + assert_eq!(count, 4); + vpi_free_object(top); + } + clear_runtime(); +} + +unsafe extern "C" fn reschedule_long_callback(data: *mut VpiCbData) -> i32 { + let count = LONG_CALLBACK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; + let delay = LONG_CALLBACK_DELAY.load(Ordering::SeqCst); + if delay != 0 && count == 500_010 { + vpi_control(VPI_FINISH); + return 0; + } + let mut time = VpiTime { + type_: VPI_SIM_TIME, + low: delay as u32, + ..VpiTime::default() + }; + // Safety: dispatch owns readable callback data, and registration copies time. + let next = unsafe { + VpiCbData { + time: &mut time, + ..*data + } + }; + unsafe { + vpi_register_cb(&next); + } + 0 +} + +#[test] +fn callback_iteration_limit_only_bounds_nonadvancing_time() { + let _serial = lock_vpi(); + for delay in [1, 0] { + let simulator = Simulator::builder(DESIGN, "Top").build().unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + LONG_CALLBACK_COUNT.store(0, Ordering::SeqCst); + LONG_CALLBACK_DELAY.store(delay, Ordering::SeqCst); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + low: delay as u32, + ..VpiTime::default() + }; + let callback = VpiCbData { + reason: CB_AFTER_DELAY, + cb_rtn: Some(reschedule_long_callback), + obj: ptr::null_mut(), + time: &mut time, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + unsafe { + assert!(!vpi_register_cb(&callback).is_null()); + } + let result = run_callbacks_result(); + if delay != 0 { + assert!(result.unwrap()); + assert_eq!(LONG_CALLBACK_COUNT.load(Ordering::SeqCst), 500_010); + assert_eq!(celox_vpi_current_time(), 500_010); + } else { + assert!( + result + .unwrap_err() + .to_string() + .contains("without advancing time") + ); + } + clear_runtime(); + } +} fn lock_vpi() -> std::sync::MutexGuard<'static, ()> { VPI_TEST_LOCK @@ -366,7 +503,21 @@ fn compile_time_objects_are_not_exposed_as_writable_registers() { .unwrap(); unsafe { - assert!(vpi_handle_by_name(c"Top.WIDTH".as_ptr(), ptr::null_mut()).is_null()); + let width = vpi_handle_by_name(c"Top.WIDTH".as_ptr(), ptr::null_mut()); + assert!(!width.is_null()); + assert_eq!(vpi_get(VPI_TYPE, width), VPI_PARAMETER); + let replacement = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + assert!(vpi_put_value(width, &replacement, ptr::null(), VPI_NO_DELAY).is_null()); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(width, &mut value); + assert_eq!(value.value.integer, 8); + vpi_free_object(width); assert!(vpi_handle_by_name(c"Top.BIAS".as_ptr(), ptr::null_mut()).is_null()); let output = vpi_handle_by_name(c"Top.y".as_ptr(), ptr::null_mut()); assert!(!output.is_null()); @@ -2820,7 +2971,10 @@ fn interface_members_are_navigable_after_native_image_round_trip() { assign y = s_axis.valid ? s_axis.data + 1 : 0; endmodule module Top(output logic [7:0] y); - Axis s_axis(), s$axis(); + Axis s_axis(), s$axis(), lanes[2](), shifted[-1:1](); + assign lanes[0].data=8'h34; + assign lanes[1].data=8'h56; + assign shifted[-1].data=8'h78; logic [7:0] cash$flow; assign cash$flow = 3; Child uut(s_axis, y); @@ -2842,6 +2996,21 @@ fn interface_members_are_navigable_after_native_image_round_trip() { let _session = install_runtime(runtime).unwrap(); unsafe { let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + for (name, expected) in [ + (c"Top.lanes[0].data", 0x34), + (c"Top.lanes[1].data", 0x56), + (c"Top.shifted[-1].data", 0x78), + ] { + let member = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!member.is_null(), "{name:?}"); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(member, &mut value); + assert_eq!(value.value.integer, expected); + vpi_free_object(member); + } let bus = vpi_handle_by_name(c"s_axis".as_ptr(), top); assert!(!bus.is_null(), "the declared interface must have a scope"); let data = vpi_handle_by_name(c"data".as_ptr(), bus); diff --git a/crates/celox-vpi/tests/diagnostics.rs b/crates/celox-vpi/tests/diagnostics.rs index 82bfae2c8ce..be874d50d0b 100644 --- a/crates/celox-vpi/tests/diagnostics.rs +++ b/crates/celox-vpi/tests/diagnostics.rs @@ -87,3 +87,61 @@ fn run_and_build_share_project_target_and_cli_diagnostic_precedence() { assert!(!denied.status.success()); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn aggregate_input_defaults_can_be_enabled_with_diagnostic_policy() { + let project = tempfile::tempdir().unwrap(); + fs::write( + project.path().join("top.sv"), + r#" + module Child(input logic [7:0] a[2]='{8'ha5,8'h5a}, output logic [15:0] y); + assign y={a[0],a[1]}; + endmodule + module Top(output logic [15:0] omitted, connected); + logic [7:0] a[2]; + assign a[0]=8'h12; + assign a[1]=8'h34; + Child c0(.y(omitted)); + Child c1(.a(a),.y(connected)); + initial begin #1; + assert(omitted===16'ha55a && connected===16'h1234) else $fatal(1,"defaults"); + $display("ok"); $finish; + end + endmodule + "#, + ) + .unwrap(); + fs::write( + project.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\n[diagnostics]\nunpacked_port_default='warn'\n", + ) + .unwrap(); + let run = |overrides: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(project.path()) + .arg("run") + .args(overrides) + .output() + .unwrap() + }; + let warned = run(&[]); + assert!( + warned.status.success(), + "{}", + String::from_utf8_lossy(&warned.stderr) + ); + assert_eq!(warned.stdout, b"ok\n"); + assert!(String::from_utf8_lossy(&warned.stderr).contains("unpacked_port_default")); + let allowed = run(&["--diagnostic", "unpacked_port_default=allow"]); + assert!( + allowed.status.success(), + "{}", + String::from_utf8_lossy(&allowed.stderr) + ); + assert_eq!(allowed.stdout, b"ok\n"); + assert!(!String::from_utf8_lossy(&allowed.stderr).contains("unpacked_port_default")); + let rejected = run(&["--diagnostic", "unpacked_port_default=error"]); + assert!(!rejected.status.success()); + assert!(String::from_utf8_lossy(&rejected.stderr).contains("unpacked_port_default")); +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 608c8c4bc75..f0ab19b077a 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 19; +const CONTAINER_VERSION: u16 = 20; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index b417d2b7dc0..a5e56e04cb0 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -18,7 +18,7 @@ pub enum DiagnosticLevel { /// Overrides keyed by the code shown in a compilation diagnostic. /// Unlisted diagnostics retain their default severity. Only explicitly -/// recoverable errors (currently `mixed_timescale`) can be relaxed. +/// recoverable errors can be relaxed. #[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct DiagnosticPolicy(pub BTreeMap); @@ -70,14 +70,13 @@ impl DiagnosticPolicy { } pub(crate) fn level(&self, code: &str) -> DiagnosticLevel { - self.0 - .get(code) - .copied() - .unwrap_or(if code == "mixed_timescale" { + self.0.get(code).copied().unwrap_or( + if matches!(code, "mixed_timescale" | "unpacked_port_default") { DiagnosticLevel::Error } else { DiagnosticLevel::Warn - }) + }, + ) } #[cfg(feature = "systemverilog")] diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 89dd6f342ef..00743b70397 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -988,10 +988,7 @@ impl RuntimeProgram { let instance = self.design.instance(scope.instance_id).unwrap(); for state_address in instance.state_addresses() { let variable = self.design.variable(state_address).unwrap(); - if matches!( - variable.var_kind, - VariableKind::Parameter | VariableKind::Constant - ) { + if variable.var_kind == VariableKind::Constant { continue; } if instance.path_index.get(&variable.path) != Some(&Some(*state_address)) { @@ -1024,6 +1021,7 @@ impl RuntimeProgram { _ => SignalDirection::Internal, }; signals.push(ReflectionSignal { + is_parameter: variable.var_kind == VariableKind::Parameter, full_name: format!("{parent_name}.{name}"), name: name.clone(), parent: scope_ids[&parent_name], diff --git a/crates/celox/tests/frontends/systemverilog/generate.rs b/crates/celox/tests/frontends/systemverilog/generate.rs index ff43db4c49b..f62f64887a3 100644 --- a/crates/celox/tests/frontends/systemverilog/generate.rs +++ b/crates/celox/tests/frontends/systemverilog/generate.rs @@ -1,6 +1,40 @@ use super::*; sv_backends! { + fn generated_constants_select_words_from_128_bit_parameters_at_o2(sim) { + @setup { + // Icarus 13 rejects packed array parameters; the same source is + // independently checked with Verilator. + let source = r#" + module Top #(parameter logic [3:0][31:0] WORDS={4{32'd4}})( + output logic [15:0] widths, output logic [31:0] first,last,edge_first,edge_last); + for(genvar i=0;i<4;i=i+1) begin:g + localparam C=$clog2(WORDS[i]+1); + assign widths[i*4 +: 4]=C; + end + localparam FIRST=WORDS[0], LAST=WORDS[3]; + localparam logic [3:0][31:0] EDGE=128'h80000000000000040000000480000000; + localparam E0=EDGE[0], E3=EDGE[3]; + assign edge_first=E0; + assign edge_last=E3; + assign first=FIRST; + assign last=LAST; + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("constant_word.sv"))], "Top") + .opt_level(celox::OptLevel::O2); + assert_eq!(sim.get(sim.signal("widths")), BigUint::from(0x3333u32)); + assert_eq!(sim.get(sim.signal("first")), BigUint::from(4u8)); + assert_eq!(sim.get(sim.signal("last")), BigUint::from(4u8)); + assert_eq!(sim.get(sim.signal("edge_first")), BigUint::from(0x80000000u32)); + assert_eq!(sim.get(sim.signal("edge_last")), BigUint::from(0x80000000u32)); + } + + fn generate_local_typedefs_keep_lexical_scope(sim) { + @case "generate::generate_local_typedefs_keep_lexical_scope"; + } + fn bits_of_generate_local_array_element_localparam(sim) { @case "generate::bits_of_generate_local_array_element_localparam"; } @@ -236,3 +270,65 @@ fn keeps_four_state_generate_function_guards_nonexhaustive() { "{error}" ); } + +// Icarus 13 rejects enum labels inside generate scopes and crashes while +// elaborating this source. Keep O2 isolation coverage in the API harness; +// the portable suite separately checks generated typedef layouts. +sv_backends! { + fn generated_enum_and_shadowed_type_scopes_survive_o2(sim) { + @setup { + let source=r#" + module Top(input logic[7:0] a, output logic[7:0] y,z,widths, + output logic[3:0] root_value, output logic[7:0] parent_value); + typedef logic[3:0] T; + T root; + assign root=a[3:0]; + assign root_value=root; + if(1) begin:left + typedef logic[7:0] T; + typedef enum logic[1:0] { OFF=0, ON=3 } state_t; + T temp; + state_t state; + assign state=ON; + assign temp=a; + assign y=(state==3) ? temp : 0; + if(1) begin:inner + typedef logic[1:0] T; + T tiny; + assign tiny=a[1:0]; + end + T after_inner; + assign after_inner=a; + assign parent_value=after_inner; + end + if(1) begin:right + typedef logic[3:0] T; + typedef enum logic[1:0] { OFF=1, ON=2 } state_t; + T temp; + state_t state; + assign state=ON; + assign temp=a[3:0]; + assign z=(state==2) ? {4'hc,temp} : 0; + end + for(genvar i=0;i<2;i=i+1) begin:lanes + typedef logic[i+2:0] lane_t; + lane_t temp; + assign temp=a; + assign widths[4*i+:4]=$bits(temp); + end + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source,Path::new("generated_enum.sv"))],"Top") + .opt_level(celox::OptLevel::O2); + let a=sim.signal("a"); + for value in [0xa7u8,0x5c] { + sim.modify(|io| io.set(a,value)).unwrap(); + assert_eq!(sim.get(sim.signal("y")),BigUint::from(value)); + assert_eq!(sim.get(sim.signal("z")),BigUint::from(0xc0|(value&15))); + assert_eq!(sim.get(sim.signal("parent_value")),BigUint::from(value)); + assert_eq!(sim.get(sim.signal("root_value")),BigUint::from(value&15)); + assert_eq!(sim.get(sim.signal("widths")),BigUint::from(0x43u8)); + } + } +} diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index da8731c3e55..87930fcef09 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,26 @@ use super::*; sv_backends! { + fn sized_parameter_actuals_follow_parent_specialization(sim) { + @case "hierarchy::sized_parameter_actuals_follow_parent_specialization"; + } + + fn generated_parameter_part_select_actuals(sim) { + @case "hierarchy::generated_parameter_part_select_actuals"; + } + + fn conditional_parameter_actuals_follow_parent_specialization(sim) { + @case "hierarchy::conditional_parameter_actuals_follow_parent_specialization"; + } + + fn concatenated_parameter_actuals_use_each_parent_specialization(sim) { + @case "hierarchy::concatenated_parameter_actuals_use_each_parent_specialization"; + } + + fn input_port_defaults_use_child_scope_and_only_omitted_connections(sim) { + @case "hierarchy::input_port_defaults_use_child_scope_and_only_omitted_connections"; + } + fn bits_query_parameter_overrides_follow_caller_specialization(sim) { @case "hierarchy::bits_query_parameter_overrides_follow_caller_specialization"; } diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 1647d3ca132..9acf8d49142 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -3,6 +3,10 @@ use super::*; // IEEE 1800-2023 11.5.1: the index operator and declaration direction // independently determine the endpoints of the selected range. sv_backends! { + fn procedural_loop_writes_memory_word_part_selects(sim) { + @case "indexed_select::procedural_loop_writes_memory_word_part_selects"; + } + fn constant_parameter_initializers_preserve_inferred_dimensions(sim) { @case "indexed_select::constant_parameter_initializers_preserve_inferred_dimensions"; } @@ -278,17 +282,9 @@ fn rejects_selected_widths_that_are_nonpositive() { } } -#[test] -fn rejects_indexed_selections_in_unlowered_constant_contexts() { - for declaration in [ - "logic [P[4 +: 4]-1:0] y; assign y = '0;", - "typedef enum logic [3:0] { E = P[4 +: 4] } nibble; nibble y; assign y = E;", - ] { - let source = - format!("module Top; localparam logic [7:0] P = 8'hab; {declaration} endmodule"); - Simulator::from_sv_sources(vec![(&source, Path::new("unlowered_constant.sv"))], "Top") - .build_cranelift() - .expect_err("unlowered indexed constants must be rejected"); +sv_backends! { + fn indexed_selections_in_constant_declaration_contexts(sim) { + @case "indexed_select::indexed_selections_in_constant_declaration_contexts"; } } diff --git a/crates/celox/tests/frontends/systemverilog/literals.rs b/crates/celox/tests/frontends/systemverilog/literals.rs index 9ee04036847..c1b77cb5bec 100644 --- a/crates/celox/tests/frontends/systemverilog/literals.rs +++ b/crates/celox/tests/frontends/systemverilog/literals.rs @@ -28,6 +28,10 @@ fn simulates_systemverilog_literals_with_widths_and_masks() { } sv_backends! { + fn string_literals_are_unsigned_packed_bytes(sim) { + @case "literals::string_literals_are_unsigned_packed_bytes"; + } + fn simulates_systemverilog_unbased_unsized_literals(sim) { @case "literals::simulates_systemverilog_unbased_unsized_literals"; } diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 58533bc3e51..39132557e13 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,20 @@ sv_backends! { + fn size_casts_resolve_generated_locals_and_parameter_expressions(sim) { + @case "operators::size_casts_resolve_generated_locals_and_parameter_expressions"; + } + + fn parameter_size_casts_in_generate_conditions(sim) { + @case "operators::parameter_size_casts_in_generate_conditions"; + } + fn forwards_replicated_parameter_values(sim) { + @case "operators::forwards_replicated_parameter_values"; + } + fn zero_count_replications_preserve_unknown_bits(sim) { + @case "operators::zero_count_replications_preserve_unknown_bits"; + } + fn zero_count_replications_preserve_concat_bits(sim) { + @case "operators::zero_count_replications_preserve_concat_bits"; + } fn multidimensional_packed_declared_ranges_four_state(sim) { @case "operators::multidimensional_packed_declared_ranges_four_state"; } fn multidimensional_packed_declared_ranges(sim) { @case "operators::multidimensional_packed_declared_ranges"; } fn multidimensional_packed_declared_range_writes(sim) { @case "operators::multidimensional_packed_declared_range_writes"; } diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 6dbb86aa139..f8b1c45eb35 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -1,4 +1,20 @@ sv_backends! { + fn constant_functions_inside_selected_parameter_initializers(sim) { + @case "procedural::constant_functions_inside_selected_parameter_initializers"; + } + + fn constant_functions_preserve_concat_operand_widths(sim) { + @case "procedural::constant_functions_preserve_concat_operand_widths"; + } + + fn static_function_scratch_arrays_are_filled_before_reads(sim) { + @case "procedural::static_function_scratch_arrays_are_filled_before_reads"; + } + + fn static_function_result_filled_by_constant_loops(sim) { + @case "procedural::static_function_result_filled_by_constant_loops"; + } + fn typedef_declaration_initializers(sim) { @case "procedural::typedef_declaration_initializers"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index f42d819d4a5..67750546b12 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5827,9 +5827,9 @@ fn rejects_constructs_that_are_not_yet_lowered() { "#, ), ( - "ANSI port default value", + "default value on a non-input port", r#" - module Top(input wire a = 1'b1, output wire y); assign y = a; endmodule + module Top(input wire a, output wire y = 1'b1); assign y = a; endmodule "#, ), (