-
Notifications
You must be signed in to change notification settings - Fork 109
BE-227: HashQL: Implement call graph analysis for MIR #8214
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
Open
indietyp
wants to merge
5
commits into
bm/be-258-hashql-implement-transformationpass-changed-detection
Choose a base branch
from
bm/be-227-hashql-implement-call-graph
base: bm/be-258-hashql-implement-transformationpass-changed-detection
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
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
240 changes: 240 additions & 0 deletions
240
libs/@local/hashql/mir/src/pass/analysis/callgraph/mod.rs
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,240 @@ | ||
| //! Call graph analysis for MIR. | ||
| //! | ||
| //! This module provides [`CallGraphAnalysis`], a pass that constructs a [`CallGraph`] representing | ||
| //! function call relationships between [`DefId`]s in the MIR. The resulting graph can be used for | ||
| //! call site enumeration, reachability analysis, and optimization decisions. | ||
| //! | ||
| //! # Graph Structure | ||
| //! | ||
| //! The call graph uses [`DefId`]s as nodes and tracks references between them as directed edges. | ||
| //! An edge from `A` to `B` means "the MIR body of A references B", annotated with a [`CallKind`] | ||
| //! describing how the reference occurs: | ||
| //! | ||
| //! - [`CallKind::Apply`]: Direct function application via an [`Apply`] rvalue | ||
| //! - [`CallKind::Filter`]: Graph-read filter function in a [`GraphReadBody::Filter`] terminator | ||
| //! - [`CallKind::Opaque`]: Any other reference (types, constants, function pointers) | ||
| //! | ||
| //! For example, given a body `@0` containing `_1 = @1(_2)`: | ||
| //! - An edge `@0 β @1` is created with kind [`CallKind::Apply`] | ||
| //! | ||
| //! # Usage Pattern | ||
| //! | ||
| //! Unlike [`DataDependencyAnalysis`] which is per-body, [`CallGraphAnalysis`] operates on a shared | ||
| //! [`CallGraph`] across multiple bodies: | ||
| //! | ||
| //! 1. Create a [`CallGraph`] with a domain containing all [`DefId`]s that may appear | ||
| //! 2. Run [`CallGraphAnalysis`] on each body to populate edges | ||
| //! 3. Query the resulting graph | ||
| //! | ||
| //! # Direct vs Indirect Calls | ||
| //! | ||
| //! Only *direct* calls are tracked as [`CallKind::Apply`] β those where the callee [`DefId`] | ||
| //! appears syntactically as the function operand. Indirect calls through locals (e.g., | ||
| //! `_1 = @fn; _2 = _1(...)`) produce an [`Opaque`] edge at the assignment site, not an | ||
| //! [`Apply`] edge at the call site. | ||
| //! | ||
| //! This is intentional: the analysis is designed to run after SROA, which propagates function | ||
| //! references through locals, eliminating most indirect call patterns. | ||
| //! | ||
| //! [`Opaque`]: CallKind::Opaque | ||
| //! [`DataDependencyAnalysis`]: super::DataDependencyAnalysis | ||
| //! [`Apply`]: crate::body::rvalue::Apply | ||
| //! [`GraphReadBody::Filter`]: crate::body::terminator::GraphReadBody::Filter | ||
|
|
||
| #[cfg(test)] | ||
| mod tests; | ||
|
|
||
| use alloc::alloc::Global; | ||
| use core::{alloc::Allocator, fmt}; | ||
|
|
||
| use hashql_core::{ | ||
| graph::{LinkedGraph, NodeId}, | ||
| id::Id as _, | ||
| }; | ||
|
|
||
| use crate::{ | ||
| body::{ | ||
| Body, | ||
| location::Location, | ||
| place::{PlaceContext, PlaceReadContext}, | ||
| rvalue::Apply, | ||
| terminator::{GraphReadBody, GraphReadLocation}, | ||
| }, | ||
| context::MirContext, | ||
| def::{DefId, DefIdSlice}, | ||
| pass::AnalysisPass, | ||
| visit::Visitor, | ||
| }; | ||
|
|
||
| /// Classification of [`DefId`] references in the call graph. | ||
| /// | ||
| /// Each edge in the [`CallGraph`] is annotated with a `CallKind` to distinguish direct call sites | ||
| /// from other kinds of references. This enables consumers to differentiate between actual function | ||
| /// invocations and incidental references. | ||
| #[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
| pub enum CallKind { | ||
| /// Direct function application at the given MIR [`Location`]. | ||
| /// | ||
| /// Created when a [`DefId`] appears syntactically as the function operand in an [`Apply`] | ||
| /// rvalue. The location identifies the exact statement where the call occurs. | ||
| /// | ||
| /// [`Apply`]: crate::body::rvalue::Apply | ||
| Apply(Location), | ||
|
|
||
| /// Graph-read filter function call at the given [`GraphReadLocation`]. | ||
| /// | ||
| /// Created when a [`DefId`] is the filter function in a [`GraphReadBody::Filter`] terminator. | ||
| /// | ||
| /// [`GraphReadBody::Filter`]: crate::body::terminator::GraphReadBody::Filter | ||
| Filter(GraphReadLocation), | ||
|
|
||
| /// Any other reference to a [`DefId`]. | ||
| /// | ||
| /// Includes type references, constant uses, function pointer assignments, and indirect call | ||
| /// targets. For indirect calls, this edge appears at the assignment site, not the call site. | ||
| Opaque, | ||
| } | ||
|
|
||
| /// A directed graph of [`DefId`] references across MIR bodies. | ||
| /// | ||
| /// Nodes correspond to [`DefId`]s and edges represent references from one definition to another, | ||
| /// annotated with [`CallKind`] to distinguish call sites from other reference types. | ||
| /// | ||
| /// The graph is populated by running [`CallGraphAnalysis`] on each MIR body. Multiple bodies | ||
| /// can contribute edges to the same graph, building up a complete picture of inter-procedural | ||
| /// references. | ||
| pub struct CallGraph<A: Allocator = Global> { | ||
| inner: LinkedGraph<(), CallKind, A>, | ||
| } | ||
|
|
||
| impl CallGraph { | ||
| /// Creates a new call graph with the given `domain` of [`DefId`]s. | ||
| /// | ||
| /// All [`DefId`]s that may appear as edge endpoints must be present in the domain. | ||
| pub fn new(domain: &DefIdSlice<impl Sized>) -> Self { | ||
| Self::new_in(domain, Global) | ||
| } | ||
| } | ||
|
|
||
| impl<A: Allocator + Clone> CallGraph<A> { | ||
| /// Creates a new call graph with the given `domain` using the specified `alloc`ator. | ||
| /// | ||
| /// All [`DefId`]s that may appear as edge endpoints must be present in the domain. | ||
| pub fn new_in(domain: &DefIdSlice<impl Sized>, alloc: A) -> Self { | ||
| let mut graph = LinkedGraph::new_in(alloc); | ||
| graph.derive(domain, |_, _| ()); | ||
|
|
||
| Self { inner: graph } | ||
| } | ||
| } | ||
|
|
||
| impl<A: Allocator> fmt::Display for CallGraph<A> { | ||
| fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| for edge in self.inner.edges() { | ||
| let source = DefId::from_usize(edge.source().as_usize()); | ||
| let target = DefId::from_usize(edge.target().as_usize()); | ||
|
|
||
| match edge.data { | ||
| CallKind::Apply(location) => { | ||
| writeln!(fmt, "@{source} -> @{target} [Apply @ {location}]")?; | ||
| } | ||
| CallKind::Filter(location) => { | ||
| writeln!(fmt, "@{source} -> @{target} [Filter @ {location}]")?; | ||
| } | ||
| CallKind::Opaque => { | ||
| writeln!(fmt, "@{source} -> @{target} [Opaque]")?; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| /// Analysis pass that populates a [`CallGraph`] from MIR bodies. | ||
| /// | ||
| /// This pass traverses a MIR body and records an edge for each [`DefId`] reference encountered, | ||
| /// annotated with the appropriate [`CallKind`]. Run this pass on each body to build a complete | ||
| /// inter-procedural call graph. | ||
| pub struct CallGraphAnalysis<'graph, A: Allocator = Global> { | ||
| graph: &'graph mut CallGraph<A>, | ||
| } | ||
|
|
||
| impl<'graph, A: Allocator> CallGraphAnalysis<'graph, A> { | ||
| /// Creates a new analysis pass that will populate the given `graph`. | ||
| pub const fn new(graph: &'graph mut CallGraph<A>) -> Self { | ||
| Self { graph } | ||
| } | ||
| } | ||
|
|
||
| impl<'env, 'heap, A: Allocator> AnalysisPass<'env, 'heap> for CallGraphAnalysis<'_, A> { | ||
| fn run(&mut self, _: &mut MirContext<'env, 'heap>, body: &Body<'heap>) { | ||
| let mut visitor = CallGraphVisitor { | ||
| kind: CallKind::Opaque, | ||
| caller: body.id, | ||
| graph: self.graph, | ||
| }; | ||
|
|
||
| Ok(()) = visitor.visit_body(body); | ||
| } | ||
| } | ||
|
|
||
| /// Visitor that collects call edges during MIR traversal. | ||
| struct CallGraphVisitor<'graph, A: Allocator = Global> { | ||
| kind: CallKind, | ||
| caller: DefId, | ||
| graph: &'graph mut CallGraph<A>, | ||
| } | ||
|
|
||
| impl<'heap, A: Allocator> Visitor<'heap> for CallGraphVisitor<'_, A> { | ||
| type Result = Result<(), !>; | ||
|
|
||
| fn visit_def_id(&mut self, _: Location, def_id: DefId) -> Self::Result { | ||
| let source = NodeId::from_usize(self.caller.as_usize()); | ||
| let target = NodeId::from_usize(def_id.as_usize()); | ||
|
|
||
| self.graph.inner.add_edge(source, target, self.kind); | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn visit_rvalue_apply( | ||
| &mut self, | ||
| location: Location, | ||
| Apply { | ||
| function, | ||
| arguments, | ||
| }: &Apply<'heap>, | ||
| ) -> Self::Result { | ||
| debug_assert_eq!(self.kind, CallKind::Opaque); | ||
| self.kind = CallKind::Apply(location); | ||
| self.visit_operand(location, function)?; | ||
| self.kind = CallKind::Opaque; | ||
|
|
||
| for argument in arguments.iter() { | ||
| self.visit_operand(location, argument)?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| fn visit_graph_read_body( | ||
| &mut self, | ||
| location: GraphReadLocation, | ||
| body: &GraphReadBody, | ||
| ) -> Self::Result { | ||
| match body { | ||
| &GraphReadBody::Filter(func, env) => { | ||
| debug_assert_eq!(self.kind, CallKind::Opaque); | ||
| self.kind = CallKind::Filter(location); | ||
| self.visit_def_id(location.base, func)?; | ||
| self.kind = CallKind::Opaque; | ||
|
|
||
| self.visit_local( | ||
| location.base, | ||
| PlaceContext::Read(PlaceReadContext::Load), | ||
| env, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
CallGraphAnalysisassumesbody.idis a valid in-domainDefId; otherwiseadd_edgewill panic (e.g., bodies produced byBodyBuilder::finishdefault toDefId::MAXunless overwritten). Consider asserting/documenting this precondition here to make failures easier to diagnose.π€ Was this useful? React with π or π