To protect your data, the CISO officer has suggested users to enable GitLab 2FA as soon as possible.

ir.rs 48.3 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
// Copyright 2017 The Australian National University
2
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
3
4
5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
9
10
11
12
13
14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
16
17
18
19
20
21
22
use ptr::P;
use types::*;
use inst::*;

use utils::vec_utils;
use utils::LinkedHashMap;
use utils::LinkedHashSet;

23
use std;
24
use std::fmt;
25
pub use std::sync::Arc;
26
27
28
use std::default;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

qinsoon's avatar
qinsoon committed
29
30
pub type WPID = usize;
pub type MuID = usize;
31
pub type MuName = Arc<String>;
qinsoon's avatar
qinsoon committed
32
pub type CName = MuName;
33
34

#[allow(non_snake_case)]
qinsoon's avatar
qinsoon committed
35
pub fn Mu(str: &'static str) -> MuName {
36
    Arc::new(str.to_string())
qinsoon's avatar
qinsoon committed
37
}
38
#[allow(non_snake_case)]
qinsoon's avatar
qinsoon committed
39
pub fn C(str: &'static str) -> CName {
40
    Arc::new(str.to_string())
qinsoon's avatar
qinsoon committed
41
}
42
43
44
45
46
47
48
49
50
51
52
53
54
55

pub type OpIndex = usize;

lazy_static! {
    pub static ref MACHINE_ID : AtomicUsize = {
        let a = ATOMIC_USIZE_INIT;
        a.store(MACHINE_ID_START, Ordering::SeqCst);
        a
    };
    pub static ref INTERNAL_ID : AtomicUsize = {
        let a = ATOMIC_USIZE_INIT;
        a.store(INTERNAL_ID_START, Ordering::SeqCst);
        a
    };
56
57
}
/// MuID reserved for machine registers
qinsoon's avatar
qinsoon committed
58
59
pub const MACHINE_ID_START: usize = 0;
pub const MACHINE_ID_END: usize = 200;
60

61
/// MuID reserved for internal types, etc.
qinsoon's avatar
qinsoon committed
62
63
64
pub const INTERNAL_ID_START: usize = 201;
pub const INTERNAL_ID_END: usize = 500;
pub const USER_ID_START: usize = 1001;
65
66
67

#[deprecated]
#[allow(dead_code)]
68
69
70
// it could happen that one same machine register get different IDs
// during serialization and restoring
// currently I hand-write fixed ID for each machine register
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
pub fn new_machine_id() -> MuID {
    let ret = MACHINE_ID.fetch_add(1, Ordering::SeqCst);
    if ret >= MACHINE_ID_END {
        panic!("machine id overflow")
    }
    ret
}

pub fn new_internal_id() -> MuID {
    let ret = INTERNAL_ID.fetch_add(1, Ordering::SeqCst);
    if ret >= INTERNAL_ID_END {
        panic!("internal id overflow")
    }
    ret
}

87
88
89
/// MuFunction represents a Mu function (not a specific definition of a function)
/// This stores function signature, and a list of all versions of this function (as ID),
/// and its current version (as ID)
90
#[derive(Debug)]
91
92
pub struct MuFunction {
    pub hdr: MuEntityHeader,
qinsoon's avatar
qinsoon committed
93

94
95
    pub sig: P<MuFuncSig>,
    pub cur_ver: Option<MuID>,
96
    pub all_vers: Vec<MuID>
97
98
}

qinsoon's avatar
qinsoon committed
99
100
101
102
rodal_struct!(MuFunction {
    hdr,
    sig,
    cur_ver,
103
    all_vers
qinsoon's avatar
qinsoon committed
104
});
105

106
impl MuFunction {
107
    pub fn new(entity: MuEntityHeader, sig: P<MuFuncSig>) -> MuFunction {
108
        MuFunction {
109
            hdr: entity,
110
111
            sig: sig,
            cur_ver: None,
112
            all_vers: vec![]
113
114
        }
    }
115
116

    /// adds a new version to this function, and it becomes the current version
117
118
119
120
121
    pub fn new_version(&mut self, fv: MuID) {
        if self.cur_ver.is_some() {
            let obsolete_ver = self.cur_ver.unwrap();
            self.all_vers.push(obsolete_ver);
        }
qinsoon's avatar
qinsoon committed
122

123
124
125
126
127
128
129
130
131
132
        self.cur_ver = Some(fv);
    }
}

impl fmt::Display for MuFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Func {}", self.hdr)
    }
}

133
134
135
136
137
/// MuFunctionVersion represents a specific definition of a Mu function
/// It owns the tree structure of MuIRs for the function version

