Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 45 additions & 19 deletions crates/celox-frontend-veryl/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,46 @@ pub struct VerylSymbolicRtl<'a> {
pub fn external_signatures(
ir: &veryl_analyzer::ir::Ir,
config: &BuildConfig,
) -> Result<crate::symbolic::artifact::ExternalHierarchy, ParserError> {
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<crate::symbolic::artifact::ExternalHierarchy, ParserError> {
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<String>,
seen: &mut crate::HashSet<StrId>,
) {
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cache native descendant traversal

For a large mixed hierarchy where exported Veryl modules share descendants—or form a chain M0 -> M1 -> ... -> Mn—each iteration of external_signatures_named recursively walks the whole subtree again, while seen deduplicates only SV names. A chain therefore performs quadratic native-module visits, and repeated fan-out can be worse, before lowering begins; memoize the SV-descendant set by native module identity/signature instead of recursively recomputing it for every exported root.

Useful? React with 👍 / 👎.

Component::Interface(_) => {}
}
}
}

let mut external = ExternalHierarchy::default();
for component in &ir.components {
let Component::Module(module) = component else {
Expand Down Expand Up @@ -74,33 +110,23 @@ pub fn external_signatures(
let mut port_ids = module.ports.values().copied().collect::<Vec<_>>();
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(
id,
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,
},
);
}
Expand Down
27 changes: 18 additions & 9 deletions crates/celox-frontend-veryl/src/hierarchy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, StrId>,
native_modules: &HashMap<String, usize>,
) -> Result<VerylSymbolicRtl<'a>, ParserError> {
parse_external_hierarchy(
ir,
Expand All @@ -74,7 +75,7 @@ fn parse_external_hierarchy<'a>(
external: &'a ExternalHierarchy,
config: &BuildConfig,
top: &StrId,
native_modules: Option<&HashMap<String, StrId>>,
native_modules: Option<&HashMap<String, usize>>,
) -> Result<VerylSymbolicRtl<'a>, ParserError> {
// Token-to-scope resolution uses process-global analyzer state and is not
// safe while independent compilations run on other test threads. Snapshot
Expand Down Expand Up @@ -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] {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate native module indices before indexing

When a caller of this public API supplies an out-of-range or stale component index, this direct indexing panics instead of returning a ParserError; the previous name-based lookup simply treated an unknown mapping as absent. Use ir.components.get(index) before matching so malformed mappings cannot abort the host process.

Useful? React with 👍 / 👎.

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);
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-frontend-veryl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
38 changes: 14 additions & 24 deletions crates/celox/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -759,19 +753,15 @@ 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"),
None,
)
})?;
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)],
Expand Down Expand Up @@ -846,9 +836,9 @@ pub fn parse_mixed(
.map(|source| (source, std::path::PathBuf::from("<sv-interface-behavior>"))),
);
};
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);
Expand Down Expand Up @@ -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<String, StrId>>,
native_modules: Option<&crate::HashMap<String, usize>>,
config: &BuildConfig,
ignored_loops: &[(
(Vec<(String, usize)>, Vec<String>),
Expand Down
21 changes: 12 additions & 9 deletions crates/celox/src/simulator/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,22 +127,25 @@ pub(super) fn elaborate_parameterized_top(
.iter()
.map(|(name, value)| (name.clone(), Value::new(*value, 64, false)))
.collect::<Vec<_>>();
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),
) else {
// 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!(),
Expand Down
18 changes: 8 additions & 10 deletions crates/celox/src/simulator/mixed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
Expand All @@ -1618,16 +1621,11 @@ pub(crate) fn specialize_foreign_module(
})
.collect::<Vec<_>>();
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();
Expand Down Expand Up @@ -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,
));
Expand Down
10 changes: 10 additions & 0 deletions crates/celox/tests/fixtures/mixed_dependency/Veryl.lock
Original file line number Diff line number Diff line change
@@ -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]
9 changes: 9 additions & 0 deletions crates/celox/tests/fixtures/mixed_dependency/Veryl.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[project]
name = "app"
version = "0.1.0"

[build]
sources = ["src"]

[dependencies]
lib = { path = "lib" }
6 changes: 6 additions & 0 deletions crates/celox/tests/fixtures/mixed_dependency/lib/Veryl.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[project]
name = "lib"
version = "0.1.0"

[build]
sources = ["src"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module Child #(
param K: u32 = 0,
) (
a: input logic<8>,
y: output logic<8>,
) {
assign y = a + 8'd2 + K;
}
8 changes: 8 additions & 0 deletions crates/celox/tests/fixtures/mixed_dependency/src/child.veryl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module Child #(
param K: u32 = 0,
) (
a: input logic<8>,
y: output logic<8>,
) {
assign y = a + 8'd1 + K;
}
9 changes: 9 additions & 0 deletions crates/celox/tests/fixtures/mixed_dependency/top.sv
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading