From 2c85a6968c1ed8ea3f1b5dd5854f741aef33a4ef Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:22:39 +0900 Subject: [PATCH 1/4] perf(native): reuse clobber walks across reload queries of one byte range Each reload snapshot ran a fresh clobber walk from its start: the walker memoized results only within one query session, and the reload clobber cache kept only the final answer per (load, start). Walks from different starts re-scanned the same memory definitions, running the alias oracle over each definition's write effects every time. On C906 the oracle took about 35% of the time after the frontend. A ClobberMemo now keeps, per queried byte range, the clobbers of accesses whose walk met no unresolved cycle. Such a walk covers an acyclic part of the graph, which determines its result whatever the start points, so later sessions reuse it without walking again. Accesses whose walk met a cycle depend on the MemoryPhi being resolved and are walked in each session as before, so every query resolves exactly as it did and the reload recipes do not change. Closes #1994 Change-Id: I93e7a99f5d74451307b5249b6e22f1c591f9e047 --- crates/celox-analysis/src/memory_ssa.rs | 208 ++++++++++++++++-- .../src/backend/native/regalloc/reload.rs | 14 +- 2 files changed, 198 insertions(+), 24 deletions(-) diff --git a/crates/celox-analysis/src/memory_ssa.rs b/crates/celox-analysis/src/memory_ssa.rs index 45a7fffac7f..39b4a803895 100644 --- a/crates/celox-analysis/src/memory_ssa.rs +++ b/crates/celox-analysis/src/memory_ssa.rs @@ -180,9 +180,25 @@ pub struct ClobberWalker { epochs: Vec, states: Vec, results: Vec>, + /// Whether a resolved access's walk met an unresolved cycle. + cyclic: Vec, epoch: u32, frames: Vec, - values: Vec, + /// Results with whether their walk met an unresolved cycle. + values: Vec<(ClobberResolution, bool)>, +} + +/// Clobbers of one alias query over one graph, kept across query sessions. +/// +/// It holds only accesses whose walk met no unresolved cycle. Such a walk +/// covers an acyclic part of the graph, which determines its result whatever +/// the session's start points, so a later session resolves the access to the +/// same result without walking it again. Accesses whose walk met a cycle +/// depend on the MemoryPhi being resolved and are walked again in each +/// session, as without the memo. +#[derive(Debug, Default)] +pub struct ClobberMemo { + results: fxhash::FxHashMap, } impl ClobberWalker { @@ -223,20 +239,40 @@ impl ClobberWalker { self.epochs.fill(0); self.epoch = 1; } + self.cyclic.resize(graph.nodes.len(), false); ClobberQuery { walker: self, graph, query, alias_oracle, + memo: None, } } + /// Like [`Self::query`], reusing and extending `memo`, which must only + /// ever be used with this graph and an equal query and alias oracle. + pub fn query_memoized<'a, D, Q, A>( + &'a mut self, + graph: &'a MemoryAccessGraph, + query: &'a Q, + alias_oracle: &'a A, + memo: &'a mut ClobberMemo, + ) -> ClobberQuery<'a, D, Q, A> + where + A: AliasOracle, + { + let mut session = self.query(graph, query, alias_oracle); + session.memo = Some(memo); + session + } + fn find_clobber( &mut self, nodes: &[MemoryAccessNode], start: usize, query: &Q, alias_oracle: &impl AliasOracle, + mut memo: Option<&mut ClobberMemo>, ) -> MemoryClobber { let current_epoch = self.epoch; self.frames.clear(); @@ -248,24 +284,32 @@ impl ClobberWalker { ResolveFrame::Enter(access) => { if self.epochs[access] == current_epoch && self.states[access] != 0 { match self.states[access] { - 1 => self.values.push(ClobberResolution::Cycle), - 2 => self.values.push( + 1 => self.values.push((ClobberResolution::Cycle, true)), + 2 => self.values.push(( self.results[access] .expect("a resolved clobber node retains its result"), - ), + self.cyclic[access], + )), _ => unreachable!("current-epoch clobber state is valid"), } continue; } self.epochs[access] = current_epoch; + if let Some(&result) = memo.as_ref().and_then(|memo| memo.results.get(&access)) + { + let result = ClobberResolution::Access(result); + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = false; + self.values.push((result, false)); + continue; + } self.states[access] = 1; self.results[access] = None; match &nodes[access] { MemoryAccessNode::LiveOnEntry => { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } MemoryAccessNode::Definition { definition, @@ -273,9 +317,7 @@ impl ClobberWalker { } => { if alias_oracle.may_alias(definition, query) { let result = ClobberResolution::Access(access); - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, false, &mut memo); } else { self.frames.push(ResolveFrame::FinishDefinition(access)); self.frames.push(ResolveFrame::Enter(previous.0)); @@ -296,7 +338,7 @@ impl ClobberWalker { } } ResolveFrame::FinishDefinition(access) => { - let result = self + let (result, cyclic) = self .values .pop() .expect("a MemoryDef predecessor produces one clobber result"); @@ -305,11 +347,10 @@ impl ClobberWalker { // resolved independently of the active MemoryPhi. self.states[access] = 0; self.results[access] = None; + self.values.push((result, cyclic)); } else { - self.states[access] = 2; - self.results[access] = Some(result); + self.resolve(access, result, cyclic, &mut memo); } - self.values.push(result); } ResolveFrame::FinishPhi { access, inputs } => { let first = self @@ -319,7 +360,9 @@ impl ClobberWalker { .expect("every MemoryPhi input produces one clobber result"); let mut common = None::; let mut diverged = false; - for result in self.values.drain(first..) { + let mut cyclic = false; + for (result, input_cyclic) in self.values.drain(first..) { + cyclic |= input_cyclic; if result == ClobberResolution::Cycle { continue; } @@ -334,14 +377,12 @@ impl ClobberWalker { } else { common.unwrap_or(ClobberResolution::Access(access)) }; - self.states[access] = 2; - self.results[access] = Some(result); - self.values.push(result); + self.resolve(access, result, cyclic, &mut memo); } } } - let resolution = self + let (resolution, _) = self .values .pop() .expect("one clobber query produces one result"); @@ -351,6 +392,24 @@ impl ClobberWalker { ClobberResolution::Cycle => MemoryClobber::Indeterminate, } } + + /// Record `access` as resolved to `result` in this session, and in `memo` + /// when its walk met no unresolved cycle. + fn resolve( + &mut self, + access: usize, + result: ClobberResolution, + cyclic: bool, + memo: &mut Option<&mut ClobberMemo>, + ) { + self.states[access] = 2; + self.results[access] = Some(result); + self.cyclic[access] = cyclic; + if let (false, ClobberResolution::Access(result), Some(memo)) = (cyclic, result, memo) { + memo.results.insert(access, result); + } + self.values.push((result, cyclic)); + } } /// Multi-point clobber query for one immutable alias query. Resolving a phi @@ -361,6 +420,7 @@ pub struct ClobberQuery<'a, D, Q, A> { graph: &'a MemoryAccessGraph, query: &'a Q, alias_oracle: &'a A, + memo: Option<&'a mut ClobberMemo>, } impl ClobberQuery<'_, D, Q, A> @@ -369,8 +429,13 @@ where { pub fn clobber(&mut self, start: MemoryAccessId) -> Option { (start.0 < self.graph.nodes.len()).then(|| { - self.walker - .find_clobber(&self.graph.nodes, start.0, self.query, self.alias_oracle) + self.walker.find_clobber( + &self.graph.nodes, + start.0, + self.query, + self.alias_oracle, + self.memo.as_deref_mut(), + ) }) } } @@ -1005,6 +1070,107 @@ mod tests { assert_eq!(analysis.graph.access_count(), 2); } + /// Sessions sharing a memo resolve every start exactly as fresh + /// sessions do, over random CFGs with loops, joins and disjoint, + /// overlapping and repeated stores. + #[test] + fn memoized_sessions_match_fresh_sessions() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + let mut cases = 0; + let mut memo_calls = 0; + let mut fresh_calls = 0; + for _ in 0..400 { + let blocks = 1 + next(7); + let successors = (0..blocks) + .map(|block| { + let mut outgoing = Vec::new(); + if block + 1 < blocks { + outgoing.push(block + 1); + } + for _ in 0..next(3) { + outgoing.push(next(blocks)); + } + outgoing + }) + .collect::>(); + let Ok(cfg) = ControlFlowGraph::analyze(successors, 0) else { + continue; + }; + let events = (0..blocks) + .map(|block| { + (0..next(4)) + .map(|index| { + let writes = if next(3) == 0 { + vec![] + } else { + vec![exact(1, 4 * next(4) as i64, 4 * (1 + next(2)))] + }; + event((block, index), vec![], writes) + }) + .collect::>() + }) + .collect::>(); + let analysis = analyze(&cfg, &events); + let accesses = analysis.graph.access_count(); + let calls = std::cell::Cell::new(0usize); + let oracle = |definition: &Instruction, query: &MemoryEffect| { + calls.set(calls.get() + 1); + analysis.writes[definition] + .iter() + .copied() + .any(|write| effects_may_alias(write, *query)) + }; + for _ in 0..4 { + let query = exact(1, 4 * next(4) as i64, 4 * (1 + next(2))); + let sessions = (0..1 + next(6)) + .map(|_| { + (0..1 + next(4)) + .map(|_| MemoryAccessId(next(accesses))) + .collect::>() + }) + .collect::>(); + let mut fresh_walker = ClobberWalker::new(); + calls.set(0); + let fresh = sessions + .iter() + .map(|starts| { + let mut session = fresh_walker.query(&analysis.graph, &query, &oracle); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + fresh_calls += calls.get(); + let mut walker = ClobberWalker::new(); + let mut memo = ClobberMemo::default(); + calls.set(0); + let memoized = sessions + .iter() + .map(|starts| { + let mut session = + walker.query_memoized(&analysis.graph, &query, &oracle, &mut memo); + starts + .iter() + .map(|&start| session.clobber(start)) + .collect::>() + }) + .collect::>(); + memo_calls += calls.get(); + assert_eq!(memoized, fresh, "{sessions:?} {query:?} {events:?}"); + } + cases += 1; + } + assert!(cases > 200, "{cases}"); + assert!(memo_calls < fresh_calls, "{memo_calls} {fresh_calls}"); + } + #[test] fn custom_alias_domain_needs_no_memory_effect_types() { let cfg = ControlFlowGraph::analyze(vec![vec![]], 0).unwrap(); diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs index b925852f893..50255234cc7 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/reload.rs @@ -11,8 +11,8 @@ use std::fmt; use celox_analysis::memory::{MemoryEffect, MemoryLocation, effects_may_alias}; use celox_analysis::memory_ssa::{ - self, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, MemoryAccessId, - MemoryClobber, MemoryPointMap, + self, ClobberMemo, ClobberWalker, MemoryAccess, MemoryAccessEvent, MemoryAccessGraph, + MemoryAccessId, MemoryClobber, MemoryPointMap, }; use crate::HashMap; @@ -1221,6 +1221,9 @@ struct ReloadMemorySsa { block_ids: Vec, walker: ClobberWalker, clobber_cache: HashMap<(StateLoad, MemoryAccessId), MemoryAccessId>, + /// Clobbers already walked for each queried byte range, so queries from + /// different starts do not walk the same definitions again. + clobber_memos: HashMap<(i64, usize), ClobberMemo>, } impl ReloadMemorySsa { @@ -1273,6 +1276,10 @@ impl ReloadMemorySsa { let writes = &self.writes; let block_ids = &self.block_ids; let clobber_cache = &mut self.clobber_cache; + let memo = self + .clobber_memos + .entry((bytes.start, byte_len)) + .or_default(); let oracle = |definition: &MemoryDefinition, query: &MemoryEffect| { writes .get(definition.write_index..definition.write_end) @@ -1283,7 +1290,7 @@ impl ReloadMemorySsa { .any(|write| effects_may_alias(write, *query)) }) }; - let mut clobber_query = self.walker.query(graph, &query, &oracle); + let mut clobber_query = self.walker.query_memoized(graph, &query, &oracle, memo); let mut clobber_access = |start| { if let Some(&access) = clobber_cache.get(&(load, start)) { return Ok(access); @@ -2228,6 +2235,7 @@ fn build_reload_memory_ssa( writes, block_ids: func.blocks.iter().map(|block| block.id).collect(), walker: ClobberWalker::new(), + clobber_memos: HashMap::default(), clobber_cache: HashMap::default(), }) } From bf01b6d9355cab099c4b0182f10ce5310b148c2d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:35:08 +0900 Subject: [PATCH 2/4] feat(cli): default celox run to the tiered backend Change-Id: Ibf4c9e23b951e1302840c46d455bbfc4cd6b04de --- crates/celox-vpi/src/bin/celox.rs | 2 +- crates/celox-vpi/src/bin/celox/runner.rs | 33 ++++++++++++++++++++---- crates/celox-vpi/tests/run_cli.rs | 19 ++++++++++++++ docs/guide/cocotb.md | 3 ++- 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 3ac3ac1a18e..eb1e030dd2d 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -177,7 +177,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { simulate_sv(simulation, max_steps, &mut std::io::stdout().lock()) }}; } - match arguments.execution.backend { + match arguments.execution.backend() { runner::Backend::Native => execute!(build), runner::Backend::Cranelift => execute!(build_cranelift), runner::Backend::Interpreter => execute!(build_interpreter), diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index 802e60033c9..cb25cfc3b1a 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -30,8 +30,11 @@ macro_rules! report { #[derive(Args, Default)] pub(super) struct ExecutionArgs { - #[arg(long, value_enum, default_value = "native")] - pub backend: Backend, + /// Defaults to `tiered`, or to `native` when an option needs native code + /// (compile-only, native images, the build cache or IR dumps) and in + /// cross-codegen builds. + #[arg(long, value_enum)] + backend: Option, #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. @@ -74,6 +77,26 @@ pub(super) struct ExecutionArgs { } impl ExecutionArgs { + pub(super) fn backend(&self) -> Backend { + self.backend.unwrap_or( + // A cross-codegen build only exports foreign native images. + if cfg!(any( + all(target_arch = "x86_64", feature = "arm64-codegen"), + all(target_arch = "aarch64", feature = "x86_64-codegen") + )) || self.compile_only + || self.native_image_output.is_some() + || self.native_image_input.is_some() + || self.build_cache_dir.is_some() + || self.dump_ir_dir.is_some() + || self.dump_ir_and_run + { + Backend::Native + } else { + Backend::Tiered + }, + ) + } + #[cfg(feature = "systemverilog")] pub(super) fn validate_sv(&self) -> Result<(), String> { if self.compile_only @@ -149,9 +172,8 @@ pub(super) enum RunError { TestFailed { message: String }, } -#[derive(Clone, Copy, Default, PartialEq, ValueEnum)] +#[derive(Clone, Copy, PartialEq, ValueEnum)] pub(super) enum Backend { - #[default] Native, Cranelift, Interpreter, @@ -182,6 +204,7 @@ pub(super) fn run( design: super::project::Design, max_steps: u64, ) -> Result<(), RunError> { + let backend = cli.backend(); let mut opts = Options { report: cli.report, require_compiled: cli.require_compiled, @@ -194,7 +217,7 @@ pub(super) fn run( }), test: design.top.clone(), opt_level: design.opt_level.unwrap_or(OptLevel::O2), - backend: cli.backend, + backend, four_state: design.four_state.unwrap_or(false), compile_only: cli.compile_only, native_image_output: cli.native_image_output, diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index e68b2bfb196..4c3a66abbf5 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -365,6 +365,25 @@ fn veryl_backends_share_cli_execution_and_opt_in_reports() { assert!(output.stdout.is_empty(), "{output:?}"); } +#[cfg(not(any( + all(target_arch = "x86_64", feature = "arm64-codegen"), + all(target_arch = "aarch64", feature = "x86_64-codegen") +)))] +#[test] +fn backend_defaults_to_tiered_unless_native_code_is_requested() { + let source = + "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(4); $finish(); } }"; + let output = run(&[("top.veryl", source)], &["--report"]); + assert!(output.status.success(), "{output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!(report.contains("backend=tiered "), "{report}"); + + let output = run(&[("top.veryl", source)], &["--report", "--compile-only"]); + assert!(output.status.success(), "{output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!(report.contains("backend=native "), "{report}"); +} + #[cfg(feature = "systemverilog")] #[test] fn sv_defaults_to_two_state_and_four_state_is_explicit() { diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 65123edabbd..ba8bae593a9 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -64,7 +64,8 @@ clock limit is needed. `--unlimited` removes the step/tick limit. Source languag `celox run` accepts `--threads N` (1–64, default 1) and `--four-state` for both languages. Both languages support `--backend native|tiered|interpreter|cranelift|wasm` -(default: native). Tiered starts interpreted and adopts compiled code at a scheduler +(default: tiered; native when `--compile-only`, a native image, `--build-cache-dir` or an +IR dump is requested). Tiered starts interpreted and adopts compiled code at a scheduler safe point while preserving pending events. For example: ```sh From 6bf6291a23e582b75fb53eff025b7503a5ac145f Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:40:01 +0900 Subject: [PATCH 3/4] perf(sir-opt): share one state SSA analysis among sink recipe stability checks Effect-case dispatch planning checked each sink recipe's loads with a StateSsa analysis of just those loads, which scans the whole execution unit: O(recipes x unit size) per selector group. State SSA versions an exact location from that location's own definitions and kills, so one analysis selecting every load of a region versions each location as an analysis of fewer loads does. The unit now builds that analysis once per region, on first use, and each recipe reads its verdict from it: - The shared analysis leaves out the loads that make their location invalid in every selection containing them, so they have no version there, as in their recipe's own analysis. - A packed load is versioned only when its recipe also has a static load of the same bits, as a slot exists only for those. If the shared analysis fails, the recipe is analyzed on its own as before. Every verdict is the same. Closes #1998 Change-Id: Ief18a8459b6318c3dc619453041e66c9fc9aa13d --- .../analysis/control_region_feasibility.rs | 331 +++++++++++++++++- 1 file changed, 328 insertions(+), 3 deletions(-) diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs index 626feadfd72..7f2b6958dbc 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/control_region_feasibility.rs @@ -18,8 +18,8 @@ use super::sir_analysis::{UseSite, collect_uses, instruction_uses}; use super::state_ssa::StateSsa; use crate::ir::cfg::SirCfg; use crate::ir::{ - BinaryOp, BlockId, ExecutionUnit, RegionedAbsoluteAddr, RegisterId, SIRInstruction, SIROffset, - SIRTerminator, SIRValue, UnaryOp, + BinaryOp, BlockId, ExecutionUnit, RegionedAbsoluteAddr, RegisterId, RegisterType, + SIRInstruction, SIROffset, SIRTerminator, SIRValue, UnaryOp, }; use crate::{HashMap, HashSet}; @@ -2014,6 +2014,7 @@ pub(crate) fn plan_best_effect_case_dispatch( )) }); + let mut load_versions = LoadVersions::new(eu, &cfg); candidates .into_iter() .find_map(|(saving, _, origin, group)| { @@ -2030,6 +2031,7 @@ pub(crate) fn plan_best_effect_case_dispatch( &incoming_values, &predecessors, &cfg, + &mut load_versions, ) }) } @@ -2048,6 +2050,7 @@ fn build_effect_case_rewrite_plan( incoming_values: &HashMap>, predecessors: &HashMap>, cfg: &SirCfg, + load_versions: &mut LoadVersions<'_>, ) -> Option { let cross_block = cross_block_selector_closure( eu, @@ -2149,7 +2152,14 @@ fn build_effect_case_rewrite_plan( known_values: recipe.known_values.clone(), }; if recipe.non_dominating_control_merges.is_empty() { - if !loads_are_stable_at(eu, cfg, definitions, sink.0, &recipe.load_frontier) { + if !loads_are_stable_at( + eu, + cfg, + definitions, + load_versions, + sink.0, + &recipe.load_frontier, + ) { return None; } sink_cases.push(executable); @@ -2172,6 +2182,7 @@ fn build_effect_case_rewrite_plan( eu, cfg, definitions, + load_versions, insertion_block, &recipe.load_frontier, ) { @@ -2283,7 +2294,167 @@ fn recipe_is_available_at_entry( }) } +/// An exact static state location: address, bit offset and width. +type ExactLocation = (RegionedAbsoluteAddr, usize, usize); + +/// Whether a two-state exact access of `width` bits through a register of +/// type `ty` gives its location a valid slot type (see `StateSsa`). +fn exact_access_typed(ty: Option<&RegisterType>, width: usize) -> bool { + ty.is_some_and(|ty| width != 0 && ty.width() == width) +} + +/// Load versions of one execution unit, shared by the stability checks of +/// all its sink recipes. +/// +/// A recipe's loads are stable at a block when each still reads the state +/// version it read originally. Analyzing each recipe's loads separately +/// scans the whole unit once per recipe. State SSA versions an exact +/// location from that location's own definitions and kills, so one analysis +/// selecting every load of a region versions each location as an analysis +/// selecting fewer loads does. What depends on the selection is which +/// locations get a slot and whether their types are valid: +/// - The shared analysis leaves out the loads that make their location +/// invalid in every selection containing them. Such a load has no version +/// there, as in its recipe's own analysis, so the recipe is not stable. +/// - A static load gives its location a slot, which a packed load of the +/// same bits then also reads; `loads_are_stable_at` checks per recipe +/// that the recipe has such a static load. +struct LoadVersions<'a> { + eu: &'a ExecutionUnit, + cfg: &'a SirCfg, + regions: BTreeMap>, +} + +impl<'a> LoadVersions<'a> { + fn new(eu: &'a ExecutionUnit, cfg: &'a SirCfg) -> Self { + Self { + eu, + cfg, + regions: BTreeMap::new(), + } + } + + /// The shared versions of `region`, or `None` when its analysis fails. + fn region(&mut self, region: u32) -> Option<&StateSsa> { + let (eu, cfg) = (self.eu, self.cfg); + self.regions + .entry(region) + .or_insert_with(|| Self::analyze(eu, cfg, region)) + .as_ref() + } + + fn analyze( + eu: &ExecutionUnit, + cfg: &SirCfg, + region: u32, + ) -> Option { + let instructions = || { + cfg.block_ids + .iter() + .flat_map(|block| &eu.blocks[block].instructions) + }; + // An exact store without a valid type makes its location invalid in + // every selection, as does a load without one. + let invalid = instructions() + .filter_map(|instruction| match instruction { + SIRInstruction::Store( + address, + SIROffset::Static(bit_offset), + width, + source, + .., + ) if address.region == region + && !exact_access_typed(eu.register_map.get(source), *width) => + { + Some((*address, *bit_offset, *width)) + } + _ => None, + }) + .collect::>(); + let loads = instructions() + .filter_map(|instruction| match instruction { + SIRInstruction::Load( + destination, + address, + SIROffset::Static(bit_offset), + width, + ) if address.region == region => { + (exact_access_typed(eu.register_map.get(destination), *width) + && !invalid.contains(&(*address, *bit_offset, *width))) + .then_some(*destination) + } + SIRInstruction::Load(destination, address, SIROffset::PackedElements { .. }, _) + if address.region == region => + { + Some(*destination) + } + _ => None, + }) + .collect::>(); + StateSsa::analyze_selected_loads_two_state(eu, cfg, region, &loads).ok() + } +} + +/// Whether every load in `loads` still reads its original state version on +/// entry to `target`, as `loads_are_stable_at_by_analysis` decides, from +/// the unit's shared load versions. fn loads_are_stable_at( + eu: &ExecutionUnit, + cfg: &SirCfg, + definitions: &HashMap, + versions: &mut LoadVersions<'_>, + target: BlockId, + loads: &BTreeSet, +) -> bool { + let mut sites = Vec::with_capacity(loads.len()); + for ®ister in loads { + let Some(site) = definitions.get(®ister) else { + return false; + }; + let SIRInstruction::Load(_, address, offset, width) = + &eu.blocks[&site.block].instructions[site.index] + else { + return false; + }; + sites.push((register, site, *address, offset, *width)); + } + if sites + .iter() + .any(|(_, _, address, ..)| versions.region(address.region).is_none()) + { + return loads_are_stable_at_by_analysis(eu, cfg, definitions, target, loads); + } + // The locations an analysis of just these loads gives a slot. + let locations = sites + .iter() + .filter_map(|(_, _, address, offset, width)| match offset { + SIROffset::Static(bit_offset) => Some((*address, *bit_offset, *width)), + _ => None, + }) + .collect::>(); + sites + .iter() + .all(|(register, site, address, offset, width)| { + let (SIROffset::Static(bit_offset) | SIROffset::PackedElements { bit_offset, .. }) = + offset + else { + return false; + }; + if !locations.contains(&(*address, *bit_offset, *width)) { + return false; + } + versions.region(address.region).is_some_and(|state| { + state + .read_version(site.block, site.index, *register) + .is_some_and(|(slot, original)| { + state.entry_version(target, slot) == Some(original) + }) + }) + }) +} + +/// `loads_are_stable_at` by an analysis of just `loads`. +fn loads_are_stable_at_by_analysis( eu: &ExecutionUnit, cfg: &SirCfg, definitions: &HashMap, @@ -2405,6 +2576,160 @@ mod tests { ) } + /// Shared load versions decide every selection of loads as an analysis + /// of just those loads does, over random units with branches, a loop, + /// overlapping exact accesses, packed, dynamic and mistyped accesses. + #[test] + fn shared_load_versions_match_per_recipe_analysis() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + // 0 -> {1, 2} -> 3 -> {3, 4} + let successors = [vec![1, 2], vec![3], vec![3], vec![3, 4], vec![]]; + let mut checked = 0; + let mut stable = 0; + for _ in 0..300 { + let mut register_map = HashMap::default(); + let mut registers = 0; + let mut register = |ty: Option, map: &mut HashMap<_, _>| { + registers += 1; + let id = RegisterId(registers); + if let Some(ty) = ty { + map.insert(id, ty); + } + id + }; + let condition = register(Some(bit(1)), &mut register_map); + let index = register(Some(bit(2)), &mut register_map); + let mut loads = Vec::new(); + let blocks = successors + .iter() + .enumerate() + .map(|(block, successors)| { + let mut instructions = Vec::new(); + for _ in 0..next(5) { + let width = if next(10) == 0 { 0 } else { 4 * (1 + next(2)) }; + let bit_offset = 4 * next(3); + // Mostly well typed; sometimes the wrong width or no + // register type at all. + let ty = match next(8) { + 0 => None, + 1 => Some(bit(width + 1)), + 2 => Some(logic(width)), + _ => Some(bit(width)), + }; + let addr = address(next(2) as u32); + let value = register(ty, &mut register_map); + match next(6) { + 0 | 1 => instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static(bit_offset), + width, + value, + Vec::new(), + Vec::new(), + )), + 2 => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::PackedElements { + bit_offset, + element_width: 4, + }, + width, + )); + loads.push(value); + } + 3 if next(3) == 0 => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::Dynamic(index), + width, + )); + loads.push(value); + } + _ => { + instructions.push(SIRInstruction::Load( + value, + addr, + SIROffset::Static(bit_offset), + width, + )); + loads.push(value); + } + } + } + let terminator = match successors.as_slice() { + [] => SIRTerminator::Return, + [target] => SIRTerminator::Jump(BlockId(*target), vec![]), + [then, otherwise] => SIRTerminator::Branch { + cond: condition, + true_block: (BlockId(*then), vec![]), + false_block: (BlockId(*otherwise), vec![]), + }, + _ => unreachable!(), + }; + ( + BlockId(block), + BasicBlock { + id: BlockId(block), + params: vec![], + instructions, + terminator, + }, + ) + }) + .collect(); + let eu = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + let cfg = SirCfg::analyze_structure(&eu).unwrap(); + let definitions = collect_definition_sites(&eu); + let mut versions = LoadVersions::new(&eu, &cfg); + for _ in 0..12 { + let selection = loads + .iter() + .copied() + .filter(|_| next(3) == 0) + .collect::>(); + for target in 0..successors.len() { + let target = BlockId(target); + let expected = loads_are_stable_at_by_analysis( + &eu, + &cfg, + &definitions, + target, + &selection, + ); + assert_eq!( + loads_are_stable_at( + &eu, + &cfg, + &definitions, + &mut versions, + target, + &selection + ), + expected, + "{selection:?} at {target:?} in {eu:?}" + ); + checked += 1; + stable += usize::from(expected && !selection.is_empty()); + } + } + } + assert!(checked > 10_000, "{checked}"); + assert!(stable > 100, "{stable}"); + } + #[test] fn exact_case_guard_requires_the_adjacent_one_bit_normalization_chain() { let selector = RegisterId(0); From 5efe018a078b30eb4afb9bb2b8d513834b8a30e3 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 10:02:59 +0900 Subject: [PATCH 4/4] feat(sv): support inout ports with a single tristate driver Both sides of an inout port connection form one net (IEEE 1800-2023 23.3.3), whose value its drivers determine and which is z without one (6.6). An inout port below the top module whose net has one continuous driver, such as `assign io = oe ? d : 'z;`, now lowers to a one-way connection carrying the value away from the side that drives it, so reads on either side see the driven value or z (0 in two-state mode). The ports whose net is driven in their module or below it are resolved over the specialized hierarchy before the driver checks. A net driven on both sides of an inout connection, or by several children, is still rejected as having multiple net drivers, and a variable or expression connected to an inout port is rejected (23.3.3.2). Inout ports of the top module and of foreign modules remain unsupported. Closes #1948 Change-Id: I76a456ac73b4a8d6e314baf63d75a9cc35a790dc --- crates/celox-frontend-sv/src/lowering.rs | 175 ++++++++++++++++-- .../src/sv/cases/hierarchy.vtest | 123 ++++++++++++ .../frontends/systemverilog/hierarchy.rs | 12 ++ .../systemverilog/review_regressions.rs | 97 ++++++++++ docs/guide/systemverilog-reference.md | 5 +- docs/ja/guide/systemverilog-reference.md | 4 +- 6 files changed, 399 insertions(+), 17 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index a7e271a6439..27d6ebb280d 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -160,6 +160,9 @@ pub(crate) struct LoweredSvModule { level_lists_lowered: Vec, /// The write streams one flip-flop evaluation may write twice. repeated_ff_writes: Vec, + /// The `inout` ports whose net has its driver in this module or below it, + /// filled in by [`resolve_inout_drivers`]. + inout_driven_inside: HashSet, } #[derive(Clone)] @@ -570,6 +573,49 @@ fn analyze_sources_with_requests( Ok((modules, root_names)) } +/// Record the `inout` ports whose net has its driver in their module or +/// below it. Both sides of an inout port connection form one net (IEEE +/// 1800-2023 23.3.3), so the connection carries the value away from the side +/// that drives it. A net driven on both sides is then reported by +/// [`validate_specialized_instance_net_drivers`]. +fn resolve_inout_drivers( + module_ids: &HashMap, + modules: &mut HashMap, +) { + loop { + let mut driven = Vec::new(); + for (&module_id, module) in modules.iter() { + for port in module.source.ports() { + if port.direction() != sv::ir::PortDirection::Inout + || module.inout_driven_inside.contains(port.name()) + { + continue; + } + if !local_driver_ranges( + &module.source, + port.name(), + &module.constants, + &module.parameter_types, + ) + .is_empty() + || !child_output_driver_ranges(module, port.name(), module_ids, modules) + .is_empty() + { + driven.push((module_id, port.name().to_string())); + } + } + } + if driven.is_empty() { + return; + } + for (module_id, port) in driven { + if let Some(module) = modules.get_mut(&module_id) { + module.inout_driven_inside.insert(port); + } + } + } +} + fn validate_specialized_instance_net_drivers( module_ids: &HashMap, modules: &HashMap, @@ -769,10 +815,13 @@ fn child_output_driver_ranges( for connection in connections { if !child.source.ports().iter().any(|port| { port.name() == connection.formal - && matches!( - port.direction(), - sv::ir::PortDirection::Output | sv::ir::PortDirection::Inout - ) + && match port.direction() { + sv::ir::PortDirection::Output => true, + sv::ir::PortDirection::Inout => { + child.inout_driven_inside.contains(port.name()) + } + _ => false, + } }) { continue; } @@ -1998,6 +2047,7 @@ fn prepare_external_hierarchy_collecting( event_assignments: Vec::new(), level_lists_lowered: Vec::new(), repeated_ff_writes: Vec::new(), + inout_driven_inside: HashSet::default(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -2167,7 +2217,7 @@ fn prepare_external_hierarchy_collecting( } } - let lowered_modules = module_ids + let mut lowered_modules = module_ids .iter() .map(|(key, &module_id)| { if let Some(module) = foreign_specializations.get(key) { @@ -2193,6 +2243,7 @@ fn prepare_external_hierarchy_collecting( )) }) .collect::, FrontendError>>()?; + resolve_inout_drivers(&module_ids, &mut lowered_modules); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let mut modules = HashMap::default(); for (key, &module_id) in &module_ids { @@ -2776,10 +2827,11 @@ fn schedule_sources_collecting( }, )?) }; - let lowered_modules = module_ids + let mut lowered_modules = module_ids .iter() .map(|(key, &module_id)| Ok((module_id, specialize(key, module_id)?))) .collect::, FrontendError>>()?; + resolve_inout_drivers(&module_ids, &mut lowered_modules); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let root = &lowered_modules[&root_id]; if let Some(port) = root @@ -3801,6 +3853,7 @@ fn lower_module_with_overrides( event_assignments, level_lists_lowered, repeated_ff_writes, + inout_driven_inside: HashSet::default(), }) } @@ -5482,9 +5535,6 @@ fn ensure_parent_output_signals( ) -> Result<(), ParserError> { for child_port_id in &child.port_order { let child_var = &child.variables[child_port_id]; - if child_var.kind != VariableKind::Output { - continue; - } let formal = child_var.path.join("."); let Some(connection) = connections .iter() @@ -5492,6 +5542,20 @@ fn ensure_parent_output_signals( else { continue; }; + if child_var.kind == VariableKind::Inout { + check_inout_port_actual( + connection, + parent_variables, + parent_signal_names, + implicit_output_signals, + parent_source, + parent_constants, + parent_parameter_types, + )?; + } + if child_port_direction(child, child_var) != Some(VariableKind::Output) { + continue; + } let Some(actual) = connection .actual_expr .as_ref() @@ -5569,6 +5633,68 @@ fn ensure_parent_output_signals( Ok(()) } +/// Rejects a variable or an expression connected to an `inout` port: only +/// nets may be on either side of one (IEEE 1800-2023 23.3.3.2). An +/// undeclared identifier is an implicit net. +fn check_inout_port_actual( + connection: &LoweredSvPortConnection, + parent_variables: &HashMap, + parent_signal_names: &HashMap, + implicit_nets: &HashSet, + parent_source: &sv::ir::Module, + parent_constants: &HashMap, + parent_parameter_types: &HashMap, +) -> Result<(), ParserError> { + let Some(actual) = connection.actual_expr.as_ref() else { + return Ok(()); + }; + let is_net = |name: &str| { + implicit_nets.contains(name) + || parent_source + .signals() + .iter() + .any(|signal| signal.name() == name && signal.is_net()) + || parent_source + .ports() + .iter() + .any(|port| port.name() == name && port.is_net()) + }; + let error = |detail: String| { + Err(ParserError::illegal_context( + "systemverilog inout port connection", + detail, + None, + )) + }; + let Some(accesses) = output_lvalue_accesses( + actual, + parent_variables, + parent_signal_names, + parent_constants, + parent_parameter_types, + ) else { + if simple_output_lvalue_ident(actual) + .is_some_and(|name| !parent_signal_names.contains_key(name)) + { + return Ok(()); + } + return error(format!( + "inout port `{}` must connect to a net, not `{}`", + connection.formal, connection.actual + )); + }; + for OutputLvalueAccess { signal, .. } in accesses { + let name = parent_variables[&signal].path.join("."); + if !is_net(&name) { + return error(format!( + "inout port `{}` must connect to a net, not variable `{name}`", + connection.formal + )); + } + } + Ok(()) +} + type SvGlue = ( Vec<(Vec, LogicPath)>, Vec<(Vec, LogicPath)>, @@ -5670,7 +5796,10 @@ fn build_instance_glue( .iter() .find(|connection| connection.formal == formal); let width = child_var.width; - match child_var.kind { + let Some(direction) = child_port_direction(child, child_var) else { + return Err(unsupported_sv_inout(formal)); + }; + match direction { VariableKind::Input => { let collapse_unknown_literal = !four_state && connection @@ -5967,9 +6096,6 @@ fn build_instance_glue( )); } } - VariableKind::Inout => { - return Err(unsupported_sv_inout(child_var.path.join("."))); - } _ => {} } } @@ -5977,6 +6103,29 @@ fn build_instance_glue( Ok((input_ports, output_ports, arena)) } +/// The direction in which the connection of `port` carries its value. An +/// `inout` port carries the value of its net out of the child when the child +/// drives the net, and into it otherwise. `None` is an inout port that the +/// child's frontend does not describe. +fn child_port_direction(child: &LoweredSvModule, port: &SvVariable) -> Option { + if port.kind != VariableKind::Inout { + return Some(port.kind); + } + let name = port.path.join("."); + child + .source + .ports() + .iter() + .any(|source| source.name() == name && source.direction() == sv::ir::PortDirection::Inout) + .then(|| { + if child.inout_driven_inside.contains(&name) { + VariableKind::Output + } else { + VariableKind::Input + } + }) +} + fn simple_output_lvalue_ident(expr: &sv::ir::Expr) -> Option<&str> { match expr { sv::ir::Expr::Ident(name) => Some(name), diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 25b0a4d8715..1dc7a3c7ed2 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1561,3 +1561,126 @@ (top Top) (run_to_finish) (expect_output "59 593\n")) + +(case inout_tristate_driver_in_child_reaches_parent + (four_state) + (source "inout_child_driver.sv" #" + module Pad(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + for (genvar i = 0; i < 8; i++) begin : g + assign ext[i] = pad[i]; + assign pad[i] = oe[i] ? dr[i] : 1'bz; + end + endmodule + module Block(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + Pad pad_cell(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + endmodule + module Top(input logic [7:0] oe, dr, output wire [7:0] ext, seen, + output logic floating); + wire [7:0] pad; + Block block(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + assign seen = pad; + assign floating = (pad[7] === 1'bz); + endmodule + "#) + (top Top) + (modify (set oe 0xff) (set dr 0xa5)) + (assert_eq ext 0xa5) + (assert_eq seen 0xa5) + (assert_eq floating 0) + (modify (set oe 0x0f)) + (assert_eq ext (fourstate 0x05 0xf0)) + (assert_eq seen (fourstate 0x05 0xf0)) + (assert_eq floating 1) + (modify (set oe 0)) + (assert_eq ext (fourstate 0 0xff)) + (assert_eq seen (fourstate 0 0xff))) + +(case inout_tristate_nets_read_zero_in_two_state + (source "inout_two_state.sv" #" + module Pad(input logic [7:0] oe, dr, inout wire [7:0] pad, + output wire [7:0] ext); + for (genvar i = 0; i < 8; i++) begin : g + assign ext[i] = pad[i]; + assign pad[i] = oe[i] ? dr[i] : 1'bz; + end + endmodule + module Reader(inout wire [7:0] io, output wire [7:0] y); + assign y = io; + endmodule + module Top(input logic [7:0] oe, dr, input logic en, input logic [7:0] a, + output bit [7:0] ext, seen, read); + wire [7:0] pad, w; + Pad pad_cell(.oe(oe), .dr(dr), .pad(pad), .ext(ext)); + assign seen = pad; + assign w = en ? a : 8'bz; + Reader reader(.io(w), .y(read)); + endmodule + "#) + (top Top) + (modify (set oe 0xff) (set dr 0x5a) (set en 1) (set a 0xc3)) + (assert_eq ext 0x5a) + (assert_eq seen 0x5a) + (assert_eq read 0xc3) + (modify (set oe 0xf0) (set en 0)) + (assert_eq ext 0x50) + (assert_eq seen 0x50) + (assert_eq read 0) + (modify (set oe 0)) + (assert_eq ext 0) + (assert_eq seen 0)) + +(case inout_tristate_driver_in_parent_reaches_child + (four_state) + (source "inout_parent_driver.sv" #" + module Reader(inout wire [3:0] io, output wire [3:0] y); + assign y = io; + endmodule + module Pass(inout wire [3:0] io, output wire [3:0] y); + Reader reader(.io(io), .y(y)); + endmodule + module Top(input logic en, input logic [3:0] a, + output wire [3:0] direct, nested, open); + wire [3:0] w; + assign w = en ? a : 4'bz; + Reader reader(.io(w), .y(direct)); + Pass pass(.io(w), .y(nested)); + Reader unconnected(.y(open)); + endmodule + "#) + (top Top) + (modify (set en 1) (set a 0x9)) + (assert_eq direct 0x9) + (assert_eq nested 0x9) + (assert_eq open (fourstate 0 0xf)) + (modify (set en 0)) + (assert_eq direct (fourstate 0 0xf)) + (assert_eq nested (fourstate 0 0xf))) + +(case inout_tristate_drivers_reach_implicit_nets + (four_state) + (source "inout_implicit_net.sv" #" + module Pad(input logic oe, d, inout wire io); + assign io = oe ? d : 1'bz; + endmodule + module Source(input logic d, output wire y); + assign y = d; + endmodule + module Reader(inout wire io, output wire y); + assign y = io; + endmodule + module Top(input logic oe, d, output wire from_pad, from_source); + Pad pad(.oe(oe), .d(d), .io(pad_net)); + Reader pad_reader(.io(pad_net), .y(from_pad)); + Source source(.d(d), .y(source_net)); + Reader source_reader(.io(source_net), .y(from_source)); + endmodule + "#) + (top Top) + (modify (set oe 1) (set d 1)) + (assert_eq from_pad 1) + (assert_eq from_source 1) + (modify (set oe 0) (set d 0)) + (assert_eq from_pad (fourstate 0 1)) + (assert_eq from_source 0)) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index f50db145ec4..617a4470cd9 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -709,6 +709,18 @@ sv_backends! { fn child_ports_keep_the_bit_ranges_of_selected_connections(sim) { @case "hierarchy::child_ports_keep_the_bit_ranges_of_selected_connections"; } + fn inout_tristate_driver_in_child_reaches_parent(sim) { + @case "hierarchy::inout_tristate_driver_in_child_reaches_parent"; + } + fn inout_tristate_nets_read_zero_in_two_state(sim) { + @case "hierarchy::inout_tristate_nets_read_zero_in_two_state"; + } + fn inout_tristate_driver_in_parent_reaches_child(sim) { + @case "hierarchy::inout_tristate_driver_in_parent_reaches_child"; + } + fn inout_tristate_drivers_reach_implicit_nets(sim) { + @case "hierarchy::inout_tristate_drivers_reach_implicit_nets"; + } } #[test] diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 3b4348a8717..578c6c460fa 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -4841,6 +4841,103 @@ fn expands_function_calls_in_child_input_connections() { assert_eq!(sim.get(y), 1u8.into()); } +#[test] +fn rejects_inout_nets_with_several_drivers() { + // Both sides of an inout connection are one net (IEEE 1800-2023 23.3.3); + // resolving several drivers of it is not supported yet. + let pad = r#" + module Pad(input logic oe, inout wire io); assign io = oe ? 1'b1 : 1'bz; endmodule + module Pass(input logic oe, inout wire io); Pad pad(.oe(oe), .io(io)); endmodule + "#; + for top in [ + // Two children drive the net. + r#"module Top(input logic a, b, output wire y); + wire w; + Pad left(.oe(a), .io(w)); + Pad right(.oe(b), .io(w)); + assign y = w; + endmodule"#, + // The parent and a child below a pass-through module drive the net. + r#"module Top(input logic a, b, output wire y); + wire w; + assign w = a ? 1'b0 : 1'bz; + Pass pass(.oe(b), .io(w)); + assign y = w; + endmodule"#, + // A child output and a child inout drive the net. + r#"module Source(output logic y); assign y = 1'b0; endmodule + module Top(input logic a, output wire y); + wire w; + Source source(.y(w)); + Pad pad(.oe(a), .io(w)); + assign y = w; + endmodule"#, + ] { + let error = cranelift_build_error(&format!("{pad}{top}")); + assert!(error.contains("multiple net drivers for `w`"), "{error}"); + } + // A driver of the net inside the child and one on the parent's side of + // an inout port of the child. + let error = cranelift_build_error( + r#" + module Pad(input logic oe, inout wire io); assign io = oe ? 1'b1 : 1'bz; endmodule + module Block(input logic a, b, inout wire io); + assign io = a ? 1'b0 : 1'bz; + Pad pad(.oe(b), .io(io)); + endmodule + module Top(input logic a, b, output wire y); + wire w; + Block block(.a(a), .b(b), .io(w)); + assign y = w; + endmodule + "#, + ); + assert!(error.contains("multiple net drivers for `io`"), "{error}"); +} + +#[test] +fn rejects_variables_and_expressions_on_inout_ports() { + // Only nets may be on either side of an inout port (IEEE 1800-2023 + // 23.3.3.2). + let reader = r#" + module Reader(inout wire [3:0] io, output wire [3:0] y); assign y = io; endmodule + module Pad(input logic oe, inout wire [3:0] io); assign io = oe ? 4'h1 : 4'hz; endmodule + "#; + for (top, variable) in [ + ( + r#"module Top(input logic [3:0] a, output wire [3:0] y); + logic [3:0] v; + assign v = a; + Reader reader(.io(v), .y(y)); + endmodule"#, + Some("variable `v`"), + ), + ( + r#"module Top(input logic oe, output logic [3:0] v); + Pad pad(.oe(oe), .io(v)); + endmodule"#, + Some("variable `v`"), + ), + ( + r#"module Top(input logic [3:0] a, output wire [3:0] y); + wire [3:0] w; + Reader reader(.io(w[3:0] ^ a), .y(y)); + endmodule"#, + None, + ), + ] { + let error = cranelift_build_error(&format!("{reader}{top}")); + assert!( + error.contains("inout port `io` must connect to a net"), + "{error}" + ); + assert!( + variable.is_none_or(|variable| error.contains(variable)), + "{error}" + ); + } +} + #[test] fn rejects_local_drivers_of_implicit_child_output_nets() { let source = r#" diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 779e2e7260e..9115fbed642 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -16,7 +16,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Modules | ANSI ports, non-ANSI ports (a header of port names and body `input` / `output` / `inout` declarations, optionally completed by a net or variable declaration of the same name), `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | +| Modules | ANSI ports, non-ANSI ports (a header of port names and body `input` / `output` / `inout` declarations, optionally completed by a net or variable declaration of the same name), `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them), `inout` ports below the top module whose net has one continuous driver on either side, such as a tristate `assign io = oe ? d : 'z;` (both sides read the driven value, or `z`) | | 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) | @@ -221,7 +221,8 @@ 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. + exports, nets with several drivers (including tri-state buses) and `inout` + ports of the top module. ### Interface restrictions {#interface-restrictions} diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index efe68525764..b2ec786604f 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -15,7 +15,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| モジュール | ANSI ポート、non-ANSI ポート(ヘッダのポート名と本体の `input` / `output` / `inout` 宣言。同名のネットまたは変数の宣言で型を補える)、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割) | +| モジュール | ANSI ポート、non-ANSI ポート(ヘッダのポート名と本体の `input` / `output` / `inout` 宣言。同名のネットまたは変数の宣言で型を補える)、`parameter` / `localparam`、型パラメータ(`parameter type`)、名前付き・位置指定のポート/パラメータ接続、階層、インスタンス配列(接続は全要素に共通、または全要素の幅に等しければ要素ごとに分割)、トップ以外のモジュールの `inout` ポートで、どちらか一方の側に連続代入のドライバが1つだけあるネット(`assign io = oe ? d : 'z;` のようなトライステートを含む。両側から駆動値または `z` が読める) | | プログラム | ポートとパラメータを持つ `program` 宣言。モジュールと同じくモジュールからインスタンス化し、その `initial` 手続きはリアクティブ領域セットで実行します(下記の「プログラム」を参照) | | generate | `for`(`genvar`)、`if`、`case`。`**` を含む定数式 | | package | 型、パラメータ、enum、関数。`import p::*;`、`import p::x;`、`p::x` で参照 | @@ -192,7 +192,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 使われていないパラメータや関数本体の中を含め、書かれた 場所にかかわらず名前を示して報告します。システムタスクでもシステム関数でもない `$` 名、 引数の数が誤っている呼び出し、既定値のない引数の省略、値として使ったタスクはエラーです。 -- [DPI-C の対応範囲](#dpi-c-imports)を超える機能と DPI export、トライステートバスと複数ドライバ、階層参照。 +- [DPI-C の対応範囲](#dpi-c-imports)を超える機能と DPI export、複数のドライバを持つネット(トライステートバスを含む)、トップモジュールの `inout` ポート、階層参照。 ## 実行時の挙動 {#semantics-worth-knowing}