// FIXME: currently part of compilation information is also stored in this data structure
// we should move them (see Issue #18)
138
rodal_named!(MuFunctionVersion);
139
140
pub struct MuFunctionVersion {
    pub hdr: MuEntityHeader,
141

142
143
    pub func_id: MuID,
    pub sig: P<MuFuncSig>,
qinsoon's avatar
qinsoon committed
144
145
    orig_content: Option<FunctionContent>, // original IR
    pub content: Option<FunctionContent>,  // IR that may have been rewritten during compilation
146
147
148
149
    is_defined: bool,
    is_compiled: bool,
    pub context: FunctionContext,
    pub force_inline: bool,
150
    pub block_trace: Option<Vec<MuID>> // only available after Trace Generation Pass
151
}
qinsoon's avatar
qinsoon committed
152
153
154
rodal_struct!(Callsite {
    name,
    exception_destination,
155
    stack_arg_size
qinsoon's avatar
qinsoon committed
156
});
157
158
159
pub struct Callsite {
    pub name: MuName,
    pub exception_destination: Option<MuName>,
160
    pub stack_arg_size: usize
161
162
}
impl Callsite {
qinsoon's avatar
qinsoon committed
163
164
165
    pub fn new(
        name: MuName,
        exception_destination: Option<MuName>,
166
        stack_arg_size: usize
qinsoon's avatar
qinsoon committed
167
168
169
170
    ) -> Callsite {
        Callsite {
            name: name,
            exception_destination: exception_destination,
171
            stack_arg_size: stack_arg_size
qinsoon's avatar
qinsoon committed
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
impl fmt::Display for MuFunctionVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "FuncVer {} of Func #{}", self.hdr, self.func_id)
    }
}

impl fmt::Debug for MuFunctionVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "FuncVer {} of Func #{}\n", self.hdr, self.func_id).unwrap();
        write!(f, "Signature: {}\n", self.sig).unwrap();
        write!(f, "IR:\n").unwrap();
        if self.content.is_some() {
            write!(f, "{:?}\n", self.content.as_ref().unwrap()).unwrap();
        } else {
            write!(f, "Empty\n").unwrap();
        }
        if self.block_trace.is_some() {
            write!(f, "Block Trace: {:?}\n", self.block_trace.as_ref().unwrap())
        } else {
            write!(f, "Trace not available\n")
        }
    }
}

impl MuFunctionVersion {
200
    /// creates an empty function version
201
    pub fn new(entity: MuEntityHeader, func: MuID, sig: P<MuFuncSig>) -> MuFunctionVersion {
qinsoon's avatar
qinsoon committed
202
        MuFunctionVersion {
203
            hdr: entity,
204
205
206
207
208
209
210
211
            func_id: func,
            sig: sig,
            orig_content: None,
            content: None,
            is_defined: false,
            is_compiled: false,
            context: FunctionContext::new(),
            block_trace: None,
212
            force_inline: false
213
214
215
        }
    }

216
    /// creates a complete function version
qinsoon's avatar
qinsoon committed
217
218
219
220
221
    pub fn new_(
        hdr: MuEntityHeader,
        id: MuID,
        sig: P<MuFuncSig>,
        content: FunctionContent,
222
        context: FunctionContext
qinsoon's avatar
qinsoon committed
223
    ) -> MuFunctionVersion {
224
225
226
227
228
229
230
231
232
233
        MuFunctionVersion {
            hdr: hdr,
            func_id: id,
            sig: sig,
            orig_content: Some(content.clone()),
            content: Some(content),
            is_defined: true,
            is_compiled: false,
            context: context,
            block_trace: None,
234
            force_inline: false
235
236
237
238
239
240
241
        }
    }

    pub fn get_orig_ir(&self) -> Option<&FunctionContent> {
        self.orig_content.as_ref()
    }

242
    /// defines function content
243
244
245
246
247
248
249
250
251
252
253
254
255
    pub fn define(&mut self, content: FunctionContent) {
        if self.is_defined {
            panic!("alread defined the function: {}", self);
        }

        self.is_defined = true;
        self.orig_content = Some(content.clone());
        self.content = Some(content);
    }

    pub fn is_compiled(&self) -> bool {
        self.is_compiled
    }
256

257
258
259
260
    pub fn set_compiled(&mut self) {
        self.is_compiled = true;
    }

261
262
    pub fn new_ssa(&mut self, entity: MuEntityHeader, ty: P<MuType>) -> P<TreeNode> {
        let id = entity.id();
qinsoon's avatar
qinsoon committed
263
        let val = P(Value {
264
            hdr: entity,
265
            ty: ty,
266
            v: Value_::SSAVar(id)
267
268
        });

qinsoon's avatar
qinsoon committed
269
270
271
        self.context
            .values
            .insert(id, SSAVarEntry::new(val.clone()));
272
273

        P(TreeNode {
274
            v: TreeNode_::Value(val)
275
276
277
        })
    }

278
279
280
281
282
283
284
285
286
287
    pub fn new_machine_reg(&mut self, v: P<Value>) -> P<TreeNode> {
        self.context
            .values
            .insert(v.id(), SSAVarEntry::new(v.clone()));

        P(TreeNode {
            v: TreeNode_::Value(v)
        })
    }

288
    pub fn new_constant(&mut self, v: P<Value>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
289
        P(TreeNode {
290
            v: TreeNode_::Value(v)
291
292
        })
    }
qinsoon's avatar
qinsoon committed
293

294
    pub fn new_global(&mut self, v: P<Value>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
295
        P(TreeNode {
296
            v: TreeNode_::Value(v)
297
298
299
300
        })
    }

    pub fn new_inst(&mut self, v: Instruction) -> Box<TreeNode> {
qinsoon's avatar
qinsoon committed
301
        Box::new(TreeNode {
302
            v: TreeNode_::Instruction(v)
303
304
305
        })
    }

306
307
    /// gets call outedges in this function
    /// returns Map(CallSiteID -> FuncID)
308
309
310
311
312
313
314
315
316
317
318
    pub fn get_static_call_edges(&self) -> LinkedHashMap<MuID, MuID> {
        let mut ret = LinkedHashMap::new();

        let f_content = self.content.as_ref().unwrap();

        for (_, block) in f_content.blocks.iter() {
            let block_content = block.content.as_ref().unwrap();

            for inst in block_content.body.iter() {
                match inst.v {
                    TreeNode_::Instruction(ref inst) => {
319
                        let ref ops = inst.ops;
320
321

                        match inst.v {
qinsoon's avatar
qinsoon committed
322
323
324
325
                            Instruction_::ExprCall { ref data, .. } |
                            Instruction_::ExprCCall { ref data, .. } |
                            Instruction_::Call { ref data, .. } |
                            Instruction_::CCall { ref data, .. } => {
326
327
328
                                let ref callee = ops[data.func];

                                match callee.v {
qinsoon's avatar
qinsoon committed
329
330
331
332
333
334
335
336
                                    TreeNode_::Instruction(_) => {}
                                    TreeNode_::Value(ref pv) => {
                                        match pv.v {
                                            Value_::Constant(Constant::FuncRef(id)) => {
                                                ret.insert(inst.id(), id);
                                            }
                                            _ => {}
                                        }
337
338
                                    }
                                }
qinsoon's avatar
qinsoon committed
339
                            }
340
341
342
343
344
                            _ => {
                                // do nothing
                            }
                        }
                    }
345
                    _ => unreachable!()
346
347
348
349
350
351
352
                }
            }
        }

        ret
    }

353
354
    // TODO: It may be more efficient to compute this when the instructions
    // are added to the function version and store the result in a field
355
356
357
358
359
360
361
362
363
364
    pub fn has_throw(&self) -> bool {
        let f_content = self.content.as_ref().unwrap();

        for (_, block) in f_content.blocks.iter() {
            let block_content = block.content.as_ref().unwrap();

            for inst in block_content.body.iter() {
                match inst.v {
                    TreeNode_::Instruction(ref inst) => {
                        match inst.v {
qinsoon's avatar
qinsoon committed
365
366
367
                            Instruction_::Throw(_) => {
                                return true;
                            }
368
369
370
371
372
                            _ => {
                                // do nothing
                            }
                        }
                    }
373
                    _ => unreachable!()
374
375
376
377
378
379
                }
            }
        }

        false
    }
380
381
382
383
384
385
386
387
388
389
390

    pub fn has_tailcall(&self) -> bool {
        let f_content = self.content.as_ref().unwrap();

        for (_, block) in f_content.blocks.iter() {
            let block_content = block.content.as_ref().unwrap();

            for inst in block_content.body.iter() {
                match inst.v {
                    TreeNode_::Instruction(ref inst) => {
                        match inst.v {
qinsoon's avatar
qinsoon committed
391
392
393
                            Instruction_::TailCall(_) => {
                                return true;
                            }
394
395
396
                            _ => {
                                // do nothing
                            }
397
398
                        }
                    }
399
                    _ => unreachable!()
400
401
402
403
404
405
406
407
                }
            }
        }

        false
    }
}

408
/// FunctionContent contains all blocks (which include all instructions) for the function
409
#[derive(Clone)]
410
411
412
pub struct FunctionContent {
    pub entry: MuID,
    pub blocks: LinkedHashMap<MuID, Block>,
413
    pub exception_blocks: LinkedHashSet<MuID> // this field only valid after control flow analysis
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
}

