diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 18232d0b2a4..f955fda9e87 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1962,6 +1962,7 @@ pub fn lower_frontend_artifact( reset_clock_map, processes, package_bindings: HashMap::default(), + hierarchical_bindings: HashMap::default(), counter_slots, pending_slots: Vec::new(), comb_alternatives: Vec::new(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index ec42afd1a4a..80dffff18d2 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -130,6 +130,10 @@ pub struct SimModule { /// 1800-2023 26.2). Every instance of the module refers to that one /// object instead of a state object of its own. pub package_bindings: HashMap, + /// Variables of the module that denote a variable of another instance, + /// named by a hierarchical name (IEEE 1800-2023 23.6). Each instance of + /// the module refers to the object its binding locates from it. + pub hierarchical_bindings: HashMap, /// Counter objects of the signals that a unit of the module may store /// twice between two runtime checks (see /// `crate::watch::multi_store_candidates`). Assembly counts a signal's @@ -191,6 +195,28 @@ impl NbaSwitch { } } +/// The variable of another instance a module variable denotes. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct HierarchicalBinding { + pub start: HierarchicalStart, + /// The instance path segments from the start instance to the instance + /// that holds the target, as in [`crate::InstancePath`]. + pub path: Vec<(String, usize)>, + /// The target variable, by the module of that instance: instances of + /// one module may reach instances of different modules. + pub targets: Vec<(ModuleId, SourceVarId)>, +} + +/// Where the instance path of a [`HierarchicalBinding`] starts. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum HierarchicalStart { + /// The top instance. + Root, + /// The ancestor that many levels above the instance holding the + /// variable; 0 is that instance. + Ancestor(usize), +} + /// The package variable a module variable denotes. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct PackageBinding { @@ -225,6 +251,7 @@ impl fmt::Debug for SimModule { .field("reset_clock_map", &self.reset_clock_map) .field("processes", &self.processes) .field("package_bindings", &self.package_bindings) + .field("hierarchical_bindings", &self.hierarchical_bindings) .finish() } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 8c11b502974..aff5ec85d2c 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2,8 +2,8 @@ use num_bigint::BigUint; use std::collections::{BTreeMap, BTreeSet}; use crate::symbolic::artifact::{ - FfPart, NbaSwitch, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr, - SymbolicRtl, + FfPart, HierarchicalStart, NbaSwitch, RelocationModule, SimModule, SplitCommit, + SymbolicGlueAddr as GlueAddr, SymbolicRtl, }; use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, @@ -186,6 +186,7 @@ pub(crate) struct PackageBindings { impl PackageBindings { fn new( + expanded: &HashMap, instance_modules: &HashMap, modules: &HashMap, package_instances: &HashMap, @@ -244,6 +245,98 @@ impl PackageBindings { ); } } + let mut paths: Option> = None; + for (&instance_id, module_id) in instance_modules { + let module = &modules[module_id]; + for (&var_id, binding) in &module.hierarchical_bindings { + let paths = paths + .get_or_insert_with(|| expanded.iter().map(|(path, &id)| (id, path)).collect()); + let mut path = match binding.start { + HierarchicalStart::Root => Vec::new(), + HierarchicalStart::Ancestor(levels) => { + let own = &paths[&instance_id].0; + own[..own.len().saturating_sub(levels)].to_vec() + } + }; + path.extend(binding.path.iter().cloned()); + let error = |reason: &str| { + ParserError::illegal_context( + "hierarchical reference", + format!( + "module `{}` binds `{}` {reason}", + module.name, + module + .variables + .get(&var_id) + .map_or_else(String::new, |variable| variable.path.join(".")), + ), + None, + ) + }; + let target_instance = *expanded + .get(&InstancePath(path)) + .ok_or_else(|| error("to an instance that does not exist"))?; + let target_module_id = instance_modules[&target_instance]; + let target_module = &modules[&target_module_id]; + let target_var = binding + .targets + .iter() + .find(|(module, _)| *module == target_module_id) + .map(|&(_, var)| var) + .ok_or_else(|| error("to an instance of another module"))?; + let (Some(variable), Some(target)) = ( + module.variables.get(&var_id), + target_module.variables.get(&target_var), + ) else { + return Err(error("to an unknown variable")); + }; + let (variable, target) = (&variable.metadata, &target.metadata); + if ( + variable.width, + variable.is_4state, + &variable.array_dims, + variable.value_kind, + ) != ( + target.width, + target.is_4state, + &target.array_dims, + target.value_kind, + ) { + return Err(error("to a variable of another type")); + } + targets.insert( + AbsoluteAddr { + instance_id, + var_id, + }, + AbsoluteAddr { + instance_id: target_instance, + var_id: target_var, + }, + ); + } + } + // A hierarchical name may denote a variable that itself denotes a + // package variable or another instance's variable. + if paths.is_some() { + let sources: Vec<_> = targets.keys().copied().collect(); + for source in sources { + let mut target = targets[&source]; + let mut steps = 0; + while let Some(&next) = targets.get(&target) { + steps += 1; + if next == source || steps > targets.len() { + return Err(ParserError::illegal_context( + "hierarchical reference", + "a hierarchical name denotes itself".to_string(), + None, + )); + } + target = next; + } + targets.insert(source, target); + } + } Ok(Self { targets }) } @@ -288,7 +381,13 @@ fn check_package_variable_drivers( package_instances: &HashMap, comb_blocks: &[celox_slt::LogicPath], ) -> Result<(), ParserError> { - let packages: HashSet = bindings.targets.values().copied().collect(); + let package_instance_ids: HashSet = package_instances.values().copied().collect(); + let packages: HashSet = bindings + .targets + .values() + .copied() + .filter(|target| package_instance_ids.contains(&target.instance_id)) + .collect(); if packages.is_empty() { return Ok(()); } @@ -663,7 +762,8 @@ pub fn schedule_symbolic_rtl_reporting_loops( .iter() .map(|(&instance, module)| (instance, modules[module].time_scale)) .collect::>(); - let bindings = &PackageBindings::new(&instance_modules, &modules, &package_instances)?; + let bindings = + &PackageBindings::new(&expanded, &instance_modules, &modules, &package_instances)?; let global_boundaries = timed_sub!( "propagate_boundaries", propagate_boundaries(bindings, &expanded, &instance_modules, &modules) @@ -1644,17 +1744,33 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) }) .collect(); - let mut initial_memory_values: Vec> = initial_instances + // A write through a binding, such as a folded `initial` assignment + // through a hierarchical name, follows the declaration values of every + // instance, its target's among them. + let (mut initial_memory_values, bound_initials): (Vec<_>, Vec<_>) = initial_instances .into_iter() .flat_map(|(&instance_id, module_id)| { modules[module_id] .initial_memory_values .iter() - .map(move |init| InitialStateValue { - address: bindings.locate(instance_id, init.address), - data: init.data.clone(), + .map(move |init| { + ( + bindings.is_bound(&AbsoluteAddr { + instance_id, + var_id: init.address, + }), + InitialStateValue { + address: bindings.locate(instance_id, init.address), + data: init.data.clone(), + }, + ) }) }) + .partition(|(bound, _)| !bound); + let mut initial_memory_values: Vec> = initial_memory_values + .drain(..) + .chain(bound_initials) + .map(|(_, init)| init) .collect(); let state_objects: HashMap = instance_modules .iter() @@ -2299,8 +2415,11 @@ fn module_variables( let mut variables = HashMap::default(); let mut paths: HashMap, Option> = HashMap::default(); for (&source_id, variable) in &module.variables { - // A package variable belongs to the package's instance. - if module.package_bindings.contains_key(&source_id) { + // A package variable belongs to the package's instance, and a + // hierarchically named one to its own instance. + if module.package_bindings.contains_key(&source_id) + || module.hierarchical_bindings.contains_key(&source_id) + { continue; } // Only module-scope variables are externally addressable. Locals diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 23720aafaee..0202c7f5c14 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -41,6 +41,7 @@ mod comb; mod comb_retention; mod ff; mod floating; +mod hierarchy; mod procedural; type RegionedVarAddr = RegionedVarAddrBase; @@ -323,6 +324,7 @@ fn interface_signatures_collecting( warnings, &[], LevelLists::Processes, + &HashMap::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -587,11 +589,65 @@ fn validate_specialized_instance_net_drivers( } } + // A hierarchical name denotes another instance's object, which its + // own instance checks; only procedural writes of variables may + // reach it through the name. + let mut written = None; + for signal in module.source.signals() { + let Some(name) = signal.hierarchical() else { + continue; + }; + let driven = if signal.is_net() { + written + .get_or_insert_with(|| { + let source = &module.source; + let mut written = HashSet::default(); + for body in source + .comb_processes() + .iter() + .map(sv::ir::CombProcess::body) + .chain(source.ff_processes().iter().map(sv::ir::FfProcess::body)) + .chain( + source + .initial_processes() + .iter() + .map(|process| process.body()), + ) + { + procedural::written_names_with_calls(source, body, &mut written); + } + written + }) + .contains(signal.name()) + } else { + !continuous_driver_ranges( + &module.source, + signal.name(), + &module.constants, + &module.parameter_types, + ) + .is_empty() + }; + if driven + || !child_output_driver_ranges(module, signal.name(), module_ids, modules) + .is_empty() + { + return Err(sv::AnalyzerError::Unsupported(format!( + "{} through hierarchical name `{name}`", + if signal.is_net() { + "driver of a net" + } else { + "continuous assignment to a variable" + } + ))); + } + } + let net_names = module .source .signals() .iter() - .filter(|signal| signal.is_net()) + .filter(|signal| signal.is_net() && signal.hierarchical().is_none()) .map(|signal| signal.name()) .chain( module @@ -611,7 +667,7 @@ fn validate_specialized_instance_net_drivers( .source .signals() .iter() - .filter(|signal| !signal.is_net()) + .filter(|signal| !signal.is_net() && signal.hierarchical().is_none()) .map(|signal| signal.name()) .chain( module @@ -841,6 +897,7 @@ fn lower_package_states( warnings, &[], LevelLists::Processes, + &HashMap::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -998,10 +1055,15 @@ fn driver_ranges_overlap(drivers: &[(usize, Option<(i128, i128)>)]) -> bool { /// Memories may have several edge-sensitive writers. Their NBA stores update /// selected elements; always_ff additionally requires a single writing process. +/// +/// A memory that repeating processes of other modules write through +/// hierarchical names (`foreign_writes`) has writers outside the module, so +/// its edge writes update selected elements too. fn shared_edge_memories( module: &sv::ir::Module, constants: &HashMap, parameter_types: &HashMap, + foreign_writes: &HashMap, warnings: &mut Vec, ) -> HashSet { let mut memories = HashSet::default(); @@ -1019,6 +1081,15 @@ fn shared_edge_memories( { continue; } + if foreign_writes + .get(signal.name()) + .is_some_and(|writes| writes.repeating > 0) + { + if !drivers.is_empty() { + memories.insert(signal.name().into()); + } + continue; + } let overlaps = drivers.iter().enumerate().any(|(i, a)| { drivers[i + 1..] .iter() @@ -1056,12 +1127,14 @@ fn shared_edge_memories( /// only the 64-bit chunks the process wrote, so a write from another scope /// that lands between the evaluation and the commit of the process can be /// lost only within those chunks, where a whole-array commit loses it -/// everywhere. A writer outside `module` (a hierarchical reference) that -/// must not lose such writes has to be excluded here. +/// everywhere. Arrays that processes of other modules write through +/// hierarchical names (`foreign_writes`) keep the whole-array commit, which +/// they are ordered against. fn edge_only_memories( module: &sv::ir::Module, constants: &HashMap, parameter_types: &HashMap, + foreign_writes: &HashMap, ) -> HashSet { let first_ff = module.comb_processes().len(); let end_ff = first_ff + module.ff_processes().len(); @@ -1094,6 +1167,7 @@ fn edge_only_memories( !s.is_net() && !s.r#type().unpacked_ranges().is_empty() && nonblocking.contains(s.name()) + && !foreign_writes.contains_key(s.name()) }) .filter(|signal| { let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); @@ -1115,10 +1189,13 @@ fn edge_only_memories( /// evaluates, so its writes, such as memory initialization, are not /// included. /// -/// These are the writers within `module`. A writer outside it (a -/// hierarchical reference) that can write after it suspends has to be added -/// here. -fn kernel_window_writes(module: &sv::ir::Module) -> HashSet { +/// Processes of other modules that write variables of `module` through +/// hierarchical names (`foreign_writes`) may run in that window as well, so +/// those variables are included whatever region the writes run in. +fn kernel_window_writes( + module: &sv::ir::Module, + foreign_writes: &HashMap, +) -> HashSet { let subroutines = module.subroutines(); let mut names = HashSet::default(); for process in module @@ -1142,6 +1219,7 @@ fn kernel_window_writes(module: &sv::ir::Module) -> HashSet { 0, ); } + names.extend(foreign_writes.keys().cloned()); names } @@ -1246,6 +1324,77 @@ fn kernel_written_names( } } +/// Check the drivers of the variables that processes of other modules write +/// through hierarchical names as if those processes were the module's own: a +/// continuous or `always_comb` driver excludes every other writer (IEEE +/// 1800-2023 6.5, 9.2.2.2), an `always_ff` one every other process +/// (9.2.2.4), and two repeating processes may only write a shared memory, +/// whose edge writes update selected elements. +fn validate_foreign_drivers( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, + shared_memories: &HashSet, + foreign_writes: &HashMap, +) -> Result<(), sv::AnalyzerError> { + if foreign_writes.is_empty() { + return Ok(()); + } + let first_ff = module.comb_processes().len(); + let mut written_once = None; + let mut always_ff = None; + for (name, writes) in foreign_writes { + // Drivers of nets through hierarchical names are rejected with the + // instance's net drivers. + if module + .signals() + .iter() + .any(|signal| signal.name() == name && signal.is_net()) + { + continue; + } + let drivers = local_driver_ranges(module, name, constants, parameter_types); + let continuous = drivers.iter().any(|(id, _)| *id < first_ff); + let repeating = writes.repeating + usize::from(!drivers.is_empty()); + let local_always_ff = always_ff + .get_or_insert_with(|| { + let mut written = HashSet::default(); + for process in module.ff_processes().iter().filter(|p| p.is_always_ff()) { + procedural::written_names_with_calls(module, process.body(), &mut written); + } + written + }) + .contains(name); + let local_once = written_once + .get_or_insert_with(|| { + let mut written = HashSet::default(); + for process in module.initial_processes().iter().filter(|p| !p.repeats()) { + procedural::written_names_with_calls(module, process.body(), &mut written); + } + written + }) + .contains(name); + let reason = if continuous { + Some("its module drives it continuously or from always_comb") + } else if writes.always_ff && (!drivers.is_empty() || local_once || writes.repeating > 1) { + Some("an always_ff process writes it") + } else if local_always_ff { + Some("an always_ff process of its module writes it") + } else if repeating > 1 && !shared_memories.contains(name) { + Some("another process writes it too") + } else { + None + }; + if let Some(reason) = reason { + return Err(sv::AnalyzerError::Unsupported(format!( + "multiple variable drivers for `{name}`, which another module writes through a \ + hierarchical name: {reason}" + ))); + } + } + Ok(()) +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, @@ -1940,6 +2089,7 @@ fn prepare_external_hierarchy_collecting( false, warnings, LevelLists::Processes, + HierarchicalNames::default(), )?; for instance in &lowered.instances { let child_key = LoweredSvModuleKey::instance_key(instance); @@ -1984,6 +2134,7 @@ fn prepare_external_hierarchy_collecting( false, warnings, LevelLists::Processes, + HierarchicalNames::default(), )?, )) }) @@ -2014,6 +2165,7 @@ fn prepare_external_hierarchy_collecting( four_state, allow_inferred_latches, true, + &HashSet::default(), warnings, )?; modules.insert( @@ -2435,21 +2587,35 @@ fn schedule_sources_collecting( module_specialization_counts.insert(root_key.name.clone(), 1usize); let mut queue = vec![root_key.clone()]; let mut index = 0; + let mut elaborated = HashMap::default(); + let mut hierarchical_modules = Vec::new(); while index < queue.len() { let key = queue[index].clone(); index += 1; let base = analyzed .get(&key.name) .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let lowered = specialize_module( + let module_id = module_ids[&key]; + let module = match specialize_module( base, &key, four_state, false, warnings, LevelLists::Processes, - )?; - for instance in &lowered.instances { + HierarchicalNames::default(), + ) { + Ok(lowered) => hierarchy::ElaboratedModule::from_lowered(lowered), + // Elaborate the hierarchy below the module before resolving its + // hierarchical names. + Err(error) if hierarchical_reference_path(&error).is_some() => { + hierarchical_modules.push(module_id); + specialize_module_declarations(base, &key)? + } + Err(error) => return Err(error.into()), + }; + let module = elaborated.entry(module_id).or_insert(module); + for instance in module.instances() { let child_key = LoweredSvModuleKey::instance_key(instance); if !analyzed.contains_key(&child_key.name) { return Err(unsupported_sv_instance(child_key.name.clone()).into()); @@ -2469,33 +2635,96 @@ fn schedule_sources_collecting( } } + let keys: HashMap = + module_ids.iter().map(|(key, &id)| (id, key)).collect(); + let hierarchy = hierarchy::Hierarchy::new( + (&root_key, root_id), + &keys, + &module_ids, + &elaborated, + &analyzed, + ); + // The signals that hierarchical names write gain writers outside their + // own modules. Collect them from the analyzed modules, independently of + // the order the modules are lowered in. + let mut references = HashMap::default(); + let mut analyses = HashMap::default(); + let mut foreign_writes: HashMap> = + HashMap::default(); + for &module_id in &hierarchical_modules { + let key = keys[&module_id]; + let mut resolved = hierarchy::resolve(&hierarchy, module_id); + let ir = loop { + let signals: Vec<_> = resolved + .iter() + .map(|reference| reference.signal.clone()) + .collect(); + match analyze_specialization(&analyzed[&key.name], key, &signals, &mut Vec::new()) { + Ok(ir) => break ir, + // A name with an instance index that is a constant + // expression reaches the analysis with the index evaluated. + Err(error) => match hierarchical_reference_path(&error) { + Some(path) + if hierarchy::resolve_name( + &hierarchy, + module_id, + &path.split('.').map(str::to_string).collect::>(), + &mut resolved, + )? => {} + _ => return Err(error.into()), + }, + } + }; + if let Some(module) = ir.modules().iter().find(|module| module.name() == key.name) { + hierarchy::collect_foreign_writes(module, &resolved, &mut foreign_writes); + } + references.insert(module_id, resolved); + analyses.insert(module_id, ir); + } + // The elaboration only served to resolve the hierarchical names. + drop(hierarchy); + drop(elaborated); + // A combinational loop through an `always @(list)` lowered like // `always @*` may converge as a process: demote the lists in the loop // and schedule again, until no lowered list takes part in it. let no_demotions = HashSet::default(); let mut demoted: HashMap> = HashMap::default(); let mut trace = trace; + let no_foreign_writes = HashMap::default(); loop { + let mut specialize = |key: &LoweredSvModuleKey, + module_id: ModuleId| + -> Result { + let base = analyzed + .get(&key.name) + .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; + let level_lists = LevelLists::Lowered { + demoted: demoted.get(&module_id).unwrap_or(&no_demotions), + }; + let signals: Vec<_> = references + .get(&module_id) + .into_iter() + .flatten() + .map(|reference: &hierarchy::HierarchicalReference| reference.signal.clone()) + .collect(); + Ok(specialize_module( + base, + key, + four_state, + parallel.enabled(), + warnings, + level_lists, + HierarchicalNames { + signals: &signals, + foreign_writes: foreign_writes.get(&module_id).unwrap_or(&no_foreign_writes), + analyzed: analyses.get(&module_id), + }, + )?) + }; let lowered_modules = module_ids .iter() - .map(|(key, &module_id)| { - let base = analyzed - .get(&key.name) - .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let level_lists = LevelLists::Lowered { - demoted: demoted.get(&module_id).unwrap_or(&no_demotions), - }; - let lowered = specialize_module( - base, - key, - four_state, - parallel.enabled(), - warnings, - level_lists, - ) - .map_err(FrontendError::from)?; - Ok((module_id, lowered)) - }) + .map(|(key, &module_id)| Ok((module_id, specialize(key, module_id)?))) .collect::, FrontendError>>()?; validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let root = &lowered_modules[&root_id]; @@ -2515,11 +2744,27 @@ fn schedule_sources_collecting( &mut HashSet::default(), )?; + // Waits and flip-flop domains of other modules may watch the + // signals that hierarchical names reach. + let mut hierarchical_targets: HashMap> = HashMap::default(); + for reference in references.values().flatten() { + for (module, target) in &reference.targets { + hierarchical_targets + .entry(*module) + .or_default() + .insert(target.clone()); + } + } + let no_targets = HashSet::default(); let mut modules = HashMap::default(); let mut module_names = HashMap::default(); for (key, &module_id) in &module_ids { let lowered = &lowered_modules[&module_id]; let mut sim_module = lowered.sim_module.clone(); + if let Some(references) = references.get(&module_id) { + sim_module.hierarchical_bindings = + hierarchy::bindings(references, lowered, &lowered_modules)?; + } attach_instance_glue( &mut sim_module, lowered, @@ -2529,6 +2774,7 @@ fn schedule_sources_collecting( four_state, allow_inferred_latches, false, + hierarchical_targets.get(&module_id).unwrap_or(&no_targets), warnings, )?; module_names.insert(module_id, key.name.clone()); @@ -2710,39 +2956,80 @@ fn validate_sv_module_graph( Ok(()) } -fn specialize_module( - module: &AnalyzedSvModule, +/// The value, type and pattern parameter bindings of specialization `key`. +/// Type bindings are already resolved in the caller scope. +#[allow(clippy::type_complexity)] +fn specialization_overrides( key: &LoweredSvModuleKey, - four_state: bool, - ff_parts: bool, - warnings: &mut Vec, - level_lists: LevelLists<'_>, -) -> Result { +) -> Result< + ( + HashMap, + Vec<(String, sv::ast::Type)>, + Vec<(String, sv::ast::BoundPattern)>, + ), + sv::AnalyzerError, +> { let overrides = evaluated_parameter_overrides(&key.parameter_overrides)?; - // Type bindings are already resolved in the caller scope. - let type_overrides: Vec<_> = key + let types = key .parameter_overrides .iter() .filter_map(|parameter| Some((parameter.name.clone(), parameter.bound_type.clone()?))) .collect(); - let pattern_overrides: Vec<_> = key + let patterns = key .parameter_overrides .iter() .filter_map(|parameter| Some((parameter.name.clone(), parameter.bound_pattern.clone()?))) .collect(); - let analyzed = module.source.analyze_module( + Ok((overrides, types, patterns)) +} + +/// Analyze specialization `key` of `module`, whose hierarchical names denote +/// `hierarchical`. +fn analyze_specialization( + module: &AnalyzedSvModule, + key: &LoweredSvModuleKey, + hierarchical: &[sv::ast::HierarchicalSignal], + warnings: &mut Vec, +) -> Result { + let (overrides, type_overrides, pattern_overrides) = specialization_overrides(key)?; + let analyzed = module.source.analyze_module_with_hierarchy( &module.name, &overrides, &type_overrides, &pattern_overrides, &module.interfaces, &module.packages, + hierarchical, ); if let Err(error) = &analyzed { warnings.extend(crate::warning::analyzer_warnings(error.warnings())); } let ir = analyzed?; warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); + Ok(ir) +} + +#[allow(clippy::too_many_arguments)] +fn specialize_module( + module: &AnalyzedSvModule, + key: &LoweredSvModuleKey, + four_state: bool, + ff_parts: bool, + warnings: &mut Vec, + level_lists: LevelLists<'_>, + hierarchical: HierarchicalNames<'_>, +) -> Result { + let analyzed; + let ir = match hierarchical.analyzed { + Some(ir) => { + warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); + ir + } + None => { + analyzed = analyze_specialization(module, key, hierarchical.signals, warnings)?; + &analyzed + } + }; let specialized = ir .modules() .iter() @@ -2767,8 +3054,54 @@ fn specialize_module( warnings, &local_forces, level_lists, + hierarchical.foreign_writes, )?; - for instance in &mut lowered.instances { + propagate_force_signals(&mut lowered.instances, &key.force_signals); + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(module.packages.global_time_precision()) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?; + Ok(lowered) +} + +/// What hierarchical names (IEEE 1800-2023 23.6) contribute to the +/// lowering of a specialization. +#[derive(Clone, Copy)] +struct HierarchicalNames<'a> { + /// The signals of other instances that the module's names denote. + signals: &'a [sv::ast::HierarchicalSignal], + /// The module's signals that names in other modules write. + foreign_writes: &'a HashMap, + /// The analysis of the module with `signals`, if it is done already. + analyzed: Option<&'a sv::Ir>, +} + +impl Default for HierarchicalNames<'_> { + fn default() -> Self { + static EMPTY: std::sync::LazyLock> = + std::sync::LazyLock::new(HashMap::default); + Self { + signals: &[], + foreign_writes: &EMPTY, + analyzed: None, + } + } +} + +/// The hierarchical name at which the analysis of a module failed, which +/// needs the specialized hierarchy below it. +fn hierarchical_reference_path(error: &sv::AnalyzerError) -> Option<&str> { + match error { + sv::AnalyzerError::HierarchicalReference { path } => Some(path), + sv::AnalyzerError::WithWarnings { error, .. } => hierarchical_reference_path(error), + _ => None, + } +} + +/// Hand each instance the force targets of `force_signals` below it. +fn propagate_force_signals(instances: &mut [LoweredSvInstance], force_signals: &[String]) { + for instance in instances { let name = if let Some((index, _)) = instance.array_element { format!( "{}[{}]", @@ -2779,18 +3112,33 @@ fn specialize_module( instance.instance_name.clone() }; let prefix = format!("{name}."); - instance.force_signals = key - .force_signals + instance.force_signals = force_signals .iter() .filter_map(|path| path.strip_prefix(&prefix).map(str::to_string)) .collect(); } - lowered.sim_module.time_precision = Some( - celox_design::TimePrecision::try_from(module.packages.global_time_precision()) - .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, - ); - lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?; - Ok(lowered) +} + +/// The declarations and instances of specialization `key`. +fn specialize_module_declarations( + module: &AnalyzedSvModule, + key: &LoweredSvModuleKey, +) -> Result { + let (overrides, type_overrides, pattern_overrides) = specialization_overrides(key)?; + let ir = module.source.analyze_module_hierarchy( + &module.name, + &overrides, + &type_overrides, + &pattern_overrides, + &module.interfaces, + &module.packages, + )?; + let specialized = ir + .modules() + .iter() + .find(|candidate| candidate.name() == module.name) + .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; + hierarchy::ElaboratedModule::from_declarations(specialized, &key.force_signals) } fn scope_time_scale( @@ -2810,6 +3158,7 @@ fn scope_time_scale( }) } +#[allow(clippy::too_many_arguments)] fn lower_module( module: &sv::ir::Module, four_state: bool, @@ -2818,6 +3167,7 @@ fn lower_module( warnings: &mut Vec, force_signals: &[String], level_lists: LevelLists<'_>, + foreign_writes: &HashMap, ) -> Result { lower_module_with_overrides( module, @@ -2828,6 +3178,7 @@ fn lower_module( warnings, force_signals, level_lists, + foreign_writes, ) } @@ -2909,21 +3260,9 @@ fn lower_module_with_overrides( warnings: &mut Vec, force_signals: &[String], level_lists: LevelLists<'_>, + foreign_writes: &HashMap, ) -> Result { - let parameter_types = module - .imported_parameters() - .iter() - .chain(module.parameters()) - .filter_map(|parameter| { - Some(( - parameter.name().to_string(), - ( - parameter.resolved_width()?, - parameter.resolved_signed().unwrap_or(false), - ), - )) - }) - .collect(); + let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); let fallbacks = module .ff_processes() @@ -2957,8 +3296,21 @@ fn lower_module_with_overrides( }); } } - let shared_memories = shared_edge_memories(module, &constants, ¶meter_types, warnings); + let shared_memories = shared_edge_memories( + module, + &constants, + ¶meter_types, + foreign_writes, + warnings, + ); validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; + validate_foreign_drivers( + module, + &constants, + ¶meter_types, + &shared_memories, + foreign_writes, + )?; let scheduled = module .ff_processes() .iter() @@ -3091,8 +3443,12 @@ fn lower_module_with_overrides( force_control: None, }; name_to_id.insert(signal.name().to_string(), id); - // The package's object has its own default value. - if (signal.is_net() || type_info.is_4state) && signal.package_variable().is_none() { + // The package's object, or the other instance's, has its own + // default value. + if (signal.is_net() || type_info.is_4state) + && signal.package_variable().is_none() + && signal.hierarchical().is_none() + { let written_mask = (BigUint::from(1u8) << type_info.width) - BigUint::from(1u8); let value = if signal.is_net() { BigUint::default() @@ -3294,6 +3650,7 @@ fn lower_module_with_overrides( ff_parts, &ff_event_roles, &shared_memories, + foreign_writes, &mut repeated_ff_writes, )?; ( @@ -3334,69 +3691,7 @@ fn lower_module_with_overrides( .iter() .map(|(&id, variable)| (id, variable.to_symbolic_variable())) .collect(); - let mut instances = Vec::new(); - for instance in module.instances() { - if let Some(condition) = instance.condition() { - let condition = - sv::typecheck::eval_const_expr_with_types(condition, &constants, ¶meter_types) - .ok_or_else(|| { - sv::AnalyzerError::Unsupported( - "unknown conditional-generate condition".to_string(), - ) - })?; - if condition == 0 { - continue; - } - } - // An instance array is one instance per element, all under one name. - // Elements are listed from the lowest index up and numbered from the - // lower bound, so the hierarchy uses the declared indices; each keeps - // its position in declaration order, which decides its connections. - let array_index_base = match instance.array_range() { - Some((left, right)) => usize::try_from(left.min(right)).map_err(|_| { - sv::AnalyzerError::Unsupported(format!( - "module instance array `{}` with a negative index", - instance.name() - )) - })?, - None => 0, - }; - let elements = instance.array_len().map_or(vec![None], |len| { - let descending = instance - .array_range() - .is_some_and(|(left, right)| left >= right); - (0..len) - .map(|offset| { - let position = if descending { len - 1 - offset } else { offset }; - Some((position, len)) - }) - .collect() - }); - for array_element in elements { - instances.push(LoweredSvInstance { - module_name: instance.module_name().to_string(), - instance_name: instance.name().to_string(), - force_signals: Vec::new(), - parameter_overrides: lower_parameter_overrides( - instance, - &constants, - ¶meter_types, - ), - port_connections: instance - .port_connections() - .iter() - .map(|connection| LoweredSvPortConnection { - formal: connection.formal().to_string(), - actual: connection.actual().to_string(), - actual_expr: connection.actual_expr().cloned(), - bound_pattern: connection.bound_pattern().cloned(), - }) - .collect(), - array_element, - array_index_base, - }); - } - } + let instances = lower_instances(module, &constants, ¶meter_types)?; Ok(LoweredSvModule { source: module.clone(), @@ -3428,6 +3723,7 @@ fn lower_module_with_overrides( reset_clock_map, processes, package_bindings: HashMap::default(), + hierarchical_bindings: HashMap::default(), counter_slots: Vec::new(), pending_slots: Vec::new(), comb_alternatives: Vec::new(), @@ -3496,6 +3792,79 @@ fn evaluated_parameter_overrides( Ok(evaluated) } +/// The instances of a specialized module, one per element of an instance +/// array, without those of false conditional-generate branches. +fn lower_instances( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, +) -> Result, sv::AnalyzerError> { + let mut instances = Vec::new(); + for instance in module.instances() { + if let Some(condition) = instance.condition() { + let condition = + sv::typecheck::eval_const_expr_with_types(condition, constants, parameter_types) + .ok_or_else(|| { + sv::AnalyzerError::Unsupported( + "unknown conditional-generate condition".to_string(), + ) + })?; + if condition == 0 { + continue; + } + } + // An instance array is one instance per element, all under one name. + // Elements are listed from the lowest index up and numbered from the + // lower bound, so the hierarchy uses the declared indices; each keeps + // its position in declaration order, which decides its connections. + let array_index_base = match instance.array_range() { + Some((left, right)) => usize::try_from(left.min(right)).map_err(|_| { + sv::AnalyzerError::Unsupported(format!( + "module instance array `{}` with a negative index", + instance.name() + )) + })?, + None => 0, + }; + let elements = instance.array_len().map_or(vec![None], |len| { + let descending = instance + .array_range() + .is_some_and(|(left, right)| left >= right); + (0..len) + .map(|offset| { + let position = if descending { len - 1 - offset } else { offset }; + Some((position, len)) + }) + .collect() + }); + for array_element in elements { + instances.push(LoweredSvInstance { + module_name: instance.module_name().to_string(), + instance_name: instance.name().to_string(), + force_signals: Vec::new(), + parameter_overrides: lower_parameter_overrides( + instance, + constants, + parameter_types, + ), + port_connections: instance + .port_connections() + .iter() + .map(|connection| LoweredSvPortConnection { + formal: connection.formal().to_string(), + actual: connection.actual().to_string(), + actual_expr: connection.actual_expr().cloned(), + bound_pattern: connection.bound_pattern().cloned(), + }) + .collect(), + array_element, + array_index_base, + }); + } + } + Ok(instances) +} + fn lower_parameter_overrides( instance: &sv::ir::Instance, constants: &HashMap, @@ -3836,6 +4205,7 @@ pub(crate) fn attach_instance_glue( four_state: bool, allow_inferred_latches: bool, foreign: bool, + hierarchical_targets: &HashSet, warnings: &mut Vec, ) -> Result<(), ParserError> { let mut signal_names = lowered.signal_names.clone(); @@ -3969,7 +4339,8 @@ pub(crate) fn attach_instance_glue( // An `always_comb` alternative is kept only if a wait or a flip-flop // domain counts one of its targets. Within the module, they name its // wait terms, its triggers and whole-variable copies of them; beyond - // it, ports, instance connections and package variables. Every counter + // it, ports, instance connections, package variables and the signals + // hierarchical names reach, in either module. Every counter // a design declares also keeps nonblocking writes queued, so a design // with a nonblocking switch lowers every alternative, and so does a // module of a design with foreign modules, which this module does not see. @@ -4025,6 +4396,12 @@ pub(crate) fn attach_instance_glue( .filter_map(|name| signal_names.get(name).copied()), ); seeds.extend(port_assignments.iter().map(|(target, _)| *target)); + seeds.extend(module.hierarchical_bindings.keys().copied()); + seeds.extend( + hierarchical_targets + .iter() + .filter_map(|name| signal_names.get(name).copied()), + ); seeds }); let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) = @@ -8763,6 +9140,7 @@ fn lower_ff_processes( ff_parts: bool, ff_event_roles: &[FfEventRole], shared_memories: &HashSet, + foreign_writes: &HashMap, repeated_writes: &mut Vec, ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); @@ -8833,7 +9211,19 @@ fn lower_ff_processes( Ok((id, role.kind)) }) .collect::, sv::AnalyzerError>>()?; - let mut event_vars = FfEventVars::new(global_events.into_iter()); + // A hierarchical name denotes another instance's object, whose own + // declaration decides how it is sensed there: sense it on copies here. + let hierarchical: HashSet = module + .signals() + .iter() + .filter(|signal| signal.hierarchical().is_some()) + .filter_map(|signal| pm.id(signal.name())) + .collect(); + let mut event_vars = FfEventVars::new( + global_events + .into_iter() + .filter(|(id, _)| !hierarchical.contains(id)), + ); // Reflection must retain associations from scheduled host processes too. // Resolve sensed roles just as retained FF trigger sets do, including aliases // when one authored signal has more than one clock/reset role. @@ -8850,8 +9240,9 @@ fn lower_ff_processes( } } - let edge_memories = edge_only_memories(module, pm.constants, pm.parameter_types); - let window_writes = kernel_window_writes(module); + let edge_memories = + edge_only_memories(module, pm.constants, pm.parameter_types, foreign_writes); + let window_writes = kernel_window_writes(module, foreign_writes); let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { let mut events = events @@ -8978,12 +9369,28 @@ fn runs_as_process( .and_then(|r#type| signal_type_from_sv(r#type, constants, parameter_types).ok()) .is_some_and(|type_info| type_info.width != 1) }; + // A blocking write through a hierarchical name updates the other + // instance's object at once, outside that instance's flip-flop commit. + let writes_other_instance = || { + let mut hierarchical = module + .signals() + .iter() + .filter(|signal| signal.hierarchical().is_some()) + .peekable(); + if hierarchical.peek().is_none() { + return false; + } + let mut written = HashSet::default(); + procedural::written_names_with_calls(module, process.body(), &mut written); + hierarchical.any(|signal| written.contains(signal.name())) + }; !process.is_always_ff() && (clock_event_from_ff_process(process).is_none() || process .events() .iter() - .any(|event| multi_bit(event.signal()))) + .any(|event| multi_bit(event.signal())) + || writes_other_instance()) } fn clock_event_from_ff_process(process: &sv::ir::FfProcess) -> Option<&sv::ir::FfEvent> { @@ -9450,6 +9857,24 @@ fn sv_comparison_operand_width( ) } +/// The widths and signedness of the parameters a module can name. +fn module_parameter_types(module: &sv::ir::Module) -> HashMap { + module + .imported_parameters() + .iter() + .chain(module.parameters()) + .filter_map(|parameter| { + Some(( + parameter.name().to_string(), + ( + parameter.resolved_width()?, + parameter.resolved_signed().unwrap_or(false), + ), + )) + }) + .collect() +} + fn module_constants_with_overrides( module: &sv::ir::Module, parameter_overrides: &[LoweredSvParameterOverride], @@ -9730,15 +10155,15 @@ mod tests { comb_alternatives(&format!("{child}\n{port}")).contains("y"), "child output port" ); - // Only ports reach the variables of another module: a hierarchical - // reference is rejected, so no wait names them otherwise. + // A hierarchical name reaches the variables of another module too. let hierarchical = "module Top(input bit [7:0] s); Child child(.s(s), .y()); initial forever @(child.y) ; endmodule"; - let error = try_comb_alternatives(&format!("{child}\n{hierarchical}")) - .expect_err("a hierarchical reference is rejected"); - assert!(error.to_string().contains("child.y"), "{error}"); + assert!( + comb_alternatives(&format!("{child}\n{hierarchical}")).contains("y"), + "hierarchical name" + ); } /// Only the `always @(list)` processes of a combinational loop stay diff --git a/crates/celox-frontend-sv/src/lowering/hierarchy.rs b/crates/celox-frontend-sv/src/lowering/hierarchy.rs new file mode 100644 index 00000000000..0e96fc96b2c --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/hierarchy.rs @@ -0,0 +1,614 @@ +//! Hierarchical names (IEEE 1800-2023 23.6, 23.8) resolved against the +//! elaborated hierarchy. +//! +//! The analyzer works on one module specialization at a time and cannot see +//! the instances below it. A module whose analysis meets a hierarchical name +//! is first elaborated from its declarations only, so that the hierarchy +//! below it can be specialized. Once every specialization is known, each of +//! its dotted names that starts at an instance of the module, at the module's +//! own name or at `$root` is followed through the specialized instances to a +//! signal. The module is then analyzed again with a local signal for each +//! such name, and assembly binds that local signal, per instance, to the +//! object of the instance the name denotes. + +use celox_design::ModuleId; +use celox_frontend_core::SourceVarId; +use celox_frontend_core::symbolic::artifact::{HierarchicalBinding, HierarchicalStart}; +use celox_sv_analyzer as sv; +use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; + +use super::{ + AnalyzedSvModule, LoweredSvInstance, LoweredSvModule, LoweredSvModuleKey, lower_instances, + module_constants_with_overrides, module_parameter_types, propagate_force_signals, + unpacked_range_bounds, +}; + +/// A specialization as the hierarchy below it was elaborated: its +/// instances and the signals names can denote. +pub(super) struct ElaboratedModule { + name: String, + /// Ports and signals, by local name, with their net kind. + signals: Vec<(String, sv::ir::Type, bool)>, + instances: Vec, + constants: HashMap, + parameter_types: HashMap, +} + +impl ElaboratedModule { + pub(super) fn from_lowered(lowered: LoweredSvModule) -> Self { + Self { + name: lowered.source.name().to_string(), + signals: signals(&lowered.source), + instances: lowered.instances, + constants: lowered.constants, + parameter_types: lowered.parameter_types, + } + } + + /// The declarations and instances of a module with hierarchical names. + pub(super) fn from_declarations( + source: &sv::ir::Module, + force_signals: &[String], + ) -> Result { + let parameter_types = module_parameter_types(source); + let constants = module_constants_with_overrides(source, &[]); + let mut instances = lower_instances(source, &constants, ¶meter_types)?; + propagate_force_signals(&mut instances, force_signals); + Ok(Self { + name: source.name().to_string(), + signals: signals(source), + instances, + constants, + parameter_types, + }) + } + + pub(super) fn instances(&self) -> &[LoweredSvInstance] { + &self.instances + } +} + +/// The ports and signals of a module that a hierarchical name can denote: +/// not those that denote another object themselves. +fn signals(module: &sv::ir::Module) -> Vec<(String, sv::ir::Type, bool)> { + module + .ports() + .iter() + .map(|port| { + ( + port.name().to_string(), + port.r#type().clone(), + port.is_net(), + ) + }) + .chain( + module + .signals() + .iter() + .filter(|signal| signal.hierarchical().is_none()) + .map(|signal| { + ( + signal.name().to_string(), + signal.r#type().clone(), + signal.is_net(), + ) + }), + ) + .collect() +} + +/// The signal of another instance that a hierarchical name of a module +/// denotes. +#[derive(Clone)] +pub(super) struct HierarchicalReference { + pub signal: sv::ast::HierarchicalSignal, + start: HierarchicalStart, + path: Vec<(String, usize)>, + /// The specializations that hold the signal, from the different + /// instances of the module, and its local name in each. + pub targets: Vec<(ModuleId, String)>, +} + +/// The specialized hierarchy, for following names through it. +pub(super) struct Hierarchy<'a> { + root: (&'a LoweredSvModuleKey, ModuleId), + keys: &'a HashMap, + module_ids: &'a HashMap, + elaborated: &'a HashMap, + analyzed: &'a HashMap, + /// The specializations that instantiate each specialization. + parents: HashMap>, +} + +/// A name followed to a signal, relative to where the following started. +#[derive(Clone, PartialEq, Eq)] +struct Found { + /// How many instances above the name's module the following started. + levels: usize, + path: Vec<(String, usize)>, + /// How many leading components name the signal. + length: usize, + target: String, + r#type: sv::ast::Type, + is_net: bool, + /// The specializations that hold the signal. + modules: Vec, +} + +impl Found { + /// Whether two followings reach the same relative object, if from + /// different specializations. + fn same_object(&self, other: &Found) -> bool { + ( + self.levels, + &self.path, + self.length, + &self.target, + &self.r#type, + self.is_net, + ) == ( + other.levels, + &other.path, + other.length, + &other.target, + &other.r#type, + other.is_net, + ) + } +} + +impl<'a> Hierarchy<'a> { + pub(super) fn new( + root: (&'a LoweredSvModuleKey, ModuleId), + keys: &'a HashMap, + module_ids: &'a HashMap, + elaborated: &'a HashMap, + analyzed: &'a HashMap, + ) -> Self { + let mut parents: HashMap> = HashMap::default(); + for (&parent, module) in elaborated { + for instance in module.instances() { + if let Some(&child) = module_ids.get(&LoweredSvModuleKey::instance_key(instance)) { + let parents = parents.entry(child).or_default(); + if !parents.contains(&parent) { + parents.push(parent); + } + } + } + } + Self { + root, + keys, + module_ids, + elaborated, + analyzed, + parents, + } + } + + /// The name `module` has in the source, which hierarchical names spell. + fn authored_name(&self, module: ModuleId) -> &str { + let name = &self.keys[&module].name; + self.analyzed.get(name).map_or(name, |analyzed| { + analyzed.packages.authored_module_name(name) + }) + } + + /// Follow `components[at..]` down from an instance of `module`: the + /// longest instance name at each level, which may carry generate scope + /// prefixes (`g[1].u`) or an array index (`u[3]`), then the longest + /// signal name of the last instance. + fn walk( + &self, + mut module: ModuleId, + components: &[String], + mut at: usize, + ) -> Result, sv::AnalyzerError> { + let mut path = Vec::new(); + 'instances: while at < components.len() { + let elaborated = &self.elaborated[&module]; + for end in (at + 1..components.len()).rev() { + let name = components[at..end].join("."); + if let Some((segment, child)) = find_instance(elaborated, &name) { + module = *self + .module_ids + .get(&LoweredSvModuleKey::instance_key(child)) + .ok_or_else(|| { + sv::AnalyzerError::Unsupported(format!( + "instance `{name}` of hierarchical reference `{}`", + components.join(".") + )) + })?; + path.push(segment); + at = end; + continue 'instances; + } + } + break; + } + let elaborated = &self.elaborated[&module]; + let analyzed = &self.analyzed[&elaborated.name]; + let Some((length, target, r#type, is_net)) = + (at + 1..=components.len()).rev().find_map(|end| { + let name = components[at..end].join("."); + let (target, r#type, is_net) = find_signal(elaborated, analyzed, &name)?; + Some((end, target, r#type, is_net)) + }) + else { + return Ok(None); + }; + let r#type = resolved_type(elaborated, r#type).ok_or_else(|| { + sv::AnalyzerError::Unsupported(format!( + "hierarchical reference `{}` to a signal of this type", + components[..length].join(".") + )) + })?; + Ok(Some(Found { + levels: 0, + path, + length, + target, + r#type, + is_net, + modules: vec![module], + })) + } + + /// Follow a name written in `module` down from it: from an instance of + /// it, or from the module's own name (IEEE 1800-2023 23.8). + fn downward( + &self, + module: ModuleId, + components: &[String], + ) -> Result, sv::AnalyzerError> { + let elaborated = &self.elaborated[&module]; + if starts_at_instance(elaborated, components) { + return Ok(self + .walk(module, components, 0)? + .filter(|found| !found.path.is_empty())); + } + if components[0] == self.authored_name(module) { + return self.walk(module, components, 1); + } + Ok(None) + } + + /// Follow a name upwards from every instance of `module` (IEEE 1800-2023 + /// 23.8): at each enclosing instance, from an instance of its scope or + /// from its module name. The name must denote the same relative object + /// from each instance; `None` if it denotes none from some instance. + fn upward( + &self, + module: ModuleId, + components: &[String], + memo: &mut HashMap>, + ) -> Result, sv::AnalyzerError> { + let mut found: Option = None; + let parents = self.parents.get(&module).map_or(&[][..], Vec::as_slice); + if parents.is_empty() { + return Ok(None); + } + for &parent in parents { + let from_parent = match memo.get(&parent) { + Some(cached) => cached.clone(), + None => { + let resolved = match self.downward(parent, components)? { + Some(found) => Some(found), + None => self.upward(parent, components, memo)?, + }; + memo.insert(parent, resolved.clone()); + resolved + } + }; + let Some(mut from_parent) = from_parent else { + return Ok(None); + }; + from_parent.levels += 1; + match &mut found { + None => found = Some(from_parent), + Some(found) if found.same_object(&from_parent) => { + for module in from_parent.modules { + if !found.modules.contains(&module) { + found.modules.push(module); + } + } + } + Some(_) => { + return Err(sv::AnalyzerError::Unsupported(format!( + "upward hierarchical reference `{}` that denotes different relative \ + objects in instances of module `{}`", + components.join("."), + self.authored_name(module) + ))); + } + } + } + Ok(found) + } +} + +/// Resolve the hierarchical names of specialization `module` that its +/// source spells with literal instance indices. +pub(super) fn resolve(hierarchy: &Hierarchy<'_>, module: ModuleId) -> Vec { + let analyzed = &hierarchy.analyzed[&hierarchy.keys[&module].name]; + let mut references = Vec::new(); + for components in analyzed + .source + .hierarchical_names(&analyzed.name, &analyzed.packages) + { + // The scan also finds names in inactive generate branches. A name + // the analysis uses reaches `resolve_name` again with its error. + let _ = resolve_name(hierarchy, module, &components, &mut references); + } + references +} + +/// Add the reference of the hierarchical name `components` of `module` to +/// `references`. Whether the name denotes a signal not referenced yet. +pub(super) fn resolve_name( + hierarchy: &Hierarchy<'_>, + module: ModuleId, + components: &[String], + references: &mut Vec, +) -> Result { + let elaborated = &hierarchy.elaborated[&module]; + let resolved = if components[0] == "$root" { + // `$root.top. ...` (IEEE 1800-2023 23.3.1). + if components.get(1) != Some(&hierarchy.root.0.name) { + return Ok(false); + } + hierarchy + .walk(hierarchy.root.1, components, 2)? + .map(|found| (HierarchicalStart::Root, found)) + } else if starts_at_instance(elaborated, components) + || components[0] == hierarchy.authored_name(module) + { + hierarchy + .downward(module, components)? + .map(|found| (HierarchicalStart::Ancestor(0), found)) + } else if declares(elaborated, &components[0]) { + // A variable, generate block or interface of the module. + None + } else { + hierarchy + .upward(module, components, &mut HashMap::default())? + .map(|found| (HierarchicalStart::Ancestor(found.levels), found)) + }; + let Some((start, found)) = resolved else { + return Ok(false); + }; + let written = components[..found.length].join("."); + if references + .iter() + .any(|reference| reference.signal.paths.contains(&written)) + { + return Ok(false); + } + // A name that starts at the module's own name and names no instance + // denotes the module's own signal (IEEE 1800-2023 23.8). + if found.levels == 0 && found.path.is_empty() && start == HierarchicalStart::Ancestor(0) { + references.push(HierarchicalReference { + signal: sv::ast::HierarchicalSignal { + paths: vec![written], + name: found.target, + r#type: found.r#type, + is_net: found.is_net, + local: true, + }, + start, + path: Vec::new(), + targets: Vec::new(), + }); + return Ok(true); + } + references.push(HierarchicalReference { + signal: sv::ast::HierarchicalSignal { + paths: vec![written.clone()], + name: written, + r#type: found.r#type, + is_net: found.is_net, + local: false, + }, + start, + path: found.path, + targets: found + .modules + .into_iter() + .map(|module| (module, found.target.clone())) + .collect(), + }); + Ok(true) +} + +/// The bindings of the local signals of `references` in `lowered`. +pub(super) fn bindings( + references: &[HierarchicalReference], + lowered: &LoweredSvModule, + lowered_modules: &HashMap, +) -> Result, sv::AnalyzerError> { + references + .iter() + .filter(|reference| !reference.signal.local) + .map(|reference| { + let var_id = lowered.signal_names[&reference.signal.name]; + let targets = reference + .targets + .iter() + .map(|(module, target)| { + let var_id = lowered_modules[module] + .signal_names + .get(target) + .copied() + .ok_or_else(|| { + sv::AnalyzerError::Unsupported(format!( + "hierarchical reference `{}`", + reference.signal.name + )) + })?; + Ok((*module, var_id)) + }) + .collect::>()?; + Ok(( + var_id, + HierarchicalBinding { + start: reference.start, + path: reference.path.clone(), + targets, + }, + )) + }) + .collect() +} + +/// How processes of other modules write a signal through hierarchical names. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ForeignWrites { + /// The number of module specializations whose processes that run + /// repeatedly (all but `initial` ones) write the signal. + pub repeating: usize, + /// Whether an `always_ff` process writes it. + pub always_ff: bool, +} + +/// Add the signals that the hierarchical names of `module` (`module_id`), +/// which denote `references`, write to `writes`, by specialization and local +/// name. +pub(super) fn collect_foreign_writes( + module: &sv::ir::Module, + references: &[HierarchicalReference], + writes: &mut HashMap>, +) { + let mut once = HashSet::default(); + let mut repeatedly = HashSet::default(); + let mut always_ff = HashSet::default(); + for process in module.initial_processes() { + let written = if process.repeats() { + &mut repeatedly + } else { + &mut once + }; + super::procedural::written_names_with_calls(module, process.body(), written); + } + for process in module.comb_processes() { + super::procedural::written_names_with_calls(module, process.body(), &mut repeatedly); + } + for process in module.ff_processes() { + let written = if process.is_always_ff() { + &mut always_ff + } else { + &mut repeatedly + }; + super::procedural::written_names_with_calls(module, process.body(), written); + } + for reference in references { + let name = &reference.signal.name; + let by_always_ff = always_ff.contains(name); + let repeating = by_always_ff || repeatedly.contains(name); + if !repeating && !once.contains(name) { + continue; + } + for (target_module, target) in &reference.targets { + let entry = writes + .entry(*target_module) + .or_default() + .entry(target.clone()) + .or_default(); + entry.repeating += usize::from(repeating); + entry.always_ff |= by_always_ff; + } + } +} + +/// Whether leading components of a name name an instance of the module. +fn starts_at_instance(module: &ElaboratedModule, components: &[String]) -> bool { + (1..components.len()).any(|end| find_instance(module, &components[..end].join(".")).is_some()) +} + +/// Whether `name` is declared in the module, other than as an instance, so +/// that a dotted name starting with it is not an upward reference. +fn declares(module: &ElaboratedModule, name: &str) -> bool { + let scoped = |candidate: &str| { + candidate == name + || candidate + .strip_prefix(name) + .is_some_and(|rest| rest.starts_with(['.', '[', '$'])) + }; + module.signals.iter().any(|(signal, _, _)| scoped(signal)) + || module + .instances + .iter() + .any(|instance| instance.instance_name.starts_with(&format!("{name}."))) +} + +/// The instance path segment and instance of the element named `name`. +fn find_instance<'a>( + module: &'a ElaboratedModule, + name: &str, +) -> Option<((String, usize), &'a LoweredSvInstance)> { + let mut positions: HashMap<&str, usize> = HashMap::default(); + for instance in &module.instances { + // Glue blocks, and so hierarchy indices, follow listing order. + let position = positions.entry(&instance.instance_name).or_default(); + let index = instance.array_index_base + *position; + *position += 1; + let matches = if instance.array_element.is_some() { + name.strip_prefix(instance.instance_name.as_str()) + .is_some_and(|rest| rest == format!("[{index}]")) + } else { + name == instance.instance_name + }; + if matches { + return Some(((instance.instance_name.clone(), index), instance)); + } + } + None +} + +/// The local name, type and net kind of signal `name` of a module. +fn find_signal<'a>( + module: &'a ElaboratedModule, + analyzed: &AnalyzedSvModule, + name: &str, +) -> Option<(String, &'a sv::ir::Type, bool)> { + let flat = analyzed + .interface_member_paths + .iter() + .find(|(_, path)| path.segments.join(".") == name) + .map_or(name, |(flat, _)| flat.as_str()); + module + .signals + .iter() + .find(|(candidate, _, _)| candidate == flat) + .map(|(candidate, r#type, is_net)| (candidate.clone(), r#type, *is_net)) +} + +/// `r#type` with the bounds it has in its specialization. +fn resolved_type(module: &ElaboratedModule, r#type: &sv::ir::Type) -> Option { + let kind = match r#type.kind() { + sv::ir::TypeKind::Bit => sv::ast::TypeKind::Bit, + sv::ir::TypeKind::Logic => sv::ast::TypeKind::Logic, + sv::ir::TypeKind::Reg => sv::ast::TypeKind::Reg, + sv::ir::TypeKind::Implicit => sv::ast::TypeKind::Implicit, + _ => return None, + }; + let eval = |expr| { + sv::typecheck::eval_const_expr_with_types(expr, &module.constants, &module.parameter_types) + }; + let packed = r#type + .packed_ranges() + .iter() + .map(|range| Some((eval(range.left())?, eval(range.right())?))) + .collect::>>()?; + let unpacked = r#type + .unpacked_ranges() + .iter() + .map(|range| unpacked_range_bounds(range, &module.constants, &module.parameter_types)) + .collect::>>()?; + Some(sv::ast::Type::resolved( + kind, + r#type.is_signed(), + r#type.signed_element_depth(), + &packed, + &unpacked, + )) +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 242b4f53b89..def194c3e1d 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2599,6 +2599,22 @@ pub(super) fn written_names(stmts: &[sv::ir::Stmt], names: &mut HashSet) } } +/// The names a statement list of `module` writes, also through the +/// subroutines it calls and their written arguments. +pub(super) fn written_names_with_calls( + module: &sv::ir::Module, + stmts: &[sv::ir::Stmt], + names: &mut HashSet, +) { + super::kernel_written_names( + module.subroutines(), + stmts, + names, + &mut HashSet::default(), + 0, + ); +} + /// The lvalue an output argument writes back to. /// The variables a call of `function` writes through its arguments, such as /// the seed of `$random(seed)`. diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 2c9bcdd35ec..49fdb07fc6b 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -673,6 +673,7 @@ pub(crate) fn project_module_with_ids( .collect(), processes: Vec::new(), package_bindings: HashMap::default(), + hierarchical_bindings: HashMap::default(), counter_slots: Vec::new(), pending_slots: Vec::new(), comb_alternatives: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index a9c7a6e64a7..e325f3f6db9 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -146,6 +146,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { signal.is_net(), ) .with_package_variable(signal.package_variable()) + .with_hierarchical(signal.hierarchical()) }) .collect(); let instances = module diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 019490d81eb..aaa87e9e7f1 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -257,6 +257,22 @@ pub(crate) struct ModuleParameterBindings<'a> { pub values: &'a HashMap, pub types: &'a [(String, Type)], pub patterns: &'a [(String, BoundPattern)], + pub hierarchical: &'a [HierarchicalSignal], +} + +/// A signal of another instance that hierarchical names of the analyzed +/// module denote (IEEE 1800-2023 23.6), resolved by the caller against the +/// elaborated hierarchy. The module refers to it by a local signal `name`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HierarchicalSignal { + /// The names that denote the signal, as [`crate::ParsedSource::hierarchical_names`] + /// spells them. + pub paths: Vec, + pub name: String, + pub r#type: Type, + pub is_net: bool, + /// The names denote the module's own signal `name`, which they alias. + pub local: bool, } impl Source { @@ -366,6 +382,7 @@ impl Source { values: parameter_overrides, types: &[], patterns: &[], + hierarchical: &[], }, extra_interfaces, &packages, @@ -422,6 +439,27 @@ impl Source { type_parameters::bind(syntax_tree, &own_types)?; imported.pattern_parameter_bindings = type_parameters::bind_patterns(syntax_tree, bindings.patterns)?; + // A hierarchical name reads and writes the local signal + // bound to the other instance's object. + for signal in bindings.hierarchical { + for path in &signal.paths { + imported + .interface_members + .insert(path.clone(), signal.name.clone()); + } + if signal.local { + imported.local_aliases.extend(signal.paths.iter().cloned()); + continue; + } + imported.state_signals.push(Signal { + is_const: false, + name: signal.name.clone(), + r#type: signal.r#type.clone(), + is_net: signal.is_net, + package_variable: None, + hierarchical: signal.paths.first().cloned(), + }); + } if let Some(mut module) = interface_binding::analyze_module( syntax_tree, path, @@ -1050,6 +1088,7 @@ impl Module { // declarations (IEEE 1800-2023 27.6, 23.9). let scope_heads: HashSet<&str> = signals .iter() + .filter(|signal| signal.hierarchical.is_none()) .map(Signal::name) .chain(instances.iter().map(Instance::name)) .filter_map(generate_scope_head) @@ -1349,6 +1388,7 @@ impl Module { ff_processes: ff_processes.clone(), aliases: imported.aliases.clone(), interface_members: imported.interface_members.clone(), + local_aliases: imported.local_aliases.clone(), interface_types: imported.interface_types.clone(), interface_arrays: imported.interface_arrays.clone(), interface_scopes: imported.interface_scopes.clone(), @@ -1729,6 +1769,9 @@ pub struct Signal { is_net: bool, /// The package variable the signal denotes, as `(package, variable)`. package_variable: Option<(String, String)>, + /// The hierarchical name of the signal of another instance the signal + /// denotes (IEEE 1800-2023 23.6). + hierarchical: Option, } impl Signal { @@ -1739,6 +1782,7 @@ impl Signal { is_net: false, is_const: false, package_variable: None, + hierarchical: None, } } @@ -1749,9 +1793,16 @@ impl Signal { is_net: true, is_const: false, package_variable: None, + hierarchical: None, } } + /// The hierarchical name of the signal of another instance the signal + /// denotes, as written. + pub fn hierarchical(&self) -> Option<&str> { + self.hierarchical.as_deref() + } + /// The package variable (IEEE 1800-2023 26.2) the signal denotes, as /// `(package, variable)`: every module that uses it shares that object. pub fn package_variable(&self) -> Option<(&str, &str)> { @@ -2052,6 +2103,36 @@ impl Type { pub fn unpacked_ranges(&self) -> &[UnpackedRange] { &self.unpacked_ranges } + + /// How many leading packed dimensions select an element of a signed + /// named type (IEEE 1800-2023 7.4.1). + pub fn signed_element_depth(&self) -> Option { + self.signed_element_depth + } + + /// A type with constant `(left, right)` packed and unpacked bounds. + pub fn resolved( + kind: TypeKind, + is_signed: bool, + signed_element_depth: Option, + packed: &[(i128, i128)], + unpacked: &[(i128, i128)], + ) -> Self { + let literal = |value: i128| ConstExpr::Literal(value.to_string()); + Self { + is_signed, + signed_element_depth, + packed_ranges: packed + .iter() + .map(|&(left, right)| PackedRange::new(literal(left), literal(right))) + .collect(), + unpacked_ranges: unpacked + .iter() + .map(|&(left, right)| UnpackedRange::new(literal(left), literal(right))) + .collect(), + ..Self::new(kind) + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 0c42bc267c0..16cbbb7cb00 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -475,6 +475,7 @@ pub(super) fn analyze_module( is_net: port.is_net, is_const: false, package_variable: None, + hierarchical: None, }; module.symbols.as_mut().unwrap().signals.push(signal); let Some(connection) = connections @@ -748,8 +749,8 @@ pub(super) fn analyze_module( // Check authored declarations before module collection can prefer a local // function/type/constant over an imported interface binding of the same name. let authored = imports::scope_names(tree)?; - for bound in imported.interface_members.values() { - if authored.contains(bound) { + for (path, bound) in &imported.interface_members { + if authored.contains(bound) && !imported.local_aliases.contains(path) { return Err(unsupported(format!( "interface binding collides with declaration `{bound}`" ))); diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 18b69492bd8..c5b420aa162 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -112,6 +112,15 @@ impl Package { } impl Packages { + /// The authored name of module `name`, which differs for a + /// specialization of a module with generic interface ports. + pub fn authored_module_name<'a>(&'a self, name: &'a str) -> &'a str { + self.interface_plan + .modules + .get(name) + .map_or(name, |plan| plan.original.as_str()) + } + /// Global simulation precision, as a power of ten seconds (IEEE 1800-2023 3.14.3). pub fn global_time_precision(&self) -> i32 { self.timescales.global_precision() diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index e9f47900bf7..6a2b2ac2a71 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -27,6 +27,21 @@ pub(super) fn bind_interface_path( false } +/// A path that starts at no variable or interface of the scope is a +/// hierarchical name of another scope (IEEE 1800-2023 23.6). +fn unknown_member( + path: &[String], + bound_interface: bool, + dimensions: &PackedDimensions, +) -> AnalyzerError { + if !bound_interface && dimensions.get(&path[0]).is_none() { + return AnalyzerError::HierarchicalReference { + path: path.join("."), + }; + } + unsupported(format!("structure member `{}`", path.join("."))) +} + fn selected_member<'a>( path: &[String], dimensions: &'a PackedDimensions, @@ -125,7 +140,7 @@ pub(in crate::ast) fn whole_member( return Ok(LValue::Ident(path[0].clone())); } let (offset, ty) = selected_member(&path, dimensions) - .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; + .ok_or_else(|| unknown_member(&path, bound_interface, dimensions))?; finish_lvalue( state, &path, @@ -159,7 +174,7 @@ pub(in crate::ast) fn select_member( return select(path[0].clone(), dimensions, false); } let (offset, ty) = selected_member(&path, dimensions) - .ok_or_else(|| unsupported(format!("structure member `{}`", path.join("."))))?; + .ok_or_else(|| unknown_member(&path, bound_interface, dimensions))?; let relative = select( path[0].clone(), &member_dimensions(&path[0], ty, dimensions), diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 62b0e4857b7..70106aa411e 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -49,6 +49,9 @@ pub(super) struct ScopeSymbols { pub aliases: HashMap, /// Hierarchical interface member paths bound to semantic signal names. pub interface_members: HashMap, + /// The paths of `interface_members` that are hierarchical names of the + /// scope's own declarations. + pub local_aliases: HashSet, pub interface_types: HashMap, pub interface_arrays: HashMap, pub interface_scopes: HashMap, @@ -422,6 +425,7 @@ impl ScopeSymbols { .iter() .map(|(path, name)| (path.clone(), rename.name(name))) .collect(), + local_aliases: self.local_aliases.clone(), type_parameter_bindings: self.type_parameter_bindings.clone(), pattern_parameter_bindings: self.pattern_parameter_bindings.clone(), const_env, diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 21ca3735bbf..32df6c7df93 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -396,6 +396,7 @@ pub struct Signal { r#type: Type, is_net: bool, package_variable: Option<(String, String)>, + hierarchical: Option, } impl Signal { @@ -405,9 +406,23 @@ impl Signal { r#type, is_net, package_variable: None, + hierarchical: None, } } + pub(crate) fn with_hierarchical(mut self, hierarchical: Option<&str>) -> Self { + self.hierarchical = hierarchical.map(str::to_string); + self + } + + /// The hierarchical name (IEEE 1800-2023 23.6) of the signal of another + /// instance the signal denotes: the module reads and writes that object, + /// bound by the caller that resolved the name (see + /// [`crate::ast::HierarchicalSignal`]). + pub fn hierarchical(&self) -> Option<&str> { + self.hierarchical.as_deref() + } + pub(crate) fn with_package_variable(mut self, package_variable: Option<(&str, &str)>) -> Self { self.package_variable = package_variable.map(|(package, variable)| (package.to_string(), variable.to_string())); @@ -680,10 +695,17 @@ pub struct Type { packed_ranges: Vec, unpacked_ranges: Vec, resolved_width: Option, + signed_element_depth: Option, class: Option, } impl Type { + /// How many leading packed dimensions select an element of a signed + /// named type (IEEE 1800-2023 7.4.1). + pub fn signed_element_depth(&self) -> Option { + self.signed_element_depth + } + /// Nominal identity of a tagged union, retained for port type checking. pub fn tagged_identity(&self) -> Option<&str> { self.tagged_identity.as_deref() @@ -772,6 +794,7 @@ impl Type { let kind = r#type.kind().into(); let is_signed = r#type.is_signed(); let class = r#type.class().map(str::to_owned); + let signed_element_depth = r#type.signed_element_depth(); let (packed_ranges, unpacked_ranges, resolved_width) = convert_type(r#type, constants); Self { tagged_identity, @@ -780,6 +803,7 @@ impl Type { packed_ranges, unpacked_ranges, resolved_width, + signed_element_depth, class, } } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index d6d6b598f7a..19ec606ecd2 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -66,6 +66,11 @@ pub enum AnalyzerError { Parse(String), #[error("Unsupported SystemVerilog construct: {0}")] Unsupported(String), + /// A dotted name whose first component names no variable or interface + /// of the scope: a hierarchical name (IEEE 1800-2023 23.6) that the + /// caller did not resolve to a signal of another instance. + #[error("unresolved hierarchical reference `{path}`")] + HierarchicalReference { path: String }, /// A delay, event control or wait statement in a function, an /// `always_comb` or an `always_ff` body (IEEE 1800-2023 9.2.2.2, /// 9.2.2.4, 13.4). diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index d3706a66139..102832162c1 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -22,6 +22,14 @@ pub struct ParsedSource { warnings: HashMap>, } +/// What a module analysis lowers. +#[derive(Clone, Copy)] +enum ModuleAnalysis<'a> { + /// The whole module, with the signals its hierarchical names denote. + Full(&'a [ast::HierarchicalSignal]), + DeclarationsOnly, +} + impl ParsedSource { pub fn parse(code: &str, path: &Path) -> Result { let tree = source_tree::parse_source(code, path)?; @@ -209,9 +217,126 @@ impl ParsedSource { pattern_overrides, interfaces, packages, + ModuleAnalysis::Full(&[]), + ) + } + + /// [`Self::analyze_module`] for a module whose hierarchical names + /// denote `hierarchical`, signals of other instances. + #[allow(clippy::too_many_arguments)] + pub fn analyze_module_with_hierarchy( + &self, + module_name: &str, + overrides: &HashMap, + type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], + interfaces: &ModuleInterfaces, + packages: &Packages, + hierarchical: &[ast::HierarchicalSignal], + ) -> Result { + self.analyze_module_with_packages( + module_name, + overrides, + type_overrides, + pattern_overrides, + interfaces, + packages, + ModuleAnalysis::Full(hierarchical), ) } + /// The declarations and instances of a specialization, without its + /// procedures, for elaborating the hierarchy below a module before its + /// hierarchical names are resolved. + pub fn analyze_module_hierarchy( + &self, + module_name: &str, + overrides: &HashMap, + type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], + interfaces: &ModuleInterfaces, + packages: &Packages, + ) -> Result { + self.analyze_module_with_packages( + module_name, + overrides, + type_overrides, + pattern_overrides, + interfaces, + packages, + ModuleAnalysis::DeclarationsOnly, + ) + } + + /// The dotted names `a.b.c` written in module `module_name`, the + /// candidates for hierarchical names (IEEE 1800-2023 23.6), as their + /// normalized components. A constant decimal index of a component other + /// than the last stays part of it, as in `u[1]`. Callers decide which + /// names denote another instance's signal. A specialization of a module + /// with generic interface ports is scanned in its authored module. + pub fn hierarchical_names(&self, module_name: &str, packages: &Packages) -> Vec> { + use celox_sv_syntax::TokenKind; + let original = packages.authored_module_name(module_name); + let mut names = Vec::new(); + for scope in self.index.scopes(original) { + let Ok(unit) = scope.root_unit() else { + continue; + }; + let tokens = &scope.declarations().tokens; + let significant: Vec<_> = tokens[unit.tokens.range()] + .iter() + .filter(|token| !token.is_trivia()) + .collect(); + let is_name = |index: usize| { + significant.get(index).is_some_and(|token| { + matches!( + token.kind, + TokenKind::Identifier | TokenKind::EscapedIdentifier + ) || (token.kind == TokenKind::SystemIdentifier && token.text == "$root") + }) + }; + let text = |index: usize| significant.get(index).map(|token| token.text.as_str()); + for start in 0..significant.len() { + if !is_name(start) + || start + .checked_sub(1) + .and_then(text) + .is_some_and(|previous| previous == "." || previous == "::") + { + continue; + } + let mut components = vec![ast::normalize_identifier(&significant[start].text)]; + let mut at = start + 1; + loop { + if text(at) == Some("[") + && significant + .get(at + 1) + .is_some_and(|token| token.kind == TokenKind::Number) + && text(at + 2) == Some("]") + && text(at + 3) == Some(".") + && let Ok(index) = text(at + 1).unwrap().replace('_', "").parse::() + { + components + .last_mut() + .unwrap() + .push_str(&format!("[{index}]")); + at += 3; + } + if text(at) == Some(".") && is_name(at + 1) { + components.push(ast::normalize_identifier(&significant[at + 1].text)); + at += 2; + } else { + break; + } + } + if components.len() > 1 && !names.contains(&components) { + names.push(components); + } + } + } + names + } + /// Inspect declaration shapes without lowering procedures or tasks. /// The returned IR is metadata for tooling, not an executable simulation. pub fn analyze_module_declarations( @@ -235,6 +360,7 @@ impl ParsedSource { values: &overrides, types: &[], patterns: &[], + hierarchical: &[], }, &ModuleInterfaces::default(), packages, @@ -251,7 +377,15 @@ impl ParsedSource { interfaces: &ModuleInterfaces, ) -> Result { let packages = Self::analyze_packages(&[self])?; - self.analyze_module_with_packages(module_name, overrides, &[], &[], interfaces, &packages) + self.analyze_module_with_packages( + module_name, + overrides, + &[], + &[], + interfaces, + &packages, + ModuleAnalysis::Full(&[]), + ) } fn validate_module_namespace( @@ -274,6 +408,7 @@ impl ParsedSource { Ok(()) } + #[allow(clippy::too_many_arguments)] fn analyze_module_with_packages( &self, module_name: &str, @@ -282,16 +417,13 @@ impl ParsedSource { pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, + analysis: ModuleAnalysis<'_>, ) -> Result { let overrides = overrides .iter() .map(|(name, value)| (name.clone(), value.clone().into())) .collect(); - let original = packages - .interface_plan - .modules - .get(module_name) - .map_or(module_name, |plan| plan.original.as_str()); + let original = packages.authored_module_name(module_name); let warnings = self.warnings.get(original).cloned().unwrap_or_default(); let ir = (|| { self.validate_module_namespace(original, packages)?; @@ -301,10 +433,14 @@ impl ParsedSource { &self.index, module_name, ast::ModuleParameterBindings { - declarations_only: false, + declarations_only: matches!(analysis, ModuleAnalysis::DeclarationsOnly), values: &overrides, types: type_overrides, patterns: pattern_overrides, + hierarchical: match analysis { + ModuleAnalysis::Full(hierarchical) => hierarchical, + ModuleAnalysis::DeclarationsOnly => &[], + }, }, interfaces, packages, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 94290b6f9ef..19cb12d383a 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -584,7 +584,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_urandom_narrow_seed` | execute | icarus | 1 | Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks. | | `sv_verilator_random_algorithm` | execute | verilator | 2 | Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator. | | `sv_verilator_time_in_combinational_logic` | execute | verilator | 1 | Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one. | -| `sv_verilator_intermediate_writes` | execute | verilator | 7 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. | +| `sv_verilator_intermediate_writes` | execute | verilator | 8 | Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. [Standalone probes](verification/repros/sv_intermediate_writes_verilator.json) print the spec counts in Icarus 13.0 and 1 or 0 in Verilator. | | `sv_icarus_port_pulses` | execute | icarus | 1 | Icarus 13.0 collapses a child's output port with the parent's net, so a waiter in the parent sees each value the child's always_comb writes inside one evaluation and counts 3 instead of 1. Both are conforming: the port is a continuous assignment (IEEE 1800-2023 23.3.3), evaluated after the child's process yields, and 4.7 leaves that order open. The case asserts the settled count, which Verilator 5.052 and Celox give. The [standalone probe](verification/repros/sv_port_pulses_icarus.json) retains both outputs. | | `sv_verilator_active_region_waiters` | execute | verilator | 2 | Verilator 5.052 resumes a process woken by a blocking write of an edge-triggered process only after the same edge's nonblocking updates: with `y = ~y; q <= q + 1;` a waiter on `@(y)` reads the updated q, and with `y = 1; y <= 0; y <= 1;` from 0 it does not wait again before the nonblocking updates and counts 1 instead of 3. IEEE 1800-2023 4.5 makes the blocking write an update event of the active region and enters the NBA region only when the active and inactive regions are empty, so the waiter runs first (9.4.2). [Standalone probes](verification/repros/sv_active_region_waiters_verilator.json) print the spec values in Icarus 13.0 and the post-NBA values in Verilator. | | `sv_program_reactive_region` | execute | icarus, verilator | 10 | Verilator 5.052 and Icarus 13.0 run program procedures in the active region set: a program reads design values before the design's nonblocking updates of the time slot, its `#0` resumes before the design's, and a flip-flop clocked by a program write runs before the program's `#0` and its nonblocking update of the flip-flop's input. IEEE 1800-2023 24.3.1 schedules program procedures in the Reactive region, `#0` in the Re-Inactive region and their nonblocking updates in the Re-NBA region, and 4.5 empties the reactive region set before the active region set runs again. xezim 0.11.3 agrees with every case except the flip-flop one, where it also runs the flip-flop first. The pre-exclusion results are [Icarus](verification/sv/limitations/programs-icarus.json) and [Verilator](verification/sv/limitations/programs-verilator.json). | diff --git a/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest b/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest new file mode 100644 index 00000000000..6f9d257fce0 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest @@ -0,0 +1,490 @@ +(group hierarchical_references (category hierarchy)) + +; Downward hierarchical names (IEEE 1800-2023 23.6) read nets and variables +; of instances below the referencing module. +(case reads_signals_of_instances_below + (source "downward_reads.sv" #" + module Leaf(input logic [7:0] a, output logic [7:0] y); + logic [7:0] doubled; + assign doubled = a << 1; + assign y = doubled + 8'd1; + endmodule + module Mid(input logic [7:0] a, output logic [7:0] y); + wire [7:0] inner = a ^ 8'h0f; + Leaf leaf(.a(inner), .y(y)); + endmodule + module Top; + logic clk = 0; + logic [7:0] a = 8'd3; + logic [7:0] y; + logic [7:0] seen; + Mid mid(.a(a), .y(y)); + always #5 clk = ~clk; + always @(posedge clk) seen <= mid.leaf.doubled; + initial begin + #1 $display("inner=%0d doubled=%0d low=%0d", mid.inner, mid.leaf.doubled, + mid.leaf.doubled[3:0]); + a = 8'd5; + #10 $display("seen=%0d y=%0d", seen, Top.mid.leaf.y); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "inner=12 doubled=24 low=8\nseen=20 y=21\n")) + +; Procedural assignments through hierarchical names write variables of other +; instances, including element bit selects of unpacked arrays, alongside the +; writes of the instance's own processes. +(case writes_memory_elements_of_instances_below + (source "downward_writes.sv" #" + module Ram #(parameter W = 2, parameter A = 2)(input logic clk, input logic we, + input logic [A-1:0] addr, input logic [W-1:0] d, output logic [W-1:0] q); + logic [W-1:0] mem [(2**A)-1:0]; + always @(posedge clk) begin + if (we) mem[addr] <= d; + q <= mem[addr]; + end + endmodule + module Banks(input logic clk, input logic we, input logic [2:0] addr, + input logic [15:0] d, output logic [15:0] q); + Ram #(.W(8), .A(3)) lo(.clk(clk), .we(we), .addr(addr), .d(d[7:0]), .q(q[7:0])); + Ram #(.W(8), .A(3)) hi(.clk(clk), .we(we), .addr(addr), .d(d[15:8]), .q(q[15:8])); + endmodule + module Top; + logic clk = 0; + logic we = 0; + logic [2:0] addr = 0; + logic [15:0] d = 0; + logic [15:0] q; + integer i; + Banks banks(.clk(clk), .we(we), .addr(addr), .d(d), .q(q)); + always #5 clk = ~clk; + initial begin + for (i = 0; i < 8; i = i + 1) begin + Top.banks.lo.mem[i][7:0] = 8'h10 + i; + banks.hi.mem[i] = 8'h80 + i; + end + banks.hi.mem[7][3:0] = 4'h0; + addr = 3'd6; + @(posedge clk) #1 $display("q=%h", q); + we = 1; addr = 3'd2; d = 16'hbeef; + @(posedge clk) #1 we = 0; + $display("lo2=%h hi2=%h hi7=%h", banks.lo.mem[2], banks.hi.mem[2], + banks.hi.mem[7]); + banks.lo.mem[2] = 8'h5a; + @(posedge clk) #1 $display("q=%h", q); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "q=8616\nlo2=ef hi2=be hi7=80\nq=be5a\n")) + +; A component may name an element of an instance array or an instance of a +; generate block. +(case names_instance_array_elements_and_generated_instances + (source "scoped_instances.sv" #" + module Cell #(parameter V = 0)(output logic [7:0] y); + logic [7:0] value = V; + assign y = value; + endmodule + module Top; + + logic [7:0] g0, g1; + Cell #(.V(7)) cells [1:0] (.y()); + for (genvar k = 0; k < 2; k++) begin : g + Cell #(.V(20 + k)) c(.y()); + end + initial begin + cells[1].value = 8'd9; + #1 $display("%0d %0d %0d %0d", cells[0].value, cells[1].value, + g[0].c.value, g[1].c.y); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "7 9 20 21\n")) + +; Upward names (IEEE 1800-2023 23.8) start at the module name of an +; enclosing instance; each instance of the referencing module resolves its +; own copy. +(case reads_signals_of_enclosing_instances_by_module_name + (source "upward.sv" #" + module Leaf; + logic [7:0] seen; + logic [7:0] ticks = 8'd0; + always_comb seen = Mid.local_v + Top.base; + always @(posedge Top.clk) ticks <= ticks + 8'd1; + endmodule + module Mid; + logic [7:0] local_v = 8'd5; + Leaf leaf(); + endmodule + module Top; + logic clk = 0; + logic [7:0] base = 8'd40; + Mid m0(); + Mid m1(); + always #5 clk = ~clk; + initial begin + #1 m1.local_v = 8'd6; + #1 $display("%0d %0d", m0.leaf.seen, m1.leaf.seen); + base = 8'd50; + #20 $display("%0d %0d ticks=%0d", m0.leaf.seen, Top.m1.leaf.seen, m1.leaf.ticks); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "45 46\n55 56 ticks=2\n")) + +; Hierarchical blocking writes from another module's processes in the time +; step of a nonblocking element write: those to other elements, or before the +; nonblocking update to the same element, keep their effect (IEEE 1800-2023 +; 4.4.2.2, 10.4.2). +(case foreign_writes_interleave_with_nonblocking_element_writes + (source "foreign_writes.sv" #" + module A(input logic clk, input logic we, input logic [1:0] wa, input logic [7:0] wd); + logic [7:0] mem [4]; + always @(posedge clk) if (we) mem[wa] <= wd; + endmodule + module Top; + logic clk = 0; + logic we = 0; + logic [1:0] wa = 0; + logic [7:0] wd = 0; + A a(.clk(clk), .we(we), .wa(wa), .wd(wd)); + always #5 clk = ~clk; + always @(posedge clk) if (we) a.mem[3][3:0] = 4'h5; + initial begin + for (int i = 0; i < 4; i++) a.mem[i] = 8'h10 * i; + we = 1; wa = 1; wd = 8'haa; + @(posedge clk); + a.mem[1][7:4] = 4'hf; + a.mem[2] = 8'h77; + #1 $display("%h %h %h %h", a.mem[0], a.mem[1], a.mem[2], a.mem[3]); + wa = 2; wd = 8'hbb; + @(posedge clk); + a.mem[0][0] = 1'b1; + #1 we = 0; + $display("%h %h %h %h", a.mem[0], a.mem[1], a.mem[2], a.mem[3]); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "00 aa 77 35\n01 aa bb 35\n")) + +; Modules may write each other's arrays through hierarchical names, here a +; downward and an upward one, next to the nonblocking writes of their own. +(case mutual_hierarchical_writes_next_to_nonblocking_writes + (source "mutual.sv" #" + module B(input logic clk); + logic [7:0] bm [2]; + always @(posedge clk) bm[0] <= bm[0] + 8'd1; + always @(posedge clk) A.am[1] = bm[0]; + endmodule + module A(input logic clk); + logic [7:0] am [2]; + B b(.clk(clk)); + always @(posedge clk) am[0] <= am[0] + 8'd2; + always @(posedge clk) b.bm[1] = am[0]; + endmodule + module Top; + logic clk = 0; + A a(.clk(clk)); + always #5 clk = ~clk; + initial begin + a.am[0] = 0; a.am[1] = 0; a.b.bm[0] = 0; a.b.bm[1] = 0; + #16 $display("%0d %0d %0d %0d", a.am[0], a.am[1], a.b.bm[0], a.b.bm[1]); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "4 1 2 2\n")) + +; A hierarchical blocking write of some bits of an element keeps its effect +; when a nonblocking write of other bits of the same element follows it in +; the time step. +(case foreign_bit_writes_survive_nonblocking_writes_of_other_bits + (source "same_element.sv" #" + module A(input logic clk); + logic [7:0] mem [4]; + always @(posedge clk) mem[3][7:4] <= 4'ha; + endmodule + module Top; + logic clk = 0; + A a(.clk(clk)); + always #5 clk = ~clk; + always @(posedge clk) a.mem[3][3:0] = 4'h5; + initial begin + a.mem[3] = 8'h00; + @(posedge clk); + #1 $display("%h", a.mem[3]); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "a5\n")) + +; The index of an instance array element in a hierarchical name is a +; constant expression (IEEE 1800-2023 23.6), here a local parameter and a +; sized literal. +(case names_instance_array_elements_by_constant_expressions + (source "constant_indices.sv" #" + module Cell; + logic [7:0] value = 8'd3; + endmodule + module Top; + localparam IDX = 1; + Cell cells [1:0] (); + initial begin + cells[IDX].value = 8'd9; + #1 $display("%0d %0d", cells[1'b1].value, cells[IDX - 1].value); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "9 3\n")) + +; The declaration initializer of a variable takes effect before any initial +; procedure starts (IEEE 1800-2023 6.8), so an initial write through a +; hierarchical name overrides it. +(case initial_writes_through_names_follow_declaration_initializers + (source "initial_order.sv" #" + module Child; + logic [7:0] v = 8'd1; + endmodule + module Top; + Child c(); + initial c.v = 8'd5; + initial begin + #1 $display("%0d", c.v); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "5\n")) + +; An upward name resolves in the instance that encloses each referencing +; instance, also when those instances have different parameter values. +(case upward_names_resolve_in_each_parameterized_parent + (source "upward_parameterized.sv" #" + module Leaf; + logic [7:0] seen; + always_comb seen = Mid.local_v + 8'd1; + endmodule + module Mid #(parameter W = 1); + logic [7:0] local_v = W; + logic [W-1:0] other; + Leaf leaf(); + endmodule + module Top; + Mid #(.W(1)) m0(); + Mid #(.W(2)) m1(); + initial begin + #1 $display("%0d %0d", m0.leaf.seen, m1.leaf.seen); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "2 3\n")) + +; A task called from an edge process writes an element of another +; instance's array through a hierarchical name, next to that instance's +; nonblocking writes of other elements. +(case subroutines_write_through_hierarchical_names + (source "task_writes.sv" #" + module A(input logic clk, input logic we, input logic [1:0] wa, input logic [7:0] wd); + logic [7:0] mem [4]; + always @(posedge clk) if (we) mem[wa] <= wd; + endmodule + module Top; + logic clk = 0; + logic we = 0; + logic [1:0] wa = 0; + logic [7:0] wd = 0; + A a(.clk(clk), .we(we), .wa(wa), .wd(wd)); + task automatic poke; + a.mem[3][3:0] = 4'h5; + endtask + always #5 clk = ~clk; + always @(posedge clk) if (we) poke(); + initial begin + for (int i = 0; i < 4; i++) a.mem[i] = 8'h10 * i; + we = 1; + wa = 1; + wd = 8'haa; + @(posedge clk); + #1 $display("%h %h %h %h", a.mem[0], a.mem[1], a.mem[2], a.mem[3]); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "00 aa 20 35\n")) + +; A write through a hierarchical name from an inactive-region resumption +; (`#0`) lands between the evaluation of an edge process and the NBA region +; that publishes its nonblocking bit write, which then updates only that bit +; (IEEE 1800-2023 4.4.2.3, 10.4.2). +(case foreign_inactive_writes_precede_nonblocking_bit_writes + (source "inactive_window.sv" #" + module C(input logic clk, input logic [2:0] idx); + logic [7:0] q = 8'd0; + always @(posedge clk) q[idx] <= 1'b1; + endmodule + module Top; + logic clk = 0; + logic [2:0] idx = 3'd7; + C c(.clk(clk), .idx(idx)); + always #5 clk = ~clk; + initial begin + @(posedge clk); + #0 c.q[0] = 1'b1; + #1 $display("%h", c.q); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "81\n")) + +; A wait through a hierarchical name sees every store to the variable it +; names, including one a later store of the same always_comb evaluation +; overwrites (IEEE 1800-2023 4.3, 9.4.2), as a wait in the module does. +(case waits_through_names_see_intermediate_combinational_writes + (source "intermediate.sv" #" + module Child; + logic c = 0; + logic [7:0] a = 8'h15, b = 8'h1, y; + always_comb begin y = 8'h0; if (c && b != 8'h9) y = a; end + initial begin + #2 c = 1; + #1 a = 8'h16; + #1 b = 8'h2; + end + endmodule + module Top; + int n; + Child child(); + initial #1 forever begin @(child.y); n++; end + initial begin + #5 $display("y=%h n=%0d", child.y, n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "y=16 n=3\n")) + +; Passing a hierarchical name to an input argument of a task reads the +; object; it neither drives the net nor writes the variable. +(case input_arguments_read_through_hierarchical_names + (source "input_arguments.sv" #" + module C(input logic [7:0] a); + wire [7:0] n = 8'd3; + logic [7:0] v; + assign v = a + 8'd1; + endmodule + module Top; + logic [7:0] a = 8'd4; + C c(.a(a)); + task automatic show(input logic [7:0] x, input logic [7:0] y); + $display("%0d %0d", x, y); + endtask + initial begin + #1 show(c.n, c.v); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "3 5\n")) + +; A name that starts at the module's own name denotes the module's own +; signal (IEEE 1800-2023 23.8), so a read through it sees a blocking write +; of the same process. +(case names_from_the_module_name_denote_its_own_signals + (source "own_name.sv" #" + module Top; + logic clk = 0; + logic [7:0] q = 8'd0, r = 8'd0, p = 8'd0, s = 8'd0; + always @(posedge clk) begin q = 8'd1; r <= Top.q; end + always_ff @(posedge clk) begin p = 8'd2; s <= Top.p; end + initial begin + #1 clk = 1; + #1 $display("%0d %0d", r, s); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "1 2\n")) + +; Names in generate branches that are not elaborated need not resolve to a +; supported signal. +(case names_in_inactive_generate_branches_are_ignored + (source "inactive_branches.sv" #" + module C; + bit v = 1; + real r = 1.5; + endmodule + module Top; + C c(); + initial begin + #1 $display("%0d", c.v); + $finish; + end + if (0) begin : g + initial $display("%f", c.r); + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "1\n")) + +; An element of a packed array of a signed named type is signed although +; the array is not (IEEE 1800-2023 7.4.1), also through a hierarchical name. +(case signed_elements_through_hierarchical_names + (source "signed_elements.sv" #" + module C; + typedef logic signed [3:0] nibble_t; + nibble_t [1:0] a = 8'h80; + endmodule + module Top; + C c(); + logic [15:0] x; + initial begin + #1 x = c.a[1]; + $display("%h", x); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "fff8\n")) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index d9dda2a25ce..b47bdb76bb8 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -79,6 +79,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/generate.vtest", text: include_str!("generate.vtest"), }, + Group { + file: "src/sv/cases/hierarchical_references.vtest", + text: include_str!("hierarchical_references.vtest"), + }, Group { file: "src/sv/cases/hierarchy.vtest", text: include_str!("hierarchy.vtest"), diff --git a/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json index d34cf8fbc9f..0f03b47c5e4 100644 --- a/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json +++ b/crates/celox-test-suite/verification/repros/sv_intermediate_writes_verilator.json @@ -139,6 +139,29 @@ "exit_code": 0, "output": "y=01 r=2\n/probe.sv:7: $finish called at 4 (1s)\n" } + }, + { + "name": "hierarchical_wait", + "note": "The suite case waits_through_names_see_intermediate_combinational_writes.", + "source": "module Child;\n logic c = 0;\n logic [7:0] a = 8'h15, b = 8'h1, y;\n always_comb begin y = 8'h0; if (c && b != 8'h9) y = a; end\n initial begin\n #2 c = 1;\n #1 a = 8'h16;\n #1 b = 8'h2;\n end\nendmodule\nmodule Top;\n int n;\n Child child();\n initial #1 forever begin @(child.y); n++; end\n initial begin\n #5 $display(\"y=%h n=%0d\", child.y, n);\n $finish;\n end\nendmodule\n", + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "y=16 n=2\n- /probe.sv:17: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 5ps; walltime 0.000 s; speed 134.481 ns/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "y=16 n=3\n/probe.sv:17: $finish called at 5 (1s)\n" + } } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index fe1ffd7e92f..e9f97a5cddb 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2012,7 +2012,8 @@ "timing::intermediate_combinational_writes_keep_other_drivers", "timing::parallel_flip_flop_parts_keep_pulses", "timing::staged_nonblocking_writes_follow_later_blocking_writes", - "timing::derived_clocks_follow_superseded_publications" + "timing::derived_clocks_follow_superseded_publications", + "hierarchical_references::waits_through_names_see_intermediate_combinational_writes" ] } }, diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index c60badcb104..47395f55d5a 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -3,6 +3,7 @@ "verilator/always_comb.json", "verilator/class.json", "verilator/generate.json", + "verilator/hierarchical_references.json", "verilator/hierarchy.json", "verilator/indexed_select.json", "verilator/interfaces.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/hierarchical_references.json b/crates/celox-test-suite/verification/sv/verilator/hierarchical_references.json new file mode 100644 index 00000000000..08e39e56544 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/hierarchical_references.json @@ -0,0 +1,27 @@ +{ + "cases": [ + { + "category": "Hierarchy", + "detail": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_intermediate_writes_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_intermediate_writes", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 wakes a process waiting on a variable only for the value an evaluation leaves: an always_comb or edge-triggered body that rewrites a variable 1 -> 0 -> 1, and nonblocking updates `y <= 0; y <= 1;` from 1, wake no waiter, nor does a pulse that one always_ff writes to some bits of a variable while other processes write its other bits, or a nonblocking update that rises from the final blocking value. IEEE 1800-2023 4.3 and 9.4.2 make every store an update event that triggers the waiter, and 10.4.2 applies nonblocking updates in issue order, each its own update. Standalone probes print the spec counts in Icarus 13.0 and 1 or 0 in Verilator.", + "upstream": [] + }, + "name": "hierarchical_references::waits_through_names_see_intermediate_combinational_writes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs b/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs new file mode 100644 index 00000000000..828aca9bfa2 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs @@ -0,0 +1,212 @@ +use super::*; + +sv_backends! { + fn reads_signals_of_instances_below(sim) { + @case "hierarchical_references::reads_signals_of_instances_below"; + } + fn writes_memory_elements_of_instances_below(sim) { + @case "hierarchical_references::writes_memory_elements_of_instances_below"; + } + fn names_instance_array_elements_and_generated_instances(sim) { + @case "hierarchical_references::names_instance_array_elements_and_generated_instances"; + } + fn reads_signals_of_enclosing_instances_by_module_name(sim) { + @case "hierarchical_references::reads_signals_of_enclosing_instances_by_module_name"; + } + fn foreign_writes_interleave_with_nonblocking_element_writes(sim) { + @case "hierarchical_references::foreign_writes_interleave_with_nonblocking_element_writes"; + } + fn mutual_hierarchical_writes_next_to_nonblocking_writes(sim) { + @case "hierarchical_references::mutual_hierarchical_writes_next_to_nonblocking_writes"; + } + fn foreign_bit_writes_survive_nonblocking_writes_of_other_bits(sim) { + @case "hierarchical_references::foreign_bit_writes_survive_nonblocking_writes_of_other_bits"; + } + fn names_instance_array_elements_by_constant_expressions(sim) { + @case "hierarchical_references::names_instance_array_elements_by_constant_expressions"; + } + fn initial_writes_through_names_follow_declaration_initializers(sim) { + @case "hierarchical_references::initial_writes_through_names_follow_declaration_initializers"; + } + fn upward_names_resolve_in_each_parameterized_parent(sim) { + @case "hierarchical_references::upward_names_resolve_in_each_parameterized_parent"; + } + fn subroutines_write_through_hierarchical_names(sim) { + @case "hierarchical_references::subroutines_write_through_hierarchical_names"; + } + fn foreign_inactive_writes_precede_nonblocking_bit_writes(sim) { + @case "hierarchical_references::foreign_inactive_writes_precede_nonblocking_bit_writes"; + } + fn waits_through_names_see_intermediate_combinational_writes(sim) { + @case "hierarchical_references::waits_through_names_see_intermediate_combinational_writes"; + } + fn input_arguments_read_through_hierarchical_names(sim) { + @case "hierarchical_references::input_arguments_read_through_hierarchical_names"; + } + fn names_from_the_module_name_denote_its_own_signals(sim) { + @case "hierarchical_references::names_from_the_module_name_denote_its_own_signals"; + } + fn names_in_inactive_generate_branches_are_ignored(sim) { + @case "hierarchical_references::names_in_inactive_generate_branches_are_ignored"; + } + fn signed_elements_through_hierarchical_names(sim) { + @case "hierarchical_references::signed_elements_through_hierarchical_names"; + } +} + +fn displayed(source: &str) -> Vec { + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("hier.sv"))], "Top") + .build_cranelift() + .unwrap(); + sim.run_until(1_000_000).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Display { message } => Some(String::from_utf8(message).unwrap()), + _ => None, + }) + .collect() +} + +fn build_error(source: &str) -> String { + Simulator::from_sv_sources(vec![(source, Path::new("hier.sv"))], "Top") + .build_cranelift() + .expect_err("the design must be rejected") + .to_string() + // The report wraps long messages. + .replace('│', " ") + .split_whitespace() + .collect::>() + .join(" ") +} + +// `$root` names the top instance from anywhere in the hierarchy (IEEE +// 1800-2023 23.3.1), including as an edge event of a flip-flop. +#[test] +fn root_names_start_at_the_top_instance() { + let source = r#" + `timescale 1ns/1ns + module Leaf; + logic [7:0] ticks = 8'd0; + always @(posedge $root.Top.clk) ticks <= ticks + 8'd1; + endmodule + module Top; + logic clk = 0; + Leaf l0(); + Leaf l1(); + always #5 clk = ~clk; + initial begin + #22 $display("%0d %0d", $root.Top.l0.ticks, l1.ticks); + $finish; + end + endmodule + "#; + assert_eq!(displayed(source), ["2 2"]); +} + +#[test] +fn rejects_unsupported_hierarchical_drivers_by_name() { + let child = "module Child; logic [7:0] v; wire [7:0] n = 8'd3; endmodule"; + let error = build_error(&format!( + "{child} module Top(input logic [7:0] a); Child c(); assign c.v = a; endmodule" + )); + assert!( + error.contains("continuous assignment to a variable through hierarchical name `c.v`"), + "{error}" + ); + let error = build_error(&format!( + "{child} module Top; Child c(); initial c.n = 8'd1; endmodule" + )); + assert!( + error.contains("driver of a net through hierarchical name `c.n`"), + "{error}" + ); +} + +#[test] +fn rejects_names_that_denote_no_signal() { + let error = build_error( + "module Child; logic v; endmodule \ + module Top; logic y; Child c(); initial y = c.missing; endmodule", + ); + assert!( + error.contains("unresolved hierarchical reference `c.missing`"), + "{error}" + ); +} + +#[test] +fn rejects_hierarchical_writes_next_to_exclusive_drivers() { + let error = build_error( + "module C(input logic [7:0] a); logic [7:0] v; assign v = a; endmodule \ + module Top; logic [7:0] a = 1; C c(.a(a)); initial #1 c.v = 8'd5; endmodule", + ); + assert!( + error.contains("which another module writes through a hierarchical name: its module drives it continuously"), + "{error}" + ); + let error = build_error( + "module C(input logic clk); logic [7:0] v = 0; always @(posedge clk) v <= v + 1; endmodule \ + module Top; logic clk = 0; C c(.clk(clk)); always_ff @(posedge clk) c.v <= 8'd9; endmodule", + ); + assert!(error.contains("an always_ff process writes it"), "{error}"); + // Two repeating writers of one packed variable would lose bits. + let error = build_error( + "module C(input logic clk, input logic [2:0] idx); logic [7:0] q = 0; \ + always @(posedge clk) q[idx] <= 1'b1; endmodule \ + module Top; logic clk = 0; logic [2:0] idx = 7; C c(.clk(clk), .idx(idx)); \ + always @(posedge clk) c.q[0] = 1'b1; endmodule", + ); + assert!(error.contains("another process writes it too"), "{error}"); +} + +// Names in a module with an interface port resolve in the module as +// written, not in the specialization made for the interface, including +// names that start at its own name. +#[test] +fn names_resolve_below_instances_with_interface_ports() { + let source = r#" + `timescale 1ns/1ns + interface Bus; logic [7:0] d; endinterface + module C; logic [7:0] v = 8'd4; endmodule + module Leaf(interface bus); + C c(); + bit q = 1; + initial #1 $display("%0d %0d", c.v, Leaf.q); + endmodule + module Top; Bus b(); Leaf l(.bus(b)); endmodule + "#; + assert_eq!(displayed(source), ["4 1"]); +} + +// A forced signal that is the target of a hierarchical name stays forceable +// in the specialization the name resolution makes. +#[test] +fn forced_targets_of_hierarchical_names_stay_forceable() { + let source = r#" + `timescale 1ns/1ns + module C; logic [7:0] v = 8'd4; logic [7:0] q = 8'd1; endmodule + module Top; + C c(); + initial #1 $display("%0d %0d", c.v, c.q); + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("hier.sv"))], "Top") + .native_force_support(true) + .signal_access(celox::SignalAccessOptions { + force_signals: vec!["Top.c.q".into()], + ..Default::default() + }) + .build_cranelift() + .unwrap(); + sim.run_until(10).unwrap(); + let displayed: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Display { message } => Some(String::from_utf8(message).unwrap()), + _ => None, + }) + .collect(); + assert_eq!(displayed, ["4 1"]); +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 979045aa957..e33f385b835 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -115,6 +115,8 @@ mod file_core; mod file_io; #[path = "frontends/systemverilog/generate.rs"] mod generate; +#[path = "frontends/systemverilog/hierarchical_references.rs"] +mod hierarchical_references; #[path = "frontends/systemverilog/hierarchy.rs"] mod hierarchy; #[path = "frontends/systemverilog/indexed_select.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index aa944c98e4d..d62c298f673 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -19,6 +19,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) | | Programs | `program` declarations with ports and parameters, instantiated from modules like a module; their `initial` procedures run in the reactive region set (see [Programs](#programs)) | | Generate | `for` (with `genvar`), `if`, `case`; constant expressions including `**` | +| Hierarchical references | reads of nets and variables of other instances, and procedural writes of their variables, including selects of unpacked array elements (`u.mem[i][7:0] = v`), through names that start at an instance of the module (also of a generate block or an instance array element), at the module's own name, at an enclosing module's name (upward) or at `$root`; see [Hierarchical references](#hierarchical-references) | | Packages | types, parameters, enums and functions, through `import p::*;`, `import p::x;` and `p::x` | | Interfaces | interfaces with value and type parameters, header package imports, `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 and other interfaces; interface ports with or without a modport, generic `interface` and `interface.mp` ports, and arrays of interface ports; explicit and implicit named interface connections (`.bus(bus)` and `.bus`); 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(...)`, `h[i].f(...)` with a constant element index) | @@ -214,7 +215,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: 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. + exports, tri-state buses and multiple drivers. ### Interface restrictions {#interface-restrictions} @@ -253,6 +254,21 @@ index: `child_signal(&[("u", 3)], "y")` and `dut.u[3]` reach `u[3]` of `Child u[3:2](...)`, and `InstanceHierarchy::index` holds the index. Arrays with a negative bound are rejected. +### Hierarchical references {#hierarchical-references} + +A hierarchical name is resolved once against the elaborated hierarchy and +then reads and writes the object of the instance it denotes, like a name of +that instance: there is no run-time lookup. Only the selected element of an +array, such as `i` in `u.mem[i]`, may vary at run time. Each instance of a +module resolves its upward names from its own position; an upward name must +denote the same relative object from every instance of the module. + +Not supported, and rejected with the name: continuous assignments to a +variable and any driver of a net through a hierarchical name, names in port +connections, names of tasks, functions, named blocks, parameters or +structure members of another scope, names that start inside a generate block +relative to it, and names of `real`, `string` or class-typed signals. + ### Strings {#strings} A `string` variable holds a reference to text in the simulator's heap, so