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
use std::collections::HashSet;

use crate::mir::ops;
use crate::mir::value::Value;

fn remove_unused_cond_ops(
    cond_op: ops::CondOp,
    used_regs: &mut HashSet<ops::RegId>,
) -> Option<ops::CondOp> {
    let ops::CondOp {
        reg_phi,
        test_reg,
        true_ops,
        false_ops,
    } = cond_op;

    // Determine if our output is used
    let used_reg_phi = reg_phi.filter(|reg_phi| used_regs.contains(&reg_phi.output_reg));

    // Instead of cloning `used_regs` just rollback any changes we make do it
    let (rollback_true_reg, rollback_false_reg) = match used_reg_phi {
        Some(ops::RegPhi {
            true_result_reg,
            false_result_reg,
            ..
        }) => (
            Some(true_result_reg).filter(|_| !used_regs.insert(true_result_reg)),
            Some(false_result_reg).filter(|_| !used_regs.insert(false_result_reg)),
        ),
        _ => (None, None),
    };

    let used_true_ops = remove_unused_branch_ops(true_ops, used_regs);
    let used_false_ops = remove_unused_branch_ops(false_ops, used_regs);

    if used_true_ops.is_empty() && used_false_ops.is_empty() && used_reg_phi.is_none() {
        // We can disappear!
        if let Some(rollback_true_reg) = rollback_true_reg {
            used_regs.remove(&rollback_true_reg);
        }
        if let Some(rollback_false_reg) = rollback_false_reg {
            used_regs.remove(&rollback_false_reg);
        }

        None
    } else {
        used_regs.insert(test_reg);
        Some(ops::CondOp {
            reg_phi: used_reg_phi,
            test_reg,
            true_ops: used_true_ops,
            false_ops: used_false_ops,
        })
    }
}

fn remove_unused_branch_ops(
    ops: Box<[ops::Op]>,
    used_regs: &mut HashSet<ops::RegId>,
) -> Box<[ops::Op]> {
    let mut reverse_ops = ops
        .into_vec()
        .into_iter()
        .rev()
        .filter_map(|op| {
            let ops::Op { span, kind } = op;

            match kind {
                ops::OpKind::Cond(cond_op) => remove_unused_cond_ops(cond_op, used_regs)
                    .map(|cond_op| ops::Op::new(span, ops::OpKind::Cond(cond_op))),
                _ => {
                    // Does this have no side effects and its output is unused?
                    if !kind.has_side_effects()
                        && kind
                            .output_reg()
                            .map(|output_reg| !used_regs.contains(&output_reg))
                            .unwrap_or(true)
                    {
                        None
                    } else {
                        kind.add_input_regs(used_regs);
                        Some(ops::Op { span, kind })
                    }
                }
            }
        })
        .collect::<Vec<ops::Op>>();

    // If we do .rev() on the iterator before we collect it will change the order we iterate in
    reverse_ops.reverse();
    reverse_ops.into_boxed_slice()
}

pub fn remove_unused_fun_ops(ops: Box<[ops::Op]>) -> Box<[ops::Op]> {
    // Nothing is used at the beginning of a function
    let mut used_regs = HashSet::new();
    remove_unused_branch_ops(ops, &mut used_regs)
}

/// Adds regs referenced by the passed value
fn add_value_used_regs(value: &Value, used_regs: &mut HashSet<ops::RegId>) {
    match value {
        Value::Const(_)
        | Value::RustFun(_)
        | Value::TyPred(_)
        | Value::EqPred
        | Value::RecordCons(_)
        | Value::FieldAccessor(_, _) => {}
        Value::ArretFun(arret_fun) => {
            for (_, free_value) in arret_fun.env_values().free_values.iter() {
                add_value_used_regs(free_value, used_regs);
            }
        }
        Value::Reg(reg_value) => {
            used_regs.insert(reg_value.reg.into());
        }
        Value::Record(_, field_values) => {
            for field_value in field_values.iter() {
                add_value_used_regs(field_value, used_regs);
            }
        }
        Value::List(fixed_values, rest_value) => {
            for fixed_value in fixed_values.iter() {
                add_value_used_regs(fixed_value, used_regs);
            }

            if let Some(rest_value) = rest_value {
                add_value_used_regs(rest_value, used_regs);
            }
        }
    }
}

