Skip to content

feat!: Handle CallIndirect in Dataflow Analysis #2059

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 20 commits into from
Apr 16, 2025
Merged
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
63 changes: 17 additions & 46 deletions hugr-passes/src/const_fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,11 @@ use std::{collections::HashMap, sync::Arc};
use thiserror::Error;

use hugr_core::{
hugr::{
hugrmut::HugrMut,
views::{DescendantsGraph, ExtractHugr, HierarchyView},
},
hugr::hugrmut::HugrMut,
ops::{
constant::OpaqueValue, handle::FuncID, Const, DataflowOpTrait, ExtensionOp, LoadConstant,
OpType, Value,
constant::OpaqueValue, Const, DataflowOpTrait, ExtensionOp, LoadConstant, OpType, Value,
},
types::{EdgeKind, TypeArg},
types::EdgeKind,
HugrView, IncomingPort, Node, NodeIndex, OutgoingPort, PortIndex, Wire,
};
use value_handle::ValueHandle;
Expand Down Expand Up @@ -102,7 +98,7 @@ impl ConstantFoldPass {
n,
in_vals.iter().map(|(p, v)| {
let const_with_dummy_loc = partial_from_const(
&ConstFoldContext(hugr),
&ConstFoldContext,
ConstLocation::Field(p.index(), &fresh_node.into()),
v,
);
Expand All @@ -112,7 +108,7 @@ impl ConstantFoldPass {
.map_err(|opty| ConstFoldError::InvalidEntryPoint(n, opty))?;
}

let results = m.run(ConstFoldContext(hugr), []);
let results = m.run(ConstFoldContext, []);
let mb_root_inp = hugr.get_io(hugr.root()).map(|[i, _]| i);

let wires_to_break = hugr
Expand All @@ -131,7 +127,7 @@ impl ConstantFoldPass {
n,
ip,
results
.try_read_wire_concrete::<Value, _, _>(Wire::new(src, outp))
.try_read_wire_concrete::<Value>(Wire::new(src, outp))
.ok()?,
))
})
Expand Down Expand Up @@ -205,60 +201,35 @@ pub fn constant_fold_pass<H: HugrMut>(h: &mut H) {
c.run(h).unwrap()
}

struct ConstFoldContext<'a, H>(&'a H);

impl<H: HugrView> std::ops::Deref for ConstFoldContext<'_, H> {
type Target = H;
fn deref(&self) -> &H {
self.0
}
}
struct ConstFoldContext;

impl<H: HugrView<Node = Node>> ConstLoader<ValueHandle<H::Node>> for ConstFoldContext<'_, H> {
type Node = H::Node;
impl ConstLoader<ValueHandle<Node>> for ConstFoldContext {
type Node = Node;

fn value_from_opaque(
&self,
loc: ConstLocation<H::Node>,
loc: ConstLocation<Node>,
val: &OpaqueValue,
) -> Option<ValueHandle<H::Node>> {
) -> Option<ValueHandle<Node>> {
Some(ValueHandle::new_opaque(loc, val.clone()))
}

fn value_from_const_hugr(
&self,
loc: ConstLocation<H::Node>,
loc: ConstLocation<Node>,
h: &hugr_core::Hugr,
) -> Option<ValueHandle<H::Node>> {
) -> Option<ValueHandle<Node>> {
Some(ValueHandle::new_const_hugr(loc, Box::new(h.clone())))
}

fn value_from_function(
&self,
node: H::Node,
type_args: &[TypeArg],
) -> Option<ValueHandle<H::Node>> {
if !type_args.is_empty() {
// TODO: substitution across Hugr (https://github.com/CQCL/hugr/issues/709)
return None;
};
// Returning the function body as a value, here, would be sufficient for inlining IndirectCall
// but not for transforming to a direct Call.
let func = DescendantsGraph::<FuncID<true>>::try_new(&**self, node).ok()?;
Some(ValueHandle::new_const_hugr(
ConstLocation::Node(node),
Box::new(func.extract_hugr()),
))
}
}

