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

6
use utils::vec_utils;
7 8

use std::fmt;
qinsoon's avatar
qinsoon committed
9
use std::sync::RwLock;
10

qinsoon's avatar
qinsoon committed
11
#[derive(Debug)]
qinsoon's avatar
qinsoon committed
12
// this implements RustcEncodable, RustcDecodable, Clone and Display
13
pub struct Instruction {
qinsoon's avatar
qinsoon committed
14
    pub hdr: MuEntityHeader,
qinsoon's avatar
qinsoon committed
15
    pub value : Option<Vec<P<Value>>>,
qinsoon's avatar
qinsoon committed
16
    pub ops : RwLock<Vec<P<TreeNode>>>,
17 18 19
    pub v: Instruction_
}

qinsoon's avatar
qinsoon committed
20 21
impl_mu_entity!(Instruction);

qinsoon's avatar
qinsoon committed
22 23 24
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
impl Encodable for Instruction {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
qinsoon's avatar
qinsoon committed
25 26 27
        s.emit_struct("Instruction", 4, |s| {
            try!(s.emit_struct_field("hdr", 0, |s| self.hdr.encode(s)));
            try!(s.emit_struct_field("value", 1, |s| self.value.encode(s)));
qinsoon's avatar
qinsoon committed
28 29
            
            let ops = &self.ops.read().unwrap();
qinsoon's avatar
qinsoon committed
30
            try!(s.emit_struct_field("ops", 2, |s| ops.encode(s)));
qinsoon's avatar
qinsoon committed
31
            
qinsoon's avatar
qinsoon committed
32
            try!(s.emit_struct_field("v", 3, |s| self.v.encode(s)));
qinsoon's avatar
qinsoon committed
33 34 35 36 37 38 39 40
            
            Ok(()) 
        })        
    }
}

