WARNING! Access to this system is limited to authorised users only.
Unauthorised users may be subject to prosecution.
Unauthorised access to this system is a criminal offence under Australian law (Federal Crimes Act 1914 Part VIA)
It is a criminal offence to:
(1) Obtain access to data without authority. -Penalty 2 years imprisonment.
(2) Damage, delete, alter or insert data without authority. -Penalty 10 years imprisonment.
User activity is monitored and recorded. Anyone using this system expressly consents to such monitoring and recording.

To protect your data, the CISO officer has suggested users to enable 2FA as soon as possible.
Currently 2.6% of users enabled 2FA.

ir.rs 26.5 KB
Newer Older
qinsoon's avatar
qinsoon committed
1 2 3 4 5
use ptr::P;
use types::*;
use inst::*;
use op::*;

6
use utils::vec_utils;
7

8
use std::collections::HashMap;
qinsoon's avatar
qinsoon committed
9
use std::fmt;
10
use std::default;
11
use std::sync::RwLock;
qinsoon's avatar
qinsoon committed
12
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
qinsoon's avatar
qinsoon committed
13

qinsoon's avatar
qinsoon committed
14 15
pub type WPID  = usize;
pub type MuID  = usize;
16
pub type MuName = String;
17
pub type CName  = MuName;
qinsoon's avatar
qinsoon committed
18

19 20 21
#[allow(non_snake_case)]
pub fn Mu(str: &'static str) -> MuName {str.to_string()}

22 23
pub type OpIndex = usize;

qinsoon's avatar
qinsoon committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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
    };
} 
pub const  MACHINE_ID_START : usize = 0;
pub const  MACHINE_ID_END   : usize = 100;

pub const  INTERNAL_ID_START: usize = 101;
pub const  INTERNAL_ID_END  : usize = 200;
pub const  USER_ID_START    : usize = 201;

qinsoon's avatar
qinsoon committed
43 44 45 46 47
#[deprecated]
#[allow(dead_code)]
/// 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
qinsoon's avatar
qinsoon committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
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
}
qinsoon's avatar
qinsoon committed
63

qinsoon's avatar
qinsoon committed
64
#[derive(Debug, RustcEncodable, RustcDecodable)]
65
pub struct MuFunction {
66
    pub hdr: MuEntityHeader,
qinsoon's avatar
qinsoon committed
67
    
68
    pub sig: P<MuFuncSig>,
qinsoon's avatar
qinsoon committed
69 70
    pub cur_ver: Option<MuID>,
    pub all_vers: Vec<MuID>
71 72 73
}

impl MuFunction {
qinsoon's avatar
qinsoon committed
74
    pub fn new(id: MuID, sig: P<MuFuncSig>) -> MuFunction {
75
        MuFunction {
76
            hdr: MuEntityHeader::unnamed(id),
77 78 79 80 81
            sig: sig,
            cur_ver: None,
            all_vers: vec![]
        }
    }
82 83 84 85 86 87 88 89 90
    
    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);
        }
        
        self.cur_ver = Some(fv);
    }
91 92
}

qinsoon's avatar
qinsoon committed
93 94
impl fmt::Display for MuFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95
        write!(f, "Func {}", self.hdr)
qinsoon's avatar
qinsoon committed
96 97 98
    }
}

99
#[derive(RustcEncodable, RustcDecodable)]
100
pub struct MuFunctionVersion {
101
    pub hdr: MuEntityHeader,
qinsoon's avatar
qinsoon committed
102 103
         
    pub func_id: MuID,
qinsoon's avatar
qinsoon committed
104
    pub sig: P<MuFuncSig>,
105
    pub content: Option<FunctionContent>,
106
    pub context: FunctionContext,
107

qinsoon's avatar
qinsoon committed
108 109 110 111 112
    pub block_trace: Option<Vec<MuID>> // only available after Trace Generation Pass
}

impl fmt::Display for MuFunctionVersion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113
        write!(f, "FuncVer {} of Func #{}", self.hdr, self.func_id)
qinsoon's avatar
qinsoon committed
114
    }
115 116
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
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, "{:?}\n", self.block_trace.as_ref().unwrap())
        } else {
            write!(f, "Trace not available\n")
        }
    }
}

135
impl MuFunctionVersion {
qinsoon's avatar
qinsoon committed
136
    pub fn new(id: MuID, func: MuID, sig: P<MuFuncSig>) -> MuFunctionVersion {
137
        MuFunctionVersion{
138
            hdr: MuEntityHeader::unnamed(id),
qinsoon's avatar
qinsoon committed
139
            func_id: func,
qinsoon's avatar
qinsoon committed
140 141 142
            sig: sig,
            content: None,
            context: FunctionContext::new(),
qinsoon's avatar
qinsoon committed
143 144
            block_trace: None
        }
qinsoon's avatar
qinsoon committed
145
    }
qinsoon's avatar
qinsoon committed
146

147
    pub fn define(&mut self, content: FunctionContent) {
qinsoon's avatar
qinsoon committed
148
        self.content = Some(content);
149
    }
150

qinsoon's avatar
qinsoon committed
151
    pub fn new_ssa(&mut self, id: MuID, ty: P<MuType>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
152 153 154 155 156 157 158
        let val = P(Value{
            hdr: MuEntityHeader::unnamed(id),
            ty: ty,
            v: Value_::SSAVar(id)
        });

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

160
        P(TreeNode {
qinsoon's avatar
qinsoon committed
161 162
            op: pick_op_code_for_ssa(&val.ty),
            v: TreeNode_::Value(val)
163 164
        })
    }
165

qinsoon's avatar
qinsoon committed
166
    pub fn new_constant(&mut self, v: P<Value>) -> P<TreeNode> {
167
        P(TreeNode{
qinsoon's avatar
qinsoon committed
168 169 170 171 172
            op: pick_op_code_for_value(&v.ty),
            v: TreeNode_::Value(v)
        })
    }
    
qinsoon's avatar
qinsoon committed
173
    pub fn new_global(&mut self, v: P<Value>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
174 175
        P(TreeNode{
            op: pick_op_code_for_value(&v.ty),
qinsoon's avatar
qinsoon committed
176 177
            v: TreeNode_::Value(v)
        })
178
    }
qinsoon's avatar
qinsoon committed
179

qinsoon's avatar
qinsoon committed
180
    pub fn new_inst(&mut self, v: Instruction) -> Box<TreeNode> {
qinsoon's avatar
qinsoon committed
181
        Box::new(TreeNode{
qinsoon's avatar
qinsoon committed
182
            op: pick_op_code_for_inst(&v),
qinsoon's avatar
qinsoon committed
183 184
            v: TreeNode_::Instruction(v),
        })
qinsoon's avatar
qinsoon committed
185
    }
186 187
}

qinsoon's avatar
qinsoon committed
188
#[derive(RustcEncodable, RustcDecodable, Clone)]
189
pub struct FunctionContent {
qinsoon's avatar
qinsoon committed
190 191
    pub entry: MuID,
    pub blocks: HashMap<MuID, Block>
192 193
}

194 195 196 197 198 199 200 201 202 203 204 205 206
impl fmt::Debug for FunctionContent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let entry = self.get_entry_block();
        write!(f, "{:?}\n", entry).unwrap();
        
        for blk_id in self.blocks.keys() {
            let block = self.get_block(*blk_id);
            write!(f, "{:?}\n", block).unwrap();
        }
        Ok(())
    }
}

207 208
impl FunctionContent {
    pub fn get_entry_block(&self) -> &Block {
qinsoon's avatar
qinsoon committed
209
        self.get_block(self.entry)
qinsoon's avatar
qinsoon committed
210
    } 
211

212
    pub fn get_entry_block_mut(&mut self) -> &mut Block {
qinsoon's avatar
qinsoon committed
213 214
        let entry = self.entry;
        self.get_block_mut(entry)
215
    }
216

qinsoon's avatar
qinsoon committed
217 218
    pub fn get_block(&self, id: MuID) -> &Block {
        let ret = self.blocks.get(&id);
qinsoon's avatar
qinsoon committed
219 220
        match ret {
            Some(b) => b,
qinsoon's avatar
qinsoon committed
221
            None => panic!("cannot find block #{}", id)
qinsoon's avatar
qinsoon committed
222
        }
223
    }
224

qinsoon's avatar
qinsoon committed
225 226
    pub fn get_block_mut(&mut self, id: MuID) -> &mut Block {
        let ret = self.blocks.get_mut(&id);
qinsoon's avatar
qinsoon committed
227 228
        match ret {
            Some(b) => b,
qinsoon's avatar
qinsoon committed
229
            None => panic!("cannot find block #{}", id)
qinsoon's avatar
qinsoon committed
230
        }
231
    }
232 233
}

