GitLab will be upgraded on 30 Jan 2023 from 2.00 pm (AEDT) to 3.00 pm (AEDT). During the update, GitLab and Mattermost services will not be available. If you have any concerns with this, please talk to us at N110 (b) CSIT building.

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

5
use std::collections::HashMap;
qinsoon's avatar
qinsoon committed
6
use std::fmt;
qinsoon's avatar
qinsoon committed
7
use std::cell::Cell;
8
use std::cell::RefCell;
qinsoon's avatar
qinsoon committed
9

qinsoon's avatar
qinsoon committed
10
11
12
13
14
pub type WPID  = usize;
pub type MuID  = usize;
pub type MuTag = &'static str;
pub type Address = usize; // TODO: replace this with Address(usize)

15
16
pub type OpIndex = usize;

17
#[derive(Debug)]
qinsoon's avatar
qinsoon committed
18
19
20
pub struct MuFunction {
    pub fn_name: MuTag,
    pub sig: P<MuFuncSig>,
21
    pub content: Option<FunctionContent>,
qinsoon's avatar
qinsoon committed
22
    pub context: FunctionContext
23
24
25
26
}

#[derive(Debug)]
pub struct FunctionContent {
qinsoon's avatar
qinsoon committed
27
28
    pub entry: MuTag,
    pub blocks: Vec<(MuTag, Block)>
qinsoon's avatar
qinsoon committed
29
30
}

qinsoon's avatar
qinsoon committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#[derive(Debug)]
pub struct FunctionContext {
    pub values: HashMap<MuID, ValueEntry>
}

impl FunctionContext {
    fn new() -> FunctionContext {
        FunctionContext {
            values: HashMap::new()
        }
    }
    
    pub fn get_value(&self, id: MuID) -> Option<&ValueEntry> {
        self.values.get(&id)
    }
46
47
48
49
    
    pub fn get_value_mut(&mut self, id: MuID) -> Option<&mut ValueEntry> {
        self.values.get_mut(&id)
    }
qinsoon's avatar
qinsoon committed
50
51
}

52
53
impl MuFunction {
    pub fn new(fn_name: MuTag, sig: P<MuFuncSig>) -> MuFunction {
qinsoon's avatar
qinsoon committed
54
        MuFunction{fn_name: fn_name, sig: sig, content: None, context: FunctionContext::new()}
55
56
57
58
59
60
61
    }
    
    pub fn define(&mut self, content: FunctionContent) {
        self.content = Some(content)
    }
    
    pub fn new_ssa(&mut self, id: MuID, tag: MuTag, ty: P<MuType>) -> P<TreeNode> {
62
        self.context.values.insert(id, ValueEntry{id: id, tag: tag, ty: ty.clone(), use_count: Cell::new(0), expr: None});
63
64
        
        P(TreeNode {
qinsoon's avatar
qinsoon committed
65
66
67
68
69
            v: TreeNode_::Value(P(Value{
                tag: tag,
                ty: ty,
                v: Value_::SSAVar(id)
            }))
70
71
72
        })
    }
    
qinsoon's avatar
qinsoon committed
73
    pub fn new_constant(&mut self, tag: MuTag, ty: P<MuType>, v: Constant) -> P<TreeNode> {
74
        P(TreeNode{
qinsoon's avatar
qinsoon committed
75
76
77
78
79
80
            v: TreeNode_::Value(P(Value{
                tag: tag,
                ty: ty, 
                v: Value_::Constant(v)
            }))
        })
81
82
83
84
    }
    
    pub fn new_value(&mut self, v: P<Value>) -> P<TreeNode> {
        P(TreeNode{
qinsoon's avatar
qinsoon committed
85
86
            v: TreeNode_::Value(v)
        })
87
88
89
    }    
}

90
#[derive(Debug)]
91
pub struct Block {
92
93
    pub label: MuTag,
    pub content: Option<BlockContent>
qinsoon's avatar
qinsoon committed
94
95
}

96
97
98
99
100
101
impl Block {
    pub fn new(label: MuTag) -> Block {
        Block{label: label, content: None}
    }
}

102
#[derive(Debug)]
103
pub struct BlockContent {
qinsoon's avatar
qinsoon committed
104
105
106
    pub args: Vec<P<TreeNode>>,
    pub body: Vec<P<TreeNode>>,
    pub keepalives: Option<Vec<P<TreeNode>>>    
107
108
}

qinsoon's avatar
qinsoon committed
109
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
110
111
/// always use with P<TreeNode>
pub struct TreeNode {
qinsoon's avatar
qinsoon committed
112
//    pub op: OpCode,
113
    pub v: TreeNode_
qinsoon's avatar
qinsoon committed
114
115
}

116
117
118
impl TreeNode {   
    pub fn new_inst(v: Instruction) -> P<TreeNode> {
        P(TreeNode{v: TreeNode_::Instruction(v)})
qinsoon's avatar
qinsoon committed
119
    }
120
121
122
123
124
125
126
127
128
129
130
131
    
    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
132
133
134
135
}

impl fmt::Debug for TreeNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136
137
138
        match self.v {
            TreeNode_::Value(ref pv) => {
                match pv.v {
139
140
                    Value_::SSAVar(id) => {
                        write!(f, "{:?} %{}#{}", pv.ty, pv.tag, id)
141
142
143
144
145
146
147
148
149
                    },
                    Value_::Constant(ref c) => {
                        write!(f, "{:?} {:?}", pv.ty, c) 
                    }
                }
            },
            TreeNode_::Instruction(ref inst) => {
                write!(f, "{:?}", inst)
            }
qinsoon's avatar
qinsoon committed
150
        }
qinsoon's avatar
qinsoon committed
151
    }
qinsoon's avatar
qinsoon committed
152
153
}

154
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
155
pub enum TreeNode_ {
qinsoon's avatar
qinsoon committed
156
    Value(P<Value>),
157
    Instruction(Instruction)
qinsoon's avatar
qinsoon committed
158
159
160
}

/// always use with P<Value>
161
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
162
pub struct Value {
163
    pub tag: MuTag,
qinsoon's avatar
qinsoon committed
164
165
    pub ty: P<MuType>,
    pub v: Value_
qinsoon's avatar
qinsoon committed
166
167
}

168
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
169
pub enum Value_ {
170
    SSAVar(MuID),
qinsoon's avatar
qinsoon committed
171
    Constant(Constant)
qinsoon's avatar
qinsoon committed
172
173
}

174
175
176
177
178
#[derive(Clone)]
pub struct ValueEntry {
    pub id: MuID,
    pub tag: MuTag,
    pub ty: P<MuType>,
179
180
181
182
183
184
185
186
    pub use_count: Cell<usize>,  // how many times this entry is used
    pub expr: Option<Instruction>
}

impl ValueEntry {
    pub fn assign_expr(&mut self, expr: Instruction) {
        self.expr = Some(expr)
    }
187
188
189
190
191
192
193
194
}

impl fmt::Debug for ValueEntry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} {}({})", self.ty, self.tag, self.id)
    }
}

195
#[derive(Clone)]
196
pub enum Constant {
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    Int(usize),
    Float(f32),
    Double(f64),
    IRef(Address),
    FuncRef(Address),
    UFuncRef(Address),
    Vector(Vec<Constant>),    
}

impl fmt::Debug for Constant {
    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),
            &Constant::IRef(v) => write!(f, "{}", v),
            &Constant::FuncRef(v) => write!(f, "{}", v),
            &Constant::UFuncRef(v) => write!(f, "{}", v),
            &Constant::Vector(ref v) => write!(f, "{:?}", v)
        }
    }
qinsoon's avatar
qinsoon committed
218
219
}

220
#[derive(Clone)]
221
222
223
224
pub struct Instruction {
    pub value : Option<Vec<P<TreeNode>>>,
    pub ops : RefCell<Vec<P<TreeNode>>>,
    pub v: Instruction_
qinsoon's avatar
qinsoon committed
225
226
}

qinsoon's avatar
qinsoon committed
227
228
impl fmt::Debug for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229
        write!(f, "{:?} (value: {:?}, ops: {:?})", self.v, self.value, self.ops.borrow())
230
231
232
    }
}

233
#[derive(Clone)]
234
235
236
237
238
239
240
pub enum Instruction_ {
    // non-terminal instruction
    
    // expressions
    
    BinOp(BinOp, OpIndex, OpIndex), 
    CmpOp(CmpOp, OpIndex, OpIndex),
qinsoon's avatar
qinsoon committed
241
242
243
244
245
246
247
248
249
    
    // yields a tuple of results from the call
    ExprCall{
        data: CallData,
        is_abort: bool, // T to abort, F to rethrow
    },
    