impl Decodable for Instruction {
    fn decode<D: Decoder>(d: &mut D) -> Result<Instruction, D::Error> {
qinsoon's avatar
qinsoon committed
41 42 43
        d.read_struct("Instruction", 4, |d| {
            let hdr = try!(d.read_struct_field("hdr", 0, |d| Decodable::decode(d)));
            let value = try!(d.read_struct_field("value", 1, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
44
            
qinsoon's avatar
qinsoon committed
45
            let ops = try!(d.read_struct_field("ops", 2, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
46
            
qinsoon's avatar
qinsoon committed
47
            let v = try!(d.read_struct_field("v", 3, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
48 49
            
            Ok(Instruction{
qinsoon's avatar
qinsoon committed
50
                hdr: hdr,
qinsoon's avatar
qinsoon committed
51 52 53 54 55 56 57 58 59 60 61
                value: value,
                ops: RwLock::new(ops),
                v: v
            })
        })
    }
}

impl Clone for Instruction {
    fn clone(&self) -> Self {
        Instruction {
qinsoon's avatar
qinsoon committed
62
            hdr: self.hdr.clone(),
qinsoon's avatar
qinsoon committed
63 64 65 66 67 68 69
            value: self.value.clone(),
            ops: RwLock::new(self.ops.read().unwrap().clone()),
            v: self.v.clone()
        }
    }
}

70 71 72 73 74 75 76 77
impl Instruction {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        self.v.debug_str(ops)
    }
}

impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
78
        let ops = &self.ops.read().unwrap();
79
        if self.value.is_some() {
qinsoon's avatar
qinsoon committed
80
            write!(f, "{} = {}", vec_utils::as_str(self.value.as_ref().unwrap()), self.v.debug_str(ops))
81 82 83 84 85 86
        } else {
            write!(f, "{}", self.v.debug_str(ops))
        }
    }
}

qinsoon's avatar
qinsoon committed
87
#[allow(non_camel_case_types)]
qinsoon's avatar
qinsoon committed
88
#[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
89 90
pub enum Instruction_ {
    // non-terminal instruction
91

92
    // expressions
93 94

    BinOp(BinOp, OpIndex, OpIndex),
95
    CmpOp(CmpOp, OpIndex, OpIndex),
96 97 98 99 100 101
    ConvOp{
        operation: ConvOp,
        from_ty: P<MuType>,
        to_ty: P<MuType>,
        operand: OpIndex
    },
102

103 104 105
    // yields a tuple of results from the call
    ExprCall{
        data: CallData,
qinsoon's avatar
qinsoon committed
106
        is_abort: bool, // T to abort, F to rethrow - FIXME: current, always rethrow for now
107
    },
108

qinsoon's avatar
qinsoon committed
109 110 111 112 113
    ExprCCall{
        data: CallData,
        is_abort: bool
    },

114 115 116 117 118 119
    // yields the memory value
    Load{
        is_ptr: bool,
        order: MemoryOrder,
        mem_loc: OpIndex
    },
120

121 122 123
    // yields nothing
    Store{
        is_ptr: bool,
124
        order: MemoryOrder,
125 126 127
        mem_loc: OpIndex,
        value: OpIndex
    },
128

129 130 131 132 133 134 135 136 137 138
    // yields pair (oldvalue, boolean (T = success, F = failure))
    CmpXchg{
        is_ptr: bool,
        is_weak: bool,
        success_order: MemoryOrder,
        fail_order: MemoryOrder,
        mem_loc: OpIndex,
        expected_value: OpIndex,
        desired_value: OpIndex
    },
139

140 141 142 143 144 145 146 147
    // yields old memory value
    AtomicRMW{
        is_ptr: bool, // T for iref, F for ptr
        order: MemoryOrder,
        op: AtomicRMWOp,
        mem_loc: OpIndex,
        value: OpIndex // operand for op
    },
148

149 150
    // yields a reference of the type
    New(P<MuType>),
151

152 153
    // yields an iref of the type
    AllocA(P<MuType>),
154

155 156
    // yields ref
    NewHybrid(P<MuType>, OpIndex),
157

158 159
    // yields iref
    AllocAHybrid(P<MuType>, OpIndex),
160

161 162 163
    // yields stack ref
    NewStack(OpIndex), // func
                           // TODO: common inst
164

165 166
    // yields thread reference
    NewThread(OpIndex, Vec<OpIndex>), // stack, args
167

168 169
    // yields thread reference (thread resumes with exceptional value)
    NewThreadExn(OpIndex, OpIndex), // stack, exception
170

171 172
    // yields frame cursor
    NewFrameCursor(OpIndex), // stack
173

174 175
    // ref<T> -> iref<T>
    GetIRef(OpIndex),
176

177 178 179 180
    // iref|uptr<struct|hybrid<T>> int<M> -> iref|uptr<U>
    GetFieldIRef{
        is_ptr: bool,
        base: OpIndex, // iref or uptr
181
        index: usize // constant
182
    },
183

184 185 186 187 188 189
    // iref|uptr<array<T N>> int<M> -> iref|uptr<T>
    GetElementIRef{
        is_ptr: bool,
        base: OpIndex,
        index: OpIndex // can be constant or ssa var
    },
190

191 192 193 194 195 196
    // iref|uptr<T> int<M> -> iref|uptr<T>
    ShiftIRef{
        is_ptr: bool,
        base: OpIndex,
        offset: OpIndex
    },
197

198 199 200 201 202
    // iref|uptr<hybrid<T U>> -> iref|uptr<U>
    GetVarPartIRef{
        is_ptr: bool,
        base: OpIndex
    },
203

204 205 206 207 208 209 210 211 212
//    PushFrame{
//        stack: P<Value>,
//        func: P<Value>
//    },
//    PopFrame{
//        stack: P<Value>
//    }

    Fence(MemoryOrder),
213

214 215 216
    // terminal instruction
    Return(Vec<OpIndex>),
    ThreadExit, // TODO:  common inst
217
    Throw(OpIndex),
218 219 220 221 222 223 224 225
    TailCall(CallData),
    Branch1(Destination),
    Branch2{
        cond: OpIndex,
        true_dest: Destination,
        false_dest: Destination,
        true_prob: f32
    },
qinsoon's avatar
qinsoon committed
226 227 228 229 230
    Select{
        cond: OpIndex,
        true_val: OpIndex,
        false_val: OpIndex
    },
231 232 233 234 235 236 237 238
    Watchpoint{ // Watchpoint NONE ResumptionData
                //   serves as an unconditional trap. Trap to client, and resume with ResumptionData
                // Watchpoint (WPID dest) ResumptionData
                //   when disabled, jump to dest
                //   when enabled, trap to client and resume
        id: Option<WPID>,
        disable_dest: Option<Destination>,
        resume: ResumptionData
239
    },
240
    WPBranch{
241
        wp: WPID,
242 243 244 245 246 247 248
        disable_dest: Destination,
        enable_dest: Destination
    },
    Call{
        data: CallData,
        resume: ResumptionData
    },
qinsoon's avatar
qinsoon committed
249 250 251 252
    CCall{
        data: CallData,
        resume: ResumptionData
    },
253 254 255 256 257 258 259 260 261 262 263 264
    SwapStack{
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>,
        resume: ResumptionData
    },
    Switch{
        cond: OpIndex,
        default: Destination,
        branches: Vec<(OpIndex, Destination)>
    },
    ExnInstruction{
qinsoon's avatar
qinsoon committed
265
        inner: Box<Instruction>,
266
        resume: ResumptionData
267 268 269 270
    },

    // common inst
    CommonInst_GetThreadLocal,
271 272 273 274
    CommonInst_SetThreadLocal(OpIndex),

    // internal use: mov from ops[0] to value
    Move(OpIndex)
275 276 277 278 279 280 281
}

impl Instruction_ {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        match self {
            &Instruction_::BinOp(op, op1, op2) => format!("{:?} {} {}", op, ops[op1], ops[op2]),
            &Instruction_::CmpOp(op, op1, op2) => format!("{:?} {} {}", op, ops[op1], ops[op2]),
qinsoon's avatar
qinsoon committed
282 283 284
            &Instruction_::ConvOp{operation, ref from_ty, ref to_ty, operand} => {
                format!("{:?} {} {} {}", operation, from_ty, to_ty, ops[operand])
            }
285 286 287 288
            &Instruction_::ExprCall{ref data, is_abort} => {
                let abort = select_value!(is_abort, "ABORT_ON_EXN", "RETHROW");
                format!("CALL {} {}", data.debug_str(ops), abort)
            },
qinsoon's avatar
qinsoon committed
289 290 291 292
            &Instruction_::ExprCCall{ref data, is_abort} => {
                let abort = select_value!(is_abort, "ABORT_ON_EXN", "RETHROW");
                format!("CCALL {} {}", data.debug_str(ops), abort)
            }
293 294
            &Instruction_::Load{is_ptr, mem_loc, order} => {
                let ptr = select_value!(is_ptr, "PTR", "");
295
                format!("LOAD {} {:?} {}", ptr, order, ops[mem_loc])
296 297 298 299 300
            },
            &Instruction_::Store{value, is_ptr, mem_loc, order} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                format!("STORE {} {:?} {} {}", ptr, order, ops[mem_loc], ops[value])
            },
301
            &Instruction_::CmpXchg{is_ptr, is_weak, success_order, fail_order,
302 303 304
                mem_loc, expected_value, desired_value} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                let weak = select_value!(is_weak, "WEAK", "");
305 306
                format!("CMPXCHG {} {} {:?} {:?} {} {} {}",
                    ptr, weak, success_order, fail_order, ops[mem_loc], ops[expected_value], ops[desired_value])
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
            },
            &Instruction_::AtomicRMW{is_ptr, order, op, mem_loc, value} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                format!("ATOMICRMW {} {:?} {:?} {} {}", ptr, order, op, ops[mem_loc], ops[value])
            },
            &Instruction_::New(ref ty) => format!("NEW {}", ty),
            &Instruction_::AllocA(ref ty) => format!("ALLOCA {}", ty),
            &Instruction_::NewHybrid(ref ty, len) => format!("NEWHYBRID {} {}", ty, ops[len]),
            &Instruction_::AllocAHybrid(ref ty, len) => format!("ALLOCAHYBRID {} {}", ty, ops[len]),
            &Instruction_::NewStack(func) => format!("NEWSTACK {}", ops[func]),
            &Instruction_::NewThread(stack, ref args) => format!("NEWTHREAD {} PASS_VALUES {}", ops[stack], op_vector_str(args, ops)),
            &Instruction_::NewThreadExn(stack, exn) => format!("NEWTHREAD {} THROW_EXC {}", ops[stack], ops[exn]),
            &Instruction_::NewFrameCursor(stack) => format!("NEWFRAMECURSOR {}", ops[stack]),
            &Instruction_::GetIRef(reference) => format!("GETIREF {}", ops[reference]),
            &Instruction_::GetFieldIRef{is_ptr, base, index} => {
                let ptr = select_value!(is_ptr, "PTR", "");
323
                format!("GETFIELDIREF {} {} {}", ptr, ops[base], index)
324 325 326 327 328 329 330 331 332 333 334 335 336
            },
            &Instruction_::GetElementIRef{is_ptr, base, index} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                format!("GETELEMENTIREF {} {} {}", ptr, ops[base], ops[index])
            },
            &Instruction_::ShiftIRef{is_ptr, base, offset} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                format!("SHIFTIREF {} {} {}", ptr, ops[base], ops[offset])
            },
            &Instruction_::GetVarPartIRef{is_ptr, base} => {
                let ptr = select_value!(is_ptr, "PTR", "");
                format!("GETVARPARTIREF {} {}", ptr, ops[base])
            },