impl fmt::Debug for FunctionContent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let entry = self.get_entry_block();
        write!(f, "Entry block: ").unwrap();
        write!(f, "{:?}\n", entry).unwrap();

        write!(f, "Body:").unwrap();
        for blk_id in self.blocks.keys() {
            let block = self.get_block(*blk_id);
            write!(f, "{:?}\n", block).unwrap();
        }
        Ok(())
    }
}

impl FunctionContent {
    pub fn new(entry: MuID, blocks: LinkedHashMap<MuID, Block>) -> FunctionContent {
        FunctionContent {
            entry: entry,
            blocks: blocks,
436
            exception_blocks: LinkedHashSet::new()
437
438
439
440
441
        }
    }

    pub fn get_entry_block(&self) -> &Block {
        self.get_block(self.entry)
qinsoon's avatar
qinsoon committed
442
    }
443
444
445
446
447
448
449
450
451
452

    pub fn get_entry_block_mut(&mut self) -> &mut Block {
        let entry = self.entry;
        self.get_block_mut(entry)
    }

    pub fn get_block(&self, id: MuID) -> &Block {
        let ret = self.blocks.get(&id);
        match ret {
            Some(b) => b,
453
            None => panic!("cannot find block #{}", id)
454
455
456
457
458
459
460
        }
    }

    pub fn get_block_mut(&mut self, id: MuID) -> &mut Block {
        let ret = self.blocks.get_mut(&id);
        match ret {
            Some(b) => b,
461
            None => panic!("cannot find block #{}", id)
462
463
        }
    }
464

465
    pub fn get_block_by_name(&self, name: MuName) -> &Block {
466
        for block in self.blocks.values() {
467
            if block.name() == name {
468
469
470
471
472
473
                return block;
            }
        }

        panic!("cannot find block {}", name)
    }
474
475
}

476
477
/// FunctionContext contains compilation information about the function
// FIXME: should move this out of ast crate and bind its lifetime with compilation (Issue #18)
478
#[derive(Default, Debug)]
479
pub struct FunctionContext {
480
    pub values: LinkedHashMap<MuID, SSAVarEntry>
481
482
483
484
485
}

impl FunctionContext {
    fn new() -> FunctionContext {
        FunctionContext {
486
            values: LinkedHashMap::new()
487
488
        }
    }
489
490

    /// makes a TreeNode of an SSA variable
491
    pub fn make_temporary(&mut self, id: MuID, ty: P<MuType>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
492
        let val = P(Value {
493
494
            hdr: MuEntityHeader::unnamed(id),
            ty: ty,
495
            v: Value_::SSAVar(id)
496
497
498
499
500
        });

        self.values.insert(id, SSAVarEntry::new(val.clone()));

        P(TreeNode {
501
            v: TreeNode_::Value(val)
502
503
504
        })
    }

505
    /// shows the name for an SSA by ID
506
507
508
    pub fn get_temp_display(&self, id: MuID) -> String {
        match self.get_value(id) {
            Some(entry) => format!("{}", entry.value()),
509
            None => "CANT_FOUND_ID".to_string()
510
511
512
        }
    }

513
    /// returns a &SSAVarEntry for the given ID
514
515
516
517
    pub fn get_value(&self, id: MuID) -> Option<&SSAVarEntry> {
        self.values.get(&id)
    }

518
    /// returns a &mut SSAVarEntry for the given ID
519
520
521
522
523
    pub fn get_value_mut(&mut self, id: MuID) -> Option<&mut SSAVarEntry> {
        self.values.get_mut(&id)
    }
}

524
/// Block contains BlockContent, which includes all the instructions for the block
525
526
//  FIXME: control_flow field should be moved out of ast crate (Issue #18)
//  FIXME: trace_hint should also be moved
527
#[derive(Clone)]
528
529
pub struct Block {
    pub hdr: MuEntityHeader,
530
    /// the actual content of this block
531
    pub content: Option<BlockContent>,
532
533
534
    /// a trace scheduling hint about where to layout this block
    pub trace_hint: TraceHint,
    /// control flow info about this block (predecessors, successors, etc)
535
    pub control_flow: ControlFlow
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
}

impl fmt::Debug for Block {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "Block {}", self.hdr).unwrap();
        writeln!(f, "with preds: {:?}", self.control_flow.preds).unwrap();
        writeln!(f, "     succs: {:?}", self.control_flow.succs).unwrap();
        if self.content.is_some() {
            writeln!(f, "{:?}", self.content.as_ref().unwrap()).unwrap();
        } else {
            writeln!(f, "Empty").unwrap();
        }
        Ok(())
    }
}

552
553
554
555
556
557
impl fmt::Display for Block {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

558
impl Block {
559
    pub fn new(entity: MuEntityHeader) -> Block {
qinsoon's avatar
qinsoon committed
560
561
562
563
        Block {
            hdr: entity,
            content: None,
            trace_hint: TraceHint::None,
564
            control_flow: ControlFlow::default()
qinsoon's avatar
qinsoon committed
565
        }
566
    }
567
568

