symjit 2.16.1

a lightweight just-in-time (JIT) optimizer compiler
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use anyhow::Result;

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use crate::config::Config;
use crate::mir::Mir;
use crate::node::Node;
use crate::statement::Statement;
use crate::symbol::{Loc, Symbol, SymbolTable};

//****************************************************//

#[derive(Debug, Clone)]
pub struct Block {
    pub stmts: Vec<Statement>,
    pub sym_table: SymbolTable,
    pub num_tmp: usize,
    pub calls: HashMap<(String, u64), Node>,
    pub config: Config,
}

impl Block {
    pub fn new(config: Config) -> Block {
        Block {
            stmts: Vec::new(),
            sym_table: SymbolTable::new(config.is_complex()),
            num_tmp: 0,
            calls: HashMap::new(),
            config,
        }
    }

    pub fn clear(&mut self) {
        self.stmts.clear();
        self.sym_table.syms.clear();
    }

    // add_* functions create a new Statement

    pub fn add_label(&mut self, label: &str) {
        self.stmts.push(Statement::Label {
            label: label.to_string(),
        });
    }

    pub fn add_branch(&mut self, label: &str) {
        self.stmts.push(Statement::Branch {
            label: label.to_string(),
        })
    }

    pub fn add_branch_if(&mut self, cond: Node, label: &str, is_else: bool) {
        self.stmts.push(Statement::BranchIf {
            cond,
            label: label.to_string(),
            is_else,
        })
    }

    pub fn add_assign(&mut self, lhs: Node, rhs: Node) {
        let rhs = self.process(rhs);
        self.stmts.push(Statement::assign(lhs, rhs));
    }

    // **************** Compile the Block! *********************

    pub fn compile(&mut self, ir: &mut Mir) -> Result<()> {
        for stmt in self.stmts.iter_mut() {
            stmt.compile(ir)?;
        }

        Ok(())
    }

    // create_* functions create a new Node

    pub fn create_mem(&mut self, name: &str) {
        self.sym_table.add_mem(name);
    }

    pub fn create_tmp(&mut self) -> Node {
        let name = format!("ψ{}", self.num_tmp);
        self.num_tmp += 1;
        self.create_tmp_named(&name)
    }

    pub fn create_tmp_named(&mut self, name: &str) -> Node {
        self.sym_table.add_stack(name);
        let sym = self.sym_table.find_sym(name).unwrap();

        Node::Var {
            sym,
            // status: VarStatus::Unknown,
        }
    }

    pub fn var_exists(&self, name: &str) -> bool {
        self.sym_table.contains(name)
    }

    pub fn create_void(&mut self) -> Node {
        Node::create_void()
    }

    pub fn create_const(&mut self, val: f64, idx: u32) -> Node {
        Node::create_const(val, idx)
    }

    pub fn create_var(&mut self, sym: Rc<RefCell<Symbol>>) -> Node {
        Node::create_var(sym)
    }

    pub fn create_unary(&mut self, op: &str, arg: Node) -> Node {
        Node::create_unary(op, arg, 1)
    }

    pub fn create_binary(&mut self, op: &str, left: Node, right: Node) -> Node {
        Node::create_binary(op, left, right, 1, None)
    }

    pub fn create_powi(&mut self, arg: Node, power: i32) -> Node {
        Node::create_powi(arg, power)
    }

    pub fn create_modular_powi(&mut self, left: Node, right: Node, power: i32) -> Node {
        Node::create_modular_powi(left, right, power)
    }

    pub fn create_ifelse(&mut self, cond: Node, left: Node, right: Node) -> Node {
        let tmp = self.create_tmp();
        self.add_assign(tmp.clone(), cond);
        Node::create_ifelse(&tmp, left, right)
    }

    //******************* Tree Processing ***************************/
    fn process(&mut self, node: Node) -> Node {
        self.trim(node)
    }