qinsoon's avatar
qinsoon committed
234
#[derive(Debug, RustcEncodable, RustcDecodable)]
235
pub struct FunctionContext {
qinsoon's avatar
qinsoon committed
236
    pub values: HashMap<MuID, SSAVarEntry>
237 238 239 240 241 242 243 244
}

impl FunctionContext {
    fn new() -> FunctionContext {
        FunctionContext {
            values: HashMap::new()
        }
    }
245 246
    
    pub fn make_temporary(&mut self, id: MuID, ty: P<MuType>) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
247 248 249 250 251 252 253
        let val = P(Value{
            hdr: MuEntityHeader::unnamed(id),
            ty: ty,
            v: Value_::SSAVar(id)
        });

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

        P(TreeNode {
qinsoon's avatar
qinsoon committed
256 257
            op: pick_op_code_for_ssa(&val.ty),
            v: TreeNode_::Value(val)
258
        })
qinsoon's avatar
qinsoon committed
259 260 261 262 263 264 265 266
    }

    pub fn get_temp_display(&self, id: MuID) -> String {
        match self.get_value(id) {
            Some(entry) => format!("{}", entry.value()),
            None => "CANT_FOUND_ID".to_string()
        }
    }
qinsoon's avatar
qinsoon committed
267

qinsoon's avatar
qinsoon committed
268
    pub fn get_value(&self, id: MuID) -> Option<&SSAVarEntry> {
269 270
        self.values.get(&id)
    }
271

qinsoon's avatar
qinsoon committed
272
    pub fn get_value_mut(&mut self, id: MuID) -> Option<&mut SSAVarEntry> {
273 274 275 276
        self.values.get_mut(&id)
    }
}

qinsoon's avatar
qinsoon committed
277
#[derive(RustcEncodable, RustcDecodable, Clone)]
278
pub struct Block {
279
    pub hdr: MuEntityHeader,
280 281
    pub content: Option<BlockContent>,
    pub control_flow: ControlFlow
qinsoon's avatar
qinsoon committed
282 283
}

284 285 286 287 288 289 290 291 292 293 294 295 296 297
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(())
    }
}

298
impl Block {
qinsoon's avatar
qinsoon committed
299
    pub fn new(id: MuID) -> Block {
300
        Block{hdr: MuEntityHeader::unnamed(id), content: None, control_flow: ControlFlow::default()}
301
    }
qinsoon's avatar
qinsoon committed
302 303 304 305
    
    pub fn is_exception_block(&self) -> bool {
        return self.content.as_ref().unwrap().exn_arg.is_some()
    }
306 307
}

qinsoon's avatar
qinsoon committed
308
#[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
309
pub struct ControlFlow {
qinsoon's avatar
qinsoon committed
310
    pub preds : Vec<MuID>,
311 312 313
    pub succs : Vec<BlockEdge>
}

314
impl ControlFlow {
qinsoon's avatar
qinsoon committed
315
    pub fn get_hottest_succ(&self) -> Option<MuID> {
316 317 318 319 320
        if self.succs.len() == 0 {
            None
        } else {
            let mut hot_blk = self.succs[0].target;
            let mut hot_prob = self.succs[0].probability;
321

322 323 324 325 326 327
            for edge in self.succs.iter() {
                if edge.probability > hot_prob {
                    hot_blk = edge.target;
                    hot_prob = edge.probability;
                }
            }
328

329 330 331 332 333
            Some(hot_blk)
        }
    }
}

334 335
impl fmt::Display for ControlFlow {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
336 337
        write!(f, "preds: [{}], ", vec_utils::as_str(&self.preds)).unwrap();
        write!(f, "succs: [{}]", vec_utils::as_str(&self.succs))
338 339 340 341 342 343 344 345 346
    }
}

impl default::Default for ControlFlow {
    fn default() -> ControlFlow {
        ControlFlow {preds: vec![], succs: vec![]}
    }
}

qinsoon's avatar
qinsoon committed
347
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
348
pub struct BlockEdge {
qinsoon's avatar
qinsoon committed
349
    pub target: MuID,
350 351 352 353 354 355 356 357 358 359 360
    pub kind: EdgeKind,
    pub is_exception: bool,
    pub probability: f32
}

