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
use crate::traversal::{Action, Named, VisResult, Visitor};
use calyx_ir::{self as ir, Attributes, Enable, RRC};
use ir::Nothing;
use linked_hash_map::LinkedHashMap;
use std::iter::Iterator;
use std::mem;
use std::rc::Rc;

#[derive(Default)]
/// under a par control block, if multiple groups have the same static attribute, then
/// merge them together.
///
/// Running this pass removes unnecessary FSM transitions
///
/// #Example
/// 1. Under a par block
/// group A<"static"=1>{
/// a; b;
/// }
/// group B<"static"=1>{
/// c; d;
/// }
/// par {A; B;}
///
/// into
///
/// group msp<"static"=1>{
/// a; b; c; d;
/// }
/// par {msp; }
///
/// note that a, b, c, d are assignments
pub struct MergeStaticPar;

impl Named for MergeStaticPar {
    fn name() -> &'static str {
        "merge-static-par"
    }

    fn description() -> &'static str {
        "merge static pars when they have the same static time"
    }
}

impl Visitor for MergeStaticPar {
    fn finish_par(
        &mut self,
        s: &mut ir::Par,
        comp: &mut ir::Component,
        sigs: &ir::LibrarySignatures,
        _comps: &[ir::Component],
    ) -> VisResult {
        let mut static_group: LinkedHashMap<u64, Vec<RRC<ir::Group>>> =
            LinkedHashMap::new();
        let (e_stmts, n_stmts): (Vec<ir::Control>, Vec<ir::Control>) =
            mem::take(&mut s.stmts).into_iter().partition(|stmt| {
                if let ir::Control::Enable(en) = stmt {
                    matches!(
                        en.group.borrow().attributes.get(ir::NumAttr::Static),
                        Some(_)
                    )
                } else {
                    false
                }
            });

        s.stmts.extend(n_stmts);

        for stmt in e_stmts {
            if let ir::Control::Enable(data) = stmt {
                let group = &data.group;
                if let Some(static_time) =
                    group.borrow().attributes.get(ir::NumAttr::Static)
                {
                    if !static_group.contains_key(&static_time) {
                        static_group.insert(static_time, Vec::new());
                    }
                    static_group
                        .get_mut(&static_time)
                        .unwrap()
                        .push(Rc::clone(group));
                }
            }
        }

        for (key, value) in static_group {
            if value.len() != 1 {
                let mut builder = ir::Builder::new(comp, sigs);
                let grp = builder.add_group("msp");
                let mut assignments: Vec<ir::Assignment<Nothing>> = Vec::new();
                for group in value.iter() {
                    assignments.extend(group.borrow().assignments.clone());
                }

                let (done_asmts, asmts): (
                    Vec<ir::Assignment<Nothing>>,
                    Vec<ir::Assignment<Nothing>>,
                ) = mem::take(&mut assignments)
                    .into_iter()
                    .partition(|x| x.dst.borrow().is_hole());

                grp.borrow_mut().assignments.extend(asmts);

                let mut fin_grd: ir::Guard<Nothing> = ir::Guard::True;
                for asmt in done_asmts.clone() {
                    let grd: ir::Guard<Nothing> = ir::Guard::Port(asmt.src);
                    fin_grd &= grd;
                    fin_grd &= *asmt.guard;
                }

                let cst = builder.add_constant(1, 1);

                let done_asmt = builder.build_assignment(
                    grp.borrow().get("done"),
                    cst.borrow().get("out"),
                    fin_grd,
                );

                grp.borrow_mut().assignments.push(done_asmt);

                grp.borrow_mut().attributes.insert(ir::NumAttr::Static, key);
                comp.get_groups_mut().add(Rc::clone(&grp));

                let mut enable: ir::Enable = Enable {
                    group: Rc::clone(&grp),
                    attributes: Attributes::default(),
                };
                enable.attributes.insert(ir::NumAttr::Static, key);
                s.stmts.push(ir::Control::Enable(enable));
            } else {
                let mut enable: ir::Enable = Enable {
                    group: Rc::clone(&value[0]),
                    attributes: Attributes::default(),
                };
                enable.attributes.insert(ir::NumAttr::Static, key);
                s.stmts.push(ir::Control::Enable(enable));
            }
        }

        Ok(Action::Continue)
    }
}