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
use crate::{
    ir::{
        function::IsIRStatement,
        quantity::{self, local, Quantity, RegisterName},
    },
    utility::{
        data_type,
        data_type::Type,
        parsing::{self, in_multispace},
    },
};
use nom::{
    bytes::complete::tag,
    character::complete::space0,
    combinator::map,
    multi::separated_list1,
    sequence::{delimited, tuple},
    IResult,
};
use serde::{Deserialize, Serialize};
use std::fmt;
/// [`Phi`]'s source.
#[derive(Debug, Eq, PartialEq, Clone, Hash, Deserialize, Serialize)]
pub struct PhiSource {
    pub value: Quantity,
    pub block: String,
}

impl PartialOrd for PhiSource {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.block.partial_cmp(&other.block)
    }
}

impl Ord for PhiSource {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.block.cmp(&other.block)
    }
}

fn parse_phi_source(code: &str) -> IResult<&str, PhiSource> {
    map(
        delimited(
            tag("["),
            tuple((quantity::parse, space0, tag(","), space0, parsing::ident)),
            tag("]"),
        ),
        |(name, _, _, _, block)| PhiSource { value: name, block },
    )(code)
}

/// [`Phi`] instruction.
#[derive(Debug, Eq, PartialEq, Clone, Hash, Serialize, Deserialize)]
pub struct Phi {
    /// Where to store the result of the phi.
    pub to: RegisterName,
    /// Type of the phi.
    pub data_type: Type,
    /// Sources of the phi.
    pub from: Vec<PhiSource>,
}

impl IsIRStatement for Phi {
    fn on_register_change(&mut self, from: &RegisterName, to: Quantity) {
        if &self.to == from {
            self.to = to.clone().unwrap_local();
        }
        for source in &mut self.from {
            if let Quantity::RegisterName(local) = &mut source.value {
                if local == from {
                    *local = to.clone().unwrap_local();
                }
            }
        }
    }
    fn generate_register(&self) -> Option<(RegisterName, Type)> {
        Some((self.to.clone(), self.data_type.clone()))
    }

    fn use_register(&self) -> Vec<RegisterName> {
        self.from
            .iter()
            .filter_map(|PhiSource { value: name, .. }| name.as_local())
            .cloned()
            .collect()
    }
}

impl fmt::Display for Phi {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} = phi {} ", self.to, self.data_type)?;
        for (i, source) in self.from.iter().enumerate() {
            if i != 0 {
                write!(f, ", ")?;
            }
            write!(f, "[{}, {}]", source.block, source.value)?;
        }
        Ok(())
    }
}

/// Parse ir code to get a [`Phi`] instruction.
pub fn parse(code: &str) -> IResult<&str, Phi> {
    map(
        tuple((
            local::parse,
            space0,
            tag("="),
            space0,
            tag("phi"),
            space0,
            data_type::parse,
            space0,
            separated_list1(in_multispace(tag(",")), in_multispace(parse_phi_source)),
        )),
        |(to, _, _, _, _, _, data_type, _, from)| Phi {
            to,
            data_type,
            from,
        },
    )(code)
}

#[cfg(test)]
pub mod test_util {
    #![allow(clippy::borrow_interior_mutable_const)]

    use super::*;
    pub fn new(
        target: &str,
        source1_bb: &str,
        source1: &str,
        source2_bb: &str,
        source2: &str,
    ) -> Phi {
        Phi {
            to: RegisterName(target.to_string()),
            data_type: data_type::I32.clone(),
            from: vec![
                PhiSource {
                    value: RegisterName(source1.to_string()).into(),
                    block: source1_bb.to_string(),
                },
                PhiSource {
                    value: RegisterName(source2.to_string()).into(),
                    block: source2_bb.to_string(),
                },
            ],
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::borrow_interior_mutable_const)]
    use super::*;

    #[test]
    fn test_parse() {
        let result = parse("%1 = phi i32 [%2, bb1], [%4, bb2]").unwrap().1;
        assert_eq!(
            result,
            Phi {
                to: RegisterName("1".to_string()),
                data_type: data_type::I32.clone(),
                from: vec![
                    PhiSource {
                        value: RegisterName("2".to_string()).into(),
                        block: "bb1".to_string(),
                    },
                    PhiSource {
                        value: RegisterName("4".to_string()).into(),
                        block: "bb2".to_string(),
                    },
                ],
            }
        );
    }
}