    /// does this block have an exception arguments?
569
    pub fn is_receiving_exception_arg(&self) -> bool {
qinsoon's avatar
qinsoon committed
570
        return self.content.as_ref().unwrap().exn_arg.is_some();
571
572
    }

573
    /// how many IR instruction does this block have?
574
575
576
577
578
579
580
581
582
    pub fn number_of_irs(&self) -> usize {
        if self.content.is_none() {
            0
        } else {
            let content = self.content.as_ref().unwrap();

            content.body.len()
        }
    }
583
584
585

    /// is this block ends with a conditional branch?
    pub fn ends_with_cond_branch(&self) -> bool {
qinsoon's avatar
qinsoon committed
586
        let block: &BlockContent = self.content.as_ref().unwrap();
587
588
589
        match block.body.last() {
            Some(node) => {
                match node.v {
qinsoon's avatar
qinsoon committed
590
591
592
593
                    TreeNode_::Instruction(Instruction {
                        v: Instruction_::Branch2 { .. },
                        ..
                    }) => true,
594
                    _ => false
595
596
                }
            }
597
            None => false
598
599
600
601
602
        }
    }

    /// is this block ends with a return?
    pub fn ends_with_return(&self) -> bool {
qinsoon's avatar
qinsoon committed
603
        let block: &BlockContent = self.content.as_ref().unwrap();
604
605
606
        match block.body.last() {
            Some(node) => {
                match node.v {
qinsoon's avatar
qinsoon committed
607
608
609
610
                    TreeNode_::Instruction(Instruction {
                        v: Instruction_::Return(_),
                        ..
                    }) => true,
611
                    _ => false
612
613
                }
            }
614
            None => false
615
616
        }
    }
617
618
}

619
/// TraceHint is a hint for the compiler to generate better trace for this block
620
621
622
623
624
625
//  Note: for a sequence of blocks that are supposed to be fast/slow path, only mark the
//  first block with TraceHint, and let the trace scheduler to normally layout other
//  blocks. Otherwise, the scheduler will take every TraceHint into consideration,
//  and may not generate the trace as expected.
//  FIXME: Issue #18
#[derive(Clone, PartialEq)]
626
627
628
629
630
631
632
633
pub enum TraceHint {
    /// no hint provided. Trace scheduler should use its own heuristics to decide
    None,
    /// this block is fast path, and should be put in straightline code where possible
    FastPath,
    /// this block is slow path, and should be kept out of hot loops
    SlowPath,
    /// this block is return sink, and should be put at the end of a function
634
    ReturnSink
635
636
}

637
/// ControlFlow stores compilation info about control flows of a block
638
//  FIXME: Issue #18
639
#[derive(Debug, Clone)]
640
pub struct ControlFlow {
qinsoon's avatar
qinsoon committed
641
    pub preds: Vec<MuID>,
642
    pub succs: Vec<BlockEdge>
643
644
645
}

impl ControlFlow {
646
647
    /// returns the successor with highest branching probability
    /// (in case of tie, returns first met successor)
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
    pub fn get_hottest_succ(&self) -> Option<MuID> {
        if self.succs.len() == 0 {
            None
        } else {
            let mut hot_blk = self.succs[0].target;
            let mut hot_prob = self.succs[0].probability;

            for edge in self.succs.iter() {
                if edge.probability > hot_prob {
                    hot_blk = edge.target;
                    hot_prob = edge.probability;
                }
            }

            Some(hot_blk)
        }
    }
}

impl fmt::Display for ControlFlow {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "preds: [{}], ", vec_utils::as_str(&self.preds)).unwrap();
        write!(f, "succs: [{}]", vec_utils::as_str(&self.succs))
    }
}

impl default::Default for ControlFlow {
    fn default() -> ControlFlow {
qinsoon's avatar
qinsoon committed
676
677
        ControlFlow {
            preds: vec![],
678
            succs: vec![]
qinsoon's avatar
qinsoon committed
679
        }
680
681
682
    }
}

683
/// BlockEdge represents an edge in control flow graph
684
#[derive(Copy, Clone, Debug)]
685
686
687
688
pub struct BlockEdge {
    pub target: MuID,
    pub kind: EdgeKind,
    pub is_exception: bool,
689
    pub probability: f32
690
691
692
693
}

impl fmt::Display for BlockEdge {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
694
695
696
697
698
699
700
701
        write!(
            f,
            "{} ({:?}{} - {})",
            self.target,
            self.kind,
            select_value!(self.is_exception, ", exceptional", ""),
            self.probability
        )
702
703
704
    }
}