337

338 339 340
            &Instruction_::Fence(order) => {
                format!("FENCE {:?}", order)
            },
341

342 343
            &Instruction_::Return(ref vals) => format!("RET {}", op_vector_str(vals, ops)),
            &Instruction_::ThreadExit => "THREADEXIT".to_string(),
344
            &Instruction_::Throw(exn_obj) => format!("THROW {}", ops[exn_obj]),
345 346 347 348 349
            &Instruction_::TailCall(ref call) => format!("TAILCALL {}", call.debug_str(ops)),
            &Instruction_::Branch1(ref dest) => format!("BRANCH {}", dest.debug_str(ops)),
            &Instruction_::Branch2{cond, ref true_dest, ref false_dest, ..} => {
                format!("BRANCH2 {} {} {}", ops[cond], true_dest.debug_str(ops), false_dest.debug_str(ops))
            },
qinsoon's avatar
qinsoon committed
350 351 352
            &Instruction_::Select{cond, true_val, false_val} => {
                format!("SELECT if {} then {} else {}", ops[cond], ops[true_val], ops[false_val])
            }
353 354 355 356 357 358 359 360 361 362 363 364 365 366
            &Instruction_::Watchpoint{id, ref disable_dest, ref resume} => {
                match id {
                    Some(id) => {
                        format!("WATCHPOINT {} {} {}", id, disable_dest.as_ref().unwrap().debug_str(ops), resume.debug_str(ops))
                    },
                    None => {
                        format!("TRAP {}", resume.debug_str(ops))
                    }
                }
            },
            &Instruction_::WPBranch{wp, ref disable_dest, ref enable_dest} => {
                format!("WPBRANCH {} {} {}", wp, disable_dest.debug_str(ops), enable_dest.debug_str(ops))
            },
            &Instruction_::Call{ref data, ref resume} => format!("CALL {} {}", data.debug_str(ops), resume.debug_str(ops)),