    /*
     * trim breaks expressions to assure the ershov_number of the root does not
     * exceed the limit set by `count_scratch`.
     * By default, `count_scratch` is 14, which is set because of 16 XMM/YMM registers
     * Note that two registers (XMM0 and XMM1) are needed as temporary and for function calls
     */
    fn trim(&mut self, node: Node) -> Node {
        match node {
            Node::Void => Node::Void,
            Node::Const { val, idx } => Node::Const { val, idx },
            Node::Var { sym } => Node::Var { sym },
            Node::Unary { op, arg, power, .. } => self.trim_unary(&op, *arg, power),
            Node::Binary {
                op,
                left,
                right,
                power,
                cond,
                ..
            } => self.trim_binary(&op, *left, *right, power, cond),
        }
    }

    fn trim_unary(&mut self, op: &str, arg: Node, power: i32) -> Node {
        let arg = self.trim(arg);

        if !self.config.is_intrinsic_unary(op) {
            self.break_call_unary(op, arg)
        } else {
            Node::create_unary(op, arg, power)
        }
    }

    fn break_call_unary(&mut self, op: &str, arg: Node) -> Node {
        let n = (op.to_string(), arg.hashof());

        if self.config.cse() {
            if let Some(lhs) = self.calls.get(&n) {
                return lhs.clone();
            }
        }

        let arg = self.create_unary("_call_", arg);
        let lhs = self.create_tmp();
        self.stmts.push(Statement::call(op, lhs.clone(), arg, 1));
        self.calls.insert(n, lhs.clone());
        lhs
    }

    fn trim_binary(
        &mut self,
        op: &str,
        left: Node,
        right: Node,
        power: i32,
        cond: Option<Loc>,
    ) -> Node {
        let left = self.trim(left);
        let right = self.trim(right);

        if !self.config.is_intrinsic_binary(op) {
            return self.break_call_binary(op, left, right);
        }

        let count_scratch = self.config.count_scratch();

        let right = if left.ershov_number() == count_scratch - 1
            && right.ershov_number() == count_scratch - 1
        {
            let lhs = self.create_tmp();
            self.stmts.push(Statement::assign(lhs.clone(), right));
            lhs
        } else {
            right
        };

        Node::create_binary(op, left, right, power, cond)
    }

    pub fn break_call_binary(&mut self, op: &str, left: Node, right: Node) -> Node {
        let n = (op.to_string(), left.hashof() ^ (right.hashof() + 1));

        if self.config.cse() {
            if let Some(lhs) = self.calls.get(&n) {
                return lhs.clone();
            }
        }

        let left = self.process(left);
        let right = self.process(right);

        let arg = self.create_binary("_call_", left, right);
        let lhs = self.create_tmp();
        self.stmts.push(Statement::call(op, lhs.clone(), arg, 2));
        self.calls.insert(n, lhs.clone());
        lhs
    }

    /*
     * eliminate performs common-subexpression-eliminaton
     * the actual CSE work is done in elimination_pass, which uses
     * a two-pass algorithm.
     * In the first pass, common subexpressions are identified.
     * In the second pass, the right side of statements are rewritten.
     */
    pub fn eliminate(&mut self) {
        for _ in 0..5 {
            if !self.elimination_pass() {
                return;
            }
        }
    }