705
#[derive(Copy, Clone, Debug)]
706
pub enum EdgeKind {
qinsoon's avatar
qinsoon committed
707
    Forward,
708
    Backward
709
710
}

711
/// BlockContent describes arguments to this block, and owns all the IR instructions
712
#[derive(Clone)]
713
714
715
716
pub struct BlockContent {
    pub args: Vec<P<Value>>,
    pub exn_arg: Option<P<Value>>,
    pub body: Vec<Box<TreeNode>>,
717
    pub keepalives: Option<Vec<P<Value>>>
718
719
720
721
722
723
724
725
726
}

impl fmt::Debug for BlockContent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "args: {}", vec_utils::as_str(&self.args)).unwrap();
        if self.exn_arg.is_some() {
            writeln!(f, "exception arg: {}", self.exn_arg.as_ref().unwrap()).unwrap();
        }
        if self.keepalives.is_some() {
qinsoon's avatar
qinsoon committed
727
728
729
730
731
            writeln!(
                f,
                "keepalives: {}",
                vec_utils::as_str(self.keepalives.as_ref().unwrap())
            ).unwrap();
732
733
734
735
736
737
738
739
740
        }
        for node in self.body.iter() {
            writeln!(f, "{}", node).unwrap();
        }
        Ok(())
    }
}

impl BlockContent {
741
    /// returns all the arguments passed to its successors
742
743
744
    pub fn get_out_arguments(&self) -> Vec<P<Value>> {
        let n_insts = self.body.len();
        let ref last_inst = self.body[n_insts - 1];
qinsoon's avatar
qinsoon committed
745
746
747

        let mut ret: Vec<P<Value>> = vec![];

748
749
        match last_inst.v {
            TreeNode_::Instruction(ref inst) => {
750
                let ref ops = inst.ops;
751
                match inst.v {
qinsoon's avatar
qinsoon committed
752
753
754
755
                    Instruction_::Return(_) |
                    Instruction_::ThreadExit |
                    Instruction_::Throw(_) |
                    Instruction_::TailCall(_) => {
756
757
758
759
                        // they do not have explicit liveouts
                    }
                    Instruction_::Branch1(ref dest) => {
                        let mut live_outs = dest.get_arguments(&ops);
qinsoon's avatar
qinsoon committed
760
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
761
                    }
qinsoon's avatar
qinsoon committed
762
763
764
765
766
                    Instruction_::Branch2 {
                        ref true_dest,
                        ref false_dest,
                        ..
                    } => {
767
768
                        let mut live_outs = true_dest.get_arguments(&ops);
                        live_outs.append(&mut false_dest.get_arguments(&ops));
qinsoon's avatar
qinsoon committed
769

qinsoon's avatar
qinsoon committed
770
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
771
                    }
qinsoon's avatar
qinsoon committed
772
773
774
775
776
                    Instruction_::Watchpoint {
                        ref disable_dest,
                        ref resume,
                        ..
                    } => {
777
                        let mut live_outs = vec![];
qinsoon's avatar
qinsoon committed
778

779
                        if disable_dest.is_some() {
qinsoon's avatar
qinsoon committed
780
781
                            live_outs
                                .append(&mut disable_dest.as_ref().unwrap().get_arguments(&ops));
782
783
784
                        }
                        live_outs.append(&mut resume.normal_dest.get_arguments(&ops));
                        live_outs.append(&mut resume.exn_dest.get_arguments(&ops));
qinsoon's avatar
qinsoon committed
785

qinsoon's avatar
qinsoon committed
786
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
787
                    }
qinsoon's avatar
qinsoon committed
788
789
790
791
792
                    Instruction_::WPBranch {
                        ref disable_dest,
                        ref enable_dest,
                        ..
                    } => {
793
794
795
                        let mut live_outs = vec![];
                        live_outs.append(&mut disable_dest.get_arguments(&ops));
                        live_outs.append(&mut enable_dest.get_arguments(&ops));
qinsoon's avatar
qinsoon committed
796
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
797
                    }
qinsoon's avatar
qinsoon committed
798
799
                    Instruction_::Call { ref resume, .. } |
                    Instruction_::CCall { ref resume, .. } |
800
                    Instruction_::SwapStackExc { ref resume, .. } |
qinsoon's avatar
qinsoon committed
801
                    Instruction_::ExnInstruction { ref resume, .. } => {
802
803
804
                        let mut live_outs = vec![];
                        live_outs.append(&mut resume.normal_dest.get_arguments(&ops));
                        live_outs.append(&mut resume.exn_dest.get_arguments(&ops));
qinsoon's avatar
qinsoon committed
805
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
806
                    }
qinsoon's avatar
qinsoon committed
807
808
809
810
811
                    Instruction_::Switch {
                        ref default,
                        ref branches,
                        ..
                    } => {
812
813
814
815
816
                        let mut live_outs = vec![];
                        live_outs.append(&mut default.get_arguments(&ops));
                        for &(_, ref dest) in branches {
                            live_outs.append(&mut dest.get_arguments(&ops));
                        }
qinsoon's avatar
qinsoon committed
817
                        vec_utils::add_all_unique(&mut ret, &mut live_outs);
818
                    }
qinsoon's avatar
qinsoon committed
819

820
                    _ => panic!("didn't expect last inst as {}", inst)
821
                }
qinsoon's avatar
qinsoon committed
822
            }
823
            _ => panic!("expect last treenode of block is a inst")
824
        }
qinsoon's avatar
qinsoon committed
825

826
827
        ret
    }
828
829
830
831
832
833