    // yields the memory value
    Load{
250
251
        is_ptr: bool,
        order: MemoryOrder,
252
        mem_loc: OpIndex
qinsoon's avatar
qinsoon committed
253
    },
qinsoon's avatar
qinsoon committed
254
    
qinsoon's avatar
qinsoon committed
255
256
    // yields nothing
    Store{
257
258
        is_ptr: bool,
        order: MemoryOrder,        
259
260
        mem_loc: OpIndex,
        value: OpIndex
qinsoon's avatar
qinsoon committed
261
262
263
    },
    
    // yields pair (oldvalue, boolean (T = success, F = failure))
qinsoon's avatar
qinsoon committed
264
    CmpXchg{
265
266
        is_ptr: bool,
        is_weak: bool,
qinsoon's avatar
qinsoon committed
267
268
        success_order: MemoryOrder,
        fail_order: MemoryOrder,
269
270
271
        mem_loc: OpIndex,
        expected_value: OpIndex,
        desired_value: OpIndex
qinsoon's avatar
qinsoon committed
272
273
    },
    
qinsoon's avatar
qinsoon committed
274
    // yields old memory value
qinsoon's avatar
qinsoon committed
275
    AtomicRMW{
276
        is_ptr: bool, // T for iref, F for ptr
qinsoon's avatar
qinsoon committed
277
278
        order: MemoryOrder,
        op: AtomicRMWOp,
279
280
        mem_loc: OpIndex,
        value: OpIndex // operand for op
qinsoon's avatar
qinsoon committed
281
282
    },
    
qinsoon's avatar
qinsoon committed
283
    // yields a reference of the type
qinsoon's avatar
qinsoon committed
284
    New(P<MuType>),
qinsoon's avatar
qinsoon committed
285
286
    
    // yields an iref of the type
qinsoon's avatar
qinsoon committed
287
    AllocA(P<MuType>),
qinsoon's avatar
qinsoon committed
288
289
    
    // yields ref
290
    NewHybrid(P<MuType>, OpIndex),
qinsoon's avatar
qinsoon committed
291
292
    
    // yields iref
293
    AllocAHybrid(P<MuType>, OpIndex),
qinsoon's avatar
qinsoon committed
294
295
    
    // yields stack ref
296
    NewStack(OpIndex), // func
297
                           // TODO: common inst
qinsoon's avatar
qinsoon committed
298
299
    
    // yields thread reference
300
    NewThread(OpIndex, Vec<OpIndex>), // stack, args
qinsoon's avatar
qinsoon committed
301
302
    
    // yields thread reference (thread resumes with exceptional value)
303
    NewThreadExn(OpIndex, OpIndex), // stack, exception
qinsoon's avatar
qinsoon committed
304
    
qinsoon's avatar
qinsoon committed
305
    // yields frame cursor
306
    NewFrameCursor(OpIndex), // stack
qinsoon's avatar
qinsoon committed
307
    
308
    // ref<T> -> iref<T>
309
    GetIRef(OpIndex),
qinsoon's avatar
qinsoon committed
310
    
311
    // iref|uptr<struct|hybrid<T>> int<M> -> iref|uptr<U>
qinsoon's avatar
qinsoon committed
312
    GetFieldIRef{
313
        is_ptr: bool,
314
315
        base: OpIndex, // iref or uptr
        index: OpIndex // constant
qinsoon's avatar
qinsoon committed
316
    },
qinsoon's avatar
qinsoon committed
317
    
318
    // iref|uptr<array<T N>> int<M> -> iref|uptr<T>
qinsoon's avatar
qinsoon committed
319
    GetElementIRef{
320
        is_ptr: bool,
321
322
        base: OpIndex,
        index: OpIndex // can be constant or ssa var
qinsoon's avatar
qinsoon committed
323
324
    },
    
325
    // iref|uptr<T> int<M> -> iref|uptr<T>
qinsoon's avatar
qinsoon committed
326
    ShiftIRef{
327
        is_ptr: bool,
328
329
        base: OpIndex,
        offset: OpIndex
qinsoon's avatar
qinsoon committed
330
331
    },
    
332
333
334
    // iref|uptr<hybrid<T U>> -> iref|uptr<U>
    GetVarPartIRef{
        is_ptr: bool,
335
        base: OpIndex
336
    },
qinsoon's avatar
qinsoon committed
337
338
339
340
341
342
343
344
    
//    PushFrame{
//        stack: P<Value>,
//        func: P<Value>
//    },
//    PopFrame{
//        stack: P<Value>
//    }
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