impl<H: HugrView<Node = Node>> DFContext<ValueHandle<H::Node>> for ConstFoldContext<'_, H> {
impl DFContext<ValueHandle<Node>> for ConstFoldContext {
fn interpret_leaf_op(
&mut self,
node: H::Node,
node: Node,
op: &ExtensionOp,
ins: &[PartialValue<ValueHandle<H::Node>>],
outs: &mut [PartialValue<ValueHandle<H::Node>>],
ins: &[PartialValue<ValueHandle<Node>>],
outs: &mut [PartialValue<ValueHandle<Node>>],
) {
let sig = op.signature();
let known_ins = sig
Expand Down
6 changes: 2 additions & 4 deletions hugr-passes/src/const_fold/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ fn value_handling(#[case] k: impl CustomConst + Clone, #[case] eq: bool) {
let n = Node::from(portgraph::NodeIndex::new(7));
let st = SumType::new([vec![k.get_type()], vec![]]);
let subject_val = Value::sum(0, [k.clone().into()], st).unwrap();
let temp = Hugr::default();
let ctx: ConstFoldContext<Hugr> = ConstFoldContext(&temp);
let ctx = ConstFoldContext;
let v1 = partial_from_const(&ctx, n, &subject_val);

let v1_subfield = {
Expand Down Expand Up @@ -114,8 +113,7 @@ fn test_add(#[case] a: f64, #[case] b: f64, #[case] c: f64) {
v.get_custom_value::<ConstF64>().unwrap().value()
}
let [n, n_a, n_b] = [0, 1, 2].map(portgraph::NodeIndex::new).map(Node::from);
let temp = Hugr::default();
let mut ctx = ConstFoldContext(&temp);
let mut ctx = ConstFoldContext;
let v_a = partial_from_const(&ctx, n_a, &f2c(a));
let v_b = partial_from_const(&ctx, n_b, &f2c(b));
assert_eq!(unwrap_float(v_a.clone()), a);
Expand Down
23 changes: 18 additions & 5 deletions hugr-passes/src/const_fold/value_handle.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
//! Total equality (and hence [AbstractValue] support for [Value]s
//! (by adding a source-Node and part unhashable constants)
use std::collections::hash_map::DefaultHasher; // Moves into std::hash in Rust 1.76.
use std::convert::Infallible;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use hugr_core::core::HugrNode;
use hugr_core::ops::constant::OpaqueValue;
use hugr_core::ops::Value;
use hugr_core::types::ConstTypeError;
use hugr_core::{Hugr, Node};
use itertools::Either;

use crate::dataflow::{AbstractValue, ConstLocation};
use crate::dataflow::{AbstractValue, AsConcrete, ConstLocation, LoadedFunction, Sum};

/// A custom constant that has been successfully hashed via [TryHash](hugr_core::ops::constant::TryHash)
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -153,9 +155,12 @@ impl<N: HugrNode> Hash for ValueHandle<N> {

// Unfortunately we need From<ValueHandle> for Value to be able to pass
// Value's into interpret_leaf_op. So that probably doesn't make sense...
impl<N: HugrNode> From<ValueHandle<N>> for Value {
fn from(value: ValueHandle<N>) -> Self {
match value {
impl<N: HugrNode> AsConcrete<ValueHandle<N>, N> for Value {
type ValErr = Infallible;
type SumErr = ConstTypeError;

fn from_value(value: ValueHandle<N>) -> Result<Self, Infallible> {
Ok(match value {
ValueHandle::Hashable(HashedConst { val, .. })
| ValueHandle::Unhashable {
leaf: Either::Left(val),
Expand All @@ -169,7 +174,15 @@ impl<N: HugrNode> From<ValueHandle<N>> for Value {
} => Value::function(Arc::try_unwrap(hugr).unwrap_or_else(|a| a.as_ref().clone()))
.map_err(|e| e.to_string())
.unwrap(),
}
})
}

fn from_sum(value: Sum<Self>) -> Result<Self, Self::SumErr> {
Self::sum(value.tag, value.values, value.st)
}

fn from_func(func: LoadedFunction<N>) -> Result<Self, crate::dataflow::LoadedFunction<N>> {
Err(func)
}
}

Expand Down
17 changes: 9 additions & 8 deletions hugr-passes/src/dataflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod results;
pub use results::{AnalysisResults, TailLoopTermination};

mod partial_value;
pub use partial_value::{AbstractValue, PartialSum, PartialValue, Sum};
pub use partial_value::{AbstractValue, AsConcrete, LoadedFunction, PartialSum, PartialValue, Sum};

use hugr_core::ops::constant::OpaqueValue;
use hugr_core::ops::{ExtensionOp, Value};
Expand All @@ -31,8 +31,8 @@ pub trait DFContext<V>: ConstLoader<V> {
&mut self,
_node: Self::Node,
_e: &ExtensionOp,
_ins: &[PartialValue<V>],
_outs: &mut [PartialValue<V>],
_ins: &[PartialValue<V, Self::Node>],
_outs: &mut [PartialValue<V, Self::Node>],
) {
}
}
Expand All @@ -55,8 +55,8 @@ impl<N> From<N> for ConstLocation<'_, N> {
}

/// Trait for loading [PartialValue]s from constant [Value]s in a Hugr.
/// Implementors will likely want to override some/all of [Self::value_from_opaque],
/// [Self::value_from_const_hugr], and [Self::value_from_function]: the defaults
/// Implementors will likely want to override either/both of [Self::value_from_opaque]
/// and [Self::value_from_const_hugr]: the defaults
/// are "correct" but maximally conservative (minimally informative).
pub trait ConstLoader<V> {
/// The type of nodes in the Hugr.
Expand All @@ -81,6 +81,7 @@ pub trait ConstLoader<V> {
/// [FuncDefn]: hugr_core::ops::FuncDefn
/// [FuncDecl]: hugr_core::ops::FuncDecl
/// [LoadFunction]: hugr_core::ops::LoadFunction
#[deprecated(note = "Automatically handled by Datalog, implementation will be ignored")]
fn value_from_function(&self, _node: Self::Node, _type_args: &[TypeArg]) -> Option<V> {
None
}
Expand All @@ -94,7 +95,7 @@ pub fn partial_from_const<'a, V, CL: ConstLoader<V>>(
cl: &CL,
loc: impl Into<ConstLocation<'a, CL::Node>>,
cst: &Value,
) -> PartialValue<V>
) -> PartialValue<V, CL::Node>
where
CL::Node: 'a,
{
Expand All @@ -120,8 +121,8 @@ where

/// A row of inputs to a node contains bottom (can't happen, the node
/// can't execute) if any element [contains_bottom](PartialValue::contains_bottom).
pub fn row_contains_bottom<'a, V: AbstractValue + 'a>(
elements: impl IntoIterator<Item = &'a PartialValue<V>>,
pub fn row_contains_bottom<'a, V: 'a, N: 'a>(
elements: impl IntoIterator<Item = &'a PartialValue<V, N>>,
) -> bool {
elements.into_iter().any(PartialValue::contains_bottom)
}
Expand Down
Loading
Loading