hugr_core/builder/cfg.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
use super::{
build_traits::SubContainer,
dataflow::{DFGBuilder, DFGWrapper},
handle::BuildHandle,
BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire,
};
use crate::extension::TO_BE_INFERRED;
use crate::ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType};
use crate::{extension::ExtensionSet, types::Signature};
use crate::{hugr::views::HugrView, types::TypeRow};
use crate::Node;
use crate::{hugr::HugrMut, type_row, Hugr};
/// Builder for a [`crate::ops::CFG`] child control
/// flow graph.
///
/// These builder methods should ensure that the first two children of a CFG
/// node are the entry node and the exit node.
///
/// # Example
/// ```
/// /* Build a control flow graph with the following structure:
/// +-----------+
/// | Entry |
/// +-/-----\---+
/// / \
/// / \
/// / \
/// / \
/// +-----/----+ +--\-------+
/// | Branch A | | Branch B |
/// +-----\----+ +----/-----+
/// \ /
/// \ /
/// \ /
/// \ /
/// +-\-------/--+
/// | Exit |
/// +------------+
/// */
/// use hugr::{
/// builder::{BuildError, CFGBuilder, Container, Dataflow, HugrBuilder, endo_sig, inout_sig},
/// extension::{prelude, ExtensionSet},
/// ops, type_row,
/// types::{Signature, SumType, Type},
/// Hugr,
/// extension::prelude::usize_t,
/// };
///
/// fn make_cfg() -> Result<Hugr, BuildError> {
/// let mut cfg_builder = CFGBuilder::new(Signature::new_endo(usize_t()))?;
///
/// // Outputs from basic blocks must be packed in a sum which corresponds to
/// // which successor to pick. We'll either choose the first branch and pass
/// // it a usize, or the second branch and pass it nothing.
/// let sum_variants = vec![vec![usize_t()].into(), type_row![]];
///
/// // The second argument says what types will be passed through to every
/// // successor, in addition to the appropriate `sum_variants` type.
/// let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), vec![usize_t()].into())?;
///
/// let [inw] = entry_b.input_wires_arr();
/// let entry = {
/// // Pack the const "42" into the appropriate sum type.
/// let left_42 = ops::Value::sum(
/// 0,
/// [prelude::ConstUsize::new(42).into()],
/// SumType::new(sum_variants.clone()),
/// )?;
/// let sum = entry_b.add_load_value(left_42);
///
/// entry_b.finish_with_outputs(sum, [inw])?
/// };
///
/// // This block will be the first successor of the entry node. It takes two
/// // `usize` arguments: one from the `sum_variants` type, and another from the
/// // entry node's `other_outputs`.
/// let mut successor_builder = cfg_builder.simple_block_builder(
/// inout_sig(vec![usize_t(), usize_t()], usize_t()),
/// 1, // only one successor to this block
/// )?;
/// let successor_a = {
/// // This block has one successor. The choice is denoted by a unary sum.
/// let sum_unary = successor_builder.add_load_const(ops::Value::unary_unit_sum());
///
/// // The input wires of a node start with the data embedded in the variant
/// // which selected this block.
/// let [_forty_two, in_wire] = successor_builder.input_wires_arr();
/// successor_builder.finish_with_outputs(sum_unary, [in_wire])?
/// };
///
/// // The only argument to this block is the entry node's `other_outputs`.
/// let mut successor_builder = cfg_builder.simple_block_builder(endo_sig(usize_t()), 1)?;
/// let successor_b = {
/// let sum_unary = successor_builder.add_load_value(ops::Value::unary_unit_sum());
/// let [in_wire] = successor_builder.input_wires_arr();
/// successor_builder.finish_with_outputs(sum_unary, [in_wire])?
/// };
/// let exit = cfg_builder.exit_block();
/// cfg_builder.branch(&entry, 0, &successor_a)?; // branch 0 goes to successor_a
/// cfg_builder.branch(&entry, 1, &successor_b)?; // branch 1 goes to successor_b
/// cfg_builder.branch(&successor_a, 0, &exit)?;
/// cfg_builder.branch(&successor_b, 0, &exit)?;
/// let hugr = cfg_builder.finish_hugr()?;
/// Ok(hugr)
/// };
/// #[cfg(not(feature = "extension_inference"))]
/// assert!(make_cfg().is_ok());
/// ```
#[derive(Debug, PartialEq)]
pub struct CFGBuilder<T> {
pub(super) base: T,
pub(super) cfg_node: Node,
pub(super) inputs: Option<TypeRow>,
pub(super) exit_node: Node,
pub(super) n_out_wires: usize,
}
impl<B: AsMut<Hugr> + AsRef<Hugr>> Container for CFGBuilder<B> {
#[inline]
fn container_node(&self) -> Node {
self.cfg_node
}
#[inline]
fn hugr_mut(&mut self) -> &mut Hugr {
self.base.as_mut()
}
#[inline]
fn hugr(&self) -> &Hugr {
self.base.as_ref()
}
}
impl<H: AsMut<Hugr> + AsRef<Hugr>> SubContainer for CFGBuilder<H> {
type ContainerHandle = BuildHandle<CfgID>;
#[inline]
fn finish_sub_container(self) -> Result<Self::ContainerHandle, BuildError> {
Ok((self.cfg_node, self.n_out_wires).into())
}
}
impl CFGBuilder<Hugr> {
/// New CFG rooted HUGR builder
pub fn new(signature: Signature) -> Result<Self, BuildError> {
let cfg_op = ops::CFG {
signature: signature.clone(),
};
let base = Hugr::new(cfg_op);
let cfg_node = base.root();
CFGBuilder::create(base, cfg_node, signature.input, signature.output)
}
}
impl HugrBuilder for CFGBuilder<Hugr> {
fn finish_hugr(mut self) -> Result<Hugr, crate::hugr::ValidationError> {
if cfg!(feature = "extension_inference") {
self.base.infer_extensions(false)?;
}
self.base.validate()?;
Ok(self.base)
}
}
impl<B: AsMut<Hugr> + AsRef<Hugr>> CFGBuilder<B> {
pub(super) fn create(
mut base: B,
cfg_node: Node,
input: TypeRow,
output: TypeRow,
) -> Result<Self, BuildError> {
let n_out_wires = output.len();
let exit_block_type = OpType::ExitBlock(ExitBlock {
cfg_outputs: output,
});
let exit_node = base
.as_mut()
// Make the extensions a parameter
.add_node_with_parent(cfg_node, exit_block_type);
Ok(Self {
base,
cfg_node,
n_out_wires,
exit_node,
inputs: Some(input),
})
}
/// Return a builder for a non-entry [`DataflowBlock`] child graph with `inputs`
/// and `outputs` and the variants of the branching Sum value
/// specified by `sum_rows`. Extension delta will be inferred.
///
/// # Errors
///
/// This function will return an error if there is an error adding the node.
pub fn block_builder(
&mut self,
inputs: TypeRow,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: TypeRow,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.block_builder_exts(inputs, sum_rows, other_outputs, TO_BE_INFERRED)
}
/// Return a builder for a non-entry [`DataflowBlock`] child graph with `inputs`
/// and `outputs` and the variants of the branching Sum value
/// specified by `sum_rows`. Extension delta will be inferred.
///
/// # Errors
///
/// This function will return an error if there is an error adding the node.
pub fn block_builder_exts(
&mut self,
inputs: TypeRow,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: TypeRow,
extension_delta: impl Into<ExtensionSet>,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.any_block_builder(
inputs,
extension_delta.into(),
sum_rows,
other_outputs,
false,
)
}
fn any_block_builder(
&mut self,
inputs: TypeRow,
extension_delta: ExtensionSet,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: TypeRow,
entry: bool,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
let sum_rows: Vec<_> = sum_rows.into_iter().collect();
let op = OpType::DataflowBlock(DataflowBlock {
inputs: inputs.clone(),
other_outputs: other_outputs.clone(),
sum_rows,
extension_delta,
});
let parent = self.container_node();
let block_n = if entry {
let exit = self.exit_node;
// TODO: Make extensions a parameter
self.hugr_mut().add_node_before(exit, op)
} else {
// TODO: Make extensions a parameter
self.hugr_mut().add_node_with_parent(parent, op)
};
BlockBuilder::create(self.hugr_mut(), block_n)
}
/// Return a builder for a non-entry [`DataflowBlock`] child graph with `inputs`
/// and `outputs` and `extension_delta` explicitly specified, plus a UnitSum type
/// (a Sum of `n_cases` unit types) to select the successor.
///
/// # Errors
///
/// This function will return an error if there is an error adding the node.
pub fn simple_block_builder(
&mut self,
signature: Signature,
n_cases: usize,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.block_builder_exts(
signature.input,
vec![type_row![]; n_cases],
signature.output,
signature.runtime_reqs,
)
}
/// Return a builder for the entry [`DataflowBlock`] child graph with `outputs`
/// and the variants of the branching Sum value specified by `sum_rows`.
/// Extension delta will be inferred.
///
/// # Errors
///
/// This function will return an error if an entry block has already been built.
pub fn entry_builder(
&mut self,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: TypeRow,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.entry_builder_exts(sum_rows, other_outputs, TO_BE_INFERRED)
}
/// Return a builder for the entry [`DataflowBlock`] child graph with `outputs`,
/// the variants of the branching Sum value specified by `sum_rows`, and
/// `extension_delta` explicitly specified. ([entry_builder](Self::entry_builder)
/// may be used to infer.)
///
/// # Errors
///
/// This function will return an error if an entry block has already been built.
pub fn entry_builder_exts(
&mut self,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: TypeRow,
extension_delta: impl Into<ExtensionSet>,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
let inputs = self
.inputs
.take()
.ok_or(BuildError::EntryBuiltError(self.cfg_node))?;
self.any_block_builder(
inputs,
extension_delta.into(),
sum_rows,
other_outputs,
true,
)
}
/// Return a builder for the entry [`DataflowBlock`] child graph with
/// `outputs` and a UnitSum type: a Sum of `n_cases` unit types.
///
/// # Errors
///
/// This function will return an error if there is an error adding the node.
pub fn simple_entry_builder(
&mut self,
outputs: TypeRow,
n_cases: usize,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.entry_builder(vec![type_row![]; n_cases], outputs)
}
/// Return a builder for the entry [`DataflowBlock`] child graph with
/// `outputs` and a Sum of `n_cases` unit types, and explicit `extension_delta`.
/// ([simple_entry_builder](Self::simple_entry_builder) may be used to infer.)
///
/// # Errors
///
/// This function will return an error if there is an error adding the node.
pub fn simple_entry_builder_exts(
&mut self,
outputs: TypeRow,
n_cases: usize,
extension_delta: impl Into<ExtensionSet>,
) -> Result<BlockBuilder<&mut Hugr>, BuildError> {
self.entry_builder_exts(vec![type_row![]; n_cases], outputs, extension_delta)
}
/// Returns the exit block of this [`CFGBuilder`].
pub fn exit_block(&self) -> BasicBlockID {
self.exit_node.into()
}
/// Set the `branch` index `successor` block of `predecessor`.
///
/// # Errors
///
/// This function will return an error if there is an error connecting the blocks.
pub fn branch(
&mut self,
predecessor: &BasicBlockID,
branch: usize,
successor: &BasicBlockID,
) -> Result<(), BuildError> {
let from = predecessor.node();
let to = successor.node();
self.hugr_mut().connect(from, branch, to, 0);
Ok(())
}
}
/// Builder for a [`DataflowBlock`] child graph.
pub type BlockBuilder<B> = DFGWrapper<B, BasicBlockID>;
impl<B: AsMut<Hugr> + AsRef<Hugr>> BlockBuilder<B> {
/// Set the outputs of the block, with `branch_wire` carrying the value of the
/// branch controlling Sum value. `outputs` are the remaining outputs.
pub fn set_outputs(
&mut self,
branch_wire: Wire,
outputs: impl IntoIterator<Item = Wire>,
) -> Result<(), BuildError> {
Dataflow::set_outputs(self, [branch_wire].into_iter().chain(outputs))
}
fn create(base: B, block_n: Node) -> Result<Self, BuildError> {
let block_op = base
.as_ref()
.get_optype(block_n)
.as_dataflow_block()
.unwrap();
let signature = block_op.inner_signature().into_owned();
let db = DFGBuilder::create_with_io(base, block_n, signature)?;
Ok(BlockBuilder::from_dfg_builder(db))
}
/// [Set outputs](BlockBuilder::set_outputs) and [finish](`BlockBuilder::finish_sub_container`).
pub fn finish_with_outputs(
mut self,
branch_wire: Wire,
outputs: impl IntoIterator<Item = Wire>,
) -> Result<<Self as SubContainer>::ContainerHandle, BuildError>
where
Self: Sized,
{
self.set_outputs(branch_wire, outputs)?;
self.finish_sub_container()
}
}
impl BlockBuilder<Hugr> {
/// Initialize a [`DataflowBlock`] rooted HUGR builder.
/// Extension delta will be inferred.
pub fn new(
inputs: impl Into<TypeRow>,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: impl Into<TypeRow>,
) -> Result<Self, BuildError> {
Self::new_exts(inputs, sum_rows, other_outputs, TO_BE_INFERRED)
}
/// Initialize a [`DataflowBlock`] rooted HUGR builder.
/// `extension_delta` is explicitly specified; alternatively, [new](Self::new)
/// may be used to infer it.
pub fn new_exts(
inputs: impl Into<TypeRow>,
sum_rows: impl IntoIterator<Item = TypeRow>,
other_outputs: impl Into<TypeRow>,
extension_delta: impl Into<ExtensionSet>,
) -> Result<Self, BuildError> {
let inputs = inputs.into();
let sum_rows: Vec<_> = sum_rows.into_iter().collect();
let other_outputs = other_outputs.into();
let op = DataflowBlock {
inputs: inputs.clone(),
other_outputs: other_outputs.clone(),
sum_rows,
extension_delta: extension_delta.into(),
};
let base = Hugr::new(op);
let root = base.root();
Self::create(base, root)
}
/// [Set outputs](BlockBuilder::set_outputs) and [finish_hugr](`BlockBuilder::finish_hugr`).
pub fn finish_hugr_with_outputs(
mut self,
branch_wire: Wire,
outputs: impl IntoIterator<Item = Wire>,
) -> Result<Hugr, BuildError> {
self.set_outputs(branch_wire, outputs)?;
self.finish_hugr().map_err(BuildError::InvalidHUGR)
}
}
#[cfg(test)]
pub(crate) mod test {
use crate::builder::{DataflowSubContainer, ModuleBuilder};
use crate::extension::prelude::usize_t;
use crate::hugr::validate::InterGraphEdgeError;
use crate::hugr::ValidationError;
use crate::type_row;
use cool_asserts::assert_matches;
use super::*;
#[test]
fn basic_module_cfg() -> Result<(), BuildError> {
let build_result = {
let mut module_builder = ModuleBuilder::new();
let mut func_builder = module_builder
.define_function("main", Signature::new(vec![usize_t()], vec![usize_t()]))?;
let _f_id = {
let [int] = func_builder.input_wires_arr();
let cfg_id = {
let mut cfg_builder =
func_builder.cfg_builder(vec![(usize_t(), int)], vec![usize_t()].into())?;
build_basic_cfg(&mut cfg_builder)?;
cfg_builder.finish_sub_container()?
};
func_builder.finish_with_outputs(cfg_id.outputs())?
};
module_builder.finish_hugr()
};
assert!(build_result.is_ok(), "{}", build_result.unwrap_err());
Ok(())
}
#[test]
fn basic_cfg_hugr() -> Result<(), BuildError> {
let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?;
build_basic_cfg(&mut cfg_builder)?;
assert_matches!(cfg_builder.finish_hugr(), Ok(_));
Ok(())
}
pub(crate) fn build_basic_cfg<T: AsMut<Hugr> + AsRef<Hugr>>(
cfg_builder: &mut CFGBuilder<T>,
) -> Result<(), BuildError> {
let usize_row: TypeRow = vec![usize_t()].into();
let sum2_variants = vec![usize_row.clone(), usize_row];
let mut entry_b = cfg_builder.entry_builder_exts(
sum2_variants.clone(),
type_row![],
ExtensionSet::new(),
)?;
let entry = {
let [inw] = entry_b.input_wires_arr();
let sum = entry_b.make_sum(1, sum2_variants, [inw])?;
entry_b.finish_with_outputs(sum, [])?
};
let mut middle_b = cfg_builder
.simple_block_builder(Signature::new(vec![usize_t()], vec![usize_t()]), 1)?;
let middle = {
let c = middle_b.add_load_const(ops::Value::unary_unit_sum());
let [inw] = middle_b.input_wires_arr();
middle_b.finish_with_outputs(c, [inw])?
};
let exit = cfg_builder.exit_block();
cfg_builder.branch(&entry, 0, &middle)?;
cfg_builder.branch(&middle, 0, &exit)?;
cfg_builder.branch(&entry, 1, &exit)?;
Ok(())
}
#[test]
fn test_dom_edge() -> Result<(), BuildError> {
let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?;
let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum());
let sum_variants = vec![type_row![]];
let mut entry_b = cfg_builder.entry_builder_exts(
sum_variants.clone(),
type_row![],
ExtensionSet::new(),
)?;
let [inw] = entry_b.input_wires_arr();
let entry = {
let sum = entry_b.load_const(&sum_tuple_const);
entry_b.finish_with_outputs(sum, [])?
};
let mut middle_b =
cfg_builder.simple_block_builder(Signature::new(type_row![], vec![usize_t()]), 1)?;
let middle = {
let c = middle_b.load_const(&sum_tuple_const);
middle_b.finish_with_outputs(c, [inw])?
};
let exit = cfg_builder.exit_block();
cfg_builder.branch(&entry, 0, &middle)?;
cfg_builder.branch(&middle, 0, &exit)?;
assert_matches!(cfg_builder.finish_hugr(), Ok(_));
Ok(())
}
#[test]
fn test_non_dom_edge() -> Result<(), BuildError> {
let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?;
let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum());
let sum_variants = vec![type_row![]];
let mut middle_b = cfg_builder
.simple_block_builder(Signature::new(vec![usize_t()], vec![usize_t()]), 1)?;
let [inw] = middle_b.input_wires_arr();
let middle = {
let c = middle_b.load_const(&sum_tuple_const);
middle_b.finish_with_outputs(c, [inw])?
};
let mut entry_b =
cfg_builder.entry_builder(sum_variants.clone(), vec![usize_t()].into())?;
let entry = {
let sum = entry_b.load_const(&sum_tuple_const);
// entry block uses wire from middle block even though middle block
// does not dominate entry
entry_b.finish_with_outputs(sum, [inw])?
};
let exit = cfg_builder.exit_block();
cfg_builder.branch(&entry, 0, &middle)?;
cfg_builder.branch(&middle, 0, &exit)?;
assert_matches!(
cfg_builder.finish_hugr(),
Err(ValidationError::InterGraphEdgeError(
InterGraphEdgeError::NonDominatedAncestor { .. }
))
);
Ok(())
}
}