    pub fn elimination_pass(&mut self) -> bool {
        if !self.config.cse() {
            return false;
        }

        // first-pass
        let mut stmts = std::mem::take(&mut self.stmts);

        let mut hs: HashSet<u64> = HashSet::new(); // hash-value-set to find collision
        let mut cs: HashMap<u64, (Node, Node)> = HashMap::new(); // collision set as (lhs, rhs)

        let mut depth: i32 = 0;

        for s in stmts.iter_mut() {
            match s {
                Statement::Assign { rhs, .. } => {
                    if depth == 0 {
                        self.find_cse(&mut hs, &mut cs, rhs);
                    }
                }
                Statement::Call { arg, .. } => {
                    if depth == 0 {
                        self.find_cse(&mut hs, &mut cs, arg);
                    }
                }
                Statement::Label { .. } => {
                    // The logic here with depth works for Sum/Product
                    // but needs improvement for general multi-block situations
                    depth += 1;
                }
                Statement::Branch { .. } | Statement::BranchIf { .. } => {
                    // assert!(depth > 0);
                    depth -= 1;
                }
            }
        }

        if cs.is_empty() {
            // self.stmts = stmts.drain(..).collect();
            self.stmts = std::mem::take(&mut stmts);
            return false;
        }

        // println!("{} sub-expressions found.", cs.len());

        let mut ls: HashSet<u64> = HashSet::new(); // a set of common subexpression lhs which are added to self.stmts

        for s in stmts {
            match s {
                Statement::Assign { lhs, rhs } => {
                    let rhs = self.rewrite_cse(&cs, &mut ls, rhs);
                    self.stmts.push(Statement::Assign { lhs, rhs });
                }
                Statement::Call {
                    op,
                    lhs,
                    arg,
                    num_args,
                } => {
                    let arg = self.rewrite_cse(&cs, &mut ls, arg);
                    self.stmts.push(Statement::Call {
                        op,
                        lhs,
                        arg,
                        num_args,
                    });
                }
                Statement::Label { label } => {
                    // TODO: Just copying here, may need to change the logic
                    self.stmts.push(Statement::Label { label });
                }
                Statement::Branch { label } => {
                    self.stmts.push(Statement::Branch { label });
                }
                Statement::BranchIf {
                    cond,
                    label,
                    is_else,
                } => {
                    let cond = self.rewrite_cse(&cs, &mut ls, cond);
                    self.stmts.push(Statement::BranchIf {
                        cond,
                        label,
                        is_else,
                    });
                }
            }
        }

        true
    }

    fn find_cse(
        &mut self,
        hs: &mut HashSet<u64>,
        cs: &mut HashMap<u64, (Node, Node)>,
        node: &mut Node,
    ) {
        if node.weightof() >= 5 && !node.is_unary("_call_") && !node.is_binary("_call_") {
            let h = node.hashof();

            if hs.contains(&h) {
                // collision detected!
                cs.entry(h).or_insert_with(|| {
                    let lhs = self.create_tmp();
                    (lhs, node.clone())
                });
            } else {
                hs.insert(h);
            };
        }

        if let Some(n) = node.first() {
            self.find_cse(hs, cs, n)
        };

        if let Some(n) = node.second() {
            self.find_cse(hs, cs, n)
        };
    }

    fn rewrite_cse(
        &mut self,
        cs: &HashMap<u64, (Node, Node)>,
        ls: &mut HashSet<u64>,
        node: Node,
    ) -> Node {
        if node.weightof() < 5 {
            return node;
        }

        match node {
            Node::Void => Node::Void,
            Node::Const { val, idx } => Node::Const { val, idx },
            Node::Var { sym } => Node::Var { sym },
            Node::Unary {
                op, arg, power, h, ..
            } => self.common_subexpr(cs, ls, h).unwrap_or_else(|| {
                let arg = self.rewrite_cse(cs, ls, *arg);
                Node::create_unary(op.as_str(), arg, power)
            }),
            Node::Binary {
                op,
                left,
                right,
                power,
                cond,
                h,
                ..
            } => self.common_subexpr(cs, ls, h).unwrap_or_else(|| {
                let left = self.rewrite_cse(cs, ls, *left);
                let right = self.rewrite_cse(cs, ls, *right);
                Node::create_binary(op.as_str(), left, right, power, cond)
            }),
        }
    }

    fn common_subexpr(
        &mut self,
        cs: &HashMap<u64, (Node, Node)>,
        ls: &mut HashSet<u64>,
        h: u64,
    ) -> Option<Node> {
        if let Some((lhs, rhs)) = cs.get(&h) {
            let k = &lhs.hashof();

            if !ls.contains(k) {
                self.stmts.push(Statement::assign(lhs.clone(), rhs.clone()));
                ls.insert(*k);
            }

            return Some(lhs.clone());
        }

        None
    }
}