pub fn remove_unused_value_ops(ops: Box<[ops::Op]>, value: &Value) -> Box<[ops::Op]> {
    let mut used_regs = HashSet::new();
    add_value_used_regs(value, &mut used_regs);

    remove_unused_branch_ops(ops, &mut used_regs)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn empty_ops() {
        let ops = remove_unused_fun_ops(Box::new([]));
        assert!(ops.is_empty());
    }

    #[test]
    fn simple_unused() {
        let reg1 = ops::RegId::alloc();
        let reg2 = ops::RegId::alloc();
        let reg3 = ops::RegId::alloc();

        let input_ops = Box::new([
            ops::OpKind::ConstBoxedNil(reg1, ()).into(),
            ops::OpKind::ConstBoxedNil(reg2, ()).into(),
            ops::OpKind::ConstBoxedNil(reg3, ()).into(),
            ops::OpKind::Ret(reg2).into(),
        ]);

        let output_ops = remove_unused_fun_ops(input_ops);

        let expected_ops: Box<[ops::Op]> = Box::new([
            ops::OpKind::ConstBoxedNil(reg2, ()).into(),
            ops::OpKind::Ret(reg2).into(),
        ]);

        assert_eq!(expected_ops, output_ops);
    }

    #[test]
    fn fully_used_cond() {
        let output_reg = ops::RegId::alloc();
        let test_reg = ops::RegId::alloc();
        let true_result_reg = ops::RegId::alloc();
        let false_result_reg = ops::RegId::alloc();

        let true_ops = Box::new([ops::OpKind::ConstBoxedNil(true_result_reg, ()).into()]);

        let false_ops = Box::new([ops::OpKind::ConstBoxedNil(false_result_reg, ()).into()]);

        let input_ops: Box<[ops::Op]> = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg,
                    false_result_reg,
                }),
                test_reg,
                true_ops,
                false_ops,
            })
            .into(),
            ops::OpKind::Ret(output_reg).into(),
        ]);

        let expected_ops = input_ops.clone();
        let output_ops = remove_unused_fun_ops(input_ops);

        assert_eq!(expected_ops, output_ops);
    }

    #[test]
    fn partially_used_cond() {
        let output_reg = ops::RegId::alloc();
        let test_reg = ops::RegId::alloc();
        let true_result_reg = ops::RegId::alloc();
        let false_result_reg = ops::RegId::alloc();

        let true_ops = Box::new([ops::OpKind::ConstBoxedNil(true_result_reg, ()).into()]);

        let false_ops = Box::new([ops::OpKind::ConstBoxedNil(false_result_reg, ()).into()]);

        let input_ops = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg, // This makes the true branch unused
                    false_result_reg,
                }),
                test_reg,
                true_ops,
                false_ops: false_ops.clone(),
            })
            .into(),
            ops::OpKind::Ret(output_reg).into(),
        ]);

        let expected_ops: Box<[ops::Op]> = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg,
                    false_result_reg,
                }),
                test_reg,
                true_ops: Box::new([]),
                false_ops,
            })
            .into(),
            ops::OpKind::Ret(output_reg).into(),
        ]);

        let output_ops = remove_unused_fun_ops(input_ops);

        assert_eq!(expected_ops, output_ops);
    }

    #[test]
    fn output_only_cond() {
        let output_reg = ops::RegId::alloc();
        let test_reg = ops::RegId::alloc();
        let true_result_reg = ops::RegId::alloc();
        let false_result_reg = ops::RegId::alloc();

        let true_ops = Box::new([ops::OpKind::ConstBoxedNil(true_result_reg, ()).into()]);

        let false_ops = Box::new([ops::OpKind::ConstBoxedNil(false_result_reg, ()).into()]);

        let input_ops = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg, // This makes the true branch unused
                    false_result_reg: test_reg, // This makes the false branch unused
                }),
                test_reg,
                true_ops,
                false_ops,
            })
            .into(),
            // However, the output of the `Cond` is still used
            ops::OpKind::Ret(output_reg).into(),
        ]);

        let expected_ops: Box<[ops::Op]> = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg,
                    false_result_reg: test_reg,
                }),
                test_reg,
                true_ops: Box::new([]),
                false_ops: Box::new([]),
            })
            .into(),
            ops::OpKind::Ret(output_reg).into(),
        ]);

        let output_ops = remove_unused_fun_ops(input_ops);

        assert_eq!(expected_ops, output_ops);
    }

    #[test]
    fn output_unused_cond() {
        let output_reg = ops::RegId::alloc();
        let test_reg = ops::RegId::alloc();

        let true_ops = Box::new([ops::OpKind::RetVoid.into()]);
        let false_ops = Box::new([ops::OpKind::RetVoid.into()]);

        let input_ops = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg, // This makes the true result unused
                    false_result_reg: test_reg, // This makes the false result unused
                }),
                test_reg,
                true_ops: true_ops.clone(),
                false_ops: false_ops.clone(),
            })
            .into(),
        ]);

        let expected_ops: Box<[ops::Op]> = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: None,
                test_reg,
                true_ops,
                false_ops,
            })
            .into(),
        ]);

        let output_ops = remove_unused_fun_ops(input_ops);

        assert_eq!(expected_ops, output_ops);
    }

    #[test]
    fn fully_unused_cond() {
        let output_reg = ops::RegId::alloc();
        let test_reg = ops::RegId::alloc();
        let true_result_reg = ops::RegId::alloc();
        let false_result_reg = ops::RegId::alloc();

        let true_ops = Box::new([ops::OpKind::ConstBoxedNil(true_result_reg, ()).into()]);

        let false_ops = Box::new([ops::OpKind::ConstBoxedNil(false_result_reg, ()).into()]);

        let input_ops = Box::new([
            ops::OpKind::ConstBoxedNil(test_reg, ()).into(),
            ops::OpKind::Cond(ops::CondOp {
                reg_phi: Some(ops::RegPhi {
                    output_reg,
                    true_result_reg: test_reg, // This makes the true branch unused
                    false_result_reg: test_reg, // This makes the false branch unused
                }),
                test_reg,
                true_ops,
                false_ops,
            })
            .into(),
        ]);

        let output_ops = remove_unused_fun_ops(input_ops);
        assert!(output_ops.is_empty());
    }
}