impl fmt::Display for BlockEdge {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ({:?}{} - {})", self.target, self.kind, select_value!(self.is_exception, ", exceptional", ""), self.probability)
    }
}

qinsoon's avatar
qinsoon committed
361
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
362 363 364 365
pub enum EdgeKind {
    Forward, Backward
}

qinsoon's avatar
qinsoon committed
366
#[derive(RustcEncodable, RustcDecodable, Clone)]
367
pub struct BlockContent {
368
    pub args: Vec<P<Value>>,
369
    pub exn_arg: Option<P<Value>>,
qinsoon's avatar
qinsoon committed
370
    pub body: Vec<Box<TreeNode>>,
371
    pub keepalives: Option<Vec<P<Value>>>
372 373
}

374 375
impl fmt::Debug for BlockContent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
376 377 378 379 380 381 382
        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() {
            writeln!(f, "keepalives: {}", vec_utils::as_str(self.keepalives.as_ref().unwrap())).unwrap();
        }
383 384 385 386 387 388 389
        for node in self.body.iter() {
            writeln!(f, "{}", node).unwrap();
        }
        Ok(())
    }
}

390 391 392 393 394 395 396 397 398
impl BlockContent {
    pub fn get_out_arguments(&self) -> Vec<P<Value>> {
        let n_insts = self.body.len();
        let ref last_inst = self.body[n_insts - 1];
        
        let mut ret : Vec<P<Value>> = vec![];
        
        match last_inst.v {
            TreeNode_::Instruction(ref inst) => {
qinsoon's avatar
qinsoon committed
399
                let ops = inst.ops.read().unwrap();
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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
                match inst.v {
                    Instruction_::Return(_)
                    | Instruction_::ThreadExit
                    | Instruction_::Throw(_)
                    | Instruction_::TailCall(_) => {
                        // they do not have explicit liveouts
                    }
                    Instruction_::Branch1(ref dest) => {
                        let mut live_outs = dest.get_arguments(&ops);
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    Instruction_::Branch2{ref true_dest, ref false_dest, ..} => {
                        let mut live_outs = true_dest.get_arguments(&ops);
                        live_outs.append(&mut false_dest.get_arguments(&ops));
                        
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    Instruction_::Watchpoint{ref disable_dest, ref resume, ..} => {
                        let mut live_outs = vec![];
                        
                        if disable_dest.is_some() {
                            live_outs.append(&mut disable_dest.as_ref().unwrap().get_arguments(&ops));
                        }
                        live_outs.append(&mut resume.normal_dest.get_arguments(&ops));
                        live_outs.append(&mut resume.exn_dest.get_arguments(&ops));
                        
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    Instruction_::WPBranch{ref disable_dest, ref enable_dest, ..} => {
                        let mut live_outs = vec![];
                        live_outs.append(&mut disable_dest.get_arguments(&ops));
                        live_outs.append(&mut enable_dest.get_arguments(&ops));
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    Instruction_::Call{ref resume, ..}
                    | Instruction_::SwapStack{ref resume, ..}
                    | Instruction_::ExnInstruction{ref resume, ..} => {
                        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));
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    Instruction_::Switch{ref default, ref branches, ..} => {
                        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));
                        }
                        vec_utils::append_unique(&mut ret, &mut live_outs);
                    }
                    
                    _ => panic!("didn't expect last inst as {:?}", inst) 
                }
            },
            _ => panic!("expect last treenode of block is a inst")
        }
        
        ret
    }
}

qinsoon's avatar
qinsoon committed
461
#[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
qinsoon's avatar
qinsoon committed
462 463
/// always use with P<TreeNode>
pub struct TreeNode {
464 465
    pub op: OpCode,
    pub v: TreeNode_,
qinsoon's avatar
qinsoon committed
466 467
}

