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
// Copyright (C) 2024 Ethan Uppal. All rights reserved.
use super::basic_block::{BasicBlock, BasicBlockCell};
use pulsar_utils::digraph::Digraph;
use std::fmt::Display;

pub struct ControlFlowGraph {
    in_graph: Digraph<BasicBlockCell, bool>,
    out_graph: Digraph<BasicBlockCell, bool>,
    entry: BasicBlockCell
}

impl ControlFlowGraph {
    pub fn new() -> Self {
        let entry = BasicBlockCell::new(BasicBlock::new());
        let mut in_graph = Digraph::new();
        let mut out_graph = Digraph::new();

        in_graph.add_node(entry.clone());
        out_graph.add_node(entry.clone());

        Self {
            in_graph,
            out_graph,
            entry
        }
    }

    pub fn entry(&self) -> BasicBlockCell {
        self.entry.clone()
    }

    pub fn new_block(&mut self) -> BasicBlockCell {
        let block = BasicBlockCell::new(BasicBlock::new());
        self.in_graph.add_node(block.clone());
        self.out_graph.add_node(block.clone());
        block
    }

    pub fn add_branch(
        &mut self, block: BasicBlockCell, condition: bool, dest: BasicBlockCell
    ) {
        self.in_graph
            .add_edge(dest.clone(), condition, block.clone());
        self.out_graph.add_edge(block, condition, dest);
    }

    pub fn size(&self) -> usize {
        self.out_graph.node_count()
    }

    pub fn blocks(&self) -> Vec<BasicBlockCell> {
        let mut result = vec![];
        self.out_graph
            .dfs(|node| result.push(node), self.entry.clone());
        result
    }
}

impl Display for ControlFlowGraph {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut i = 0;
        for basic_block in &self.out_graph.nodes() {
            if i > 0 {
                writeln!(f)?;
            }
            write!(f, "{}", basic_block)?;
            i += 1;
        }
        Ok(())
    }
}