    Fence(MemoryOrder),
    
    // terminal instruction
    Return(Vec<OpIndex>),
    ThreadExit, // TODO:  common inst
    Throw(Vec<OpIndex>),
    TailCall(CallData),
    Branch1(Destination),
    Branch2{
        cond: OpIndex,
        true_dest: Destination,
        false_dest: Destination
    },
    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
    }, 
    WPBranch{
        wp: WPID, 
        disable_dest: Destination,
        enable_dest: Destination
    },
    Call{
        data: CallData,
        resume: ResumptionData
    },
    SwapStack{
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>,
        resume: ResumptionData
    },
    Switch{
        cond: OpIndex,
        default: Destination,
        branches: Vec<(OpIndex, Destination)>
    },
    ExnInstruction{
        inner: P<Instruction>,
        resume: ResumptionData
    }
qinsoon's avatar
qinsoon committed
392
393
}

394
395
396
397
398
399
400
401
402
403
macro_rules! select {
    ($cond: expr, $res1 : expr, $res2 : expr) => {
        if $cond {
            $res1
        } else {
            $res2
        }
    }
}

404
impl fmt::Debug for Instruction_ {
405
406
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
407
408
409
            &Instruction_::BinOp(op, ref op1, ref op2) => write!(f, "{:?} {:?} {:?}", op, op1, op2),
            &Instruction_::CmpOp(op, ref op1, ref op2) => write!(f, "{:?} {:?} {:?}", op, op1, op2),
            &Instruction_::ExprCall{ref data, is_abort} => {
410
411
412
                let abort = select!(is_abort, "ABORT_ON_EXN", "RETHROW");
                write!(f, "CALL {:?} {}", data, abort)
            },
413
            &Instruction_::Load{is_ptr, ref mem_loc, order} => {
414
415
416
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "LOAD {} {:?} {:?}", ptr, order, mem_loc) 
            },
417
            &Instruction_::Store{ref value, is_ptr, ref mem_loc, order} => {
418
419
420
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "STORE {} {:?} {:?} {:?}", ptr, order, mem_loc, value)
            },
421
            &Instruction_::CmpXchg{is_ptr, is_weak, success_order, fail_order, 
422
423
424
425
426
427
                ref mem_loc, ref expected_value, ref desired_value} => {
                let ptr = select!(is_ptr, "PTR", "");
                let weak = select!(is_weak, "WEAK", "");
                write!(f, "CMPXCHG {} {} {:?} {:?} {:?} {:?} {:?}", 
                    ptr, weak, success_order, fail_order, mem_loc, expected_value, desired_value)  
            },
428
            &Instruction_::AtomicRMW{is_ptr, order, op, ref mem_loc, ref value} => {
429
430
431
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "ATOMICRMW {} {:?} {:?} {:?} {:?}", ptr, order, op, mem_loc, value)
            },
432
433
434
435
436
437
438
439
440
441
            &Instruction_::New(ref ty) => write!(f, "NEW {:?}", ty),
            &Instruction_::AllocA(ref ty) => write!(f, "ALLOCA {:?}", ty),
            &Instruction_::NewHybrid(ref ty, ref len) => write!(f, "NEWHYBRID {:?} {:?}", ty, len),
            &Instruction_::AllocAHybrid(ref ty, ref len) => write!(f, "ALLOCAHYBRID {:?} {:?}", ty, len),
            &Instruction_::NewStack(ref func) => write!(f, "NEWSTACK {:?}", func),
            &Instruction_::NewThread(ref stack, ref args) => write!(f, "NEWTHREAD {:?} PASS_VALUES {:?}", stack, args),
            &Instruction_::NewThreadExn(ref stack, ref exn) => write!(f, "NEWTHREAD {:?} THROW_EXC {:?}", stack, exn),
            &Instruction_::NewFrameCursor(ref stack) => write!(f, "NEWFRAMECURSOR {:?}", stack),
            &Instruction_::GetIRef(ref reference) => write!(f, "GETIREF {:?}", reference),
            &Instruction_::GetFieldIRef{is_ptr, ref base, ref index} => {
442
443
444
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETFIELDIREF {} {:?} {:?}", ptr, base, index)
            },
445
            &Instruction_::GetElementIRef{is_ptr, ref base, ref index} => {
446
447
448
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETELEMENTIREF {} {:?} {:?}", ptr, base, index)
            },