    pub fn clone_empty(&self) -> BlockContent {
        BlockContent {
            args: self.args.clone(),
            exn_arg: self.exn_arg.clone(),
            body: vec![],
834
            keepalives: self.keepalives.clone()
835
836
        }
    }
837
838
}

839
840
/// TreeNode represents a node in the AST, it could either be an instruction,
/// or an value (SSA, constant, global, etc)
841
#[derive(Debug, Clone)]
842
pub struct TreeNode {
843
    pub v: TreeNode_
844
845
846
}

impl TreeNode {
847
    /// creates a sharable Instruction TreeNode
848
    pub fn new_inst(v: Instruction) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
849
        P(TreeNode {
850
            v: TreeNode_::Instruction(v)
851
852
853
        })
    }

854
    /// creates an owned Instruction TreeNode
855
    pub fn new_boxed_inst(v: Instruction) -> Box<TreeNode> {
qinsoon's avatar
qinsoon committed
856
        Box::new(TreeNode {
857
            v: TreeNode_::Instruction(v)
858
859
860
        })
    }

qinsoon's avatar
qinsoon committed
861
862
863
    /// creates a sharable Value TreeNode
    pub fn new_value(v: P<Value>) -> P<TreeNode> {
        P(TreeNode {
864
            v: TreeNode_::Value(v)
qinsoon's avatar
qinsoon committed
865
866
867
        })
    }

868
869
    /// extracts the MuID of an SSA TreeNode
    /// if the node is not an SSA, returns None
870
871
872
873
874
    pub fn extract_ssa_id(&self) -> Option<MuID> {
        match self.v {
            TreeNode_::Value(ref pv) => {
                match pv.v {
                    Value_::SSAVar(id) => Some(id),
875
                    _ => None
876
                }
qinsoon's avatar
qinsoon committed
877
            }
878
            _ => None
879
880
881
        }
    }

882
883
884
    /// clones the value from the TreeNode
    /// * if this is a Instruction TreeNode, returns its first result value
    /// * if this is a value, returns a clone of it
885
    pub fn clone_value(&self) -> P<Value> {
qinsoon's avatar
qinsoon committed
886
887
888
889
890
891
892
        self.as_value().clone()
    }

    /// returns the value from the TreeNode
    /// * if this is a Instruction TreeNode, returns its first result value
    /// * if this is a value, returns a clone of it
    pub fn as_value(&self) -> &P<Value> {
893
        match self.v {
qinsoon's avatar
qinsoon committed
894
            TreeNode_::Value(ref val) => val,
895
896
897
            TreeNode_::Instruction(ref inst) => {
                let vals = inst.value.as_ref().unwrap();
                if vals.len() != 1 {
qinsoon's avatar
qinsoon committed
898
899
900
901
                    panic!(
                        "we expect an inst with 1 value, but found multiple or zero \
                         (it should not be here - folded as a child)"
                    );
902
                }
qinsoon's avatar
qinsoon committed
903
                &vals[0]
904
905
906
907
            }
        }
    }

908
    /// consumes the TreeNode, returns the value in it (or None if it is not a value)
909
910
911
    pub fn into_value(self) -> Option<P<Value>> {
        match self.v {
            TreeNode_::Value(val) => Some(val),
912
            _ => None
913
914
915
        }
    }

916
    /// consumes the TreeNode, returns the instruction in it (or None if it is not an instruction)
917
918
919
    pub fn into_inst(self) -> Option<Instruction> {
        match self.v {
            TreeNode_::Instruction(inst) => Some(inst),
920
            _ => None
921
922
        }
    }
923

924
925
926
927
928
929
930
931
    /// consumes the TreeNode, returns the instruction in it (or None if it is not an instruction)
    pub fn as_inst_ref(&self) -> &Instruction {
        match &self.v {
            &TreeNode_::Instruction(ref inst) => inst,
            _ => panic!("expected inst")
        }
    }