468
impl TreeNode {
469
    // this is a hack to allow creating TreeNode without using a &mut MuFunctionVersion
qinsoon's avatar
qinsoon committed
470
    pub fn new_inst(v: Instruction) -> P<TreeNode> {
qinsoon's avatar
qinsoon committed
471
        P(TreeNode{
qinsoon's avatar
qinsoon committed
472
            op: pick_op_code_for_inst(&v),
qinsoon's avatar
qinsoon committed
473 474
            v: TreeNode_::Instruction(v),
        })
qinsoon's avatar
qinsoon committed
475 476
    }

477 478 479 480 481 482 483 484 485 486 487
    pub fn extract_ssa_id(&self) -> Option<MuID> {
        match self.v {
            TreeNode_::Value(ref pv) => {
                match pv.v {
                    Value_::SSAVar(id) => Some(id),
                    _ => None
                }
            },
            _ => None
        }
    }
qinsoon's avatar
qinsoon committed
488

qinsoon's avatar
qinsoon committed
489
    pub fn clone_value(&self) -> P<Value> {
qinsoon's avatar
qinsoon committed
490
        match self.v {
qinsoon's avatar
qinsoon committed
491
            TreeNode_::Value(ref val) => val.clone(),
492
            TreeNode_::Instruction(ref inst) => {
493
                warn!("expecting a value, but we found an inst. Instead we use its first value");
494 495 496 497 498 499
                let vals = inst.value.as_ref().unwrap();
                if vals.len() != 1 {
                    panic!("we expect an inst with 1 value, but found multiple or zero (it should not be here - folded as a child)");
                }
                vals[0].clone()
            }
qinsoon's avatar
qinsoon committed
500
        }
qinsoon's avatar
qinsoon committed
501 502
    }

qinsoon's avatar
qinsoon committed
503 504 505
    pub fn into_value(self) -> Option<P<Value>> {
        match self.v {
            TreeNode_::Value(val) => Some(val),
qinsoon's avatar
qinsoon committed
506
            _ => None
qinsoon's avatar
qinsoon committed
507 508
        }
    }
qinsoon's avatar
qinsoon committed
509 510
}

511 512
/// use +() to display a node
impl fmt::Display for TreeNode {
qinsoon's avatar
qinsoon committed
513
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514
        match self.v {
qinsoon's avatar
qinsoon committed
515
            TreeNode_::Value(ref pv) => pv.fmt(f),
516
            TreeNode_::Instruction(ref inst) => {
517
                write!(f, "+({})", inst)
518
            }
qinsoon's avatar
qinsoon committed
519
        }
qinsoon's avatar
qinsoon committed
520
    }
qinsoon's avatar
qinsoon committed
521 522
}

qinsoon's avatar
qinsoon committed
523
#[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
qinsoon's avatar
qinsoon committed
524
pub enum TreeNode_ {
qinsoon's avatar
qinsoon committed
525
    Value(P<Value>),
526
    Instruction(Instruction)
qinsoon's avatar
qinsoon committed
527 528 529
}

/// always use with P<Value>
qinsoon's avatar
qinsoon committed
530
#[derive(Debug, PartialEq, RustcEncodable, RustcDecodable)]
qinsoon's avatar
qinsoon committed
531
pub struct Value {
532
    pub hdr: MuEntityHeader,
qinsoon's avatar
qinsoon committed
533 534
    pub ty: P<MuType>,
    pub v: Value_
qinsoon's avatar
qinsoon committed
535 536
}

537
impl Value {
qinsoon's avatar
qinsoon committed
538 539 540 541 542 543 544 545
    pub fn make_int_const(id: MuID, val: u64) -> P<Value> {
        P(Value{
            hdr: MuEntityHeader::unnamed(id),
            ty: UINT32_TYPE.clone(),
            v: Value_::Constant(Constant::Int(val))
        })
    }
    
546 547 548 549 550 551 552
    pub fn is_mem(&self) -> bool {
        match self.v {
            Value_::Memory(_) => true,
            _ => false
        }
    }
    
553 554 555 556 557 558 559 560 561 562 563 564
    pub fn is_int_reg(&self) -> bool {
        match self.v {
            Value_::SSAVar(_) => {
                if is_scalar(&self.ty) && !is_fp(&self.ty) {
                    true
                } else {
                    false
                }
            }
            _ => false
        }
    }
qinsoon's avatar
qinsoon committed
565

566 567 568 569 570 571 572 573 574 575 576 577
    pub fn is_fp_reg(&self) -> bool {
        match self.v {
            Value_::SSAVar(_) => {
                if is_scalar(&self.ty) && is_fp(&self.ty) {
                    true
                } else {
                    false
                }
            },
            _ => false
        }
    }
qinsoon's avatar
qinsoon committed
578

579 580 581
    pub fn is_int_const(&self) -> bool {
        match self.v {
            Value_::Constant(_) => {
qinsoon's avatar
qinsoon committed
582 583 584
                let ty : &MuType = &self.ty;
                match ty.v {
                    MuType_::Int(_) => true,
585 586 587 588 589
                    _ => false
                }
            }
            _ => false
        }
qinsoon's avatar
qinsoon committed
590
    }
591 592 593 594 595 596 597 598 599 600 601 602
    
