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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions libs/@local/hashql/mir/src/body/location.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use core::{fmt, fmt::Display};

use super::basic_block::BasicBlockId;

/// A precise location identifying a specific statement within the MIR control flow graph.
Expand Down Expand Up @@ -31,3 +33,14 @@ impl Location {
statement_index: usize::MAX,
};
}

impl Display for Location {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
block,
statement_index,
} = self;

write!(fmt, "bb{block}:{statement_index}")
}
}
7 changes: 7 additions & 0 deletions libs/@local/hashql/mir/src/body/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,13 @@ pub enum Source<'heap> {
/// usage and improve interning efficiency while maintaining sufficient debugging information.
#[derive(Debug, Clone)]
pub struct Body<'heap> {
/// The unique identifier for this body.
///
/// This [`DefId`] serves as a stable reference to this body within a collection of bodies,
/// enabling cross-body analyses like call graphs. The `DefId` is assigned during lowering
/// and corresponds to the body's index in the global definition table.
pub id: DefId,

/// The source location span for this entire body.
///
/// This [`SpanId`] tracks the source location of the function, closure,
Expand Down
13 changes: 13 additions & 0 deletions libs/@local/hashql/mir/src/body/terminator/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//! the HashQL graph store. They provide structured access to graph data with
//! control flow implications based on query results.

use core::{fmt, fmt::Display};

use hashql_core::heap;

use crate::{
Expand Down Expand Up @@ -33,6 +35,17 @@ pub struct GraphReadLocation {
pub graph_read_index: usize,
}

impl Display for GraphReadLocation {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
base,
graph_read_index,
} = self;

write!(fmt, "{base}:{graph_read_index}")
}
}

/// The starting point for a graph read operation.
///
/// Determines where the query begins in the bi-temporal graph. The head
Expand Down
1 change: 1 addition & 0 deletions libs/@local/hashql/mir/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ impl<'env, 'heap> BodyBuilder<'env, 'heap> {
);

Body {
id: DefId::MAX,
span: SpanId::SYNTHETIC,
return_type: return_ty,
source: Source::Intrinsic(DefId::MAX),
Expand Down
240 changes: 240 additions & 0 deletions libs/@local/hashql/mir/src/pass/analysis/callgraph/mod.rs
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,
Copy link

Choose a reason for hiding this comment

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

CallGraphAnalysis assumes body.id is a valid in-domain DefId; otherwise add_edge will panic (e.g., bodies produced by BodyBuilder::finish default to DefId::MAX unless overwritten). Consider asserting/documenting this precondition here to make failures easier to diagnose.

Fix This in Augment

πŸ€– Was this useful? React with πŸ‘ or πŸ‘Ž

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,
)
}
}
}
}
Loading
Loading