932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
    // The type of the node (for a value node)
    pub fn ty(&self) -> P<MuType> {
        match self.v {
            TreeNode_::Instruction(ref inst) => {
                if inst.value.is_some() {
                    let ref value = inst.value.as_ref().unwrap();
                    if value.len() != 1 {
                        panic!("the node {} does not have one result value", self);
                    }

                    value[0].ty.clone()
                } else {
                    panic!("expected result from the node {}", self);
                }
            }
            TreeNode_::Value(ref pv) => pv.ty.clone()
        }
    }
950
951
952
953
954
955
}

impl fmt::Display for TreeNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.v {
            TreeNode_::Value(ref pv) => pv.fmt(f),
956
            TreeNode_::Instruction(ref inst) => write!(f, "({})", inst)
957
958
959
960
        }
    }
}

961
/// TreeNode_ is used for pattern matching for TreeNode
962
#[derive(Debug, Clone)]
963
964
pub enum TreeNode_ {
    Value(P<Value>),
965
    Instruction(Instruction)
966
967
}

968
969
970
971
972
/// Value represents a value in the tree, it could be SSA variables, constants, globals,
/// which all will appear in Mu IR. Value may also represent a memory (as in transformed tree,
/// we need to represent memory as well)
///
/// Value should always be used with P<Value> (sharable)
973
#[derive(PartialEq)]
974
975
976
pub struct Value {
    pub hdr: MuEntityHeader,
    pub ty: P<MuType>,
977
    pub v: Value_
978
979
}

qinsoon's avatar
qinsoon committed
980
rodal_struct!(Value { hdr, ty, v });
981

982
impl Value {
983
    /// creates an int constant value
984
    pub fn make_int_const(id: MuID, val: u64) -> P<Value> {
985
986
987
988
        Value::make_int_const_ty(id, UINT32_TYPE.clone(), val)
    }

    pub fn make_int_const_ty(id: MuID, ty: P<MuType>, val: u64) -> P<Value> {
qinsoon's avatar
qinsoon committed
989
        P(Value {
990
            hdr: MuEntityHeader::unnamed(id),
991
            ty: ty,
992
            v: Value_::Constant(Constant::Int(val))
993
994
        })
    }
qinsoon's avatar
qinsoon committed
995

996
997
998
    pub fn is_mem(&self) -> bool {
        match self.v {
            Value_::Memory(_) => true,
999
            _ => false
1000
1001
        }
    }
1002
1003

    pub fn is_reg(&self) -> bool {
1004
        match self.v {
1005
            Value_::SSAVar(_) => true,
1006
            _ => false
1007
1008
1009
1010
1011
1012
        }
    }

    pub fn is_const(&self) -> bool {
        match self.v {
            Value_::Constant(_) => true,
1013
            _ => false
1014
1015
1016
        }
    }

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
    pub fn is_const_zero(&self) -> bool {
        match self.v {
            Value_::Constant(Constant::Int(val)) if val == 0 => true,
            Value_::Constant(Constant::Double(val)) if val == 0f64 => true,
            Value_::Constant(Constant::Float(val)) if val == 0f32 => true,
            Value_::Constant(Constant::IntEx(ref vec)) => {
                if vec.iter().all(|x| *x == 0) {
                    true
                } else {
                    false
                }
            }
            Value_::Constant(Constant::NullRef) => true,
            _ => false
        }
    }

1034
1035
1036
    /// disguises a value as another type.
    /// This is usually used for treat an integer type as an integer of a different length
    /// This method is unsafe
1037
    pub unsafe fn as_type(&self, ty: P<MuType>) -> P<Value> {
qinsoon's avatar
qinsoon committed
1038
        P(Value {
1039
1040
            hdr: self.hdr.clone(),
            ty: ty,
1041
            v: self.v.clone()
1042
1043
1044
        })
    }

1045
1046
1047
    pub fn is_int_ex_const(&self) -> bool {
        match self.v {
            Value_::Constant(Constant::IntEx(_)) => true,
1048
            _ => false
1049
1050
1051
1052
        }
    }


1053
1054
1055
1056
    pub fn is_int_const(&self) -> bool {
        match self.v {
            Value_::Constant(Constant::Int(_)) => true,
            Value_::Constant(Constant::NullRef) => true,
1057
            _ => false
1058
1059
        }
    }
1060

1061
1062
1063
1064
    pub fn is_fp_const(&self) -> bool {
        match self.v {
            Value_::Constant(Constant::Float(_)) => true,
            Value_::Constant(Constant::Double(_)) => true,
1065
            _ => false
1066
1067
        }
    }
1068

1069
    pub fn extract_int_const(&self) -> Option<u64> {
1070
        match self.v {
1071
            Value_::Constant(Constant::Int(val)) => Some(val),
qinsoon's avatar
qinsoon committed
1072
            Value_::Constant(Constant::NullRef) => Some(0),
1073
            _ => None