    pub fn extract_int_const(&self) -> u64 {
        match self.v {
            Value_::Constant(ref c) => {
                match c {
                    &Constant::Int(val) => val,
                    _ => panic!("expect int const")
                }
            },
            _ => panic!("expect int const")
        }
    }
qinsoon's avatar
qinsoon committed
603

qinsoon's avatar
qinsoon committed
604 605 606 607 608 609 610 611 612 613 614
    pub fn extract_ssa_id(&self) -> Option<MuID> {
        match self.v {
            Value_::SSAVar(id) => Some(id),
            _ => None
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.v {
qinsoon's avatar
qinsoon committed
615
            Value_::SSAVar(_) => {
616
                write!(f, "+({} %{})", self.ty, self.hdr)
qinsoon's avatar
qinsoon committed
617 618
            },
            Value_::Constant(ref c) => {
619
                write!(f, "+({} {} @{})", self.ty, c, self.hdr)
qinsoon's avatar
qinsoon committed
620
            },
621 622
            Value_::Global(ref ty) => {
                write!(f, "+(GLOBAL {} @{})", ty, self.hdr)
623 624
            },
            Value_::Memory(ref mem) => {
625
                write!(f, "+(MEM {} %{})", mem, self.hdr)
qinsoon's avatar
qinsoon committed
626 627 628
            }
        }
    }
629 630
}

qinsoon's avatar
qinsoon committed
631
#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
qinsoon's avatar
qinsoon committed
632
pub enum Value_ {
633
    SSAVar(MuID),
qinsoon's avatar
qinsoon committed
634
    Constant(Constant),
635
    Global(P<MuType>), // what type is this global (without IRef)
636
    Memory(MemoryLocation)
qinsoon's avatar
qinsoon committed
637 638
}

qinsoon's avatar
qinsoon committed
639
#[derive(Debug)]
qinsoon's avatar
qinsoon committed
640
pub struct SSAVarEntry {
qinsoon's avatar
qinsoon committed
641
    val: P<Value>,
642

643 644
    // how many times this entry is used
    // availalbe after DefUse pass
qinsoon's avatar
qinsoon committed
645
    use_count: AtomicUsize,
646

647
    // this field is only used during TreeGeneration pass
qinsoon's avatar
qinsoon committed
648
    expr: Option<Instruction>
649 650
}

qinsoon's avatar
qinsoon committed
651 652
impl Encodable for SSAVarEntry {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
qinsoon's avatar
qinsoon committed
653 654
        s.emit_struct("SSAVarEntry", 3, |s| {
            try!(s.emit_struct_field("val", 0, |s| self.val.encode(s)));
qinsoon's avatar
qinsoon committed
655
            let count = self.use_count.load(Ordering::SeqCst);
qinsoon's avatar
qinsoon committed
656 657
            try!(s.emit_struct_field("use_count", 1, |s| s.emit_usize(count)));
            try!(s.emit_struct_field("expr", 2, |s| self.expr.encode(s)));
qinsoon's avatar
qinsoon committed
658 659 660 661 662 663 664
            Ok(())
        })
    }
}

