diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 19e3a2f9d26..92b593277b3 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -650,7 +650,7 @@ chapter-7/structures/packed/signed.sv pass chapter-7/structures/packed/unsigned.sv pass chapter-7/structures/unpacked/basic.sv fail chapter-7/structures/unpacked/default-value.sv fail -chapter-7/unions/packed/basic.sv fail +chapter-7/unions/packed/basic.sv pass chapter-7/unions/tagged/basic.sv fail chapter-7/unions/tagged/packed.sv fail chapter-7/unions/unpacked/basic.sv fail diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 99251810533..ba98c0723bf 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -139,6 +139,7 @@ pub(crate) struct LoweredSvParameterOverride { pub value: Option, /// The data type bound to a `parameter type`, as source text. pub type_text: Option, + pub pattern_text: Option, } #[derive(Clone)] @@ -1281,6 +1282,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), type_text: None, + pattern_text: None, }) .collect(); requested_roots.insert(name.clone(), key.clone()); @@ -1295,6 +1297,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), type_text: None, + pattern_text: None, }) .collect(); } @@ -1355,6 +1358,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), type_text: None, + pattern_text: None, }) .collect(); requested_roots.insert(name.clone(), dependency.clone()); @@ -1563,6 +1567,7 @@ pub fn schedule_sources( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), type_text: None, + pattern_text: None, }) .collect(), }; @@ -1752,7 +1757,16 @@ fn specialize_module( .iter() .filter_map(|parameter| Some((parameter.name.clone(), parameter.type_text.clone()?))) .collect(); - let ir = module.source.analyze_module( + let pattern_overrides: Vec<_> = key + .parameter_overrides + .iter() + .filter_map(|parameter| Some((parameter.name.clone(), parameter.pattern_text.clone()?))) + .collect(); + let pattern_source = module + .source + .with_pattern_parameter_overrides(&module.name, &pattern_overrides)?; + let source = pattern_source.as_ref().unwrap_or(&module.source); + let ir = source.analyze_module( &module.name, &overrides, &type_overrides, @@ -2149,6 +2163,7 @@ fn lower_parameter_overrides( name: parameter.name().to_string(), value, type_text: parameter.type_text().map(str::to_string), + pattern_text: parameter.pattern_text().map(str::to_string), } }) .collect() @@ -2623,11 +2638,16 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr { .map(|item| item.map(&mut |operand| expr_for_state_mode(operand, four_state))) .collect(), }, - sv::ir::Expr::Call { name, args } => sv::ir::Expr::Call { + sv::ir::Expr::Call { + name, + args, + arg_order, + } => sv::ir::Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), args: args .iter() - .map(|arg| expr_for_state_mode(arg, four_state)) + .map(|arg| arg.as_ref().map(|arg| expr_for_state_mode(arg, four_state))) .collect(), }, } @@ -3968,13 +3988,16 @@ fn lower_glue_parent_expr( context_width, context_signed, ), - sv::ir::Expr::Call { name, args } - if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => - { + sv::ir::Expr::Call { + name, + args, + arg_order, + } if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => { let mut operands = Vec::with_capacity(args.len()); let mut sources = HashSet::default(); let mut source_ids = Vec::new(); for arg in args { + let arg = arg.as_ref()?; let width = sv_expr_natural_width(arg, variables, name_to_id, constants, parameter_types)?; let (inner, arg_sources, arg_source_ids) = lower_glue_parent_expr( @@ -4200,7 +4223,10 @@ fn expr_references_ident(expr: &sv::ir::Expr, name: &str) -> bool { .flat_map(sv::ir::InsideItem::exprs) .any(|operand| expr_references_ident(operand, name)) } - sv::ir::Expr::Call { args, .. } => args.iter().any(|arg| expr_references_ident(arg, name)), + sv::ir::Expr::Call { args, .. } => args + .iter() + .flatten() + .any(|arg| expr_references_ident(arg, name)), } } @@ -5127,13 +5153,16 @@ fn lower_expr_with_context( context_width, context_signed, ), - sv::ir::Expr::Call { name, args } - if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => - { + sv::ir::Expr::Call { + name, + args, + arg_order, + } if sv::typecheck::bit_vector_function_return_type(name, args.len()).is_some() => { let mut operands = Vec::with_capacity(args.len()); let mut sources = HashSet::default(); for arg in args { + let arg = arg.as_ref()?; let width = sv_expr_natural_width(arg, variables, name_to_id, constants, parameter_types)?; let (inner, arg_sources) = lower_expr_with_context( @@ -6210,6 +6239,7 @@ fn expr_uses_ident_as_condition(expr: &sv::ir::Expr, name: &str) -> bool { } sv::ir::Expr::Call { args, .. } => args .iter() + .flatten() .any(|arg| expr_uses_ident_as_condition(arg, name)), sv::ir::Expr::Ident(_) | sv::ir::Expr::Literal(_) => false, } @@ -6301,7 +6331,7 @@ fn sv_glue_expr_is_signed( sv::ir::Expr::Resize { signed, .. } => *signed, sv::ir::Expr::Select { signed, .. } => *signed, sv::ir::Expr::Inside { .. } => false, - sv::ir::Expr::Call { name, args } => { + sv::ir::Expr::Call { name, args, .. } => { sv::typecheck::bit_vector_function_return_type(name, args.len()) .is_some_and(|(_, signed)| signed) } @@ -6363,7 +6393,7 @@ fn sv_expr_is_signed_with_parameters( sv::ir::Expr::Resize { signed, .. } => *signed, sv::ir::Expr::Select { signed, .. } => *signed, sv::ir::Expr::Inside { .. } => false, - sv::ir::Expr::Call { name, args } => { + sv::ir::Expr::Call { name, args, .. } => { sv::typecheck::bit_vector_function_return_type(name, args.len()) .is_some_and(|(_, signed)| signed) } @@ -6607,7 +6637,7 @@ fn sv_expr_natural_width( )?), ), sv::ir::Expr::Inside { .. } => Some(1), - sv::ir::Expr::Call { name, args } => { + sv::ir::Expr::Call { name, args, .. } => { sv::typecheck::bit_vector_function_return_type(name, args.len()).map(|(width, _)| width) } } diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 8d23ba650fe..5a455298954 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -863,8 +863,9 @@ impl<'p, 'a> Comb<'p, 'a> { ); } let call = sv::ir::Expr::Call { + arg_order: Vec::new(), name: name.clone(), - args: lowered, + args: lowered.into_iter().map(Some).collect(), }; let sv::ir::Expr::Ident(result) = self.hoist(store, frames, &call)? else { return Err(unsupported(format!("call of `{name}` in a select"))); @@ -1151,9 +1152,13 @@ impl<'p, 'a> Comb<'p, 'a> { "DPI-C function `{name}` called in combinational logic" ))); } - Expr::Call { name, args } if self.m.subroutines.contains_key(name) => { - let args: Vec> = args.iter().cloned().map(Some).collect(); - let result = self.call(store, frames, name, &args)?; + Expr::Call { + name, + args, + arg_order, + } if self.m.subroutines.contains_key(name) => { + let args = args.clone(); + let result = self.call(store, frames, name, &args, arg_order)?; let Some((node, sources)) = result else { return Err(unsupported(format!( "void function `{name}` used as a value" @@ -1174,11 +1179,20 @@ impl<'p, 'a> Comb<'p, 'a> { self.write(store, temp, full(width), (node, sources))?; Expr::Ident(temp_name) } - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), args: args .iter() - .map(|arg| self.hoist(store, frames, arg)) + .map(|arg| { + arg.as_ref() + .map(|arg| self.hoist(store, frames, arg)) + .transpose() + }) .collect::>()?, }, Expr::Binary { left, op, right } @@ -1861,7 +1875,11 @@ impl<'p, 'a> Comb<'p, 'a> { self.set_flag(&mut store, return_flag, true)?; Ok(store) } - sv::ir::Stmt::Call { name, args } => { + sv::ir::Stmt::Call { + name, + args, + arg_order, + } => { if self.m.dpi_imports.contains_key(name) { return Err(unsupported(format!( "DPI-C function `{name}` called in combinational logic" @@ -1870,7 +1888,7 @@ impl<'p, 'a> Comb<'p, 'a> { if !self.m.subroutines.contains_key(name) { return Err(unsupported(format!("call of `{name}`"))); } - self.call(&mut store, frames, name, args)?; + self.call(&mut store, frames, name, args, arg_order)?; Ok(store) } sv::ir::Stmt::Eval(expr) => { @@ -2853,6 +2871,7 @@ impl<'p, 'a> Comb<'p, 'a> { frames: &[Frame], name: &str, args: &[Option], + arg_order: &[usize], ) -> Result, sv::AnalyzerError> { let subroutine = self .m @@ -2873,7 +2892,16 @@ impl<'p, 'a> Comb<'p, 'a> { // Copy the inputs in, left to right, in the caller's scope. let mut outputs = Vec::new(); let mut copied = Vec::new(); - for (position, param) in subroutine.params.iter().enumerate() { + let positions: Vec<_> = if arg_order.is_empty() { + (0..subroutine.params.len()).collect() + } else { + arg_order.to_vec() + }; + for position in positions { + let param = subroutine + .params + .get(position) + .ok_or_else(|| unsupported(format!("argument position of `{name}`")))?; let id = self .m .id(¶m.name) @@ -3505,7 +3533,7 @@ impl Comb<'_, '_> { record(self, part, writes); } } - sv::ir::Stmt::Call { name, args } => calls.push((name.clone(), args.clone())), + sv::ir::Stmt::Call { name, args, .. } => calls.push((name.clone(), args.clone())), _ => {} }); } @@ -3725,9 +3753,14 @@ fn substitute_literals( then_expr: Box::new(go(then_expr)), else_expr: Box::new(go(else_expr)), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), - args: args.iter().map(go).collect(), + args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { expr: Box::new(go(expr)), diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 0188e72fc2a..494d2e97a1d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -505,8 +505,9 @@ impl<'p, 'a> Ff<'p, 'a> { ); } let call = sv::ir::Expr::Call { + arg_order: Vec::new(), name: name.clone(), - args: lowered, + args: lowered.into_iter().map(Some).collect(), }; let sv::ir::Expr::Ident(result) = self.hoist(&call)? else { return Err(unsupported(format!("call of `{name}` in a select"))); @@ -770,16 +771,20 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { - Expr::Call { name, args } if self.m.dpi_imports.contains_key(name) => { + Expr::Call { + name, + args, + arg_order, + } if self.m.dpi_imports.contains_key(name) => { let import = self.m.dpi_imports[name].clone(); let Some(r#type) = import.return_type() else { return Err(unsupported(format!( "void DPI-C function `{name}` used as a value" ))); }; - let args: Vec> = args.iter().cloned().map(Some).collect(); + let args = args.clone(); let result = self - .dpi_call(&import, &args)? + .dpi_call(&import, &args, arg_order)? .expect("a non-void DPI-C import defines a result"); let (temp, temp_name) = self.m.temp( "dpi", @@ -790,8 +795,12 @@ impl<'p, 'a> Ff<'p, 'a> { self.store(temp, SIROffset::Static(0), r#type.width(), result); Expr::Ident(temp_name) } - Expr::Call { name, args } if self.m.subroutines.contains_key(name) => { - let args: Vec> = args.iter().cloned().map(Some).collect(); + Expr::Call { + name, + args, + arg_order, + } if self.m.subroutines.contains_key(name) => { + let args = args.clone(); let subroutine = self .m .subroutine(name) @@ -803,7 +812,7 @@ impl<'p, 'a> Ff<'p, 'a> { ))); }; let (width, signed, is_4state) = self.m.type_shape(&r#type)?; - let result = self.call(name, &args)?; + let result = self.call(name, &args, arg_order)?; let (temp, temp_name) = self.m.temp("call", width, signed, is_4state); let Some(result) = result else { return Err(unsupported(format!( @@ -843,11 +852,16 @@ impl<'p, 'a> Ff<'p, 'a> { else_expr: Box::new(else_expr), } } - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), args: args .iter() - .map(|arg| self.hoist(arg)) + .map(|arg| arg.as_ref().map(|arg| self.hoist(arg)).transpose()) .collect::>()?, }, Expr::Select { @@ -937,6 +951,7 @@ impl<'p, 'a> Ff<'p, 'a> { &mut self, import: &sv::ir::DpiImport, args: &[Option], + arg_order: &[usize], ) -> Result, sv::AnalyzerError> { let name = import.name(); if args.len() != import.arguments().len() { @@ -946,8 +961,18 @@ impl<'p, 'a> Ff<'p, 'a> { import.arguments().len() ))); } - let mut registers = Vec::with_capacity(args.len()); - for (arg, argument) in args.iter().zip(import.arguments()) { + let mut registers = vec![None; args.len()]; + let positions: Vec<_> = if arg_order.is_empty() { + (0..args.len()).collect() + } else { + arg_order.to_vec() + }; + // Evaluate actuals in source order, then pass registers in C formal order. + for position in positions { + let argument = import.arguments().get(position).ok_or_else(|| { + unsupported(format!("argument position of DPI-C function `{name}`")) + })?; + let arg = &args[position]; let Some(arg) = arg else { return Err(unsupported(format!( "omitted argument of DPI-C function `{name}`" @@ -956,8 +981,12 @@ impl<'p, 'a> Ff<'p, 'a> { let r#type = argument.r#type(); let arg = self.hoist(arg)?; let value = self.eval(&arg, Some((r#type.width(), r#type.is_signed())))?; - registers.push(self.dpi_register(value, r#type)); + registers[position] = Some(self.dpi_register(value, r#type)); } + let registers = registers + .into_iter() + .collect::>>() + .ok_or_else(|| unsupported(format!("missing argument of DPI-C function `{name}`")))?; let func = self.m.extern_function(import); let dst = import .return_type() @@ -1590,15 +1619,19 @@ impl<'p, 'a> Ff<'p, 'a> { self.jump(return_block); Ok(false) } - sv::ir::Stmt::Call { name, args } => { + sv::ir::Stmt::Call { + name, + args, + arg_order, + } => { if let Some(import) = self.m.dpi_imports.get(name).cloned() { - self.dpi_call(&import, args)?; + self.dpi_call(&import, args, arg_order)?; return Ok(true); } if !self.m.subroutines.contains_key(name) { return Err(unsupported(format!("call of `{name}`"))); } - self.call(name, args)?; + self.call(name, args, arg_order)?; Ok(true) } sv::ir::Stmt::Eval(expr) => { @@ -2101,6 +2134,7 @@ impl<'p, 'a> Ff<'p, 'a> { &mut self, name: &str, args: &[Option], + arg_order: &[usize], ) -> Result, sv::AnalyzerError> { let subroutine = self .m @@ -2122,7 +2156,16 @@ impl<'p, 'a> Ff<'p, 'a> { // read a formal of an enclosing call of another subroutine. let mut outputs = Vec::new(); let mut inputs = Vec::new(); - for (position, param) in subroutine.params.iter().enumerate() { + let positions: Vec<_> = if arg_order.is_empty() { + (0..subroutine.params.len()).collect() + } else { + arg_order.to_vec() + }; + for position in positions { + let param = subroutine + .params + .get(position) + .ok_or_else(|| unsupported(format!("argument position of `{name}`")))?; let id = self .m .id(¶m.name) @@ -2464,9 +2507,14 @@ fn substitute_overlay( then_expr: Box::new(go(then_expr)), else_expr: Box::new(go(else_expr)), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), - args: args.iter().map(go).collect(), + args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { expr: Box::new(go(expr)), diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index aeec717fd45..5daf7cf4e98 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -511,9 +511,14 @@ impl<'a> ProcModule<'a> { then_expr: Box::new(go(then_expr)), else_expr: Box::new(go(else_expr)), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: name.clone(), - args: args.iter().map(go).collect(), + args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), }, Expr::Inside { expr, items } => Expr::Inside { expr: Box::new(go(expr)), @@ -1572,7 +1577,10 @@ pub(super) fn expr_idents(expr: &sv::ir::Expr, names: &mut HashSet) { expr_idents(then_expr, names); expr_idents(else_expr, names); } - sv::ir::Expr::Call { args, .. } => args.iter().for_each(|arg| expr_idents(arg, names)), + sv::ir::Expr::Call { args, .. } => args + .iter() + .flatten() + .for_each(|arg| expr_idents(arg, names)), sv::ir::Expr::Inside { expr, items } => { expr_idents(expr, names); for item in items { @@ -1736,8 +1744,8 @@ pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&str) -> bool) || expr_calls(then_expr, is_callee) || expr_calls(else_expr, is_callee) } - sv::ir::Expr::Call { name, args } => { - is_callee(name) || args.iter().any(|arg| expr_calls(arg, is_callee)) + sv::ir::Expr::Call { name, args, .. } => { + is_callee(name) || args.iter().flatten().any(|arg| expr_calls(arg, is_callee)) } sv::ir::Expr::Inside { expr, items } => { expr_calls(expr, is_callee) @@ -1833,9 +1841,9 @@ pub(super) fn collect_calls( calls: &mut Vec<(String, Vec>)>, ) { match expr { - sv::ir::Expr::Call { name, args } => { - calls.push((name.clone(), args.iter().cloned().map(Some).collect())); - for arg in args { + sv::ir::Expr::Call { name, args, .. } => { + calls.push((name.clone(), args.clone())); + for arg in args.iter().flatten() { collect_calls(arg, calls); } } @@ -1940,7 +1948,7 @@ pub(super) fn stmt_calls( ) { let mut exprs: Vec<&sv::ir::Expr> = Vec::new(); match stmt { - sv::ir::Stmt::Call { name, args } => { + sv::ir::Stmt::Call { name, args, .. } => { calls.push((name.clone(), args.clone())); exprs.extend(args.iter().flatten()); } diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index a89268b5ffc..bb86536545c 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -135,6 +135,7 @@ pub fn analyze_source(source: ast::Source) -> Result { parameter.name().to_string(), parameter.value().cloned().map(Into::into), parameter.type_text().map(str::to_string), + parameter.pattern_text().map(str::to_string), ) }) .collect(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index cd41a4a5143..feae525a49a 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -738,7 +738,28 @@ impl Module { .or_insert(directions); } } + let mut dpi_imports = dpi::dpi_imports_from_module_node( + node.clone(), + syntax_tree, + &const_env, + &type_aliases, + )?; + for import in &dpi_imports { + subroutine_params.insert( + import.name().to_string(), + import + .arguments() + .iter() + .map(|arg| arg.name().to_string()) + .collect(), + ); + subroutine_directions.insert( + import.name().to_string(), + vec![crate::procedural::ParamDirection::Input; import.arguments().len()], + ); + } packed_dimensions.subroutine_param_shapes = Arc::new(subroutine_shapes.clone()); + packed_dimensions.subroutine_param_names = Arc::new(subroutine_params.clone()); let mut instances = instances_from_module_node( node.clone(), syntax_tree, @@ -832,12 +853,6 @@ impl Module { }, ) })); - let mut dpi_imports = dpi::dpi_imports_from_module_node( - node.clone(), - syntax_tree, - &const_env, - &type_aliases, - )?; packed_dimensions .function_return_types .extend(dpi_imports.iter().filter_map(|import| { @@ -1227,6 +1242,7 @@ pub struct Parameter { value: Option, declared_width: Option, packed_ranges: Vec, + members: Vec, declared_signed: Option, declared_is_2state: bool, has_declared_type: bool, @@ -1250,6 +1266,7 @@ impl Parameter { value, declared_width, packed_ranges: Vec::new(), + members: Vec::new(), declared_signed, declared_is_2state, has_declared_type, @@ -1545,6 +1562,7 @@ pub struct ParameterOverride { value: Option, /// The source text of a data type, for a `parameter type` override. type_text: Option, + pattern_text: Option, } impl ParameterOverride { @@ -1553,6 +1571,7 @@ impl ParameterOverride { name, value, type_text: None, + pattern_text: None, } } @@ -1561,9 +1580,15 @@ impl ParameterOverride { name, value: None, type_text: Some(type_text), + pattern_text: None, } } + /// A constant assignment pattern, evaluated in the caller scope. + pub fn pattern_text(&self) -> Option<&str> { + self.pattern_text.as_deref() + } + pub fn name(&self) -> &str { &self.name } @@ -2066,6 +2091,7 @@ fn function_argument_metadata(params: &[FunctionParam]) -> Arc<[FunctionArgument params .iter() .map(|param| FunctionArgumentMetadata { + name: param.name.clone(), direction: param.direction, has_default: param.has_default, }) @@ -2076,7 +2102,8 @@ fn dpi_argument_metadata(import: &crate::ir::DpiImport) -> Arc<[FunctionArgument import .arguments() .iter() - .map(|_| FunctionArgumentMetadata { + .map(|argument| FunctionArgumentMetadata { + name: argument.name().to_string(), direction: ParamDirection::Input, has_default: false, }) @@ -2166,7 +2193,10 @@ pub enum Expr { }, Call { name: String, - args: Vec, + /// Missing actuals retain their formal slots for declaration-scope defaults. + args: Vec>, + /// Formal positions in source evaluation/copy-out order; empty means positional. + arg_order: Vec, }, /// `expr inside { items }`: true when `expr` matches any item. Inside { @@ -2293,8 +2323,9 @@ struct VariableDimensions { type VariablePackedDimensions = HashMap; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] struct FunctionArgumentMetadata { + name: String, direction: ParamDirection, has_default: bool, } @@ -2328,6 +2359,7 @@ struct PackedDimensions { /// The declared shape of each argument of each subroutine, for /// assignment patterns passed as arguments. subroutine_param_shapes: Arc>>, + subroutine_param_names: Arc>>, } impl PackedDimensions { @@ -2348,6 +2380,7 @@ impl PackedDimensions { scope_types_complete: false, type_query: false, subroutine_param_shapes: Arc::default(), + subroutine_param_names: Arc::default(), } } } diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index c394fd96cec..1b319eeb356 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -52,7 +52,7 @@ pub(super) fn expr_is_two_state(expr: &Expr, packed_dimensions: &PackedDimension || (expr_is_two_state(condition, packed_dimensions) && expr_is_two_state(else_expr, packed_dimensions))) } - Expr::Call { name, args } => { + Expr::Call { name, args, .. } => { typecheck::bit_vector_function_return_type(name, args.len()).is_some() || packed_dimensions .function_return_types diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index 224530fc0de..f7cc2223d0a 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -216,6 +216,27 @@ pub(super) fn constant_cast_const_expr( cast_constant_operand(operand, &cast.nodes.0, syntax_tree, const_env, type_aliases) } +/// Evaluate a constant cast with the scope's four-state parameter literals. +pub(super) fn constant_cast_with_dimensions( + cast: &sv_parser::ConstantCast, + syntax_tree: &SyntaxTree, + dimensions: &PackedDimensions, +) -> Option { + let operand = indexed_select_base( + RefNode::ConstantExpression(&cast.nodes.2.nodes.1), + syntax_tree, + dimensions, + ) + .ok()?; + cast_constant_operand( + operand, + &cast.nodes.0, + syntax_tree, + &dimensions.const_env, + &dimensions.type_aliases, + ) +} + pub(super) fn runtime_constant_cast_const_expr( cast: &sv_parser::Cast, syntax_tree: &SyntaxTree, @@ -268,7 +289,14 @@ pub(super) fn cast_constant_operand( typecheck::parse_integral_literal(&operand_literal) })? }; - let target_type = cast_target_type(casting_type, syntax_tree, const_env, type_aliases)?; + let target_type = if let sv_parser::CastingType::Signing(signing) = casting_type { + ExprType { + width: literal.width, + signed: matches!(**signing, sv_parser::Signing::Signed(_)), + } + } else { + cast_target_type(casting_type, syntax_tree, const_env, type_aliases)? + }; // A numeric size cast keeps the source expression's signedness; a type // cast takes the target type's signedness. let signed = if casting_type_is_numeric_size(casting_type, syntax_tree, const_env, type_aliases) diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index 421fb84ed06..29fedc1f4e9 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -79,14 +79,16 @@ pub(super) fn expr_static_width( expr_static_width(then_expr, packed_dimensions)? .max(expr_static_width(else_expr, packed_dimensions)?), ), - Expr::Call { name, args } => typecheck::bit_vector_function_return_type(name, args.len()) - .map(|(width, _)| width) - .or_else(|| { - packed_dimensions - .function_return_types - .get(name) - .and_then(|metadata| metadata.width) - }), + Expr::Call { name, args, .. } => { + typecheck::bit_vector_function_return_type(name, args.len()) + .map(|(width, _)| width) + .or_else(|| { + packed_dimensions + .function_return_types + .get(name) + .and_then(|metadata| metadata.width) + }) + } } } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index e32f72481b2..0be37d4607b 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -22,6 +22,8 @@ const MAX_DEPTH: usize = 64; #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ConstantFunction { params: Vec<(String, crate::ir::Type)>, + argument_names: Vec, + argument_defaults: Vec>, return_var: Option<(String, crate::ir::Type)>, body: Vec, } @@ -42,6 +44,8 @@ thread_local! { static LOCALS: RefCell>> = RefCell::new(Arc::default()); static ERRORS: RefCell> = RefCell::new(Arc::default()); static DEPTH: Cell = const { Cell::new(0) }; + // Reuse signatures without copying every function for each initializer. + static ARGUMENT_NAMES: RefCell<(Arc, Arc>>)> = RefCell::new((Arc::default(), Arc::default())); } /// Restores the previously installed functions when dropped. @@ -97,6 +101,22 @@ pub(super) fn conversion_error(name: &str) -> Option { }) } +/// Source formal names used to bind named calls in constant syntax. +pub(super) fn argument_names() -> Arc>> { + let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); + ARGUMENT_NAMES.with(|cached| { + let mut cached = cached.borrow_mut(); + if !Arc::ptr_eq(&cached.0, &functions) { + let names = functions + .iter() + .map(|(name, function)| (name.clone(), function.argument_names.clone())) + .collect(); + *cached = (functions, Arc::new(names)); + } + cached.1.clone() + }) +} + pub(super) fn is_constant_function(name: &str) -> bool { FUNCTIONS.with(|current| current.borrow().contains_key(name)) } @@ -176,6 +196,19 @@ impl ConstantFunctions { ( name(function_name), ConstantFunction { + argument_names: function.argument_names.clone(), + argument_defaults: function + .argument_defaults + .iter() + .map(|default| { + default.clone().map(|expr| { + let Stmt::Eval(expr) = stmt(Stmt::Eval(expr)) else { + unreachable!("renaming preserves statement variants") + }; + expr + }) + }) + .collect(), params: function .params .iter() @@ -221,12 +254,13 @@ impl ConstantFunctions { params: function .params .iter() - .map(|(name, ty)| crate::ir::SubroutineParam { + .enumerate() + .map(|(position, (name, ty))| crate::ir::SubroutineParam { name: name.clone(), - source_name: name.clone(), + source_name: function.argument_names[position].clone(), direction: crate::procedural::ParamDirection::Input, r#type: ty.clone(), - default: None, + default: function.argument_defaults[position].clone().map(Into::into), }) .collect(), body: function @@ -269,6 +303,60 @@ pub(super) fn symbolic_module_constant_functions( type_aliases: &HashMap, parameter_literals: &HashMap, symbolic_parameters: &HashSet, +) -> ConstantFunctions { + if !node + .clone() + .into_iter() + .any(|child| matches!(child, RefNode::FunctionDeclaration(_))) + { + return ConstantFunctions::default(); + } + let needs_bootstrap = !generate::root_subroutines_only() + && node.clone().into_iter().any(|child| { + matches!( + child, + RefNode::ConditionalGenerateConstruct(_) | RefNode::LoopGenerateConstruct(_) + ) + }); + if !needs_bootstrap { + return collect_module_constant_functions( + node, + tree, + const_env, + type_aliases, + parameter_literals, + symbolic_parameters, + ); + } + let mut roots = generate::with_root_subroutines(|| { + collect_module_constant_functions( + node.clone(), + tree, + const_env, + type_aliases, + parameter_literals, + symbolic_parameters, + ) + }); + roots.extend_missing(&scope::imported().constant_functions); + let _installed = install(roots); + collect_module_constant_functions( + node, + tree, + const_env, + type_aliases, + parameter_literals, + symbolic_parameters, + ) +} + +fn collect_module_constant_functions( + node: RefNode<'_>, + tree: &SyntaxTree, + const_env: &HashMap, + type_aliases: &HashMap, + parameter_literals: &HashMap, + symbolic_parameters: &HashSet, ) -> ConstantFunctions { let has_functions = node .clone() @@ -301,6 +389,7 @@ pub(super) fn symbolic_module_constant_functions( Err(error) => return ConstantFunctions::unconverted(error), }; let mut dimensions = PackedDimensions::new(HashMap::default(), const_env, type_aliases); + dimensions.subroutine_param_names = Arc::new(subroutine_params.clone()); dimensions.subroutine_param_shapes = Arc::new(subroutine_shapes); let mut locals = Vec::new(); let mut counter = 0usize; @@ -342,6 +431,16 @@ pub(super) fn symbolic_module_constant_functions( Some(( subroutine.name.clone(), ConstantFunction { + argument_names: subroutine + .params + .iter() + .map(|param| param.source_name.clone()) + .collect(), + argument_defaults: subroutine + .params + .iter() + .map(|param| param.default.clone()) + .collect(), params, return_var: Some(return_var?), body: subroutine.body, @@ -364,6 +463,53 @@ pub(super) fn symbolic_module_constant_functions( } } +/// Fill defaults in the declaration's bound scope; runtime IR keeps its holes. +pub(super) fn resolved_arguments(name: &str, args: &[Option]) -> Option> { + let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); + let Some(function) = functions.get(name) else { + return args.iter().cloned().collect(); + }; + if args.len() > function.params.len() { + return None; + } + (0..function.params.len()) + .map(|position| { + args.get(position) + .cloned() + .flatten() + .or_else(|| function.argument_defaults[position].clone()) + }) + .collect() +} + +/// A named constant call can be folded only when its body and actuals evaluate. +pub(super) fn eval_expression_literal( + expr: &Expr, + constants: &HashMap, +) -> Option { + let Expr::Call { name, .. } = expr else { + return None; + }; + let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); + let (_, ty) = functions.get(name)?.return_var.as_ref()?; + let width = ty + .resolved_width() + .or_else(|| typecheck::resolve_packed_width_in_env(ty.packed_ranges(), constants))?; + let mut frame = Frame { + constants, + values: HashMap::default(), + types: HashMap::default(), + temporaries: 0, + iterations: 0, + }; + let value = frame.eval(expr)?; + typecheck::parse_integral_literal(&format_typed_parameter_literal( + value, + width, + ty.is_signed(), + )) +} + /// The value of a call of an installed constant function. pub(crate) fn eval_call( name: &str, @@ -386,19 +532,42 @@ pub(crate) fn eval_call( result } +/// Preserve the declared result type when freezing a caller's function value. +pub(super) fn eval_call_literal( + name: &str, + args: &[crate::ir::ConstExpr], + constants: &HashMap, +) -> Option { + let functions = FUNCTIONS.with(|functions| functions.borrow().clone()); + let (_, ty) = functions.get(name)?.return_var.as_ref()?; + let width = ty + .resolved_width() + .or_else(|| typecheck::resolve_packed_width_in_env(ty.packed_ranges(), constants))?; + let value = eval_call(name, args, constants)?; + typecheck::parse_integral_literal(&format_typed_parameter_literal( + value, + width, + ty.is_signed(), + )) +} + fn call( function: &ConstantFunction, args: &[i128], constants: &dyn ConstantEnvironment, ) -> Option { - let frame = Frame { + let mut frame = Frame { constants, values: HashMap::default(), types: HashMap::default(), temporaries: 0, iterations: 0, }; - call_in_frame(function, args, frame) + let mut values = args.to_vec(); + for position in args.len()..function.params.len() { + values.push(frame.eval(function.argument_defaults[position].as_ref()?)?); + } + call_in_frame(function, &values, frame) } fn call_in_frame(function: &ConstantFunction, args: &[i128], mut frame: Frame<'_>) -> Option { @@ -558,9 +727,9 @@ impl Frame<'_> { self.lower(else_expr)? } } - Expr::Call { name, args } => ConstExpr::Function { + Expr::Call { name, args, .. } => ConstExpr::Function { name: name.clone(), - args: args + args: resolved_arguments(name, args)? .iter() .map(|arg| self.lower(arg)) .collect::>()?, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs index ff7f12240bc..a25a4ff5fd6 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs @@ -41,6 +41,8 @@ fn fixed_ty(width: usize, signed: bool) -> crate::ir::Type { fn function(name: &str, params: Vec<(&str, crate::ir::Type)>, body: Vec) -> ConstantFunction { ConstantFunction { + argument_names: params.iter().map(|(name, _)| (*name).to_string()).collect(), + argument_defaults: vec![None; params.len()], params: params .into_iter() .map(|(name, ty)| (name.into(), ty)) @@ -70,6 +72,7 @@ fn functions() -> ConstantFunctions { vec![("x", fixed_ty(32, true))], vec![Stmt::Return(Some(binary( Expr::Call { + arg_order: Vec::new(), name: "read".into(), args: vec![], }, @@ -85,8 +88,9 @@ fn functions() -> ConstantFunctions { then_body: vec![Stmt::Return(Some(ident("GLOBAL")))], else_body: vec![Stmt::Return(Some(binary( Expr::Call { + arg_order: Vec::new(), name: "recursive".into(), - args: vec![binary(ident("n"), BinaryOp::Sub, literal("1"))], + args: vec![Some(binary(ident("n"), BinaryOp::Sub, literal("1")))], }, BinaryOp::Add, literal("1"), diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index 2ff1c23f35b..a4b3eb12f6c 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -210,11 +210,16 @@ pub(super) fn simplify_constant_mux_conditions( }) .collect(), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name, args: args .into_iter() - .map(|arg| simplify_constant_mux_conditions(arg, const_env)) + .map(|arg| arg.map(|arg| simplify_constant_mux_conditions(arg, const_env))) .collect(), }, Expr::Ident(_) | Expr::Literal(_) => expr, @@ -369,9 +374,11 @@ fn constant_with_folded_selections_with_lookup( then_expr: Box::new(convert(then_expr)?), else_expr: Box::new(convert(else_expr)?), }), - Expr::Call { name, args } => Some(ConstExpr::call( + Expr::Call { name, args, .. } => Some(ConstExpr::call( name.clone(), - args.iter().map(convert).collect::>>()?, + args.iter() + .map(|arg| convert(arg.as_ref()?)) + .collect::>>()?, )), _ => expr_to_const(expr.clone()), } diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs index a917073e8c6..ae7881497f8 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs @@ -128,15 +128,17 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { ), ( Expr::Call { + arg_order: Vec::new(), name: "$countones".into(), - args: vec![ident("A")], + args: vec![Some(ident("A"))], }, 1, ), ( Expr::Call { + arg_order: Vec::new(), name: "unresolved_function".into(), - args: vec![ident("B")], + args: vec![Some(ident("B"))], }, 1, ), diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index 01c17a90ffc..5085b31315d 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -382,19 +382,25 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( }) .collect(), }, - Expr::Call { name, args } => { + Expr::Call { + name, + args, + arg_order, + } => { let args: Vec<_> = args .into_iter() .map(|arg| { - substitute_expr_constants_with_parameter_literals( - arg, - const_env, - parameter_literals, - ) + arg.map(|arg| { + substitute_expr_constants_with_parameter_literals( + arg, + const_env, + parameter_literals, + ) + }) }) .collect(); if matches!(name.as_str(), "$signed" | "$unsigned") - && let [arg] = args.as_slice() + && let [Some(arg)] = args.as_slice() && let Some(constant) = expr_to_const(arg.clone()) && let Some(ty) = infer_const_expr_type(&constant, ¶meter_types_from_const_env(const_env)) @@ -406,9 +412,20 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( } } else if name == "$countbits" { // Resolve constant calls before SLT lowering while retaining X/Z masks. - fold_const_integral_expr_preserving_mask(Expr::Call { name, args }, const_env) + fold_const_integral_expr_preserving_mask( + Expr::Call { + name, + args, + arg_order, + }, + const_env, + ) } else { - Expr::Call { name, args } + Expr::Call { + name, + args, + arg_order, + } } } } @@ -792,10 +809,21 @@ pub(super) fn expr_to_const(expr: Expr) -> Option { then_expr: Box::new(expr_to_const(*then_expr)?), else_expr: Box::new(expr_to_const(*else_expr)?), }), - Expr::Call { name, args } => Some(ConstExpr::call( + Expr::Call { name, - args.into_iter().map(expr_to_const).collect::>()?, - )), + args, + arg_order, + } => { + if !arg_order.is_empty() { + return None; + } + Some(ConstExpr::call( + name, + args.into_iter() + .map(|arg| expr_to_const(arg?)) + .collect::>()?, + )) + } Expr::Select { .. } | Expr::Concat(_) | Expr::RepeatConcat { .. } @@ -853,12 +881,23 @@ pub(super) fn expr_to_index_const(expr: Expr, dimensions: &PackedDimensions) -> then_expr: Box::new(expr_to_index_const(*then_expr, dimensions)?), else_expr: Box::new(expr_to_index_const(*else_expr, dimensions)?), }), - Expr::Call { name, args } => Some(ConstExpr::call( + Expr::Call { name, - args.into_iter() - .map(|arg| expr_to_index_const(arg, dimensions)) - .collect::>()?, - )), + args, + arg_order, + } => { + // Pure calls were expanded before index conversion. Retaining a + // named call here would discard the order of its procedural effects. + if !arg_order.is_empty() { + return None; + } + Some(ConstExpr::call( + name, + args.into_iter() + .map(|arg| expr_to_index_const(arg?, dimensions)) + .collect::>()?, + )) + } Expr::Select { expr, msb, @@ -1330,13 +1369,7 @@ pub(super) fn const_expr_from_ref_node_with_env( CALL_CONTEXT_COPIES.with(|count| count.set(count.get() + 1)); PackedDimensions::new(HashMap::default(), const_env, type_aliases) }; - return Ok(expr_from_function_subroutine_call( - &call.nodes.0, - syntax_tree, - &dimensions, - ) - .ok() - .and_then(expr_to_const)); + return Ok(const_user_call(tf_call, syntax_tree, dimensions, const_env)); } if let Some(ty) = size_system_function_expr_type(primary, syntax_tree, const_env, type_aliases) @@ -1540,6 +1573,48 @@ fn const_select_expr( })) } +fn const_user_call( + call: &sv_parser::TfCall, + tree: &SyntaxTree, + mut dimensions: PackedDimensions, + constants: &HashMap, +) -> Option { + dimensions.subroutine_param_names = const_functions::argument_names(); + let expression = expr_from_tf_call(call, tree, &dimensions).ok()?; + if let Expr::Call { + args, arg_order, .. + } = &expression + && (!arg_order.is_empty() || args.iter().any(Option::is_none)) + { + // Effectful runtime named calls keep their source order. Constant calls + // are folded only when their bodies and actuals evaluate successfully. + let literal = const_functions::eval_expression_literal(&expression, constants)?; + let Expr::Call { name, args, .. } = &expression else { + unreachable!() + }; + let types = parameter_types_from_const_env(constants) + .into_iter() + .map(|(name, ty)| (name, (ty.width, ty.signed))) + .collect(); + let args = const_functions::resolved_arguments(name, args)? + .into_iter() + .map(|arg| { + expr_to_const(arg.clone()).or_else(|| { + constant_folding::constant_with_folded_selections(&arg, constants, &types) + }) + }) + .collect::>>()?; + // Keep references to parameters for consumers that re-specialize the + // declaration contract; retain the native function's result type too. + return Some(ConstExpr::Resize { + expr: Box::new(ConstExpr::call(name.clone(), args)), + width: literal.width, + signed: literal.signed, + }); + } + expr_to_const(expression) +} + /// A system function call in a constant expression. The call is checked /// against the system function catalog: no path converts a call it rejects. fn const_expr_from_function_subroutine_call( @@ -1553,11 +1628,12 @@ fn const_expr_from_function_subroutine_call( // procedural lowering evaluates it before the operation. Without // parentheses the name parses as a call but is an identifier. sv_parser::SubroutineCall::TfCall(tf_call) if tf_call.nodes.2.is_some() => { - return Ok( - expr_from_tf_call(tf_call, syntax_tree, &PackedDimensions::default()) - .ok() - .and_then(expr_to_const), - ); + return Ok(const_user_call( + tf_call, + syntax_tree, + PackedDimensions::new(HashMap::default(), const_env, &HashMap::default()), + const_env, + )); } // `$unit::x` names an item of the compilation unit. sv_parser::SubroutineCall::TfCall(tf_call) @@ -1635,9 +1711,10 @@ fn countbits_constant_call( expression: Expr, const_env: &HashMap, ) -> Option { - let Expr::Call { name, mut args } = expression else { + let Expr::Call { name, args, .. } = expression else { return None; }; + let mut args = args.into_iter().collect::>>()?; let operand = args.remove(0); let controls = args .into_iter() diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 90c4d54cd4a..c359dbce04d 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -146,7 +146,7 @@ pub(super) fn ports_from_module_node( } /// The positional interface of a module: its ports in declaration order and -/// the overridable (non-local, non-type) parameters of its `#(...)` list. +/// its overridable value parameters: in the header when present, otherwise body. pub(super) fn module_interface_from_node( node: RefNode<'_>, syntax_tree: &SyntaxTree, @@ -170,7 +170,7 @@ pub(super) fn module_interface_from_node( } } let mut parameters = Vec::new(); - if let Some(RefNode::ParameterPortList(list)) = module_parameter_port_list(node) { + if let Some(RefNode::ParameterPortList(list)) = module_parameter_port_list(node.clone()) { let push_declaration = |declaration: &sv_parser::ParameterPortDeclaration, parameters: &mut Vec| { if matches!( @@ -218,6 +218,25 @@ pub(super) fn module_interface_from_node( sv_parser::ParameterPortList::Empty(_) => {} } } + if module_parameter_port_list(node.clone()).is_none() { + for declaration in scope_declarations(node) { + let sv_parser::PackageOrGenerateItemDeclaration::ParameterDeclaration(declaration) = + declaration + else { + continue; + }; + for child in RefNode::ParameterDeclaration(&declaration.0) { + if let RefNode::ParamAssignment(parameter) = child + && let Some(name) = identifier_text( + RefNode::ParameterIdentifier(¶meter.nodes.0), + syntax_tree, + ) + { + parameters.push(name); + } + } + } + } Ok(ModuleInterface { ports, parameters }) } @@ -593,27 +612,6 @@ fn signals_from_module_common_item( selected_name: Option<&str>, signals: &mut Vec, ) -> Result<(), AnalyzerError> { - if let sv_parser::ModuleCommonItem::AlwaysConstruct(always) = item - && always_kind(always) == AlwaysKind::Comb - { - // A variable declared inside an `always_comb` block is hoisted to a - // module signal. A clash with another signal of the same name is - // reported as a duplicate internal signal. - for node in RefNode::Statement(&always.nodes.1) { - if let RefNode::DataDeclaration(data) = node { - let mut declared = signals_from_data_declaration( - data, - syntax_tree, - type_aliases, - const_env, - selected_name, - )?; - substitute_signal_local_constants(&mut declared, const_env); - signals.extend(declared); - } - } - return Ok(()); - } if let sv_parser::ModuleCommonItem::ModuleOrGenerateItemDeclaration(declaration) = item { let sv_parser::ModuleOrGenerateItemDeclaration::PackageOrGenerateItemDeclaration( declaration, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index ecbe5349130..d2ecd16423f 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -924,7 +924,7 @@ fn size_function_expression_type_from_dimensions( // (IEEE 1800-2023 6.20.2), even without explicit dimensions. Expr::Ident(name) => variable_size_function_width(const_env, name, true) .or_else(|| parameter_type_from_const_env(const_env, name).map(|ty| ty.width)), - Expr::Call { name, args } => { + Expr::Call { name, args, .. } => { typecheck::bit_vector_function_return_type(name, args.len()) .map(|(width, _)| width) .or_else(|| { @@ -1861,7 +1861,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), is_2state: parameter.declared_is_2state, - members: Vec::new(), + members: parameter.members.clone(), signed_element_depth: parameter.signed_element_depth, }, ) diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 415637d3496..1a096acf412 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -119,13 +119,17 @@ pub(super) fn expr_from_expression_for_lvalue( if let LValue::Ident(name) = lhs && let Some(shape) = packed_dimensions.get(name) { - return patterns::expr_from_pattern( + let value = patterns::expr_from_pattern( &pattern.nodes.1, shape, syntax_tree, packed_dimensions, - ) - .or_else(|pattern_error| { + ); + // The legacy structure fallback cannot concatenate union aliases. + if shape.members.len() > 1 && shape.members.iter().all(|member| member.offset() == 0) { + return value; + } + return value.or_else(|pattern_error| { // A packed structure or a vector `default` fill. expr_from_assignment_pattern(&pattern.nodes.1, lhs, syntax_tree, packed_dimensions) .map_err(|_| pattern_error) @@ -363,9 +367,17 @@ pub(super) fn guard_zero_divisions(expr: Expr) -> Expr { .map(|item| item.map(&mut |operand| guard_zero_divisions(operand))) .collect(), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name, - args: args.into_iter().map(guard_zero_divisions).collect(), + args: args + .into_iter() + .map(|arg| arg.map(guard_zero_divisions)) + .collect(), }, } } @@ -663,8 +675,9 @@ fn expr_from_system_function_call( )?); } Ok(Expr::Call { + arg_order: Vec::new(), name: name.to_string(), - args, + args: args.into_iter().map(Some).collect(), }) } "$clog2" | "$countones" | "$onehot" | "$onehot0" | "$isunknown" => { @@ -688,8 +701,9 @@ fn expr_from_system_function_call( return Ok(Expr::Literal(value.to_string())); } Ok(Expr::Call { + arg_order: Vec::new(), name: name.to_string(), - args: vec![arg], + args: vec![Some(arg)], }) } _ => Err(AnalyzerError::Unsupported(format!( @@ -749,26 +763,28 @@ pub(super) fn expr_from_tf_call( .and_then(|metadata| metadata.arguments.as_deref()) }) .flatten(); - let actuals = match call.nodes.2.as_ref().map(|paren| &paren.nodes.1) { - None => Vec::new(), - Some(sv_parser::ListOfArguments::Ordered(args)) => { - let contents = args.nodes.0.contents(); - if contents.len() == 1 && contents[0].is_none() { - Vec::new() - } else { - contents - } - } - Some(sv_parser::ListOfArguments::Named(_)) => { - return Err(unsupported(format!("named arguments of `{name}`"))); - } + let query_names; + let signatures = if let Some(formals) = query_formals { + query_names = HashMap::from_iter([( + name.clone(), + formals.iter().map(|formal| formal.name.clone()).collect(), + )]); + &query_names + } else { + &packed_dimensions.subroutine_param_names }; + let (bindings, arg_order) = bind_call_arguments( + &name, + call.nodes.2.as_ref().map(|paren| &paren.nodes.1), + syntax_tree, + signatures, + )?; if let Some(formals) = query_formals { - if actuals.len() > formals.len() { + if bindings.len() > formals.len() { return Err(unsupported(format!("extra arguments of `{name}`"))); } for (position, formal) in formals.iter().enumerate() { - if actuals.get(position).is_none_or(|actual| actual.is_none()) && !formal.has_default { + if bindings.get(position).is_none_or(|actual| actual.is_none()) && !formal.has_default { return Err(unsupported(format!( "omitted argument {} of `{name}`", position + 1 @@ -777,18 +793,10 @@ pub(super) fn expr_from_tf_call( } } let mut args = Vec::new(); - for (position, expression) in actuals.into_iter().enumerate() { - let Some(expression) = expression.as_ref() else { - if query_formals.is_some_and(|formals| formals[position].has_default) { - // The query never evaluates the call or its default expression. - // Keep the argument positions while querying the return type. - args.push(Expr::Literal("0".into())); - continue; - } - return Err(unsupported(format!( - "omitted argument {} of `{name}`", - position + 1 - ))); + for (position, expr) in bindings.into_iter().enumerate() { + let Some(expr) = expr else { + args.push(None); + continue; }; let shape = packed_dimensions .subroutine_param_shapes @@ -796,14 +804,14 @@ pub(super) fn expr_from_tf_call( .and_then(|shapes| shapes.get(position)); if let Some(shape) = shape { check_unpacked_array_assignment( - expression, + expr, shape, || format!("argument {} of `{name}`", position + 1), syntax_tree, packed_dimensions, )?; } - let argument = match (patterns::pattern_expression(expression), shape) { + let arg = match (patterns::pattern_expression(expr), shape) { (Some(pattern), Some(shape)) if pattern.nodes.0.is_none() => { patterns::expr_from_pattern( &pattern.nodes.1, @@ -812,19 +820,23 @@ pub(super) fn expr_from_tf_call( packed_dimensions, )? } - _ => expr_from_expression_with_types(expression, syntax_tree, packed_dimensions)?, + _ => expr_from_expression_with_types(expr, syntax_tree, packed_dimensions)?, }; if query_formals.is_some_and(|formals| formals[position].direction.is_written()) - && !query_actual_is_writable(&argument, packed_dimensions) + && !query_actual_is_writable(&arg, packed_dimensions) { return Err(unsupported(format!( "non-writable argument {} of `{name}`", position + 1 ))); } - args.push(argument); + args.push(Some(arg)); } - Ok(Expr::Call { name, args }) + Ok(Expr::Call { + name, + args, + arg_order, + }) } fn query_actual_is_writable(expression: &Expr, dimensions: &PackedDimensions) -> bool { @@ -931,3 +943,74 @@ pub(super) fn system_tf_call_parts<'a>( }; Some((syntax_tree.get_str(&identifier.nodes.0)?, args)) } + +/// Bind actuals to formal positions while retaining their source order. +/// IEEE 1800-2023 13.5.4 allows positional actuals followed by named actuals. +pub(super) fn bind_call_arguments<'a>( + name: &str, + args: Option<&'a sv_parser::ListOfArguments>, + tree: &SyntaxTree, + signatures: &HashMap>, +) -> Converted<(Vec>, Vec)> { + let Some(args) = args else { + return Ok((Vec::new(), Vec::new())); + }; + let (mut positional, named): (Vec<_>, Vec<_>) = match args { + sv_parser::ListOfArguments::Ordered(args) => { + let contents = args.nodes.0.contents(); + let positional = if contents.len() == 1 && contents[0].is_none() { + Vec::new() + } else { + contents.into_iter().map(|arg| arg.as_ref()).collect() + }; + ( + positional, + args.nodes + .1 + .iter() + .map(|(_, _, identifier, value)| (identifier, value.nodes.1.as_ref())) + .collect(), + ) + } + sv_parser::ListOfArguments::Named(args) => { + let mut named = vec![(&args.nodes.1, args.nodes.2.nodes.1.as_ref())]; + named.extend( + args.nodes + .3 + .iter() + .map(|(_, _, identifier, value)| (identifier, value.nodes.1.as_ref())), + ); + (Vec::new(), named) + } + }; + if named.is_empty() { + return Ok((positional, Vec::new())); + } + let params = signatures + .get(name) + .ok_or_else(|| unsupported(format!("named arguments of `{name}`")))?; + if positional.len() > params.len() { + return Err(unsupported(format!("too many arguments of `{name}`"))); + } + let mut order: Vec<_> = (0..positional.len()).collect(); + let mut bound: HashSet<_> = order.iter().copied().collect(); + positional.resize(params.len(), None); + for (identifier, expr) in named { + let formal = identifier_text(RefNode::Identifier(identifier), tree) + .ok_or_else(|| unsupported("named argument"))?; + let position = params + .iter() + .position(|param| *param == formal) + .ok_or_else(|| unsupported(format!("argument `{formal}` of `{name}`")))?; + if !bound.insert(position) { + return Err(unsupported(format!( + "duplicate argument `{formal}` of `{name}`" + ))); + } + positional[position] = expr; + order.push(position); + } + // Defaults for unbound formals are resolved by the call lowerer. + order.extend((0..params.len()).filter(|position| !bound.contains(position))); + Ok((positional, order)) +} diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 62c4a634f1d..5654cb9e59a 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -1773,6 +1773,7 @@ fn function_expr_from_conditional_statement( } Some(Expr::Call { + arg_order: Vec::new(), name: "$unsupported_mixed_function_conditional".to_string(), args: Vec::new(), }) @@ -1926,6 +1927,7 @@ fn function_expr_from_case_statement( } Some(Expr::Call { + arg_order: Vec::new(), name: "$unsupported_mixed_function_case".to_string(), args: Vec::new(), }) diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 16775d9055c..3d468392e59 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -13,6 +13,27 @@ pub(super) use scope_views::ScopeViews; // Temporary identifiers protect definition-site bindings while functions are // inlined into a generate scope. They are removed when that item's names are // qualified, and never reach the public analyzer IR. +thread_local! { + static ROOT_SUBROUTINES: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub(super) fn root_subroutines_only() -> bool { + ROOT_SUBROUTINES.with(std::cell::Cell::get) +} + +/// Seed module functions before conditions need to call them. The full pass +/// still selects generate scopes and reports every generate diagnostic. +pub(super) fn with_root_subroutines(f: impl FnOnce() -> T) -> T { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + ROOT_SUBROUTINES.with(|flag| flag.set(self.0)); + } + } + let _restore = Restore(ROOT_SUBROUTINES.with(|flag| flag.replace(true))); + f() +} + const OUTER_BINDING: &str = "\0generate_outer:"; // Whitespace terminates an escaped identifier (IEEE 1800-2023 5.6.1). @@ -106,6 +127,14 @@ impl Item<'_> { if !dimensions.functions.is_empty() { local.functions = Arc::new(self.functions(&dimensions.functions)); } + if !dimensions.subroutine_param_names.is_empty() { + local.subroutine_param_names = + Arc::new(self.function_aliases((*dimensions.subroutine_param_names).clone())); + } + if !dimensions.subroutine_param_shapes.is_empty() { + local.subroutine_param_shapes = + Arc::new(self.function_aliases((*dimensions.subroutine_param_shapes).clone())); + } if !dimensions.function_return_types.is_empty() { local.function_return_types = self.function_aliases(dimensions.function_return_types.clone()); @@ -231,9 +260,9 @@ impl Item<'_> { } } } - Expr::Call { name, args } => { + Expr::Call { name, args, .. } => { *name = self.name(name); - args.iter_mut().for_each(|e| self.expr(e)); + args.iter_mut().flatten().for_each(|e| self.expr(e)); } } } @@ -335,13 +364,24 @@ pub(super) fn subroutine_items<'a>( env: &HashMap, aliases: &HashMap, ) -> Result>, AnalyzerError> { - items_with_literal_use(node, tree, env, aliases, LiteralUse::Subroutines) + items_with_literal_use( + node, + tree, + env, + aliases, + if root_subroutines_only() { + LiteralUse::RootSubroutines + } else { + LiteralUse::Subroutines + }, + ) } #[derive(Clone, Copy)] enum LiteralUse { All, Subroutines, + RootSubroutines, } fn items_with_literal_use<'a>( @@ -383,6 +423,18 @@ fn items_with_literal_use<'a>( return Ok(elaborator.items); } for item in module_non_port_items(node) { + if matches!(literal_use, LiteralUse::RootSubroutines) + && RefNode::NonPortModuleItem(item).into_iter().any(|node| { + matches!( + node, + RefNode::GenerateRegion(_) + | RefNode::ConditionalGenerateConstruct(_) + | RefNode::LoopGenerateConstruct(_) + ) + }) + { + continue; + } match item { sv_parser::NonPortModuleItem::GenerateRegion(region) => { for item in ®ion.nodes.1 { @@ -422,10 +474,12 @@ fn parameter_literal_references( // whole generate constructs, whose conditions, imports and local // declarations participate in elaboration for every collector. Keep // procedural declarations too, as type queries can name their scopes. - if matches!(literal_use, LiteralUse::Subroutines) - && let RefNode::NonPortModuleItem(sv_parser::NonPortModuleItem::ModuleOrGenerateItem( - item, - )) = &node + if matches!( + literal_use, + LiteralUse::Subroutines | LiteralUse::RootSubroutines + ) && let RefNode::NonPortModuleItem(sv_parser::NonPortModuleItem::ModuleOrGenerateItem( + item, + )) = &node && let sv_parser::ModuleOrGenerateItem::ModuleItem(item) = &**item && matches!( item.nodes.1, @@ -488,10 +542,14 @@ impl<'a> Elaborator<'a, '_> { else { return Ok(None); }; - let Some(mut expr) = expr_to_const(substitute_expr_idents( - const_expr_to_expr(expr), - &scope.literals, - )) else { + let dimensions = PackedDimensions { + const_env: scope.env.clone(), + ..PackedDimensions::default() + }; + let Some(mut expr) = expr_to_index_const( + substitute_expr_idents(const_expr_to_expr(expr), &scope.literals), + &dimensions, + ) else { return Ok(None); }; Ok(self.expand_constant_calls(&mut expr, scope).map(|()| expr)) @@ -579,11 +637,17 @@ impl<'a> Elaborator<'a, '_> { .collect(); self.expression(expr, scope)? .and_then(|expr| { - typecheck::eval_const_integral_literal_with_types(&expr.into(), &scope.env, &types) + let expr = expr.into(); + // Preserve four-state truth first (IEEE 1800-2023 12.4). + // The numeric interpreter additionally handles user functions + // kept symbolic for declaration-contract specialization. + typecheck::eval_const_integral_literal_with_types(&expr, &scope.env, &types) + .map(|literal| typecheck::integral_literal_truth(&literal) == Some(true)) + .or_else(|| { + typecheck::eval_const_expr_with_types(&expr, &scope.env, &types) + .map(|value| value != 0) + }) }) - // Unknown truth takes the false branch; a known one bit still makes - // a vector true even when other bits are X/Z (IEEE 1800-2023 12.4). - .map(|literal| typecheck::integral_literal_truth(&literal) == Some(true)) .ok_or_else(|| AnalyzerError::Unsupported(detail.to_string())) } diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index ca6ea20eec2..0df8a11fc6e 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -97,14 +97,16 @@ pub(super) fn expr_signedness_with_return_types( )?, ), Expr::Inside { .. } => Some(false), - Expr::Call { name, args } => typecheck::bit_vector_function_return_type(name, args.len()) - .map(|(_, signed)| signed) - .or_else(|| functions.get(name).map(|function| function.return_signed)) - .or_else(|| { - function_return_types - .get(name) - .map(|metadata| metadata.signed) - }), + Expr::Call { name, args, .. } => { + typecheck::bit_vector_function_return_type(name, args.len()) + .map(|(_, signed)| signed) + .or_else(|| functions.get(name).map(|function| function.return_signed)) + .or_else(|| { + function_return_types + .get(name) + .map(|metadata| metadata.signed) + }) + } } } @@ -130,8 +132,8 @@ pub(super) fn calls_subroutine(expr: &Expr) -> bool { } } match expr { - Expr::Call { name, args } => { - !system_functions::is_system_name(name) || args.iter().any(calls_subroutine) + Expr::Call { name, args, .. } => { + !system_functions::is_system_name(name) || args.iter().flatten().any(calls_subroutine) } Expr::Ident(_) | Expr::Literal(_) => false, Expr::Select { expr, msb, lsb, .. } => { @@ -312,36 +314,57 @@ pub(super) fn expand_expr_calls( }) .collect(), }, - Expr::Call { name, args } => { + Expr::Call { + name, + args, + arg_order, + } => { let args = args .into_iter() .map(|arg| { - expand_expr_calls( - arg, - functions, - expression_signedness, - depth, - apply_return_type, - ) + arg.map(|arg| { + expand_expr_calls( + arg, + functions, + expression_signedness, + depth, + apply_return_type, + ) + }) }) .collect::>(); let Some(function) = functions.get(&name) else { - return Expr::Call { name, args }; + return Expr::Call { + name, + args, + arg_order, + }; }; let Some(function_body) = &function.body else { - return Expr::Call { name, args }; + return Expr::Call { + name, + args, + arg_order, + }; }; // Inlining copies or drops an argument with its parameter, and // copies the calls of the body with their sites; a subroutine call // in either runs once per evaluation instead. - if function.params.len() != args.len() || args.iter().any(calls_subroutine) { - return Expr::Call { name, args }; + if function.params.len() != args.len() + || args.iter().any(Option::is_none) + || args.iter().flatten().any(calls_subroutine) + { + return Expr::Call { + name, + args, + arg_order, + }; } let call_args = args.clone(); let env = function .params .iter() - .zip(args) + .zip(args.into_iter().flatten()) .map(|(param, arg)| { let mut arg = if apply_return_type && let Some(width) = param.width { let assigned = Expr::Resize { @@ -377,6 +400,7 @@ pub(super) fn expand_expr_calls( ); if calls_subroutine(&expanded) { return Expr::Call { + arg_order, name, args: call_args, }; @@ -474,11 +498,16 @@ pub(super) fn substitute_expr_idents(expr: Expr, env: &HashMap) -> .map(|item| item.map(&mut |operand| substitute_expr_idents(operand, env))) .collect(), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name, args: args .into_iter() - .map(|arg| substitute_expr_idents(arg, env)) + .map(|arg| arg.map(|arg| substitute_expr_idents(arg, env))) .collect(), }, } diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 08b9f942cc9..9e5ab3fd0b0 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -468,6 +468,15 @@ fn parameter_override( .ok_or_else(|| AnalyzerError::Unsupported("parameter type override".to_string()))?; return Ok(ParameterOverride::type_override(name, text)); } + if RefNode::ParamExpression(expr) + .into_iter() + .any(|node| matches!(node, RefNode::AssignmentPatternExpression(_))) + { + let text = constant_pattern_text(expr, syntax_tree, packed_dimensions)?; + let mut bound = ParameterOverride::new(name, None); + bound.pattern_text = Some(text); + return Ok(bound); + } let value = const_expr_from_param_expression(expr, syntax_tree)? .ok_or_else(|| AnalyzerError::Unsupported("parameter override expression".to_string()))?; // A bare name that denotes a type (a typedef, or the instantiating @@ -503,3 +512,184 @@ fn type_source_text(r#type: &Type, const_env: &HashMap) -> Option< } Some(text) } + +fn constant_pattern_literal( + mut expression: ConstExpr, + dimensions: &PackedDimensions, + types: &HashMap, +) -> Converted { + fn freeze(expr: &mut ConstExpr, constants: &HashMap) { + match expr { + ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} + ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => { + freeze(expr, constants) + } + ConstExpr::Select { expr, bit } => { + freeze(expr, constants); + freeze(bit, constants); + } + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + freeze(expr, constants); + freeze(msb, constants); + freeze(lsb, constants); + } + ConstExpr::Binary { left, right, .. } => { + freeze(left, constants); + freeze(right, constants); + } + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => { + freeze(condition, constants); + freeze(then_expr, constants); + freeze(else_expr, constants); + } + ConstExpr::Function { name, args, .. } => { + for arg in args.iter_mut() { + freeze(arg, constants); + } + let lowered = args.iter().cloned().map(Into::into).collect::>(); + if let Some(literal) = const_functions::eval_call_literal(name, &lowered, constants) + { + *expr = ConstExpr::Literal(typecheck::format_integral_literal_binary(&literal)); + } + } + } + } + // System/literal expressions retain their four-state masks. User functions + // run through the installed interpreter, with the caller's constant scope + // and their declared result widths, before the leaf is serialized. + freeze(&mut expression, &dimensions.const_env); + typecheck::eval_const_integral_literal_with_types( + &expression.into(), + &dimensions.const_env, + types, + ) + .ok_or_else(|| unsupported("nonconstant parameter pattern element")) +} + +/// Freeze pattern leaves in the instantiating module's constant environment. +/// Reparse in the callee to apply the target array/structure shape. +fn constant_pattern_text( + expression: &sv_parser::ParamExpression, + tree: &SyntaxTree, + dimensions: &PackedDimensions, +) -> Result { + let node = RefNode::ParamExpression(expression); + let tokens: Vec<_> = node + .clone() + .into_iter() + .filter_map(|node| { + if let RefNode::Locate(locate) = node { + Some(locate) + } else { + None + } + }) + .collect(); + let start = tokens + .iter() + .map(|locate| locate.offset) + .min() + .ok_or_else(|| unsupported("parameter pattern"))?; + let end = tokens + .iter() + .map(|locate| locate.offset + locate.len) + .max() + .unwrap(); + let original = tree + .get_str(&sv_parser::Locate { + offset: start, + line: 0, + len: end - start, + }) + .ok_or_else(|| unsupported("parameter pattern text"))?; + let types = parameter_types_from_const_env(&dimensions.const_env) + .into_iter() + .map(|(name, ty)| (name, (ty.width, ty.signed))) + .collect(); + let mut edits = Vec::new(); + for child in node { + let value = match child { + RefNode::AssignmentPatternExpression(pattern) if pattern.nodes.0.is_some() => Some( + patterns::constant_typed_pattern_text(pattern, tree, dimensions)?, + ), + RefNode::Primary(primary) + if !matches!( + primary, + sv_parser::Primary::PrimaryLiteral(_) + | sv_parser::Primary::MintypmaxExpression(_) + | sv_parser::Primary::AssignmentPatternExpression(_) + ) => + { + let expr = sv_parser::Expression::Primary(Box::new(primary.clone())); + let value = indexed_select_base(RefNode::Expression(&expr), tree, dimensions)?; + Some(format!( + "({})", + typecheck::format_integral_literal_binary(&constant_pattern_literal( + value, dimensions, &types + )?,) + )) + } + RefNode::ConstantPrimary(primary) + if !matches!( + primary, + sv_parser::ConstantPrimary::PrimaryLiteral(_) + | sv_parser::ConstantPrimary::MintypmaxExpression(_) + | sv_parser::ConstantPrimary::ConstantAssignmentPatternExpression(_) + ) => + { + let expr = + sv_parser::ConstantExpression::ConstantPrimary(Box::new(primary.clone())); + let value = + indexed_select_base(RefNode::ConstantExpression(&expr), tree, dimensions)?; + Some(format!( + "({})", + typecheck::format_integral_literal_binary(&constant_pattern_literal( + value, dimensions, &types + )?,) + )) + } + // Retain literals, operators and parentheses for the callee's + // assignment context, including unbased fills and wider arithmetic. + // Descendant primary references still bind in the caller, also + // inside constant-expression repetition counts and index keys. + _ => None, + }; + let Some(replacement) = value else { + continue; + }; + let tokens: Vec<_> = child + .into_iter() + .filter_map(|node| { + if let RefNode::Locate(locate) = node { + Some(locate) + } else { + None + } + }) + .collect(); + let low = tokens.iter().map(|locate| locate.offset).min().unwrap(); + let high = tokens + .iter() + .map(|locate| locate.offset + locate.len) + .max() + .unwrap(); + edits.push((low, high, replacement)); + } + edits.sort_by_key(|(low, high, _)| (*low, std::cmp::Reverse(*high))); + let mut result = String::new(); + let mut cursor = start; + for (low, high, replacement) in edits { + if low < cursor { + continue; + } + result.push_str(&original[cursor - start..low - start]); + result.push_str(&replacement); + cursor = high; + } + result.push_str(&original[cursor - start..]); + Ok(result) +} diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index f4a299b3418..4c857203a54 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -493,7 +493,7 @@ impl Flow<'_> { } Ok(Exits::default()) } - Stmt::Call { name, args } => { + Stmt::Call { name, args, .. } => { let mut outputs = false; for (index, arg) in args.iter().enumerate() { let Some(arg) = arg else { @@ -577,7 +577,7 @@ impl Flow<'_> { } // A task may write an output or inout argument; one of a // subroutine whose directions are unknown may be either. - Stmt::Call { name, args } => { + Stmt::Call { name, args, .. } => { let directions = self.directions.get(name); writes |= args.iter().enumerate().any(|(index, arg)| { arg.as_ref().is_some_and(|arg| expr_reads(arg, self.name)) @@ -608,7 +608,7 @@ impl Flow<'_> { visit_calls(expr, &mut |name, args| { let directions = self.directions.get(name); writes |= args.iter().enumerate().any(|(index, arg)| { - expr_reads(arg, self.name) + arg.as_ref().is_some_and(|arg| expr_reads(arg, self.name)) && directions .and_then(|directions| directions.get(index)) .is_some_and(|direction| { @@ -665,12 +665,12 @@ fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { } /// Call `f` with the name and arguments of every call in `expr`. -fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e str, &'e [Expr])) { +fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e str, &'e [Option])) { match expr { Expr::Ident(_) | Expr::Literal(_) => {} - Expr::Call { name, args } => { + Expr::Call { name, args, .. } => { f(name, args); - for arg in args { + for arg in args.iter().flatten() { visit_calls(arg, f); } } @@ -732,7 +732,7 @@ fn expr_reads(expr: &Expr, name: &str) -> bool { || expr_reads(then_expr, name) || expr_reads(else_expr, name) } - Expr::Call { args, .. } => args.iter().any(|arg| expr_reads(arg, name)), + Expr::Call { args, .. } => args.iter().flatten().any(|arg| expr_reads(arg, name)), Expr::Inside { expr, items } => { expr_reads(expr, name) || items.iter().any(|item| match item { @@ -801,7 +801,7 @@ fn expr_is_constant(expr: &Expr) -> bool { // A call is constant when it folds, as a pure system function or a // constant function of constant arguments does. Expr::Call { args, .. } => { - args.iter().all(expr_is_constant) + args.iter().flatten().all(expr_is_constant) && expr_to_const(expr.clone()) .and_then(|call| eval_ast_const_expr(&call, &HashMap::default())) .is_some() diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index e2ae15591c7..ed56c767397 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -27,6 +27,10 @@ impl PackedMember { self } + pub(in crate::ast) fn offset(&self) -> usize { + self.offset + } + pub(in crate::ast) fn name(&self) -> &str { &self.name } diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index 676553e30b1..c95ce5b92e9 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -16,7 +16,9 @@ pub(in crate::ast) fn parse_type( const_env: &HashMap, aliases: &HashMap, ) -> Option { - if !matches!(data.nodes.0, sv_parser::StructUnion::Struct(_)) { + let union = matches!(data.nodes.0, sv_parser::StructUnion::Union(_)); + // Tagged unions require a discriminator and are not integral aliases. + if !union && !matches!(data.nodes.0, sv_parser::StructUnion::Struct(_)) { return None; } let (_, signing) = data.nodes.1.as_ref()?; @@ -84,8 +86,18 @@ pub(in crate::ast) fn parse_type( let mut width = 0usize; // The first declared member occupies the most significant bits. for member in members.iter_mut().rev() { - member.offset = width; - width = width.checked_add(expr_type_from_type(&member.r#type, const_env)?.width)?; + let member_width = expr_type_from_type(&member.r#type, const_env)?.width; + if union { + // IEEE 1800-2023 7.3.1: hard packed members share all bits + // and must have the same width. + if width != 0 && width != member_width { + return None; + } + width = member_width; + } else { + member.offset = width; + width = width.checked_add(member_width)?; + } } let kind = if members .iter() diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs index 184b3967cd2..95def768938 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs @@ -10,6 +10,8 @@ fn preserves_layout_signedness_and_state_kind() { typedef struct packed { logic signed [3:0] x; bit [3:0] y; } mixed_t; typedef struct packed signed { bit [3:0] x, y; } signed_t; mixed_t mixed; + union packed signed { logic signed [7:0] a; bit [7:0] b; } mixed_union; + union packed { bit [129:0] a; bit [129:0] b; } wide_union; signed_t signed_value; struct packed { byte a; shortint b; int c; longint d; } atoms; endmodule @@ -22,6 +24,8 @@ fn preserves_layout_signedness_and_state_kind() { ("mixed", 8, false, ir::TypeKind::Logic), ("signed_value", 8, true, ir::TypeKind::Bit), ("atoms", 120, false, ir::TypeKind::Bit), + ("mixed_union", 8, true, ir::TypeKind::Logic), + ("wide_union", 130, false, ir::TypeKind::Bit), ] { let ty = signals .iter() @@ -38,7 +42,9 @@ fn preserves_layout_signedness_and_state_kind() { fn rejects_invalid_or_unsupported_struct_shapes() { for body in [ "struct { logic a; } value;", - "union packed { logic a; logic b; } value;", + "union packed { logic a; logic [1:0] b; } value;", + "union tagged packed { logic a; logic b; } value;", + "union packed { logic a; logic b; } value; always_comb value = '{a: 1'b1, b: 1'b0};", "struct packed { real a; } value;", "struct packed { logic a[2]; } value;", "struct packed { logic a; logic a; } value;", diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 2097b195348..5e280f1dff3 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -433,6 +433,10 @@ pub(super) fn parameters_from_ref_node_with_environment( && declared_alias .as_ref() .is_none_or(|alias| alias.members.is_empty() && alias.unpacked_ranges.is_empty()); + let parameter_members = declared_alias + .as_ref() + .map(|ty| ty.members.clone()) + .unwrap_or_default(); let parameter_is_2state = declared_alias .or_else(|| type_from_ref_node(type_node, syntax_tree)) .is_some_and(|r#type| r#type.kind() == TypeKind::Bit); @@ -453,7 +457,9 @@ pub(super) fn parameters_from_ref_node_with_environment( if expr.into_iter().any(|node| { matches!( node, - RefNode::ConstantIndexedRange(_) | RefNode::IndexedRange(_) + RefNode::ConstantIndexedRange(_) + | RefNode::IndexedRange(_) + | RefNode::ConstantCast(_) ) }) { let mut dimensions = PackedDimensions::new( @@ -528,6 +534,7 @@ pub(super) fn parameters_from_ref_node_with_environment( is_local, ); parameter.packed_ranges = parameter_ranges.clone(); + parameter.members = parameter_members.clone(); parameter.signed_element_depth = parameter_signed_element_depth; environment.append(¶meter); parameters.push(parameter); @@ -1424,8 +1431,12 @@ pub(super) fn const_expr_to_expr(expr: ConstExpr) -> Expr { signed, }, ConstExpr::Function { name, args, .. } => Expr::Call { + arg_order: Vec::new(), name, - args: args.into_iter().map(const_expr_to_expr).collect(), + args: args + .into_iter() + .map(|arg| Some(const_expr_to_expr(arg))) + .collect(), }, ConstExpr::Unary { op, expr } => Expr::Unary { op, diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index de2a882f641..7e99be87bce 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -41,6 +41,16 @@ pub(super) fn typed_pattern( tree: &SyntaxTree, dims: &PackedDimensions, ) -> Converted { + let r#type = typed_pattern_type(pattern, tree, dims)?; + let shape = procedural::dimensions_from_type(&r#type); + expr_from_pattern(&pattern.nodes.1, &shape, tree, dims) +} + +fn typed_pattern_type( + pattern: &sv_parser::AssignmentPatternExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { let pattern_type = || unsupported("assignment pattern type"); let r#type = match pattern.nodes.0.as_ref().ok_or_else(pattern_type)? { sv_parser::AssignmentPatternExpressionType::PsTypeIdentifier(identifier) => { @@ -52,20 +62,96 @@ pub(super) fn typed_pattern( .clone() } sv_parser::AssignmentPatternExpressionType::IntegerAtomType(atom) => { - let atom = + let atom_type = integer_atom_expr_type(RefNode::IntegerAtomType(atom)).ok_or_else(pattern_type)?; - let mut r#type = Type::new(TypeKind::Bit); - r#type.is_signed = atom.signed; + let kind = if matches!( + atom.as_ref(), + sv_parser::IntegerAtomType::Integer(_) | sv_parser::IntegerAtomType::Time(_) + ) { + TypeKind::Logic + } else { + TypeKind::Bit + }; + let mut r#type = Type::new(kind); + r#type.is_signed = atom_type.signed; r#type.packed_ranges = vec![PackedRange::new( - ConstExpr::Literal((atom.width - 1).to_string()), + ConstExpr::Literal((atom_type.width - 1).to_string()), ConstExpr::Literal("0".to_string()), )]; r#type } _ => return Err(pattern_type()), }; + Ok(r#type) +} + +/// Serialize a typed constant pattern as positional values already converted +/// to its caller-side type (IEEE 1800-2023 10.9). Packed values become +/// literals; only unpacked dimensions need positional patterns. +pub(super) fn constant_typed_pattern_text( + pattern: &sv_parser::AssignmentPatternExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + let r#type = typed_pattern_type(pattern, tree, dims)?; let shape = procedural::dimensions_from_type(&r#type); - expr_from_pattern(&pattern.nodes.1, &shape, tree, dims) + let value = expr_from_pattern(&pattern.nodes.1, &shape, tree, dims)?; + let values = dims + .parameter_values + .iter() + .filter(|(name, _)| !dims.const_env.contains_key(*name)) + .map(|(name, value)| (name.clone(), value.clone())) + .collect(); + let value = substitute_expr_constants_with_parameter_literals(value, &dims.const_env, &values); + let Expr::Literal(value) = fold_const_integral_expr_preserving_mask(value, &dims.const_env) + else { + return Err(unsupported("nonconstant typed parameter pattern")); + }; + let value = typecheck::parse_integral_literal(&value) + .ok_or_else(|| unsupported("typed parameter pattern value"))?; + pattern_value_text(&value, &shape, 0, dims) +} + +fn pattern_value_text( + value: &typecheck::IntegralLiteral, + shape: &VariableDimensions, + offset: usize, + dims: &PackedDimensions, +) -> Converted { + let mut parts = Vec::new(); + if let Some((dimension, rest)) = shape.unpacked.split_first() { + let (_, _, count) = dimension_bounds(&dimension.left, &dimension.right, dims)?; + let element = VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }; + let width = shape_width(&element, dims) + .ok_or_else(|| unsupported("typed pattern element width"))?; + for position in 0..count { + parts.push(pattern_value_text( + value, + &element, + offset + position * width, + dims, + )?); + } + } else { + let width = + shape_width(shape, dims).ok_or_else(|| unsupported("typed pattern value width"))?; + let mask = (num_bigint::BigUint::from(1u8) << width) - num_bigint::BigUint::from(1u8); + let mut literal = typecheck::IntegralLiteral { + value: (&value.value >> offset) & &mask, + mask: (&value.mask >> offset) & &mask, + width, + signed: shape.signed, + }; + if shape.is_2state { + literal.value ^= &literal.value & &literal.mask; + literal.mask = num_bigint::BigUint::default(); + } + return Ok(typecheck::format_integral_literal_binary(&literal)); + } + Ok(format!("'{{{}}}", parts.join(", "))) } /// The value of one element of a pattern, as a `shape`. @@ -358,6 +444,11 @@ pub(super) fn expr_from_pattern( }); } if !shape.members.is_empty() { + // Overlapping members denote a union. A structure pattern would + // concatenate the aliases and silently produce a different value. + if shape.members.len() > 1 && shape.members.iter().all(|member| member.offset() == 0) { + return Err(unsupported("assignment pattern for a packed union")); + } return struct_pattern(pattern, shape, tree, dims); } if let Some((dimension, rest)) = shape.packed.split_first() diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 9fe7a520765..6ed41076fac 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -331,7 +331,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.rename_expr(then_expr); self.rename_expr(else_expr); } - Expr::Call { args, .. } => args.iter_mut().for_each(|arg| self.rename_expr(arg)), + Expr::Call { args, .. } => args + .iter_mut() + .flatten() + .for_each(|arg| self.rename_expr(arg)), Expr::Inside { expr, items } => { self.rename_expr(expr); for item in items { @@ -738,9 +741,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, ) .ok_or_else(|| unsupported("subroutine call"))?; - let args = + let (args, arg_order) = self.call_arguments(&name, call.nodes.2.as_ref().map(|paren| &paren.nodes.1))?; - Ok(vec![Stmt::Call { name, args }]) + Ok(vec![Stmt::Call { + name, + args, + arg_order, + }]) } sv_parser::SubroutineCall::SystemTfCall(system_call) => { let (name, args) = system_tf_call_parts(system_call, self.tree) @@ -875,38 +882,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &self, name: &str, args: Option<&sv_parser::ListOfArguments>, - ) -> Result>, AnalyzerError> { - let Some(args) = args else { - return Ok(Vec::new()); - }; - let (positional, named): (Vec>, Vec<_>) = match args { - sv_parser::ListOfArguments::Ordered(args) => { - let contents = args.nodes.0.contents(); - let positional = if contents.len() == 1 && contents[0].is_none() { - Vec::new() - } else { - contents.into_iter().map(|arg| arg.as_ref()).collect() - }; - let named = args - .nodes - .1 - .iter() - .map(|(_, _, identifier, value)| (identifier, value.nodes.1.as_ref())) - .collect(); - (positional, named) - } - sv_parser::ListOfArguments::Named(args) => { - let mut named = vec![(&args.nodes.1, args.nodes.2.nodes.1.as_ref())]; - named.extend( - args.nodes - .3 - .iter() - .map(|(_, _, identifier, value)| (identifier, value.nodes.1.as_ref())), - ); - (Vec::new(), named) - } + ) -> Result<(Vec>, Vec), AnalyzerError> { + let signatures = if self.dims.subroutine_param_names.is_empty() { + self.state.subroutine_params + } else { + &self.dims.subroutine_param_names }; - let mut lowered: Vec> = positional + let (bindings, order) = + expressions::bind_call_arguments(name, args, self.tree, signatures)?; + let args = bindings .into_iter() .enumerate() .map(|(position, arg)| { @@ -914,28 +898,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .transpose() }) .collect::>()?; - if !named.is_empty() { - let params = self - .state - .subroutine_params - .get(name) - .ok_or_else(|| unsupported(format!("named arguments to `{name}`")))?; - for (identifier, value) in named { - let formal = identifier_text(RefNode::Identifier(identifier), self.tree) - .ok_or_else(|| unsupported("named argument"))?; - let position = params - .iter() - .position(|param| *param == formal) - .ok_or_else(|| unsupported(format!("argument `{formal}` of `{name}`")))?; - if lowered.len() <= position { - lowered.resize(position + 1, None); - } - lowered[position] = value - .map(|value| self.call_argument(name, position, value)) - .transpose()?; - } - } - Ok(lowered) + Ok((args, order)) } /// One subroutine argument; an assignment pattern takes the formal's shape. @@ -989,6 +952,22 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None => Vec::new(), }; for (condition, then_body) in branches.into_iter().rev() { + // A generate index or parameter can make a procedural branch + // unreachable. Remove its writes before checking process drivers. + let constant = if inlining::calls_subroutine(&condition) { + // Even a constant return value does not make the run-time + // call's display, output or module-variable effects optional. + None + } else { + expr_to_const(condition.clone()) + .and_then(|condition| eval_ast_const_expr(&condition, &self.dims.const_env)) + }; + if let Some(value) = constant { + if value != 0 { + else_body = then_body; + } + continue; + } else_body = vec![Stmt::If { condition, then_body, @@ -1725,12 +1704,9 @@ pub(super) fn subroutine_argument_names( .collect(); let param_directions: Vec = params.iter().map(|(_, direction, ..)| *direction).collect(); - directions.insert(syntax.name.clone(), param_directions.clone()); directions.insert(qualified.clone(), param_directions); let params: Vec = params.into_iter().map(|(name, ..)| name).collect(); - names.insert(syntax.name.clone(), params.clone()); names.insert(qualified.clone(), params); - shapes.insert(syntax.name.clone(), param_shapes.clone()); shapes.insert(qualified, param_shapes); } } @@ -1873,9 +1849,14 @@ pub(super) fn subroutines_with_symbolic_parameters( }; let first_static = builder.state.statics.len(); builder.push_scope(); + // Defaults bind in the enclosing declaration scope, before + // any formal can shadow those names (IEEE 1800-2023 13.5.3). + let defaults = params + .iter() + .map(|(_, _, _, default)| default.map(|expr| builder.expr(expr)).transpose()) + .collect::, _>>()?; let mut lowered_params = Vec::new(); - for (source, direction, r#type, default) in params { - let default = default.map(|expr| builder.expr(expr)).transpose()?; + for ((source, direction, r#type, _), default) in params.into_iter().zip(defaults) { let name = builder.declare(&source, r#type.clone()); lowered_params.push(SubroutineParam { name, diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 29205d2e1af..f0aaf67e0db 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -645,9 +645,17 @@ impl Renamer<'_> { then_expr: boxed(then_expr), else_expr: boxed(else_expr), }, - Expr::Call { name, args } => Expr::Call { + Expr::Call { + name, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), name: self.name(&name), - args: args.into_iter().map(|arg| self.expr(arg)).collect(), + args: args + .into_iter() + .map(|arg| arg.map(|arg| self.expr(arg))) + .collect(), }, Expr::Inside { expr, items } => Expr::Inside { expr: boxed(expr), @@ -690,7 +698,12 @@ impl Renamer<'_> { pub fn stmt(&self, stmt: Stmt) -> Stmt { let stmt = match stmt { - Stmt::Call { name, args } => Stmt::Call { + Stmt::Call { + name, + args, + arg_order, + } => Stmt::Call { + arg_order: arg_order.clone(), name: self.name(&name), args, }, @@ -763,7 +776,12 @@ impl Renamer<'_> { /// expressions were renamed already. fn stmt_names(&self, stmt: Stmt) -> Stmt { let stmt = match stmt { - Stmt::Call { name, args } => Stmt::Call { + Stmt::Call { + name, + args, + arg_order, + } => Stmt::Call { + arg_order: arg_order.clone(), name: self.name(&name), args, }, @@ -782,6 +800,11 @@ impl Renamer<'_> { for range in &mut parameter.packed_ranges { *range = self.packed_range(range.clone()); } + parameter.members = parameter + .members + .into_iter() + .map(|member| member.with_type(|ty| self.r#type(ty))) + .collect(); parameter } diff --git a/crates/celox-sv-analyzer/src/ast/type_parameters.rs b/crates/celox-sv-analyzer/src/ast/type_parameters.rs index bcf9269b6da..3ae64df1e28 100644 --- a/crates/celox-sv-analyzer/src/ast/type_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/type_parameters.rs @@ -129,3 +129,80 @@ pub(crate) fn apply_type_parameter_overrides( } Ok(None) } + +/// Override array/structure value parameters before their target shapes are +/// lowered. Only overridable module parameters may be rebound, never locals. +pub(crate) fn apply_pattern_parameter_overrides( + code: &str, + tree: &SyntaxTree, + module_name: &str, + overrides: &[(String, String)], +) -> Result, AnalyzerError> { + if overrides.is_empty() { + return Ok(None); + } + for node in tree { + if !matches!( + node, + RefNode::ModuleDeclarationAnsi(_) | RefNode::ModuleDeclarationNonansi(_) + ) { + continue; + } + if module_name_from_node(node.clone(), tree)? != module_name { + continue; + } + let allowed = declarations::module_interface_from_node(node.clone(), tree)?.parameters; + let mut edits = Vec::new(); + let mut found = HashSet::default(); + let mut declarations = module_parameter_port_list(node.clone()) + .into_iter() + .collect::>(); + declarations.extend(scope_declarations(node.clone()).into_iter().filter_map( + |declaration| { + if let sv_parser::PackageOrGenerateItemDeclaration::ParameterDeclaration( + declaration, + ) = declaration + { + Some(RefNode::ParameterDeclaration(&declaration.0)) + } else { + None + } + }, + )); + for child in declarations.into_iter().flat_map(|node| node.into_iter()) { + let RefNode::ParamAssignment(param) = child else { + continue; + }; + let name = parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree)?; + let Some((_, bound)) = overrides.iter().find(|(candidate, _)| *candidate == name) + else { + continue; + }; + if !allowed.contains(&name) { + return Err(unsupported(format!( + "pattern override of non-overridable parameter `{name}`" + ))); + } + let Some((_, value)) = ¶m.nodes.2 else { + return Err(unsupported(format!( + "array parameter `{name}` without a default" + ))); + }; + let (start, end) = node_span(RefNode::ConstantParamExpression(value), tree) + .ok_or_else(|| unsupported("array parameter source span"))?; + edits.push(Edit { + start, + end, + replacement: bound.clone(), + }); + found.insert(name); + } + for (name, _) in overrides { + if !found.contains(name) { + return Err(unsupported(format!("unknown array parameter `{name}`"))); + } + } + return Ok(Some(apply_edits(code, (0, code.len()), edits))); + } + Err(unsupported(format!("module `{module_name}`"))) +} diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 34b74267cb7..b8e198cfe78 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -319,7 +319,8 @@ fn reject_silently_ignored_constructs_with_dimensions( } RefNode::ConstantCast(cast) if !typed_indexed_casts.contains(&RefNode::ConstantCast(cast)) - && !constant_cast_is_supported(cast, syntax_tree, const_env, type_aliases) => + && !constant_cast_is_supported(cast, syntax_tree, const_env, type_aliases) + && casts::constant_cast_with_dimensions(cast, syntax_tree, indexed_dimensions).is_none() => { return Err(AnalyzerError::Unsupported("constant cast expression".to_string())); } diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 1415195f2f8..475cef8ea03 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -415,17 +415,29 @@ pub struct ParameterOverride { name: String, value: Option, type_text: Option, + pattern_text: Option, } impl ParameterOverride { - pub(crate) fn new(name: String, value: Option, type_text: Option) -> Self { + pub(crate) fn new( + name: String, + value: Option, + type_text: Option, + pattern_text: Option, + ) -> Self { Self { name, value, type_text, + pattern_text, } } + /// A constant assignment pattern, evaluated in the caller scope. + pub fn pattern_text(&self) -> Option<&str> { + self.pattern_text.as_deref() + } + pub fn name(&self) -> &str { &self.name } @@ -924,7 +936,10 @@ pub enum Expr { }, Call { name: String, - args: Vec, + /// Missing actuals retain their formal slots for declaration-scope defaults. + args: Vec>, + /// Formal positions in source evaluation/copy-out order; empty means positional. + arg_order: Vec, }, /// `expr inside { items }`: true when `expr` matches any item. Inside { @@ -1240,9 +1255,14 @@ impl From for Expr { then_expr: Box::new((*then_expr).into()), else_expr: Box::new((*else_expr).into()), }, - ast::Expr::Call { name, args } => Expr::Call { + ast::Expr::Call { name, - args: args.into_iter().map(Into::into).collect(), + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), + name, + args: args.into_iter().map(|arg| arg.map(Into::into)).collect(), }, ast::Expr::Inside { expr, items } => Expr::Inside { expr: Box::new((*expr).into()), diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index e1f035f0724..ab7a5fbd929 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -32,6 +32,23 @@ impl ParsedSource { }) } + /// Bind assignment-pattern parameters with values frozen in the caller. + pub fn with_pattern_parameter_overrides( + &self, + module_name: &str, + overrides: &[(String, String)], + ) -> Result, AnalyzerError> { + ast::type_parameters::apply_pattern_parameter_overrides( + &self.code, + &self.tree, + module_name, + overrides, + )? + .as_deref() + .map(|code| Self::parse(code, &self.path)) + .transpose() + } + pub fn module_names(&self) -> &[String] { self.index.names() } @@ -355,3 +372,82 @@ mod tests { ); } } + +#[cfg(test)] +mod pattern_override_tests { + use super::*; + + #[test] + fn pattern_specialization_preserves_shadowed_local_parameter_declarations() { + let source = ParsedSource::parse( + r#" + module Top #(parameter byte Q [2] = '{1, 2})(output int y); + always_comb begin + localparam int Q = 9; + y = Q; + end + endmodule + "#, + Path::new("pattern_scope.sv"), + ) + .unwrap(); + let rebound = source + .with_pattern_parameter_overrides("Top", &[("Q".into(), "'{-3, -5}".into())]) + .unwrap() + .unwrap(); + assert!(rebound.code.contains("localparam int Q = 9;")); + let ir = rebound + .analyze_module_with_parameter_expr_overrides( + "Top", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + assert_eq!(ir.modules()[0].initial_processes().len(), 1); + assert_eq!( + ir.modules()[0].signals()[0].r#type().resolved_width(), + Some(16) + ); + } + + #[test] + fn pattern_override_leaves_counts_and_keys_use_the_callers_scope() { + let ir = crate::analyze_source( + r#" + module Child #(parameter int N = 1, parameter byte Q [2] = '{1, 2}); + endmodule + module Top #(parameter int N = 2); + Child #(.Q('{N{-N}})) repeated_values(); + Child #(.Q('{N-2: -N, default: N+1})) keyed_values(); + endmodule + "#, + Path::new("pattern_caller.sv"), + ) + .unwrap(); + let top = ir + .modules() + .iter() + .find(|module| module.name() == "Top") + .unwrap(); + for instance in top.instances() { + let pattern = instance.parameter_overrides()[0].pattern_text().unwrap(); + assert!(!pattern.contains('N'), "{pattern}"); + let child = ParsedSource::parse( + "module Child #(parameter int N = 1, parameter byte Q [2] = '{1, 2}); endmodule", + Path::new("child.sv"), + ) + .unwrap(); + let rebound = child + .with_pattern_parameter_overrides("Child", &[("Q".into(), pattern.into())]) + .unwrap() + .unwrap(); + rebound + .analyze_module_with_parameter_expr_overrides( + "Child", + &HashMap::default(), + &ModuleInterfaces::default(), + ) + .unwrap(); + } + } +} diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index a54eb345d24..c87018f22bd 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -51,6 +51,7 @@ pub enum StmtBase { Call { name: String, args: Vec>, + arg_order: Vec, }, /// A system function called as a statement, such as `$countones(a);`: /// the expression is evaluated like any other operand and its value is @@ -227,7 +228,12 @@ impl StmtBase { StmtBase::Break => StmtBase::Break, StmtBase::Continue => StmtBase::Continue, StmtBase::Return(value) => StmtBase::Return(value.map(fe)), - StmtBase::Call { name, args } => StmtBase::Call { + StmtBase::Call { + name, + args, + arg_order, + } => StmtBase::Call { + arg_order: arg_order.clone(), name, args: args.into_iter().map(|arg| arg.map(&mut *fe)).collect(), }, @@ -332,7 +338,7 @@ impl StmtBase { fe(value); } } - StmtBase::Call { name, args } => { + StmtBase::Call { name, args, .. } => { fname(name); for arg in args.iter_mut().flatten() { fe(arg); diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 7a111b00d3d..0a0bf8d541f 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -1409,12 +1409,15 @@ fn converts_unknowns_when_constant_casting_to_two_state_types() { module Top; typedef bit [1:0] two_t; localparam logic [1:0] P = two_t'(2'bx1); + localparam logic [7:0] X = 8'b10xz_01zx; + localparam byte unsigned U = unsigned'(byte'(X)); endmodule "#, Path::new("two_state_constant_cast.sv"), ) .expect("two-state constant casts should convert unknown bits to zero"); assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), Some(1)); + assert_eq!(ir.modules()[0].parameters()[2].resolved_value(), Some(0x84)); } #[test] @@ -3969,3 +3972,45 @@ fn isunbounded_argument_validation_is_not_skipped_by_bits() { ); } } + +#[test] +fn constant_branch_pruning_retains_runtime_subroutine_conditions() { + let ir = analyze_source( + r#" + module Top(output logic y); + function automatic int choose(input int v); + $display("choose %0d", v); + return 1; + endfunction + always_comb if (choose(1)) y = 1; else y = 0; + endmodule + "#, + Path::new("conditional_call.sv"), + ) + .unwrap(); + assert!(matches!( + ir.modules()[0].comb_processes()[0].body()[0], + crate::ir::Stmt::If { .. } + )); +} + +#[test] +fn named_constant_calls_retain_parameter_dependencies() { + let source = "module Top #(parameter W=8, parameter N=f(.value(W)))(); function automatic integer f(input integer value); return value+1; endfunction endmodule"; + let syntax = + crate::syntax::parse_source(source, std::path::Path::new("named_dependency.sv")).unwrap(); + let source = ast::Source::from_syntax(&syntax).unwrap(); + let module = &source.modules()[0]; + let _functions = module.install_constant_functions(); + let expression: ir::ConstExpr = module + .parameters() + .iter() + .find(|param| param.name() == "N") + .unwrap() + .value() + .unwrap() + .clone() + .into(); + let values = fxhash::FxHashMap::from_iter([("W".to_string(), 16i128)]); + assert_eq!(typecheck::eval_const_expr(&expression, &values), Some(17)); +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 53f69265df2..f123f8cb0fd 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -364,9 +364,12 @@ Verilator 5.052 passes the case on its unchanged stimulus and assertions. | `sv_icarus_generate_forward_reference` | execute | icarus | 1 | Icarus 13.0 resolves a name used before its declaration in the same generate block to the enclosing scope. Verilator (which warns VARHIDDEN) and Celox resolve it to the block's own declaration. | | `sv_icarus_generate_case_context` | execute | icarus | 1 | Icarus 13.0 compares a case-generate selector without the common width and signedness of the selector and all labels; IEEE 1800-2023 12.5 makes the comparison unsigned when any operand is unsigned. Verilator agrees with the expected value. | | `sv_icarus_input_port_width` | execute | icarus | 1 | Icarus 13.0 evaluates an input port connection at its self-determined width before padding, losing the carry; IEEE 1800-2023 10.8 and 11.8.2 widen the operands to the port first. Verilator agrees with the expected value. | -| `sv_icarus_syntax` | compile | icarus | 9 | Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases. | +| `sv_icarus_syntax` | compile | icarus | 12 | Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks. | | `sv_icarus_packed_array_parameters` | compile | icarus | 5 | Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported. | -| `sv_icarus_unpacked_array_parameters` | compile | icarus | 7 | Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately. | +| `sv_icarus_unpacked_array_parameters` | compile | icarus | 13 | Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately. | +| `sv_verilator_default_argument_scope` | execute | verilator | 1 | Verilator 5.052 binds the default b=a to the earlier formal a and returns 22 for f(.a(2)) when the enclosing module a is 5. IEEE 1800-2023 13.5.3 evaluates defaults in the scope containing the subroutine declaration, requiring 25. Celox passes all five backend variants. | +| `sv_verilator_typed_pattern_sign_extension` | execute | verilator | 1 | Verilator 5.052 zero-extends int'{default: 1} to a 64-bit parameter (0x00000000ffffffff). IEEE 1800-2023 10.9 gives the expression the self-determined int type, signed under 6.11.3; 6.20.2 requires assignment conversion to the parameter, giving 0xffffffffffffffff. The same Verilator probe sign-extends through an int variable or explicit int cast. | +| `sv_icarus_dynamic_argument_defaults` | compile | icarus | 1 | Icarus 13.0 requires function port defaults to be constant expressions and rejects a reference to a net or variable. IEEE 1800-2023 13.5.3 evaluates a used default in the enclosing declaration scope on each call; the shared case retains its dynamic module-signal default. | | `sv_icarus_internal_error` | compile | icarus | 3 | Icarus 13.0 crashes on these designs: a segmentation fault while compiling, or a vvp assertion (vthread.cc of_DISABLE_FLOW) while running. Verilator passes these cases. | | `sv_icarus_generate_function_scope` | execute | icarus | 1 | Icarus 13.0 evaluates a size query in a generate block with a function from another scope and reaches a $fatal in an active branch. Verilator agrees with the expected value. | | `sv_icarus_unknown_generate_condition` | compile | icarus | 1 | Icarus 13.0 rejects a loop-generate condition with unknown bits; Verilator accepts it, and Celox treats an unknown condition as false, as for if-generate (IEEE 1800-2023 12.4, 27.5). | @@ -395,7 +398,7 @@ Verilator 5.052 passes the case on its unchanged stimulus and assertions. | `sv_icarus_dimensions_type_queries` | compile | icarus | 2 | Icarus 13.0 rejects data type arguments to `$dimensions`, with syntax/type-name errors and an assertion for a multidimensional cast. IEEE 1800-2023 20.7 permits these queries. Verilator passes the integral/string/real type case. | | `sv_verilator_chandle_dimensions` | execute | verilator | 1 | Verilator 5.052 returns 1 for `$dimensions(chandle)`; IEEE 1800-2023 6.14 and 20.7 require 0 for this nonarray pointer type. | | `sv_icarus_subroutine_unpacked_ports` | compile | icarus | 4 | Icarus 13.0 rejects subroutine arguments with unpacked dimensions and passing an array to those arguments. IEEE 1800-2023 13.5 permits unpacked subroutine arguments. Verilator passes the case. | -| `sv_icarus_function_return_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for $dimensions of a call to a package function returning a multidimensional packed value. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes the case. | +| `sv_icarus_function_return_dimensions` | execute | icarus | 2 | Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases. | | `sv_icarus_one_bit_expression_dimensions` | execute | icarus | 3 | Icarus 13.0 reports 0 for one-bit vector operands of $dimensions, including sized literals, one-bit vector parameters and signing conversions. IEEE 1800-2023 6.20.2, 6.24.1 and 20.7 require vector rank 1; Slang 12.0.0 corroborates these type shapes. | | `sv_verilator_one_bit_expression_dimensions` | execute | verilator | 2 | Verilator 5.052 reports 0 for one-bit vector operands of $dimensions, including sized literals and signing conversions. IEEE 1800-2023 6.20.2, 6.24.1 and 20.7 require vector rank 1; Slang 12.0.0 corroborates these type shapes. | | `sv_verilator_timescale_constant` | compile | verilator | 1 | Verilator 5.052 cannot evaluate $timeprecision in a parameter initializer. IEEE 1800-2023 11.2.1 lists the timescale system functions in 20.4 among constant system function calls with constant arguments; this case uses no arguments. Slang 12.0.0 also rejects both timescale functions in constant expressions. | diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 42940fa16f7..c32258da1b8 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -256,3 +256,177 @@ (set sel 0)) (assert_eq out_fb 1) (assert_eq out_dyn 1)) + +; IEEE 1800-2023 5.7.1 and 10.9.1: retain the element assignment context. +(case parameter_patterns_keep_fill_and_arithmetic_context + (source "pattern_context.sv" #" + module Child #(parameter logic [15:0] Q [2] = '{0, 0}) + (output logic [31:0] y); + localparam bit CHOOSE = 0; + assign y = {Q[1], Q[0]}; + endmodule + module Scalar #(parameter logic [63:0] P = '{default: 0}) + (output logic [63:0] y); + assign y = P; + endmodule + module Top(output logic [31:0] fills, expressions, repeated, + output logic [63:0] builtin); + localparam bit CHOOSE = 1; + localparam logic [7:0] A = 8'hff; + Child #(.Q('{default: '1})) a(fills); + Child #(.Q('{A + 8'd1, CHOOSE ? '1 : '0})) b(expressions); + Child #(.Q('{2{('1)}})) c(repeated); + Scalar #(.P(int'{default: 0})) d(builtin); + endmodule + "#) + (top Top) + (assert_eq fills 0xffffffff) + (assert_eq expressions 0xffff0100) + (assert_eq repeated 0xffffffff) + (assert_eq builtin 0)) + +; Explicit pattern types are self-determined in the caller, not the child. +(case parameter_patterns_bind_caller_types + (source "typed_pattern_scope.sv" #" + module Child #(parameter logic signed [7:0] Q [2] = '{0, 0}) + (output logic [31:0] y); + typedef logic [3:0] pair_t [2]; + assign y = {16'(Q[1]), 16'(Q[0])}; + endmodule + module Top(output logic [31:0] local_type, shadowed_type); + typedef logic signed [7:0] local_pair_t [2]; + typedef logic signed [7:0] pair_t [2]; + Child #(.Q(local_pair_t'{8'shf8, '1})) a(local_type); + Child #(.Q(pair_t'{8'shf8, '1})) b(shadowed_type); + endmodule + "#) + (top Top) + (assert_eq local_type 0xfffffff8) + (assert_eq shadowed_type 0xfffffff8)) + +(case parameter_patterns_bind_nested_caller_types + (source "nested_typed_pattern_scope.sv" #" + module Child #(parameter logic signed [7:0] Q [2][2] = '{default: 0}) + (output logic [63:0] y); + assign y = {16'(Q[1][1]), 16'(Q[1][0]), 16'(Q[0][1]), 16'(Q[0][0])}; + endmodule + module Top(output logic [63:0] y); + typedef logic signed [7:0] pair_t [2]; + Child #(.Q('{pair_t'{-3, -5}, pair_t'{-7, -9}})) a(y); + endmodule + "#) + (top Top) + (assert_eq y 0xfff7fff9fffbfffd)) + +(case parameter_patterns_keep_unknown_fill + (four_state) + (source "pattern_unknown_fill.sv" #" + module Child #(parameter logic [7:0] Q [2] = '{0, 0}) + (output logic [15:0] y); + assign y = {Q[1], Q[0]}; + endmodule + module Top(output logic [15:0] xfill, zfill); + Child #(.Q('{default: 'x})) a(xfill); + Child #(.Q('{default: 'z})) b(zfill); + endmodule + "#) + (top Top) + (assert_eq xfill (fourstate 0xffff 0xffff)) + (assert_eq zfill (fourstate 0 0xffff))) + +(case parameter_patterns_evaluate_caller_constant_functions + (source "constant_pattern_calls.sv" #" + module Child #(parameter byte signed Q[2] = '{1, 2})(output logic [15:0] y); + localparam Bias = 99; + assign y = {Q[0], Q[1]}; + endmodule + module Top(output logic [15:0] y); + localparam Bias = 5; + function automatic byte signed f(input int value); return -(value + Bias); endfunction + function automatic byte signed g(input int value); return f(.value(value)); endfunction + Child #(.Q('{g(1), f(2)})) child(y); + endmodule + "#) + (top Top) + (eval) + (assert_eq y 0xfaf9)) + +(case parameter_patterns_override_body_declarations + (source "body_parameter_pattern.sv" #" + module Ansi(output logic [15:0] y); + parameter byte Q[2] = '{1, 2}; + assign y = {Q[0], Q[1]}; + endmodule + module Top(output logic [15:0] y); + Ansi #(.Q('{3, 4})) first(y); + endmodule + "#) + (top Top) + (eval) + (assert_eq y 0x0304)) + +; Typed packed patterns are values: caller field names/layout do not escape. +(case parameter_patterns_transfer_packed_values + (source "packed_pattern_values.sv" #" + package ChildTypes; + typedef struct packed {logic [7:0] a; logic [7:0] b;} child_t; + endpackage + module Child #(parameter ChildTypes::child_t P = '{default: 0}) + (output logic [15:0] y); + assign y = {P.a, P.b}; + endmodule + module Top(output logic [15:0] renamed, regrouped); + typedef struct packed {logic [7:0] x; logic [7:0] y;} caller_t; + typedef struct packed {logic [3:0] x; logic [11:0] y;} other_t; + Child #(.P(caller_t'{y: 2, x: 1})) c(renamed); + Child #(.P(other_t'{x: 10, y: 12'h123})) d(regrouped); + endmodule + "#) + (top Top) + (assert_eq renamed 0x0102) + (assert_eq regrouped 0xa123)) + +(case parameter_patterns_override_scalar_defaults + (source "scalar_pattern_values.sv" #" + module Child #(parameter int P = 0)(output logic [31:0] y); + assign y = P; + endmodule + module Wide #(parameter logic [63:0] P = 0)(output logic [63:0] y); + assign y = P; + endmodule + module Top(output logic [31:0] builtin, named, output logic [63:0] extended); + typedef logic [7:0] byte_t; + Child #(.P(int'{default: 1})) c(builtin); + Child #(.P(byte_t'{default: 1})) d(named); + Wide #(.P(int'{default: 1})) w(extended); + endmodule + "#) + (top Top) + (assert_eq builtin 0xffffffff) + (assert_eq named 0xff) + (assert_eq extended 0xffffffffffffffff)) + +(case parameter_patterns_preserve_packed_member_states + (four_state) + (source "packed_pattern_states.sv" #" + package ChildTypes; + typedef struct packed {bit [3:0] a; logic [3:0] b;} child_t; + endpackage + module Child #(parameter ChildTypes::child_t P = '{default: 0}) + (output logic [7:0] y); + assign y = {P.a, P.b}; + endmodule + module Scalar #(parameter integer P=0)(output logic [31:0] y); assign y=P; endmodule + module Top(output logic [7:0] y, output logic [31:0] xvalue, zvalue, two_state); + typedef struct packed {bit [3:0] x; logic [3:0] y;} caller_t; + Child #(.P(caller_t'{x: 'x, y: 'z})) c(y); + Scalar #(.P(integer'{default: 'x})) x(xvalue); + Scalar #(.P(integer'{default: 'z})) z(zvalue); + Scalar #(.P(int'{default: 'x})) b(two_state); + endmodule + "#) + (top Top) + (assert_eq y (fourstate 0 0x0f)) + (assert_eq xvalue (fourstate 0xffffffff 0xffffffff)) + (assert_eq zvalue (fourstate 0 0xffffffff)) + (assert_eq two_state 0)) diff --git a/crates/celox-test-suite/src/sv/cases/synthesizable.vtest b/crates/celox-test-suite/src/sv/cases/synthesizable.vtest index 550d3755ee3..60b8c620f2b 100644 --- a/crates/celox-test-suite/src/sv/cases/synthesizable.vtest +++ b/crates/celox-test-suite/src/sv/cases/synthesizable.vtest @@ -624,3 +624,114 @@ (assert_eq ones (popcount value)) (assert_eq chain (trunc 8 (+ (* (+ value 1) 2) 3))) (assert_eq swapped (| (trunc 8 (<< value 4)) (>> value 4))))) + +; IEEE 1800-2023 6.21: a nested local is a distinct binding from a top port. +(case nested_block_locals_shadow_ports + (source "nested_scope.sv" #" + module Top(input logic c, a, b, output logic t, y); + always_comb begin + t = 1'b0; + if (c) begin + logic t; + t = a; + y = t; + end else begin + y = b; + end + end + endmodule + "#) + (top Top) + (for (c a b) (list (0 0 1) (1 1 0) (1 0 1) (0 1 0)) + (modify (set c c) (set a a) (set b b)) + (assert_eq t 0) + (if c (assert_eq y a) (assert_eq y b)))) + +; Same source names in separate processes must keep separate identities. +(case block_local_names_shadow_other_signals + (source "process_scopes.sv" #" + module Top(input logic a, b, output logic t, y, z); + assign t = b; + always_comb begin logic t; t = a; y = t; end + always_comb begin logic t; t = ~a; z = t; end + endmodule + "#) + (top Top) + (for (a b) (list (0 1) (1 0) (1 1) (0 0)) + (modify (set a a) (set b b)) + (assert_eq t b) + (assert_eq y a) + (assert_eq z (^ a 1)))) + +(case named_calls_in_constant_contexts + (source "named_constants.sv" #" + module Top(output logic [31:0] y, output logic ok, output logic [7:0] query); + function automatic int f(input int a, b = 2); return a*10 + b; endfunction + assign query = {4'($dimensions(f(.a(3)))), 4'($unpacked_dimensions(f(.a(3))))}; + localparam N = f(.b(2), .a(3)); + logic [f(.b(2), .a(3))-1:0] word_value; + assign word_value = 32'h80000001; + assign y = word_value; + if (f(.b(3), .a(2)) == 23) begin : selected + assign ok = (N == 32); + end else begin : rejected + assign ok = 0; + end + endmodule + "#) + (top Top) + (eval) + (assert_eq y 0x80000001) + (assert_eq ok 1) + (assert_eq query 0x10)) + +(case named_calls_respect_generate_signatures + (source "named_scoped_calls.sv" #" + module Top(input logic [7:0] x, output logic [7:0] outer_y, inner_y); + function automatic int f(input int a); return a + 1; endfunction + assign outer_y = f(.a(x)); + if (1) begin : scoped + function automatic int f(input int b); return b + 10; endfunction + assign inner_y = f(.b(x)); + end + endmodule + "#) + (top Top) + (modify (set x 3)) + (assert_eq outer_y 4) + (assert_eq inner_y 13) + (modify (set x 8)) + (assert_eq outer_y 9) + (assert_eq inner_y 18)) + +(case named_calls_preserve_defaults_and_declaration_scope + (source "named_defaults.sv" #" + module Top(input logic clk, input logic [7:0] a, v, + output logic [7:0] y, z, positional, q, constant_value); + function automatic int f(input int a = 7, b = a); return a*10 + b; endfunction + localparam N = f(.b(3)); + assign constant_value = N; + assign y = f(.b(v)); + assign positional = f(,v); + always_comb begin + int a; + a = 99; + z = f(.a(2)); + end + always_ff @(posedge clk) q <= f(.b(v)); + endmodule + "#) + (top Top) + (modify (set a 5) (set v 3)) + (assert_eq y 73) + (assert_eq z 25) + (assert_eq positional 73) + (assert_eq constant_value 73) + (tick clk) + (assert_eq q 73) + (modify (set a 9) (set v 4)) + (assert_eq y 74) + (assert_eq z 29) + (assert_eq positional 74) + (tick clk) + (assert_eq q 74)) diff --git a/crates/celox-test-suite/verification/sv/icarus/generate.json b/crates/celox-test-suite/verification/sv/icarus/generate.json index bcfa41cc7da..8e62f79fb18 100644 --- a/crates/celox-test-suite/verification/sv/icarus/generate.json +++ b/crates/celox-test-suite/verification/sv/icarus/generate.json @@ -170,19 +170,19 @@ }, { "category": "ControlFlow", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "generate::ignores_type_aliases_in_inactive_generate_branches", "phase": "skip", diff --git a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json index 32af58207d2..15a70b06b1a 100644 --- a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json +++ b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json @@ -11,6 +11,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [] + }, + "name": "hierarchy::parameter_patterns_bind_caller_types", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [] + }, + "name": "hierarchy::parameter_patterns_bind_nested_caller_types", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [] + }, + "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_unpacked_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [] + }, + "name": "hierarchy::parameter_patterns_keep_unknown_fill", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Hierarchy", "detail": "", @@ -109,6 +201,121 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_unpacked_array_parameters", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_unpacked_array_parameters", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "hierarchy::parameter_patterns_override_body_declarations", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_transfer_packed_values", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_syntax", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_syntax", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Hierarchy", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_preserve_packed_member_states", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_syntax", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json index 41cc7f436e3..63a1792b431 100644 --- a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json +++ b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json @@ -2,19 +2,19 @@ "cases": [ { "category": "Arrays", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "indexed_select::constant_part_select_indices_of_concatenations", "phase": "skip", @@ -47,19 +47,19 @@ }, { "category": "Arrays", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "indexed_select::indexed_constants_lower_selected_concatenations", "phase": "skip", @@ -81,19 +81,19 @@ }, { "category": "Arrays", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "indexed_select::indexed_constants_work_in_ordinary_selection_indices", "phase": "skip", @@ -192,19 +192,19 @@ }, { "category": "Arrays", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "indexed_select::indexed_runtime_replications_preserve_attached_selections", "phase": "skip", @@ -215,19 +215,19 @@ }, { "category": "Arrays", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "indexed_select::indexed_select_multidimensional_packed_reads", "phase": "skip", diff --git a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json index d0864adfd20..c75b20bbe78 100644 --- a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json +++ b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json @@ -24,19 +24,19 @@ }, { "category": "Regression", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", "phase": "skip", @@ -169,19 +169,19 @@ }, { "category": "Regression", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "review_regressions::preserves_four_state_shift_and_bit_select_constants", "phase": "skip", diff --git a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json index cfc1f6b9d2c..1a4adf0dcf3 100644 --- a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json +++ b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json @@ -317,19 +317,19 @@ }, { "category": "Combinational", - "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_syntax", "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_syntax", - "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "phase": "compile", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", - "upstream": [] + ] }, "name": "synthesizable::struct_assignment_patterns_follow_the_target_layout", "phase": "skip", @@ -370,6 +370,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Combinational", + "detail": "Icarus 13.0 requires function port defaults to be constant expressions and rejects a reference to a net or variable. IEEE 1800-2023 13.5.3 evaluates a used default in the enclosing declaration scope on each call; the shared case retains its dynamic module-signal default.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_dynamic_argument_defaults", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 requires function port defaults to be constant expressions and rejects a reference to a net or variable. IEEE 1800-2023 13.5.3 evaluates a used default in the enclosing declaration scope on each call; the shared case retains its dynamic module-signal default.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Combinational", + "detail": "Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases.", + "expectation": "Simulation", + "name": "synthesizable::named_calls_in_constant_contexts", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_function_return_dimensions", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index 27a40d321b5..774779cc9e3 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -250,19 +250,19 @@ }, { "category": "Functions", - "detail": "Icarus 13.0 returns 0 for $dimensions of a call to a package function returning a multidimensional packed value. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes the case.", + "detail": "Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases.", "expectation": "Simulation", "known_issue": { + "id": "sv_icarus_function_return_dimensions", "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases.", + "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" - ], - "id": "sv_icarus_function_return_dimensions", - "observed_version": "Icarus 13.0", - "phase": "execute", - "reason": "Icarus 13.0 returns 0 for $dimensions of a call to a package function returning a multidimensional packed value. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes the case.", - "upstream": [] + ] }, "name": "system_functions::dimensions_resolves_imported_function_returns", "phase": "skip", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index b482688a0b5..478bf0750c8 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -92,7 +92,7 @@ "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", - "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed assignment patterns, and parameter type declarations in generate blocks. Verilator passes these cases.", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -108,7 +108,10 @@ "indexed_select::indexed_select_multidimensional_packed_reads", "synthesizable::struct_assignment_patterns_follow_the_target_layout", "review_regressions::preserves_four_state_shift_and_bit_select_constants", - "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays" + "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", + "hierarchy::parameter_patterns_transfer_packed_values", + "hierarchy::parameter_patterns_override_scalar_defaults", + "hierarchy::parameter_patterns_preserve_packed_member_states" ] } }, @@ -146,9 +149,15 @@ ], "cases": { "icarus": [ + "hierarchy::parameter_patterns_bind_caller_types", + "hierarchy::parameter_patterns_bind_nested_caller_types", + "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", + "hierarchy::parameter_patterns_keep_unknown_fill", "procedural::aggregate_parameters_are_constant_tables", "system_functions::dimensions_resolves_package_array_constants", "system_functions::isunbounded_reports_bounded_array_parameters", + "hierarchy::parameter_patterns_evaluate_caller_constant_functions", + "hierarchy::parameter_patterns_override_body_declarations", "system_functions::unpacked_dimensions_publishes_array_parameters_before_declarations", "system_functions::unpacked_dimensions_resolves_package_array_constants", "system_functions::unpacked_dimensions_resolves_types_and_constant_scopes", @@ -719,7 +728,7 @@ "category": "simulator_disagreement", "phase": "execute", "observed_version": "Icarus 13.0", - "reason": "Icarus 13.0 returns 0 for $dimensions of a call to a package function returning a multidimensional packed value. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes the case.", + "reason": "Icarus 13.0 returns 0 for $dimensions of package functions returning multidimensional packed values and named/defaulted integral function calls. IEEE 1800-2023 20.7 requires the declared return rank. Verilator passes these cases.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -727,7 +736,8 @@ ], "cases": { "icarus": [ - "system_functions::dimensions_resolves_imported_function_returns" + "system_functions::dimensions_resolves_imported_function_returns", + "synthesizable::named_calls_in_constant_contexts" ] } }, @@ -1085,28 +1095,45 @@ } }, { - "id": "sv_icarus_unpacked_dimensions_element", + "id": "sv_verilator_printtimescale_special_scopes", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 rejects standalone $unit and $root operands of $printtimescale, expecting :: and a dotted hierarchy respectively. IEEE 1800-2023 20.4.2 explicitly accepts both special scope operands.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "system_functions::printtimescale_displays_unit_and_global_precision" + ] + } + }, + { + "id": "sv_verilator_printtimescale_scope", "category": "simulator_disagreement", "phase": "execute", - "observed_version": "Icarus 13.0", - "reason": "Icarus 13.0 returns 1 for $unpacked_dimensions(a[0]) when a is declared logic [7:0] a [0:1]. The selected element has no unpacked dimensions, so IEEE 1800-2023 20.7 requires 0. This four-state case is outside the Verilator adapter.", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 prints the Top caller scale for a package operand of $printtimescale, reports 1ps instead of the declared 10ps precision inside the package procedure, and omits the required parentheses around the design element name. IEEE 1800-2023 20.4.2 selects the queried/current design element and specifies the display format; 3.14.2.3 preserves its declared precision.", "upstream": [], "evidence": [ - "verification/sv/limitations/icarus.json", + "verification/sv/limitations/verilator.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { - "icarus": [ - "system_functions::unpacked_dimensions_is_independent_of_unknown_values" + "verilator": [ + "system_functions::printtimescale_preserves_package_subroutine_scope" ] } }, { - "id": "sv_icarus_unpacked_dimensions_partial_array", + "id": "sv_icarus_printtimescale_operands", "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Icarus 13.0", - "reason": "Icarus 13.0 rejects $unpacked_dimensions of a partially selected multidimensional array (\"needs 2 indices, but got only 1\") and of an unpacked array slice (\"Array cannot be indexed by a range\"). IEEE 1800-2023 20.7 permits querying the remaining array type. Verilator passes the case.", + "reason": "Icarus 13.0 rejects standalone $unit and bare package operands of $printtimescale with syntax errors. IEEE 1800-2023 20.4.2 accepts a design element argument and explicitly includes $unit and $root. The shared assertions retain their standard output and precision.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1114,17 +1141,34 @@ ], "cases": { "icarus": [ - "system_functions::unpacked_dimensions_preserves_selection_and_return_types", - "system_functions::unpacked_dimensions_checks_unevaluated_indices" + "system_functions::printtimescale_displays_unit_and_global_precision", + "system_functions::printtimescale_preserves_package_subroutine_scope" ] } }, { - "id": "sv_icarus_wildcard_typedef_shadowing", + "id": "sv_verilator_default_argument_scope", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 binds the default b=a to the earlier formal a and returns 22 for f(.a(2)) when the enclosing module a is 5. IEEE 1800-2023 13.5.3 evaluates defaults in the scope containing the subroutine declaration, requiring 25. Celox passes all five backend variants.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "synthesizable::named_calls_preserve_defaults_and_declaration_scope" + ] + } + }, + { + "id": "sv_icarus_dynamic_argument_defaults", "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Icarus 13.0", - "reason": "Icarus 13.0 reports a syntax error when a local variable declared after a wildcard import has the same name as an unpacked typedef in the package. IEEE 1800-2023 26.3 gives local declarations precedence over potentially visible wildcard imports. Verilator passes the case.", + "reason": "Icarus 13.0 requires function port defaults to be constant expressions and rejects a reference to a net or variable. IEEE 1800-2023 13.5.3 evaluates a used default in the enclosing declaration scope on each call; the shared case retains its dynamic module-signal default.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1132,50 +1176,51 @@ ], "cases": { "icarus": [ - "system_functions::unpacked_dimensions_prefers_values_over_imported_types" + "synthesizable::named_calls_preserve_defaults_and_declaration_scope" ] } }, { - "id": "sv_verilator_printtimescale_special_scopes", - "category": "simulator_compile_limitation", - "phase": "compile", - "observed_version": "Verilator 5.052", - "reason": "Verilator 5.052 rejects standalone $unit and $root operands of $printtimescale, expecting :: and a dotted hierarchy respectively. IEEE 1800-2023 20.4.2 explicitly accepts both special scope operands.", + "id": "sv_icarus_unpacked_dimensions_element", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 returns 1 for $unpacked_dimensions(a[0]) when a is declared logic [7:0] a [0:1]. The selected element has no unpacked dimensions, so IEEE 1800-2023 20.7 requires 0. This four-state case is outside the Verilator adapter.", "upstream": [], "evidence": [ - "verification/sv/limitations/verilator.json", + "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { - "verilator": [ - "system_functions::printtimescale_displays_unit_and_global_precision" + "icarus": [ + "system_functions::unpacked_dimensions_is_independent_of_unknown_values" ] } }, { - "id": "sv_verilator_printtimescale_scope", - "category": "simulator_disagreement", - "phase": "execute", - "observed_version": "Verilator 5.052", - "reason": "Verilator 5.052 prints the Top caller scale for a package operand of $printtimescale, reports 1ps instead of the declared 10ps precision inside the package procedure, and omits the required parentheses around the design element name. IEEE 1800-2023 20.4.2 selects the queried/current design element and specifies the display format; 3.14.2.3 preserves its declared precision.", + "id": "sv_icarus_unpacked_dimensions_partial_array", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects $unpacked_dimensions of a partially selected multidimensional array (\"needs 2 indices, but got only 1\") and of an unpacked array slice (\"Array cannot be indexed by a range\"). IEEE 1800-2023 20.7 permits querying the remaining array type. Verilator passes the case.", "upstream": [], "evidence": [ - "verification/sv/limitations/verilator.json", + "verification/sv/limitations/icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { - "verilator": [ - "system_functions::printtimescale_preserves_package_subroutine_scope" + "icarus": [ + "system_functions::unpacked_dimensions_preserves_selection_and_return_types", + "system_functions::unpacked_dimensions_checks_unevaluated_indices" ] } }, { - "id": "sv_icarus_printtimescale_operands", + "id": "sv_icarus_wildcard_typedef_shadowing", "category": "simulator_compile_limitation", "phase": "compile", "observed_version": "Icarus 13.0", - "reason": "Icarus 13.0 rejects standalone $unit and bare package operands of $printtimescale with syntax errors. IEEE 1800-2023 20.4.2 accepts a design element argument and explicitly includes $unit and $root. The shared assertions retain their standard output and precision.", + "reason": "Icarus 13.0 reports a syntax error when a local variable declared after a wildcard import has the same name as an unpacked typedef in the package. IEEE 1800-2023 26.3 gives local declarations precedence over potentially visible wildcard imports. Verilator passes the case.", "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", @@ -1183,8 +1228,24 @@ ], "cases": { "icarus": [ - "system_functions::printtimescale_displays_unit_and_global_precision", - "system_functions::printtimescale_preserves_package_subroutine_scope" + "system_functions::unpacked_dimensions_prefers_values_over_imported_types" + ] + } + }, + { + "id": "sv_verilator_typed_pattern_sign_extension", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 zero-extends int'{default: 1} to a 64-bit parameter (0x00000000ffffffff). IEEE 1800-2023 10.9 gives the expression the self-determined int type, signed under 6.11.3; 6.20.2 requires assignment conversion to the parameter, giving 0xffffffffffffffff. The same Verilator probe sign-extends through an int variable or explicit int cast.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "hierarchy::parameter_patterns_override_scalar_defaults" ] } } diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 312d11a92e8..33a06fd54ef 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -7,9 +7,9 @@ "passed": 0, "rejected": 0, "unexpected_accept": 1, - "mismatch": 13, + "mismatch": 14, "emission_error": 0, - "compile_error": 94, + "compile_error": 104, "runtime_error": 3, "unsupported": 0, "ignored": 0 @@ -890,6 +890,105 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_bind_caller_types", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:2: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_bind_nested_caller_types", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_keep_unknown_fill", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", + "expectation": "Simulation", + "name": "system_functions::printtimescale_displays_unit_and_global_precision", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", + "expectation": "Simulation", + "name": "system_functions::printtimescale_preserves_package_subroutine_scope", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:2: sorry: unpacked array parameters are not supported yet.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_evaluate_caller_constant_functions", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_override_body_declarations", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Combinational", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: error: A reference to a net or variable (`a') is not allowed in a constant expression.\n/source_0.sv:4: error: Unable to evaluate a as a port default expression.\n2 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Functions", "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:8: error: Array a[f(index)] needs 2 indices, but got only 1.\n1 error(s) during elaboration.\n", @@ -1004,9 +1103,9 @@ }, { "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Malformed statement\n", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_displays_unit_and_global_precision", + "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -1014,10 +1113,10 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Malformed statement\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", "expectation": "Simulation", - "name": "system_functions::printtimescale_preserves_package_subroutine_scope", + "name": "hierarchy::parameter_patterns_transfer_packed_values", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, @@ -1025,15 +1124,37 @@ "tags": [] }, { - "category": "Functions", - "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: syntax error\nI give up.\n", + "category": "Hierarchy", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in parameter value assignment list.\n/source_0.sv:10: error: Invalid module instantiation\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Syntax error in parameter value assignment list.\n/source_0.sv:11: error: Invalid module instantiation\n/source_0.sv:12: syntax error\n/source_0.sv:12: error: Syntax error in parameter value assignment list.\n/source_0.sv:12: error: Invalid module instantiation\n", "expectation": "Simulation", - "name": "system_functions::unpacked_dimensions_publishes_dependent_array_parameters", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", "phase": "compile", "status": "compile_error", "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_preserve_packed_member_states", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Combinational", + "detail": "synthesizable::named_calls_in_constant_contexts at 686:3: assert_eq query: expected 0x10, got 0x0", + "expectation": "Simulation", + "name": "synthesizable::named_calls_in_constant_contexts", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index 8cdb8b45cd6..2ac7c5a03aa 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -7,7 +7,7 @@ "passed": 0, "rejected": 0, "unexpected_accept": 0, - "mismatch": 14, + "mismatch": 16, "emission_error": 0, "compile_error": 16, "runtime_error": 1, @@ -325,6 +325,28 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Combinational", + "detail": "synthesizable::named_calls_preserve_defaults_and_declaration_scope at 727:3: assert_eq z: expected 0x19, got 0x16", + "expectation": "Simulation", + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Hierarchy", + "detail": "hierarchy::parameter_patterns_override_scalar_defaults at 407:3: assert_eq extended: expected 0xffffffffffffffff, got 0xffffffff", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/hierarchy.json b/crates/celox-test-suite/verification/sv/verilator/hierarchy.json index 43098e1afec..dc34ea1ce4d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/hierarchy.json +++ b/crates/celox-test-suite/verification/sv/verilator/hierarchy.json @@ -109,6 +109,29 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Hierarchy", + "detail": "Verilator 5.052 zero-extends int'{default: 1} to a 64-bit parameter (0x00000000ffffffff). IEEE 1800-2023 10.9 gives the expression the self-determined int type, signed under 6.11.3; 6.20.2 requires assignment conversion to the parameter, giving 0xffffffffffffffff. The same Verilator probe sign-extends through an int variable or explicit int cast.", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_override_scalar_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_verilator_typed_pattern_sign_extension", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 zero-extends int'{default: 1} to a 64-bit parameter (0x00000000ffffffff). IEEE 1800-2023 10.9 gives the expression the self-determined int type, signed under 6.11.3; 6.20.2 requires assignment conversion to the parameter, giving 0xffffffffffffffff. The same Verilator probe sign-extends through an int variable or explicit int cast.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/synthesizable.json b/crates/celox-test-suite/verification/sv/verilator/synthesizable.json index 3b04b1f6fb1..94dc69e19ea 100644 --- a/crates/celox-test-suite/verification/sv/verilator/synthesizable.json +++ b/crates/celox-test-suite/verification/sv/verilator/synthesizable.json @@ -286,6 +286,29 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Combinational", + "detail": "Verilator 5.052 binds the default b=a to the earlier formal a and returns 22 for f(.a(2)) when the enclosing module a is 5. IEEE 1800-2023 13.5.3 evaluates defaults in the scope containing the subroutine declaration, requiring 25. Celox passes all five backend variants.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_verilator_default_argument_scope", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 binds the default b=a to the earlier formal a and returns 22 for f(.a(2)) when the enclosing module a is 5. IEEE 1800-2023 13.5.3 evaluates defaults in the scope containing the subroutine declaration, requiring 25. Celox passes all five backend variants.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "synthesizable::named_calls_preserve_defaults_and_declaration_scope", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/src/simulator/mixed.rs b/crates/celox/src/simulator/mixed.rs index 00185143f1b..8158591d976 100644 --- a/crates/celox/src/simulator/mixed.rs +++ b/crates/celox/src/simulator/mixed.rs @@ -257,7 +257,7 @@ fn depends_on_header(expr: &sv::ConstExpr, signature: &InterfaceSignature) -> bo dependent |= expression(count, signature, visited); } } - Call { name, args } => { + Call { name, args, .. } => { dependent |= function(name, signature, visited); dependent |= args .iter() @@ -338,9 +338,12 @@ fn depends_on_header(expr: &sv::ConstExpr, signature: &InterfaceSignature) -> bo || expression(then_expr, signature, visited) || expression(else_expr, signature, visited) } - Call { name, args } => { + Call { name, args, .. } => { function(name, signature, visited) - || args.iter().any(|arg| expression(arg, signature, visited)) + || args + .iter() + .flatten() + .any(|arg| expression(arg, signature, visited)) } Inside { expr, items } => { expression(expr, signature, visited) diff --git a/crates/celox/tests/comb_observer.rs b/crates/celox/tests/comb_observer.rs index e6e7f945275..bf082c96e08 100644 --- a/crates/celox/tests/comb_observer.rs +++ b/crates/celox/tests/comb_observer.rs @@ -2650,14 +2650,10 @@ module Top ( } fn test_named_function_inputs_evaluate_in_source_order(sim) { - // SV frontend rejects named function arguments: "named arguments of `add`" (#88). - @ignore_on(sv); @case "comb_observer::test_named_function_inputs_evaluate_in_source_order"; } fn test_named_function_outputs_apply_in_source_order(sim) { - // SV frontend rejects named function arguments: "named arguments of `write_outputs`" (#88). - @ignore_on(sv); @case "comb_observer::test_named_function_outputs_apply_in_source_order"; } diff --git a/crates/celox/tests/duplicate_varpath.rs b/crates/celox/tests/duplicate_varpath.rs index 561f740acf8..e94fd69e400 100644 --- a/crates/celox/tests/duplicate_varpath.rs +++ b/crates/celox/tests/duplicate_varpath.rs @@ -20,9 +20,6 @@ all_backends! { // The Veryl analyzer assigns different VarIds but identical VarPaths to these scoped // variables. Without the fix this panics during JIT compilation. fn test_duplicate_scoped_var_in_always_comb(sim) { - // SV frontend rejects same-named block-local variables in two processes: - // "duplicate internal signal `tmp`" (#445). - @ignore_on(sv); @case "duplicate_varpath::test_duplicate_scoped_var_in_always_comb"; } @@ -31,9 +28,6 @@ fn test_duplicate_scoped_var_in_always_comb(sim) { // internal vars, and always_comb inside uses `var flag: logic;` in multiple // for-loop scopes. fn test_duplicate_scoped_var_with_generate_for(sim) { - // SV frontend rejects same-named block-local variables in two processes: - // "duplicate internal signal `flag`" (#445). - @ignore_on(sv); @case "duplicate_varpath::test_duplicate_scoped_var_with_generate_for"; } diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 7fe1f92815e..2c47e522b01 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,24 @@ use super::*; sv_backends! { + fn parameter_patterns_preserve_packed_member_states(sim) { @case "hierarchy::parameter_patterns_preserve_packed_member_states"; } + fn parameter_patterns_transfer_packed_values(sim) { @case "hierarchy::parameter_patterns_transfer_packed_values"; } + fn parameter_patterns_override_scalar_defaults(sim) { @case "hierarchy::parameter_patterns_override_scalar_defaults"; } + fn parameter_patterns_evaluate_caller_constant_functions(sim) { @case "hierarchy::parameter_patterns_evaluate_caller_constant_functions"; } + fn parameter_patterns_override_body_declarations(sim) { @case "hierarchy::parameter_patterns_override_body_declarations"; } + fn parameter_patterns_keep_fill_and_arithmetic_context(sim) { + @case "hierarchy::parameter_patterns_keep_fill_and_arithmetic_context"; + } + fn parameter_patterns_bind_caller_types(sim) { + @case "hierarchy::parameter_patterns_bind_caller_types"; + } + fn parameter_patterns_bind_nested_caller_types(sim) { + @case "hierarchy::parameter_patterns_bind_nested_caller_types"; + } + fn parameter_patterns_keep_unknown_fill(sim) { + @case "hierarchy::parameter_patterns_keep_unknown_fill"; + } + fn drives_omitted_and_open_child_inputs_with_z(sim) { @case "hierarchy::drives_omitted_and_open_child_inputs_with_z"; } diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 818b6f829ee..1aa8d1bb4b0 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -236,6 +236,28 @@ sv_backends! { assert_eq!(sim.get(sim.signal("y")), 0x1234_5698u32.into()); } + fn preserves_sv_named_default_constant_function_header_dependencies(sim) { + @setup { + let veryl = "module Top(a: input logic<32>, y: output logic<32>) { inst bus: $sv::Bus #(W: 16); assign bus.req = a; assign y = bus.rsp; }"; + let sv = r#" + interface Bus #(parameter W = 8, parameter N = twice(.factor())); + function automatic integer width_value(); return W; endfunction + function automatic integer twice(input integer factor = 2); return width_value() * factor; endfunction + localparam M = twice(.factor(2)); + logic [N-1:0] req; + logic [M-1:0] rsp; + assign rsp = req + N; + endinterface + "#; + } + @build Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], vec![(sv, Path::new("bus.sv"))], "Top", + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 0x1234_5678u32)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 0x1234_5698u32.into()); + } + fn avoids_foreign_specialization_name_collisions(sim) { @setup { let veryl = "module Child #(param K: u32 = 1)(a: input logic<8>, y: output logic<8>) { assign y = a + K; }"; diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index b54c4db5682..84fd51c22ff 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -93,29 +93,10 @@ fn rejects_self_reads_hidden_in_comb_function_calls() { ); } -#[test] -fn rejects_block_local_declarations_inside_always_comb() { - let error = cranelift_build_error( - r#" - module Top(input logic c, a, b, output logic t, y); - always_comb begin - t = 1'b0; - if (c) begin - logic t; - t = a; - y = t; - end else begin - y = b; - end - end - endmodule - "#, - ); - // The local `t` would be hoisted onto the output port `t`. - assert!( - error.contains("duplicate port or signal name `t`"), - "unexpected error: {error}" - ); +sv_backends! { + fn nested_block_local_declarations_shadow_ports(sim) { + @case "synthesizable::nested_block_locals_shadow_ports"; + } } #[test] @@ -5487,7 +5468,7 @@ fn rejects_constructs_that_are_not_yet_lowered() { "unpacked struct, union, or unsupported packed struct member", r#" module Top(output logic [7:0] y); - union packed { logic [7:0] a; logic [7:0] b; } value; + union packed { logic [7:0] a; logic [3:0] b; } value; assign y = value; endmodule "#, diff --git a/crates/celox/tests/frontends/systemverilog/synthesizable.rs b/crates/celox/tests/frontends/systemverilog/synthesizable.rs index 45eb289a44e..43a76939de0 100644 --- a/crates/celox/tests/frontends/systemverilog/synthesizable.rs +++ b/crates/celox/tests/frontends/systemverilog/synthesizable.rs @@ -3,6 +3,9 @@ use super::*; sv_backends! { + fn named_calls_preserve_defaults_and_declaration_scope(sim) { @case "synthesizable::named_calls_preserve_defaults_and_declaration_scope"; } + fn named_calls_in_constant_contexts(sim) { @case "synthesizable::named_calls_in_constant_contexts"; } + fn named_calls_respect_generate_signatures(sim) { @case "synthesizable::named_calls_respect_generate_signatures"; } fn enum_members_without_values_follow_their_predecessor(sim) { @case "synthesizable::enum_members_without_values_follow_their_predecessor"; } @@ -149,24 +152,9 @@ sv_backends! { } } -#[test] -fn block_local_names_may_not_shadow_other_signals() { - for source in [ - "module Top(input logic a, output logic t); \ - always_comb begin logic t; t = a; end endmodule", - "module Top(input logic a, output logic y, z); \ - always_comb begin logic t; t = a; y = t; end \ - always_comb begin logic t; t = ~a; z = t; end endmodule", - ] { - let error = Simulator::from_sv_sources(vec![(source, Path::new("shadow.sv"))], "Top") - .build_cranelift() - .expect_err("a shadowing block-local name must be rejected") - .to_string(); - assert!( - error.contains("duplicate internal signal") - || error.contains("duplicate port or signal name"), - "{error}" - ); +sv_backends! { + fn block_local_names_shadow_other_signals(sim) { + @case "synthesizable::block_local_names_shadow_other_signals"; } } diff --git a/crates/celox/tests/state_cast_semantics.rs b/crates/celox/tests/state_cast_semantics.rs index 1be0481987f..82bbe040c1f 100644 --- a/crates/celox/tests/state_cast_semantics.rs +++ b/crates/celox/tests/state_cast_semantics.rs @@ -12,9 +12,6 @@ all_backends! { fn constant_type_cast_clears_unknown_bits(sim) { @omit_veryl; - // SV frontend rejects a cast of an X/Z-valued constant in a localparam initializer: - // "constant cast expression" (#88). - @ignore_on(sv); @case "state_cast_semantics::constant_type_cast_clears_unknown_bits"; } diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index 59e21e9b10f..ee6af3f67ef 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -66,6 +66,10 @@ extern "C" fn dpi_add(x: i32, y: i32) -> i32 { x.wrapping_add(y) } +extern "C" fn dpi_digits(first: i32, second: i32) -> i32 { + first * 10 + second +} + extern "C" fn dpi_negate_byte(x: i8) -> i8 { x.wrapping_neg() } @@ -142,6 +146,38 @@ recorder!(record_wasm, "wasm"); recorder!(record_cranelift_parallel, "cranelift_parallel"); dpi_backends! { + fn named_imports_bind_formals_and_evaluate_actuals_in_source_order(sim) { + @build unsafe { + builder(r#" + module Top(input logic clk, input int a, b, + output int named_result, mixed_result, effects_result, tmp); + import "DPI-C" function int digits(input int first, input int second); + function automatic int write_tmp(input int v, output int dst); + dst = v; + return v; + endfunction + always_ff @(posedge clk) begin + named_result <= digits(.second(a), .first(b)); + mixed_result <= digits(a, .second(b)); + tmp = 0; + effects_result <= digits(.second(write_tmp(a, tmp)), .first(tmp)); + digits(.second(write_tmp(b, tmp)), .first(tmp)); + end + endmodule + "#).dpi_function("digits", dpi_digits as *const ()) + }; + let clk = sim.event("clk"); + let (a, b) = (sim.signal("a"), sim.signal("b")); + for (x, y) in [(3u32, 4u32), (7, 2)] { + sim.modify(|io| { io.set(a, x); io.set(b, y); }).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(sim.signal("named_result")), BigUint::from(10 * y + x)); + assert_eq!(sim.get(sim.signal("mixed_result")), BigUint::from(10 * x + y)); + assert_eq!(sim.get(sim.signal("effects_result")), BigUint::from(11 * x)); + assert_eq!(sim.get(sim.signal("tmp")), BigUint::from(y)); + } + } + fn int_function_in_nonblocking_assignment(sim) { @build unsafe { builder(r#" diff --git a/crates/celox/tests/veryl_context_regressions.rs b/crates/celox/tests/veryl_context_regressions.rs index c83e0b24ca5..79f9d5c51fc 100644 --- a/crates/celox/tests/veryl_context_regressions.rs +++ b/crates/celox/tests/veryl_context_regressions.rs @@ -52,9 +52,6 @@ all_backends! { @case "veryl_context_regressions::runtime_for_bound_arithmetic_uses_int_context"; } fn dynamic_param_array_read_uses_its_elements(sim) { - // SV frontend rejects the unpacked-array parameter override `#(.Q('{-3, -5}))`: - // "parameter override expression" (#88). - @ignore_on(sv); @case "veryl_context_regressions::dynamic_param_array_read_uses_its_elements"; } fn constant_case_target_uses_comparison_context(sim) { diff --git a/crates/celox/tests/veryl_upstream.rs b/crates/celox/tests/veryl_upstream.rs index 475c3ef9c00..92dcf7c4320 100644 --- a/crates/celox/tests/veryl_upstream.rs +++ b/crates/celox/tests/veryl_upstream.rs @@ -19,9 +19,6 @@ all_backends! { @case "veryl_language::parameter_expression_type_cast_widths"; } fn packed_union_members_alias(sim) { - // SV frontend does not support packed unions: - // "unpacked struct, union, or unsupported packed struct member" (#440). - @ignore_on(sv); @case "veryl_language::packed_union_members_alias"; } fn wide_shift_amount_out_of_range(sim) { diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 2051df30b7a..9b945b5449a 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -71,7 +71,7 @@ synthesis and is tested at the design level. | --- | --- | | Modules | ANSI ports, `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | | Generate | `for` (with `genvar`), `if`, `case`; constant expressions including `**` | -| Types | `logic`, `bit`, `reg`, packed vectors, packed arrays, packed structs, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | +| Types | `logic`, `bit`, `reg`, packed vectors, packed arrays, packed structs and hard packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | | Packages | types, parameters, enums and functions, through `import p::*;`, `import p::x;` and `p::x` | | Interfaces | interfaces with parameters, `localparam`s, `typedef`s, variables and nets, logic (`assign`, `always_comb`, `always_ff`, generate) and functions; interface instances and instance arrays, also inside generate blocks; interface ports with or without a modport, generic `interface` and `interface.mp` ports, and arrays of interface ports; modport `input` / `output` members and imported functions; access to members, parameters and functions through an instance or port (`h[i].m`, `h.P`, `h.f(...)`) | | Continuous logic | `assign`, `wire w = expr;` | @@ -83,7 +83,7 @@ synthesis and is tested at the design level. | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | -| Parameters | integral parameters, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables) | +| Parameters | integral parameters, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | State | two-state and four-state simulation | @@ -131,10 +131,8 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: ([#427](https://github.com/celox-sim/celox/issues/427)), wildcard `.*` connections ([#442](https://github.com/celox-sim/celox/issues/442)), gate primitives ([#457](https://github.com/celox-sim/celox/issues/457)), `bind`. - Declarations: variable declaration initializers of members of an interface - array, ANSI port default values, packed unions - ([#440](https://github.com/celox-sim/celox/issues/440)), multidimensional packed ranges that are not zero-based and - descending ([#438](https://github.com/celox-sim/celox/issues/438)), internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), block-local - variables that share a name with a variable of another process ([#445](https://github.com/celox-sim/celox/issues/445)), + array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, multidimensional packed ranges that are not zero-based and + descending ([#438](https://github.com/celox-sim/celox/issues/438)), internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs, strings and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists, and both edges of one clock ([#443](https://github.com/celox-sim/celox/issues/443)) or one @@ -153,8 +151,8 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: `$time` in an expression or `$fopen`, is reported with its name wherever it is written, including in an unused parameter and in a function body. A `$` name that is not a system task or - function, a call with the wrong number of arguments or an omitted argument - of a function, and a task used as a value are errors. + function, a call with the wrong number of arguments, an omitted argument + without a declared default, and a task used as a value are errors. - DPI-C beyond the subset described in [DPI-C imports](#dpi-c-imports), DPI exports, tri-state buses and multiple drivers, hierarchical references. @@ -265,8 +263,22 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / writes it. A top module with an interface port therefore has ports such as `bus$data`. A module with a generic `interface` port is copied once per interface it is connected to, as `M$I`. -- **Block-local variables** of an `always_comb` become signals of the module; a - name that clashes with another signal is rejected. +- **Block-local variables** have lexical scope in `always_comb` and `always_ff`. + Locals may shadow module signals and reuse names in separate blocks or processes. +- **Hard packed untagged unions** share one bit vector between all members; + every member must have the same width (IEEE 1800-2023 7.3.1). +- **Named subroutine arguments** bind by formal name. Input evaluation and output + copy-out retain source order. Expressions and call statements support omitted + arguments with ANSI-declared defaults. Defaults are evaluated only when used, + in the enclosing declaration scope (IEEE 1800-2023 13.5.3). Constant calls use + the same formal names in parameter initializers, ranges and generate conditions; + generate-local declarations retain their own signatures. Named calls with + procedural effects in selection indices are rejected. +- **Typed parameter patterns** are converted in the caller's type, preserving + width, signing and four-state values (IEEE 1800-2023 10.9, 6.20.2). Packed + values transfer by bits, so struct member names and field divisions may differ + in the child. Typed scalar patterns can override a parameter whose default is + an ordinary value. Unpacked patterns retain their positional array shape. - **Variable lifetimes** follow IEEE 1800-2023 6.21. A variable declared in a procedural block, function or task is static unless it, its subroutine or its module (`module automatic`) is declared `automatic`. A static local of a diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index d7a009b965b..44de8ed3f33 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -58,7 +58,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | --- | --- | | モジュール | ANSI ポート、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割) | | generate | `for`(`genvar`)、`if`、`case`。`**` を含む定数式 | -| 型 | `logic`、`bit`、`reg`、packed ベクタ・配列・構造体、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `logic`、`bit`、`reg`、packed ベクタ・配列・構造体、hard packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | @@ -69,7 +69,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | -| パラメータ | 整数のパラメータと、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル) | +| パラメータ | 整数のパラメータと、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 状態 | 2 値・4 値シミュレーション | @@ -98,9 +98,8 @@ package・interface の手続きは宣言元の時間単位と精度を保持し ラッチを推論する不完全な組み合わせ代入。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、packed union([#440](https://github.com/celox-sim/celox/issues/440))、0 起点の降順でない - 多次元 packed 範囲([#438](https://github.com/celox-sim/celox/issues/438))、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、別の - プロセスの変数と同名のブロックローカル変数([#445](https://github.com/celox-sim/celox/issues/445))、unpacked 構造体、文字列、`real`。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、0 起点の降順でない + 多次元 packed 範囲([#438](https://github.com/celox-sim/celox/issues/438))、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、文字列、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ オペランド([#464](https://github.com/celox-sim/celox/issues/464))、プロセスをまたいだ同一クロック([#443](https://github.com/celox-sim/celox/issues/443))・同一リセット ([#471](https://github.com/celox-sim/celox/issues/471))の両エッジの使用。 @@ -116,7 +115,7 @@ package・interface の手続きは宣言元の時間単位と精度を保持し 知っています。呼び出した位置で対応していないもの(式の中の `$time`、`$fopen` など)は、 使われていないパラメータや関数本体の中を含め、書かれた 場所にかかわらず名前を示して報告します。システムタスクでもシステム関数でもない `$` 名、 - 引数の数が誤っている呼び出しや関数の引数の省略、値として使ったタスクはエラーです。 + 引数の数が誤っている呼び出し、既定値のない引数の省略、値として使ったタスクはエラーです。 - DPI、トライステートバスと複数ドライバ、階層参照。 ## 知っておくべき挙動 @@ -150,8 +149,19 @@ package・interface の手続きは宣言元の時間単位と精度を保持し コンパイル単位の項目 `x` を指します。コンパイル単位の変数は、そのファイルのモジュールが共有する 1 つの オブジェクトで、package 変数と同じく `$unit::v` という名前になります。これを宣言できるソースファイルは 1 つだけです。コンパイル単位での DPI import は未対応です。 -- **ブロックローカル変数**(`always_comb` 内)は、モジュールの信号になります。ほかの信号と - 名前が衝突するものは拒否します。 +- **ブロックローカル変数**は、`always_comb` と `always_ff` で字句スコープを持ちます。 + モジュールの信号と同名の変数や、別のブロック・プロセスでの同名変数を扱えます。 +- **hard packed untagged union** のメンバーは、同じビットベクタを共有します。 + 全メンバーの幅が一致する必要があります(IEEE 1800-2023 7.3.1)。 +- **名前付きサブルーチン引数**は仮引数の名前で束縛し、入力の評価と出力のコピーアウトは + ソースに書かれた順序で行います。式と文のどちらでも、ANSI宣言で既定値を持つ引数を省略できます。 + 既定値は使うときだけ、サブルーチンを宣言した外側のスコープで評価します(IEEE 1800-2023 13.5.3)。 + パラメータ初期値・範囲・generate条件の定数呼び出しも仮引数名で束縛し、generate内の宣言は自身のシグネチャを使います。 + 選択の添字での副作用を伴う名前付き呼び出しは拒否します。 +- **型付きパラメータパターン**は呼び出し元の型で変換し、幅・符号・4-state の値を保持します + (IEEE 1800-2023 10.9、6.20.2)。packed 値はビット列として渡すため、子の構造体の + メンバー名やフィールド分割が異なっても扱えます。型付き scalar パターンは、既定値が + 通常の値であるパラメータも上書きできます。unpacked パターンは配列の位置と形状を保持します。 - **変数の寿命**は IEEE 1800-2023 6.21 に従います。プロセスのブロック、関数、タスクの中で宣言した 変数は、その変数自身、そのサブルーチン、またはそのモジュール(`module automatic`)が `automatic` と宣言されていない限り static です。ブロックの static なローカル変数は、ブロックの実行をまたいで値を