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
use super::Arena;
use crate::bb::BasicBlockInner;
use crate::jump::{self, ForeachTarget};
use crate::BbId;
use alloc::collections::{BTreeMap as Map, BTreeSet};
use alloc::vec::Vec;
use core::mem::{drop, take};

/// Temporary information describing the modifications to be done
/// and cached data, per BbId.
///
/// This structure is at least implicitly wrapped in an `Option` (key exists?),
/// if Some, then TR $key->$target,
/// otherwise, remove every occurence of $key if possible,
/// panic otherwise (especially if otherwise invariants would be violated)
///
/// after applying $key->$target, do
/// ```do_ignore
///   let mut t = &mut $trm[$i].target;
///   *t -= $trm[*t].offset;
/// ```
///
/// To avoid reallocations and multiple intermediate data types,
/// this structure goes through multiple stages, which contain
/// similiar, but not equivalent sets of data.
/// $offset is calculated at a different stage than $target,
/// and shouldn't be trusted earlier.
#[derive(Clone)]
struct TransInfo {
    /// for $key->$target search-and-replace; default = $key
    target: usize,

    /// offset correction for $key ($target -= $target.$offset) to
    /// accomodate removed BBs
    offset: Option<usize>,

    /// references from $i pointing to $key,
    /// useful for optimizations which rely on the fact that only
    /// one other BB depends on a BB, then they're mergable
    /// default = 1
    refs: BTreeSet<usize>,
}

impl TransInfo {
    #[inline]
    fn new(id: usize) -> Self {
        Self {
            target: id,
            offset: None,
            refs: BTreeSet::new(),
        }
    }
}

/// check function which makes sure that no reference to $exclude exists
/// inside of $container.
fn fetchk<C>(is_mergable: &mut bool, container: &C, exclude: <C as ForeachTarget>::JumpTarget)
where
    C: ForeachTarget,
    C::JumpTarget: Copy + PartialEq,
{
    container.foreach_target(move |&t| {
        if exclude == t {
            *is_mergable = false;
        }
    });
}

impl<S, C> Arena<S, C>
where
    S: ForeachTarget<JumpTarget = BbId>,
    C: ForeachTarget<JumpTarget = BbId>,
{
    pub fn optimize(&mut self) -> bool {
        let mut max = self.bbs.len();
        let mut new_in_use = Vec::with_capacity(max);

        let mut trm: Map<BbId, TransInfo> = (0..max).map(|i| (i, TransInfo::new(i))).collect();

        for (from, i) in self.bbs.iter().enumerate() {
            if i.is_public {
                new_in_use.push(from);
            } else if let BasicBlockInner::Concrete {
                statements,
                condjmp,
                next,
            } = &i.inner
            {
                if statements.is_empty() && condjmp.is_none() {
                    if let jump::Unconditional::Jump(trg) = *next {
                        let tmp_max = core::cmp::max(from, trg);
                        if max < tmp_max {
                            max = tmp_max;
                        }
                        if from != trg {
                            trm.entry(from)
                                .or_insert_with(|| TransInfo::new(from))
                                .target = trg;
                        }
                    }
                }
            }
        }

        // recursively mark anything as in-use only if reachable from in-use or pub
        let mut in_use = BTreeSet::new();
        while !new_in_use.is_empty() {
            for i in take(&mut new_in_use) {
                if in_use.insert(i) {
                    // really new entry
                    self.bbs[i].foreach_target(|&trg| {
                        trm.entry(trg)
                            .or_insert_with(|| TransInfo::new(trg))
                            .refs
                            .insert(i);
                        new_in_use.push(trg);
                    });
                }
            }
        }
        drop(new_in_use);

        // check all references for one-refs (which may be mergable)
        for (&n, ti) in trm.iter() {
            if ti.refs.len() != 1 {
                continue;
            }
            let bbheadref = *ti.refs.iter().next().unwrap();
            if bbheadref == n {
                continue;
            }
            if trm.get(&bbheadref).map(|hti| hti.target != bbheadref) == Some(true) {
                // head is already redirected, skip
                continue;
            }
            let mut is_mergable = false;
            if let Some(bbhead) = self.bbs.get_mut(bbheadref) {
                if let BasicBlockInner::Concrete {
                    statements,
                    condjmp,
                    next,
                } = &mut bbhead.inner
                {
                    is_mergable = condjmp.is_none() && *next == jump::Unconditional::Jump(n);

                    // make sure that we don't have any additional references to bbtail
                    fetchk(&mut is_mergable, statements, n);
                }
            }
            if !is_mergable {
                continue;
            }
            let bbtail = if let Some(bbtail) = self.bbs.get_mut(n) {
                if bbtail.is_public || !bbtail.inner.is_concrete() {
                    continue;
                }
                fetchk(&mut is_mergable, bbtail, n);
                if !is_mergable {
                    continue;
                }
                take(&mut bbtail.inner)
            } else {
                continue;
            };

            // mergable
            if let BasicBlockInner::Concrete {
                mut statements,
                condjmp,
                next,
            } = bbtail
            {
                if let BasicBlockInner::Concrete {
                    statements: ref mut h_statements,
                    condjmp: ref mut h_condjmp,
                    next: ref mut h_next,
                } = &mut self.bbs.get_mut(bbheadref).unwrap().inner
                {
                    in_use.remove(&n);
                    if h_statements.is_empty() {
                        // this normally only happens if $head.is_public
                        // merge labels manually
                        for (_, ltrg) in self.labels.iter_mut() {
                            if *ltrg == n {
                                *ltrg = bbheadref;
                            }
                        }
                    }
                    h_statements.append(&mut statements);
                    *h_condjmp = condjmp;
                    *h_next = next;
                } else {
                    unreachable!();
                }
            } else {
                unreachable!();
            }
        }

        // calculate offsets, apply in_use
        let mut offset: BbId = 0;
        let mut modified = false;
        assert!(max >= self.bbs.len());
        for i in 0..self.bbs.len() {
            if in_use.contains(&i) {
                let e = trm.get_mut(&i).unwrap();
                if i != e.target {
                    modified = true;
                }
                e.offset = Some(offset);
            } else {
                trm.remove(&i);
                offset += 1;
            }
        }
        if offset == 0 && !modified {
            // nothing left to do, we are done
            return false;
        }
        // avoid repetition + re-execution of `unwrap_or(TransInfo::new(...))...`
        for i in self.bbs.len()..max {
            trm.entry(i).or_insert_with(|| TransInfo::new(i)).offset = Some(offset);
        }

        // finalize trm, apply offset correction to each $target
        for i in 0..max {
            if let Some(ti) = trm.get_mut(&i) {
                if i == ti.target {
                    ti.target -= ti.offset.unwrap();
                } else {
                    let old_target = ti.target;
                    let new_target = old_target - trm.get(&old_target).unwrap().offset.unwrap();
                    trm.get_mut(&i).unwrap().target = new_target;
                }
            }
        }

        let trm_get = |n: usize| trm.get(&n).map(|ti| ti.target);

        // remove to-be-removed BBs
        for n in (0..max).rev() {
            if trm.get(&n).is_none() {
                self.bbs.remove(n);
            }
        }

        // replace jump targets
        self.bbs.foreach_target_mut(|target: &mut usize| {
            *target = trm_get(*target).expect("violated invariant");
        });

        self.labels = take(&mut self.labels)
            .into_iter()
            .filter(|(_, bbid)| {
                // remove all labels which point to a BBID which should be deleted,
                // either because it is marked in trm -> None, or the BBID is invalid.
                trm.get(bbid).is_some()
            })
            .collect();

        true
    }
}