impl Decodable for SSAVarEntry {
    fn decode<D: Decoder>(d: &mut D) -> Result<SSAVarEntry, D::Error> {
qinsoon's avatar
qinsoon committed
665 666 667 668
        d.read_struct("SSAVarEntry", 3, |d| {
            let val = try!(d.read_struct_field("val", 0, |d| Decodable::decode(d)));
            let count = try!(d.read_struct_field("use_count", 1, |d| d.read_usize()));
            let expr = try!(d.read_struct_field("expr", 2, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
669 670
            
            let ret = SSAVarEntry {
qinsoon's avatar
qinsoon committed
671
                val: val,
qinsoon's avatar
qinsoon committed
672 673 674 675 676 677 678 679 680 681 682
                use_count: ATOMIC_USIZE_INIT,
                expr: expr
            };
            
            ret.use_count.store(count, Ordering::SeqCst);
            
            Ok(ret)
        })
    }
}

qinsoon's avatar
qinsoon committed
683
impl SSAVarEntry {
qinsoon's avatar
qinsoon committed
684
    pub fn new(val: P<Value>) -> SSAVarEntry {
qinsoon's avatar
qinsoon committed
685
        let ret = SSAVarEntry {
qinsoon's avatar
qinsoon committed
686
            val: val,
qinsoon's avatar
qinsoon committed
687 688 689 690 691 692 693 694
            use_count: ATOMIC_USIZE_INIT,
            expr: None
        };
        
        ret.use_count.store(0, Ordering::SeqCst);
        
        ret
    }
qinsoon's avatar
qinsoon committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

    pub fn ty(&self) -> &P<MuType> {
        &self.val.ty
    }

    pub fn value(&self) -> &P<Value> {
        &self.val
    }

    pub fn use_count(&self) -> usize {
        self.use_count.load(Ordering::SeqCst)
    }
    pub fn increase_use_count(&self) {
        self.use_count.fetch_add(1, Ordering::SeqCst);
    }

    pub fn has_expr(&self) -> bool {
        self.expr.is_some()
    }
714 715 716
    pub fn assign_expr(&mut self, expr: Instruction) {
        self.expr = Some(expr)
    }
qinsoon's avatar
qinsoon committed
717 718 719 720
    pub fn take_expr(&mut self) -> Instruction {
        debug_assert!(self.has_expr());
        self.expr.take().unwrap()
    }
721 722
}

qinsoon's avatar
qinsoon committed
723
impl fmt::Display for SSAVarEntry {
724
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
725
        write!(f, "{}", self.val)
726 727 728
    }
}

qinsoon's avatar
qinsoon committed
729
#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
730
pub enum Constant {
qinsoon's avatar
qinsoon committed
731
    Int(u64),
732 733
    Float(f32),
    Double(f64),
qinsoon's avatar
qinsoon committed
734
//    IRef(Address),
qinsoon's avatar
qinsoon committed
735 736
    FuncRef(MuID),
    UFuncRef(MuID),
737
    Vector(Vec<Constant>),
738 739
}

740
impl fmt::Display for Constant {
741 742 743 744 745
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Constant::Int(v) => write!(f, "{}", v),
            &Constant::Float(v) => write!(f, "{}", v),
            &Constant::Double(v) => write!(f, "{}", v),
qinsoon's avatar
qinsoon committed
746
//            &Constant::IRef(v) => write!(f, "{}", v),
747 748
            &Constant::FuncRef(v) => write!(f, "{}", v),
            &Constant::UFuncRef(v) => write!(f, "{}", v),
749 750 751 752 753 754 755 756 757 758
            &Constant::Vector(ref v) => {
                write!(f, "[").unwrap();
                for i in 0..v.len() {
                    write!(f, "{}", v[i]).unwrap();
                    if i != v.len() - 1 {
                        write!(f, ", ").unwrap();
                    }
                }
                write!(f, "]")
            }
759 760
        }
    }
qinsoon's avatar
qinsoon committed
761 762
}

qinsoon's avatar
qinsoon committed
763
#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
764 765 766 767 768 769 770 771 772
pub enum MemoryLocation {
    Address{
        base: P<Value>,
        offset: Option<P<Value>>,
        index: Option<P<Value>>,
        scale: Option<u8>
    },
    Symbolic{
        base: Option<P<Value>>,
qinsoon's avatar
qinsoon committed
773
        label: MuName
774 775 776 777 778 779 780
    }
}

impl fmt::Display for MemoryLocation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &MemoryLocation::Address{ref base, ref offset, ref index, scale} => {
qinsoon's avatar
qinsoon committed
781 782 783 784 785 786 787 788 789 790 791
                // base
                write!(f, "[{}", base).unwrap();
                // offset
                if offset.is_some() {
                    write!(f, " + {}", offset.as_ref().unwrap()).unwrap();
                }
                // index/scale
                if index.is_some() && scale.is_some() {
                    write!(f, " + {} * {}", index.as_ref().unwrap(), scale.unwrap()).unwrap();
                }
                write!(f, "]")
792 793 794
            }
            &MemoryLocation::Symbolic{ref base, ref label} => {
                if base.is_some() {
795
                    write!(f, "{}({})", label, base.as_ref().unwrap())
796 797 798 799 800 801 802 803
                } else {
                    write!(f, "{}", label)
                }
            }
        }
    }
}