qinsoon's avatar
qinsoon committed
367
            &Instruction_::CCall{ref data, ref resume} => format!("CCALL {} {}", data.debug_str(ops), resume.debug_str(ops)),
368 369 370 371 372 373 374 375 376 377 378 379 380
            &Instruction_::SwapStack{stack, is_exception, ref args, ref resume} => {
                format!("SWAPSTACK {} {} {} {}", ops[stack], is_exception, op_vector_str(args, ops), resume.debug_str(ops))
            },
            &Instruction_::Switch{cond, ref default, ref branches} => {
                let mut ret = format!("SWITCH {} {} {{", ops[cond], default.debug_str(ops));
                for i in 0..branches.len() {
                    let (op, ref dest) = branches[i];
                    ret.push_str(format!("{} {}", ops[op], dest.debug_str(ops)).as_str());
                    if i != branches.len() - 1 {
                        ret.push_str(", ");
                    }
                }
                ret.push_str("}}");
381

382 383 384 385
                ret
            },
            &Instruction_::ExnInstruction{ref inner, ref resume} => {
                format!("{} {}", inner.debug_str(ops), resume.debug_str(ops))
386
            },
387 388

            // common inst
389
            &Instruction_::CommonInst_GetThreadLocal => format!("COMMONINST GetThreadLocal"),