449
            &Instruction_::ShiftIRef{is_ptr, ref base, ref offset} => {
450
451
452
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "SHIFTIREF {} {:?} {:?}", ptr, base, offset)
            },
453
            &Instruction_::GetVarPartIRef{is_ptr, ref base} => {
454
455
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETVARPARTIREF {} {:?}", ptr, base)
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
            },
            
            &Instruction_::Fence(order) => {
                write!(f, "FENCE {:?}", order)
            }            
            
            &Instruction_::Return(ref vals) => write!(f, "RET {:?}", vals),
            &Instruction_::ThreadExit => write!(f, "THREADEXIT"),
            &Instruction_::Throw(ref vals) => write!(f, "THROW {:?}", vals),
            &Instruction_::TailCall(ref call) => write!(f, "TAILCALL {:?}", call),
            &Instruction_::Branch1(ref dest) => write!(f, "BRANCH {:?}", dest),
            &Instruction_::Branch2{ref cond, ref true_dest, ref false_dest} => {
                write!(f, "BRANCH2 {:?} {:?} {:?}", cond, true_dest, false_dest)
            },
            &Instruction_::Watchpoint{id, ref disable_dest, ref resume} => {
                match id {
                    Some(id) => {
                        write!(f, "WATCHPOINT {:?} {:?} {:?}", id, disable_dest.as_ref().unwrap(), resume)
                    },
                    None => {
                        write!(f, "TRAP {:?}", resume)
                    }
                }
            },
            &Instruction_::WPBranch{wp, ref disable_dest, ref enable_dest} => {
                write!(f, "WPBRANCH {:?} {:?} {:?}", wp, disable_dest, enable_dest)
            },
            &Instruction_::Call{ref data, ref resume} => write!(f, "CALL {:?} {:?}", data, resume),
            &Instruction_::SwapStack{ref stack, is_exception, ref args, ref resume} => {
                write!(f, "SWAPSTACK {:?} {:?} {:?} {:?}", stack, is_exception, args, resume)
            },
            &Instruction_::Switch{ref cond, ref default, ref branches} => {
                write!(f, "SWITCH {:?} {:?} {{{:?}}}", cond, default, branches)
            },
            &Instruction_::ExnInstruction{ref inner, ref resume} => {
                write!(f, "{:?} {:?}", inner, resume)
492
493
            }
        }
494
    }    
495
496
}

qinsoon's avatar
qinsoon committed
497
498
499
500
501
502
503
504
505
#[derive(Copy, Clone, Debug)]
pub enum MemoryOrder {
    NotAtomic,
    Relaxed,
    Consume,
    Acquire,
    Release,
    AcqRel,
    SeqCst
506
507
}

qinsoon's avatar
qinsoon committed
508
509
510
511
#[derive(Copy, Clone, Debug)]
pub enum CallConvention {
    Mu,
    Foreign(ForeignFFI)
qinsoon's avatar
qinsoon committed
512
513
}

qinsoon's avatar
qinsoon committed
514
515
516
#[derive(Copy, Clone, Debug)]
pub enum ForeignFFI {
    C
qinsoon's avatar
qinsoon committed
517
518
}

519
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
520
pub struct CallData {
521
522
    pub func: OpIndex,
    pub args: Vec<OpIndex>,
qinsoon's avatar
qinsoon committed
523
    pub convention: CallConvention
524
525
}

526
527
528
529
530
531
532
impl fmt::Debug for CallData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} {:?} ({:?})", self.convention, self.func, self.args)
    }    
}

#[derive(Clone)]
qinsoon's avatar
qinsoon committed
533
534
535
pub struct ResumptionData {
    pub normal_dest: Destination,
    pub exn_dest: Destination
536
537
}

538
539
540
541
impl fmt::Debug for ResumptionData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "normal: {:?}, exception: {:?}", self.normal_dest, self.exn_dest)
    }
542
543
}

544
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
545
546
547
pub struct Destination {
    pub target: MuTag,
    pub args: Vec<DestArg>
548
549
550
551
552
553
554
555
556
557
}

impl fmt::Debug for Destination {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{:?}", self.target, self.args)
    }
}

#[derive(Clone)]
pub enum DestArg {
558
    Normal(OpIndex),
559
560
561
562
563
564
565
566
567
568
    Freshbound(usize)
}

impl fmt::Debug for DestArg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &DestArg::Normal(ref pv) => write!(f, "{:?}", pv),
            &DestArg::Freshbound(n) => write!(f, "${}", n)
        }
    }    
569
}