804
#[repr(C)]
qinsoon's avatar
qinsoon committed
805
#[derive(Debug)] // Display, PartialEq, Clone
806
pub struct MuEntityHeader {
qinsoon's avatar
qinsoon committed
807 808
    pub id: MuID,
    pub name: RwLock<Option<MuName>>
809 810
}

qinsoon's avatar
qinsoon committed
811 812 813 814 815 816 817 818 819
impl Clone for MuEntityHeader {
    fn clone(&self) -> Self {
        MuEntityHeader {
            id: self.id,
            name: RwLock::new(self.name.read().unwrap().clone())
        }
    }
}

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
impl Encodable for MuEntityHeader {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
        s.emit_struct("MuEntityHeader", 2, |s| {
            try!(s.emit_struct_field("id", 0, |s| self.id.encode(s)));
            
            let name = &self.name.read().unwrap();
            try!(s.emit_struct_field("name", 1, |s| name.encode(s)));
            
            Ok(())
        })
    }
}

impl Decodable for MuEntityHeader {
    fn decode<D: Decoder>(d: &mut D) -> Result<MuEntityHeader, D::Error> {
        d.read_struct("MuEntityHeader", 2, |d| {
            let id = try!(d.read_struct_field("id", 0, |d| {d.read_usize()}));
            let name = try!(d.read_struct_field("name", 1, |d| Decodable::decode(d)));
            
            Ok(MuEntityHeader{
                    id: id,
                    name: RwLock::new(name)
                })
        })
    }
}

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
impl MuEntityHeader {
    pub fn unnamed(id: MuID) -> MuEntityHeader {
        MuEntityHeader {
            id: id,
            name: RwLock::new(None)
        }
    }
    
    pub fn named(id: MuID, name: MuName) -> MuEntityHeader {
        MuEntityHeader {
            id: id,
            name: RwLock::new(Some(name))
        }
    }
    
    pub fn id(&self) -> MuID {
        self.id
    }
    
    pub fn name(&self) -> Option<MuName> {
868
        self.name.read().unwrap().clone()
869 870 871 872 873 874 875 876 877 878 879 880
    }
}

impl PartialEq for MuEntityHeader {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl fmt::Display for MuEntityHeader {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.name().is_none() {
qinsoon's avatar
qinsoon committed
881
            write!(f, "UNNAMED #{}", self.id)
882 883 884 885 886 887
        } else {
            write!(f, "{} #{}", self.name().unwrap(), self.id)
        }
    }
}

qinsoon's avatar
qinsoon committed
888 889 890
pub trait MuEntity {
    fn id(&self) -> MuID;
    fn name(&self) -> Option<MuName>;
891
    fn set_name(&self, name: MuName);
qinsoon's avatar
qinsoon committed
892 893 894 895 896 897 898 899 900 901
    fn as_entity(&self) -> &MuEntity;
}

impl_mu_entity!(MuFunction);
impl_mu_entity!(MuFunctionVersion);
impl_mu_entity!(Block);
impl_mu_entity!(MuType);
impl_mu_entity!(Value);
impl_mu_entity!(MuFuncSig);

qinsoon's avatar
qinsoon committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
impl MuEntity for TreeNode {
    fn id(&self) -> MuID {
        match self.v {
            TreeNode_::Instruction(ref inst) => inst.id(),
            TreeNode_::Value(ref pv) => pv.id()
        }
    }

    fn name(&self) -> Option<MuName> {
        match self.v {
            TreeNode_::Instruction(ref inst) => inst.name(),
            TreeNode_::Value(ref pv) => pv.name()
        }
    }

    fn set_name(&self, name: MuName) {
        match self.v {
            TreeNode_::Instruction(ref inst) => inst.set_name(name),
            TreeNode_::Value(ref pv) => pv.set_name(name)
        }
    }

    fn as_entity(&self) -> &MuEntity {
        match self.v {
            TreeNode_::Instruction(ref inst) => inst.as_entity(),
            TreeNode_::Value(ref pv) => pv.as_entity()
        }
    }
}

932
pub fn op_vector_str(vec: &Vec<OpIndex>, ops: &Vec<P<TreeNode>>) -> String {
933 934 935 936 937 938
    let mut ret = String::new();
    for i in 0..vec.len() {
        let index = vec[i];
        ret.push_str(format!("{}", ops[index]).as_str());
        if i != vec.len() - 1 {
            ret.push_str(", ");
939
        }
940 941
    }
    ret
qinsoon's avatar
qinsoon committed
942
}