390 391 392 393
            &Instruction_::CommonInst_SetThreadLocal(op) => format!("COMMONINST SetThreadLocal {}", ops[op]),

            // move
            &Instruction_::Move(from) => format!("MOVE {}", ops[from])
394
        }
395
    }
396 397
}

qinsoon's avatar
qinsoon committed
398
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
399 400 401 402 403 404 405 406 407 408
pub enum MemoryOrder {
    NotAtomic,
    Relaxed,
    Consume,
    Acquire,
    Release,
    AcqRel,
    SeqCst
}

qinsoon's avatar
qinsoon committed
409
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
410 411 412 413 414
pub enum CallConvention {
    Mu,
    Foreign(ForeignFFI)
}

qinsoon's avatar
qinsoon committed
415
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
416 417 418 419
pub enum ForeignFFI {
    C
}

qinsoon's avatar
qinsoon committed
420
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
421 422 423 424 425 426 427 428 429 430 431 432
pub struct CallData {
    pub func: OpIndex,
    pub args: Vec<OpIndex>,
    pub convention: CallConvention
}

impl CallData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        format!("{:?} {} [{}]", self.convention, ops[self.func], op_vector_str(&self.args, ops))
    }
}

qinsoon's avatar
qinsoon committed
433
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
434 435 436 437 438 439 440 441 442 443 444
pub struct ResumptionData {
    pub normal_dest: Destination,
    pub exn_dest: Destination
}

impl ResumptionData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        format!("normal: {}, exception: {}", self.normal_dest.debug_str(ops), self.exn_dest.debug_str(ops))
    }
}

qinsoon's avatar
qinsoon committed
445
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
446
pub struct Destination {
qinsoon's avatar
qinsoon committed
447
    pub target: MuID,
448 449 450 451 452
    pub args: Vec<DestArg>
}

impl Destination {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
qinsoon's avatar
qinsoon committed
453
        let mut ret = format!("{} with ", self.target);
454 455 456 457 458 459 460 461 462
        ret.push('[');
        for i in 0..self.args.len() {
            let ref arg = self.args[i];
            ret.push_str(arg.debug_str(ops).as_str());
            if i != self.args.len() - 1 {
                ret.push_str(", ");
            }
        }
        ret.push(']');
463

464 465
        ret
    }
466 467 468 469 470 471 472 473 474 475
    
    pub fn get_arguments(&self, ops: &Vec<P<TreeNode>>) -> Vec<P<Value>> {
        vec_utils::map(&self.args, 
            |x| {
                match x {
                    &DestArg::Normal(i) => ops[i].clone_value(),
                    &DestArg::Freshbound(_) => unimplemented!()
                }
        })
    }
476 477
}

qinsoon's avatar
qinsoon committed
478
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
479 480 481 482 483 484 485 486 487
pub enum DestArg {
    Normal(OpIndex),
    Freshbound(usize)
}

impl DestArg {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        match self {
            &DestArg::Normal(index) => format!("{}", ops[index]),
488
            &DestArg::Freshbound(n) => format!("${}", n)
489 490
        }
    }
491
}