diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 728194843a8..c20e05c05e4 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -34,10 +34,46 @@ pub struct VerylSymbolicRtl<'a> { pub fn external_signatures( ir: &veryl_analyzer::ir::Ir, config: &BuildConfig, +) -> Result { + external_signatures_named(ir, config, |module| module.name.to_string()) +} + +/// Like [`external_signatures`], but registers each module under `name`, so +/// modules that share a source name stay distinct. +pub fn external_signatures_named( + ir: &veryl_analyzer::ir::Ir, + config: &BuildConfig, + name: impl Fn(&veryl_analyzer::ir::Module) -> String, ) -> Result { use crate::symbolic::artifact::{ExternalHierarchy, ExternalModule}; use veryl_analyzer::ir::Component; + // Veryl children link through the IR, but the SV modules beneath them + // still have to be prepared by the SV frontend. + fn sv_descendants( + module: &veryl_analyzer::ir::Module, + names: &mut Vec, + seen: &mut crate::HashSet, + ) { + for declaration in &module.declarations { + let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else { + continue; + }; + match instance.component.as_ref() { + Component::SystemVerilog(child) => { + if seen.insert(child.name) { + names.push( + veryl_parser::resource_table::get_str_value(child.name) + .unwrap_or_default(), + ); + } + } + Component::Module(child) => sv_descendants(child, names, seen), + Component::Interface(_) => {} + } + } + } + let mut external = ExternalHierarchy::default(); for component in &ir.components { let Component::Module(module) = component else { @@ -74,8 +110,15 @@ pub fn external_signatures( let mut port_ids = module.ports.values().copied().collect::>(); port_ids.sort(); let port_order = port_ids.iter().map(|id| ids[id]).collect(); - let (sim_module, _) = + let (mut sim_module, _) = project_module_with_ids(&empty, module, config, ids, &HashMap::default())?; + sim_module.name = name(module); + let mut unresolved_instances = Vec::new(); + sv_descendants( + module, + &mut unresolved_instances, + &mut crate::HashSet::default(), + ); let id = celox_design::ModuleId(external.modules.len()); external.roots.insert(sim_module.name.clone(), id); external.modules.insert( @@ -83,24 +126,7 @@ pub fn external_signatures( ExternalModule { sim_module, port_order, - // Veryl children link through the IR; only SV children are - // left for the SV frontend to resolve by name. - unresolved_instances: module - .declarations - .iter() - .filter_map(|declaration| { - let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else { - return None; - }; - let Component::SystemVerilog(module) = instance.component.as_ref() else { - return None; - }; - Some( - veryl_parser::resource_table::get_str_value(module.name) - .unwrap_or_default(), - ) - }) - .collect(), + unresolved_instances, }, ); } diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index 694584c8271..4eb67d792c7 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -49,14 +49,15 @@ pub fn parse_ir_with_external_hierarchy<'a>( /// Link the explicitly identified Veryl exports without matching SV namesakes. /// `native_modules` maps each external module name that stands for a Veryl -/// body to the name of that body in `ir`. +/// body to the index of that body in `ir.components`, so bodies that share a +/// source name stay distinct. pub fn parse_ir_with_external_hierarchy_and_native_modules<'a>( ir: &'a veryl_analyzer::ir::Ir, loop_provenance: &LoopProvenance, external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: &HashMap, + native_modules: &HashMap, ) -> Result, ParserError> { parse_external_hierarchy( ir, @@ -74,7 +75,7 @@ fn parse_external_hierarchy<'a>( external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: Option<&HashMap>, + native_modules: Option<&HashMap>, ) -> Result, ParserError> { // Token-to-scope resolution uses process-global analyzer state and is not // safe while independent compilations run on other test threads. Snapshot @@ -174,17 +175,25 @@ fn parse_external_hierarchy<'a>( binding.package = external_ids[&binding.package]; } module_names.insert(global_id, external_module.sim_module.name.clone()); - let native_name = match native_modules { - Some(names) => names.get(&external_module.sim_module.name).copied(), - None => Some(resource_table::insert_str(&external_module.sim_module.name)), + let native_module = match native_modules { + Some(names) => names + .get(&external_module.sim_module.name) + .and_then(|&index| match &ir.components[index] { + Component::Module(module) => Some(module), + _ => None, + }), + None => name_to_ir + .get(&resource_table::insert_str( + &external_module.sim_module.name, + )) + .copied(), }; - if let Some(native_name) = native_name - && let Some(&native_module) = name_to_ir.get(&native_name) + if let Some(native_module) = native_module && !module_ir.contains_key(&global_id) { module_names.insert( global_id, - resource_table::get_str_value(native_name).unwrap_or_default(), + resource_table::get_str_value(native_module.name).unwrap_or_default(), ); module_ir.insert(global_id, native_module); signature_to_id.insert(native_module.signature.clone(), global_id); diff --git a/crates/celox-frontend-veryl/src/lib.rs b/crates/celox-frontend-veryl/src/lib.rs index e6718c61f31..01bd86567e0 100644 --- a/crates/celox-frontend-veryl/src/lib.rs +++ b/crates/celox-frontend-veryl/src/lib.rs @@ -26,8 +26,8 @@ pub(crate) mod symbolic { } use crate::symbolic::artifact::ExternalModule; -pub use artifact::external_signatures; pub use artifact::{VerylSimModule as SimModule, VerylSymbolicRtl}; +pub use artifact::{external_signatures, external_signatures_named}; pub(crate) use celox_frontend_core::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, InstancePath, ScheduledRtl, ScheduledRtlOutput, SourceAddr, SourceVarId, VariableInfo, VariableKind, diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 493a8d0ead4..0cbcdc47d64 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -699,23 +699,17 @@ pub fn parse_mixed( if !native_top { external_roots.insert(top_name.clone()); } - let mut foreign = celox_frontend_veryl::external_signatures(ir, config)?; // SV instantiates a Veryl module by its emitted name. The linker binds - // that name back to the Veryl body; an SV module declaring the same name - // is a duplicate the SV analyzer reports. + // that name back to the Veryl body by its position, since modules of + // different projects can share a source name; an SV module declaring the + // same name is a duplicate the SV analyzer reports. + let foreign = + celox_frontend_veryl::external_signatures_named(ir, config, |module| names.module(module))?; let mut native_modules = crate::HashMap::default(); - let mut roots = std::mem::take(&mut foreign.roots); - for component in &ir.components { - let veryl_analyzer::ir::Component::Module(module) = component else { - continue; - }; - let Some(id) = roots.remove(&module.name.to_string()) else { - continue; - }; - let emitted = names.module(module); - foreign.modules.get_mut(&id).unwrap().sim_module.name = emitted.clone(); - foreign.roots.insert(emitted.clone(), id); - native_modules.insert(emitted, module.name); + for (index, component) in ir.components.iter().enumerate() { + if let veryl_analyzer::ir::Component::Module(module) = component { + native_modules.insert(names.module(module), index); + } } let sv_top_parameters = (!native_top).then_some((top_name.as_str(), top_parameters)); let base = ir.clone(); @@ -759,7 +753,7 @@ pub fn parse_mixed( )); } let mut prepare = || -> Result<_, ParserError> { - let native = native_modules.get(name).ok_or_else(|| { + let &index = native_modules.get(name).ok_or_else(|| { ParserError::illegal_context( "foreign module specialization", format!("`{name}` is not a Veryl module"), @@ -767,11 +761,7 @@ pub fn parse_mixed( ) })?; let module = crate::simulator::mixed::specialize_foreign_module( - &base, - context, - &native.to_string(), - parameters, - used_names, + &base, context, index, name, parameters, used_names, )?; let mut specialized = veryl_analyzer::ir::Ir { components: vec![veryl_analyzer::ir::Component::Module(module)], @@ -846,9 +836,9 @@ pub fn parse_mixed( .map(|source| (source, std::path::PathBuf::from(""))), ); }; - for component in &specializations { + for (index, component) in specializations.iter().enumerate() { if let veryl_analyzer::ir::Component::Module(module) = component { - native_modules.insert(module.name.to_string(), module.name); + native_modules.insert(module.name.to_string(), ir.components.len() + index); } } ir.components.extend(specializations); @@ -879,7 +869,7 @@ pub fn parse_with_external_hierarchy( ir: &veryl_analyzer::ir::Ir, loop_provenance: &loop_provenance::LoopProvenance, external: &celox_frontend_core::symbolic::artifact::ExternalHierarchy, - native_modules: Option<&crate::HashMap>, + native_modules: Option<&crate::HashMap>, config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index f924bbcab9a..35aa936d945 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -127,15 +127,6 @@ pub(super) fn elaborate_parameterized_top( .iter() .map(|(name, value)| (name.clone(), Value::new(*value, 64, false))) .collect::>(); - elaborate_parameterized_top_values(ir, context, top, &values) -} - -pub(super) fn elaborate_parameterized_top_values( - ir: &mut Ir, - context: &mut Context, - top: &str, - param_overrides: &[(String, Value)], -) -> Result<(), ParserError> { let top_name = resource_table::insert_str(top); let Some(top_index) = ir.components.iter().rposition( |component| matches!(component, veryl_analyzer::ir::Component::Module(module) if module.name == top_name), @@ -143,6 +134,18 @@ pub(super) fn elaborate_parameterized_top_values( // Preserve the existing TopNotFound diagnostic from the frontend. return Ok(()); }; + elaborate_parameterized_module(ir, context, top_index, top, &values) +} + +/// Re-elaborate the module at `top_index` of `ir.components` with parameter +/// overrides. `top` names it in diagnostics. +pub(super) fn elaborate_parameterized_module( + ir: &mut Ir, + context: &mut Context, + top_index: usize, + top: &str, + param_overrides: &[(String, Value)], +) -> Result<(), ParserError> { let top_token = match &ir.components[top_index] { veryl_analyzer::ir::Component::Module(module) => module.token, _ => unreachable!(), diff --git a/crates/celox/src/simulator/mixed.rs b/crates/celox/src/simulator/mixed.rs index d63f2c522b5..b0ef405191d 100644 --- a/crates/celox/src/simulator/mixed.rs +++ b/crates/celox/src/simulator/mixed.rs @@ -1597,9 +1597,12 @@ pub(crate) fn specialize_sv_instances( Ok(requests) } +/// Specialize the native module at `index` of `base.components`, which SV +/// instantiates as `name`. pub(crate) fn specialize_foreign_module( base: &veryl_analyzer::ir::Ir, context: &mut veryl_analyzer::Context, + index: usize, name: &str, parameters: &[(String, celox_frontend_sv::SvParameterValue)], used_names: &mut fxhash::FxHashSet, @@ -1618,16 +1621,11 @@ pub(crate) fn specialize_foreign_module( }) .collect::>(); if !ordinary.is_empty() { - super::builder::elaborate_parameterized_top_values(&mut ir, context, name, &ordinary)?; + super::builder::elaborate_parameterized_module(&mut ir, context, index, name, &ordinary)?; } - let module = ir - .components - .iter() - .find_map(|component| match component { - Component::Module(module) if module.name.to_string() == name => Some(module), - _ => None, - }) - .ok_or_else(|| unsupported(format!("missing native module `{name}`")))?; + let Some(Component::Module(module)) = ir.components.get(index) else { + return Err(unsupported(format!("missing native module `{name}`"))); + }; let mut signature = module.signature.clone(); let mut modports: fxhash::FxHashMap<_, Signature> = fxhash::FxHashMap::default(); let mut interface_values = fxhash::FxHashMap::default(); @@ -1799,7 +1797,7 @@ pub(crate) fn specialize_foreign_module( }; specialized.eval_assign(context); specialized.name = resource_table::insert_str(&fresh_name( - &format!("__celox_foreign_{name}"), + &format!("__celox_foreign_{}", specialized.name), used_names, &mut 0, )); diff --git a/crates/celox/tests/fixtures/mixed_dependency/Veryl.lock b/crates/celox/tests/fixtures/mixed_dependency/Veryl.lock new file mode 100644 index 00000000000..ad5c1046589 --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/Veryl.lock @@ -0,0 +1,10 @@ +# This file is automatically @generated by Veryl. +# It is not intended for manual editing. +version = 1 + +[[projects]] +name = "lib" +source = "lib" +dependencies = [] + +[projects.properties] diff --git a/crates/celox/tests/fixtures/mixed_dependency/Veryl.toml b/crates/celox/tests/fixtures/mixed_dependency/Veryl.toml new file mode 100644 index 00000000000..ca6b4b5655f --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/Veryl.toml @@ -0,0 +1,9 @@ +[project] +name = "app" +version = "0.1.0" + +[build] +sources = ["src"] + +[dependencies] +lib = { path = "lib" } diff --git a/crates/celox/tests/fixtures/mixed_dependency/lib/Veryl.toml b/crates/celox/tests/fixtures/mixed_dependency/lib/Veryl.toml new file mode 100644 index 00000000000..e9274c4b986 --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/lib/Veryl.toml @@ -0,0 +1,6 @@ +[project] +name = "lib" +version = "0.1.0" + +[build] +sources = ["src"] diff --git a/crates/celox/tests/fixtures/mixed_dependency/lib/src/child.veryl b/crates/celox/tests/fixtures/mixed_dependency/lib/src/child.veryl new file mode 100644 index 00000000000..df49b68004a --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/lib/src/child.veryl @@ -0,0 +1,8 @@ +module Child #( + param K: u32 = 0, +) ( + a: input logic<8>, + y: output logic<8>, +) { + assign y = a + 8'd2 + K; +} diff --git a/crates/celox/tests/fixtures/mixed_dependency/src/child.veryl b/crates/celox/tests/fixtures/mixed_dependency/src/child.veryl new file mode 100644 index 00000000000..adf4703c089 --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/src/child.veryl @@ -0,0 +1,8 @@ +module Child #( + param K: u32 = 0, +) ( + a: input logic<8>, + y: output logic<8>, +) { + assign y = a + 8'd1 + K; +} diff --git a/crates/celox/tests/fixtures/mixed_dependency/top.sv b/crates/celox/tests/fixtures/mixed_dependency/top.sv new file mode 100644 index 00000000000..9fe6cd111f0 --- /dev/null +++ b/crates/celox/tests/fixtures/mixed_dependency/top.sv @@ -0,0 +1,9 @@ +module Top( + input logic [7:0] a, + output logic [7:0] app_y, lib_y, app_wide, lib_wide +); + app_Child app_child(.a(a), .y(app_y)); + lib_Child lib_child(.a(a), .y(lib_y)); + app_Child #(.K(16)) app_specialized(.a(a), .y(app_wide)); + lib_Child #(.K(32)) lib_specialized(.a(a), .y(lib_wide)); +endmodule diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index fa62b1055ba..4c3a83a0c0c 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -904,6 +904,38 @@ sv_backends! { assert_eq!(sim.get(sim.signal("y")), 0x76u8.into()); } + fn reaches_systemverilog_descendants_through_native_veryl_children(sim) { + @setup { + let veryl = r#" + module Inner (a: input logic<8>, y: output logic<8>) { + inst leaf: $sv::SvLeaf (a, y); + } + module Mid #(param K: u32 = 1) (a: input logic<8>, y: output logic<8>) { + var b: logic<8>; + assign b = a + K; + inst inner: Inner (a: b, y); + } + "#; + let sv = r#" + module Top(input logic [7:0] a, output logic [7:0] y, output logic [7:0] wide); + prj_Mid plain(.a(a), .y(y)); + prj_Mid #(.K(16)) specialized(.a(a), .y(wide)); + endmodule + module SvLeaf(input logic [7:0] a, output logic [7:0] y); + assign y = a ^ 8'h55; + endmodule + "#; + } + @build Simulator::from_mixed_sources( + vec![(veryl, Path::new("mid.veryl"))], + vec![(sv, Path::new("top.sv"))], "Top", + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 0x20u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 0x74u8.into()); + assert_eq!(sim.get(sim.signal("wide")), 0x65u8.into()); + } + fn preserves_positional_veryl_to_systemverilog_port_order(sim) { @setup { let veryl = r#" @@ -1296,6 +1328,36 @@ fn rejects_sv_modules_named_like_an_emitted_veryl_module() { ); } +#[test] +fn names_same_named_modules_of_dependencies_by_their_projects() { + let project = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mixed_dependency"); + let mut metadata = veryl_metadata::Metadata::load(project.join("Veryl.toml")).unwrap(); + let sources = metadata + .paths::(&[], false, true) + .unwrap() + .into_iter() + .map(|path| (std::fs::read_to_string(&path.src).unwrap(), path.src)) + .collect::>(); + let sv = std::fs::read_to_string(project.join("top.sv")).unwrap(); + let mut sim = Simulator::from_mixed_sources( + sources + .iter() + .map(|(source, path)| (source.as_str(), path.as_path())) + .collect(), + vec![(sv.as_str(), &project.join("top.sv"))], + "Top", + ) + .with_metadata(metadata) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 0x20u8)).unwrap(); + assert_eq!(sim.get(sim.signal("app_y")), 0x21u8.into()); + assert_eq!(sim.get(sim.signal("lib_y")), 0x22u8.into()); + assert_eq!(sim.get(sim.signal("app_wide")), 0x31u8.into()); + assert_eq!(sim.get(sim.signal("lib_wide")), 0x42u8.into()); +} + // These assert the intended simulation results, so implementing the missing // bridge behavior only requires removing the ignore attributes. mod pending_interface_functions { diff --git a/flake.lock b/flake.lock index 716aba6c8b7..9b49a80e894 100644 --- a/flake.lock +++ b/flake.lock @@ -50,17 +50,17 @@ ] }, "locked": { - "lastModified": 1792219666, - "narHash": "sha256-RMO08tKD+hFIL5ryWi85VY4aHE5oIpdV1h4kVFctOkw=", + "lastModified": 1792307278, + "narHash": "sha256-wJgFFtw/vlzsjWrQFmTn40TTkSkqHM4XXN0nh4q4uMk=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "a110337465cfb76e3806b81b9db3094c3e6e770a", + "rev": "42076d1c6a0fb405ed04f9a674e4a8f69de62ba3", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "a110337465cfb76e3806b81b9db3094c3e6e770a", + "rev": "42076d1c6a0fb405ed04f9a674e4a8f69de62ba3", "type": "github" } } diff --git a/flake.nix b/flake.nix index 1e3aa08a30b..876dc07d67d 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/a110337465cfb76e3806b81b9db3094c3e6e770a"; + url = "github:oxalica/rust-overlay/42076d1c6a0fb405ed04f9a674e4a8f69de62ba3"; inputs.nixpkgs.follows = "nixpkgs"; }; };