-
Notifications
You must be signed in to change notification settings - Fork 13
feat: add hugr-core StaticGraph, deprecate hugr-passes CallGraph #2698
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7ee3bfd
Add hugr-core StaticGraph
acl-cqc 75d0b9c
Deprecate hugr-passes CallGraph, migrate dead_funcs/inline_funcs
acl-cqc 661a8fa
StaticGraph -> ModuleGraph but keep StaticNode/StaticEdge
acl-cqc 9d3c8c3
inline_funcs (test): use out_edges
acl-cqc e009e8c
Add in_edges
acl-cqc d0a40b3
test
acl-cqc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| //! Data structure summarizing static nodes of a Hugr and their uses | ||
| use std::collections::HashMap; | ||
|
|
||
| use crate::{HugrView, Node, core::HugrNode, ops::OpType}; | ||
| use petgraph::{Graph, visit::EdgeRef}; | ||
|
|
||
| /// Weight for an edge in a [`ModuleGraph`] | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| #[non_exhaustive] | ||
| pub enum StaticEdge<N = Node> { | ||
| /// Edge corresponds to a [Call](OpType::Call) node (specified) in the Hugr | ||
| Call(N), | ||
| /// Edge corresponds to a [`LoadFunction`](OpType::LoadFunction) node (specified) in the Hugr | ||
| LoadFunction(N), | ||
| /// Edge corresponds to a [LoadConstant](OpType::LoadConstant) node (specified) in the Hugr | ||
| LoadConstant(N), | ||
| } | ||
|
|
||
| /// Weight for a petgraph-node in a [`ModuleGraph`] | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| #[non_exhaustive] | ||
| pub enum StaticNode<N = Node> { | ||
| /// petgraph-node corresponds to a [`FuncDecl`](OpType::FuncDecl) node (specified) in the Hugr | ||
| FuncDecl(N), | ||
| /// petgraph-node corresponds to a [`FuncDefn`](OpType::FuncDefn) node (specified) in the Hugr | ||
| FuncDefn(N), | ||
| /// petgraph-node corresponds to the [HugrView::entrypoint], that is not | ||
| /// a [`FuncDefn`](OpType::FuncDefn). Note that it will not be a [Module](OpType::Module) | ||
| /// either, as such a node could not have edges, so is not represented in the petgraph. | ||
| NonFuncEntrypoint, | ||
| /// petgraph-node corresponds to a constant; will have no outgoing edges, and incoming | ||
| /// edges will be [StaticEdge::LoadConstant] | ||
| Const(N), | ||
| } | ||
|
|
||
| /// Details the [`FuncDefn`]s, [`FuncDecl`]s and module-level [`Const`]s in a Hugr, | ||
| /// in a Hugr, along with the [`Call`]s, [`LoadFunction`]s, and [`LoadConstant`]s connecting them. | ||
| /// | ||
| /// Each node in the `ModuleGraph` corresponds to a module-level function or const; | ||
| /// each edge corresponds to a use of the target contained in the edge's source. | ||
| /// | ||
| /// For Hugrs whose entrypoint is neither a [Module](OpType::Module) nor a [`FuncDefn`], | ||
| /// the static graph will have an additional [`StaticNode::NonFuncEntrypoint`] | ||
| /// corresponding to the Hugr's entrypoint, with no incoming edges. | ||
| /// | ||
| /// [`Call`]: OpType::Call | ||
| /// [`Const`]: OpType::Const | ||
| /// [`FuncDecl`]: OpType::FuncDecl | ||
| /// [`FuncDefn`]: OpType::FuncDefn | ||
| /// [`LoadConstant`]: OpType::LoadConstant | ||
| /// [`LoadFunction`]: OpType::LoadFunction | ||
| pub struct ModuleGraph<N = Node> { | ||
| g: Graph<StaticNode<N>, StaticEdge<N>>, | ||
| node_to_g: HashMap<N, petgraph::graph::NodeIndex<u32>>, | ||
| } | ||
|
|
||
| impl<N: HugrNode> ModuleGraph<N> { | ||
| /// Makes a new `ModuleGraph` for a Hugr. | ||
| pub fn new(hugr: &impl HugrView<Node = N>) -> Self { | ||
| let mut g = Graph::default(); | ||
| let mut node_to_g = hugr | ||
| .children(hugr.module_root()) | ||
| .filter_map(|n| { | ||
| let weight = match hugr.get_optype(n) { | ||
| OpType::FuncDecl(_) => StaticNode::FuncDecl(n), | ||
| OpType::FuncDefn(_) => StaticNode::FuncDefn(n), | ||
| OpType::Const(_) => StaticNode::Const(n), | ||
| _ => return None, | ||
| }; | ||
| Some((n, g.add_node(weight))) | ||
| }) | ||
| .collect::<HashMap<_, _>>(); | ||
| if !hugr.entrypoint_optype().is_module() && !node_to_g.contains_key(&hugr.entrypoint()) { | ||
| node_to_g.insert(hugr.entrypoint(), g.add_node(StaticNode::NonFuncEntrypoint)); | ||
| } | ||
| for (func, cg_node) in &node_to_g { | ||
| traverse(hugr, *cg_node, *func, &mut g, &node_to_g); | ||
| } | ||
| fn traverse<N: HugrNode>( | ||
| h: &impl HugrView<Node = N>, | ||
| enclosing_func: petgraph::graph::NodeIndex<u32>, | ||
| node: N, // Nonstrict-descendant of `enclosing_func`` | ||
| g: &mut Graph<StaticNode<N>, StaticEdge<N>>, | ||
| node_to_g: &HashMap<N, petgraph::graph::NodeIndex<u32>>, | ||
| ) { | ||
| for ch in h.children(node) { | ||
| traverse(h, enclosing_func, ch, g, node_to_g); | ||
| let weight = match h.get_optype(ch) { | ||
| OpType::Call(_) => StaticEdge::Call(ch), | ||
| OpType::LoadFunction(_) => StaticEdge::LoadFunction(ch), | ||
| OpType::LoadConstant(_) => StaticEdge::LoadConstant(ch), | ||
| _ => continue, | ||
| }; | ||
| if let Some(target) = h.static_source(ch) { | ||
| if h.get_parent(target) == Some(h.module_root()) { | ||
| g.add_edge(enclosing_func, node_to_g[&target], weight); | ||
| } else { | ||
| assert!(!node_to_g.contains_key(&target)); | ||
| assert!(h.get_optype(ch).is_load_constant()); | ||
| assert!(h.get_optype(target).is_const()); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| ModuleGraph { g, node_to_g } | ||
| } | ||
|
|
||
| /// Allows access to the petgraph | ||
| #[must_use] | ||
| pub fn graph(&self) -> &Graph<StaticNode<N>, StaticEdge<N>> { | ||
| &self.g | ||
| } | ||
|
|
||
| /// Convert a Hugr [Node] into a petgraph node index. | ||
| /// Result will be `None` if `n` is not a [`FuncDefn`](OpType::FuncDefn), | ||
| /// [`FuncDecl`](OpType::FuncDecl) or the [HugrView::entrypoint]. | ||
| pub fn node_index(&self, n: N) -> Option<petgraph::graph::NodeIndex<u32>> { | ||
| self.node_to_g.get(&n).copied() | ||
| } | ||
|
|
||
| /// Returns an iterator over the out-edges from the given Node, i.e. | ||
| /// edges to the functions/constants called/loaded by it. | ||
| /// | ||
| /// If the node is not recognised as a function or the entrypoint, | ||
| /// for example if it is a [`Const`](OpType::Const), the iterator will be empty. | ||
| pub fn out_edges(&self, n: N) -> impl Iterator<Item = (&StaticEdge<N>, &StaticNode<N>)> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we also want an |
||
| let g = self.graph(); | ||
| self.node_index(n).into_iter().flat_map(move |n| { | ||
| self.graph().edges(n).map(|e| { | ||
| ( | ||
| g.edge_weight(e.id()).unwrap(), | ||
| g.node_weight(e.target()).unwrap(), | ||
| ) | ||
| }) | ||
| }) | ||
| } | ||
|
|
||
| /// Returns an iterator over the in-edges to the given Node, i.e. | ||
| /// edges from the (necessarily) functions that call/load it. | ||
| /// | ||
| /// If the node is not recognised as a function or constant, | ||
| /// for example if it is a non-function entrypoint, the iterator will be empty. | ||
| pub fn in_edges(&self, n: N) -> impl Iterator<Item = (&StaticNode<N>, &StaticEdge<N>)> { | ||
| let g = self.graph(); | ||
| self.node_index(n).into_iter().flat_map(move |n| { | ||
| self.graph() | ||
| .edges_directed(n, petgraph::Direction::Incoming) | ||
| .map(|e| { | ||
| ( | ||
| g.node_weight(e.source()).unwrap(), | ||
| g.edge_weight(e.id()).unwrap(), | ||
| ) | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use itertools::Itertools as _; | ||
|
|
||
| use crate::builder::{ | ||
| Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder, endo_sig, inout_sig, | ||
| }; | ||
| use crate::extension::prelude::{ConstUsize, usize_t}; | ||
| use crate::ops::{Value, handle::NodeHandle}; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn edges() { | ||
| let mut mb = ModuleBuilder::new(); | ||
| let cst = mb.add_constant(Value::from(ConstUsize::new(42))); | ||
| let callee = mb.define_function("callee", endo_sig(usize_t())).unwrap(); | ||
| let ins = callee.input_wires(); | ||
| let callee = callee.finish_with_outputs(ins).unwrap(); | ||
| let mut caller = mb | ||
| .define_function("caller", inout_sig(vec![], usize_t())) | ||
| .unwrap(); | ||
| let val = caller.load_const(&cst); | ||
| let call = caller.call(callee.handle(), &[], vec![val]).unwrap(); | ||
| let caller = caller.finish_with_outputs(call.outputs()).unwrap(); | ||
| let h = mb.finish_hugr().unwrap(); | ||
|
|
||
| let mg = ModuleGraph::new(&h); | ||
| let call_edge = StaticEdge::Call(call.node()); | ||
| let load_const_edge = StaticEdge::LoadConstant(val.node()); | ||
|
|
||
| assert_eq!(mg.out_edges(callee.node()).next(), None); | ||
| assert_eq!( | ||
| mg.in_edges(callee.node()).collect_vec(), | ||
| [(&StaticNode::FuncDefn(caller.node()), &call_edge,)] | ||
| ); | ||
|
|
||
| assert_eq!( | ||
| mg.out_edges(caller.node()).collect_vec(), | ||
| [ | ||
| (&call_edge, &StaticNode::FuncDefn(callee.node()),), | ||
| (&load_const_edge, &StaticNode::Const(cst.node()),) | ||
| ] | ||
| ); | ||
| assert_eq!(mg.in_edges(caller.node()).next(), None); | ||
|
|
||
| assert_eq!(mg.out_edges(cst.node()).next(), None); | ||
| assert_eq!( | ||
| mg.in_edges(cst.node()).collect_vec(), | ||
| [(&StaticNode::FuncDefn(caller.node()), &load_const_edge,)] | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.