vm.rs 30.5 KB
Newer Older
qinsoon's avatar
qinsoon committed
1
2
3
4
use std::collections::HashMap;

use ast::ptr::P;
use ast::ir::*;
qinsoon's avatar
qinsoon committed
5
use ast::types;
qinsoon's avatar
qinsoon committed
6
use ast::types::*;
qinsoon's avatar
qinsoon committed
7
8
use compiler::backend;
use compiler::backend::BackendTypeInfo;
qinsoon's avatar
qinsoon committed
9
use compiler::machine_code::CompiledFunction;
10
11
use runtime::thread::*;
use runtime::ValueLocation;
qinsoon's avatar
qinsoon committed
12
use utils::ByteSize;
13
use utils::BitSize;
14
use runtime::mm as gc;
15
use vm::handle::*;
qinsoon's avatar
qinsoon committed
16
17
use vm::vm_options::VMOptions;
use vm::vm_options::MuLogLevel;
18

qinsoon's avatar
qinsoon committed
19
20
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use log::LogLevel;
qinsoon's avatar
qinsoon committed
21
use std::path;
qinsoon's avatar
qinsoon committed
22
use std::sync::RwLock;
23
use std::sync::Arc;
24
use std::sync::atomic::{AtomicUsize, AtomicBool, ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT, Ordering};
25

qinsoon's avatar
qinsoon committed
26
27
28
29
30
// FIXME:
// besides fields in VM, there are some 'globals' we need to persist
// such as STRUCT_TAG_MAP
// possibly INTERNAL_ID in ir.rs, internal types, etc

qinsoon's avatar
qinsoon committed
31
pub struct VM {
32
    // serialize
qinsoon's avatar
qinsoon committed
33
    // 0
34
    next_id: AtomicUsize,
qinsoon's avatar
qinsoon committed
35
    // 1
qinsoon's avatar
qinsoon committed
36
    id_name_map: RwLock<HashMap<MuID, MuName>>,
qinsoon's avatar
qinsoon committed
37
    // 2
qinsoon's avatar
qinsoon committed
38
    name_id_map: RwLock<HashMap<MuName, MuID>>,
qinsoon's avatar
qinsoon committed
39
    // 3
qinsoon's avatar
qinsoon committed
40
    types: RwLock<HashMap<MuID, P<MuType>>>,
qinsoon's avatar
qinsoon committed
41
42
    // 4
    backend_type_info: RwLock<HashMap<MuID, Box<BackendTypeInfo>>>,
43
    // 5
qinsoon's avatar
qinsoon committed
44
    constants: RwLock<HashMap<MuID, P<Value>>>,
qinsoon's avatar
qinsoon committed
45
    // 6
qinsoon's avatar
qinsoon committed
46
    globals: RwLock<HashMap<MuID, P<Value>>>,
47
    pub global_locations: RwLock<HashMap<MuID, ValueLocation>>,
qinsoon's avatar
qinsoon committed
48
    // 7
qinsoon's avatar
qinsoon committed
49
    func_sigs: RwLock<HashMap<MuID, P<MuFuncSig>>>,
qinsoon's avatar
qinsoon committed
50
    // 8
qinsoon's avatar
qinsoon committed
51
    funcs: RwLock<HashMap<MuID, RwLock<MuFunction>>>,
qinsoon's avatar
qinsoon committed
52
53
    // 9
    func_vers: RwLock<HashMap<MuID, RwLock<MuFunctionVersion>>>,
54
55
    // 10
    pub primordial: RwLock<Option<MuPrimordialThread>>,
qinsoon's avatar
qinsoon committed
56
57
    // 11
    is_running: AtomicBool,
qinsoon's avatar
qinsoon committed
58
59
    // 12
    pub vm_options: VMOptions,
qinsoon's avatar
qinsoon committed
60
    
61
    // partially serialize
qinsoon's avatar
qinsoon committed
62
    // 13
qinsoon's avatar
qinsoon committed
63
    compiled_funcs: RwLock<HashMap<MuID, RwLock<CompiledFunction>>>,
64
65
66

    // not serialize
    active_handles: RwLock<HashMap<MuID, Arc<APIHandle>>>
67
68
}

qinsoon's avatar
qinsoon committed
69
const VM_SERIALIZE_FIELDS : usize = 14;
qinsoon's avatar
qinsoon committed
70

71
72
impl Encodable for VM {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
73
74
        let mut field_i = 0;

qinsoon's avatar
qinsoon committed
75
76
        // serialize VM_SERIALIZE_FIELDS fields
        // PLUS ONE extra global STRUCT_TAG_MAP
77
        s.emit_struct("VM", VM_SERIALIZE_FIELDS + 2, |s| {
78
            // next_id
qinsoon's avatar
qinsoon committed
79
            trace!("...serializing next_id");
80
            try!(s.emit_struct_field("next_id", field_i, |s| {
81
82
                s.emit_usize(self.next_id.load(Ordering::SeqCst))
            }));
83
            field_i += 1;
84
85
                
            // id_name_map
qinsoon's avatar
qinsoon committed
86
            trace!("...serializing id_name_map");
87
88
            {
                let map : &HashMap<MuID, MuName> = &self.id_name_map.read().unwrap();            
89
                try!(s.emit_struct_field("id_name_map", field_i, |s| map.encode(s)));
90
            }
91
            field_i += 1;
92
93
            
            // name_id_map
qinsoon's avatar
qinsoon committed
94
            trace!("...serializing name_id_map");
95
96
            {
                let map : &HashMap<MuName, MuID> = &self.name_id_map.read().unwrap(); 
97
                try!(s.emit_struct_field("name_id_map", field_i, |s| map.encode(s)));
98
            }
99
            field_i += 1;
100
101
            
            // types
qinsoon's avatar
qinsoon committed
102
            trace!("...serializing types");
103
104
            {
                let types = &self.types.read().unwrap();
105
                try!(s.emit_struct_field("types", field_i, |s| types.encode(s)));
qinsoon's avatar
qinsoon committed
106
            }
107
108
            field_i += 1;

qinsoon's avatar
qinsoon committed
109
            // STRUCT_TAG_MAP
qinsoon's avatar
qinsoon committed
110
            trace!("...serializing struct_tag_map");
qinsoon's avatar
qinsoon committed
111
112
            {
                let struct_tag_map = types::STRUCT_TAG_MAP.read().unwrap();
113
114
115
116
117
118
119
120
121
                try!(s.emit_struct_field("struct_tag_map", field_i, |s| struct_tag_map.encode(s)));
            }
            field_i += 1;

            // HYBRID_TAG_MAP
            trace!("...serializing hybrid_tag_map");
            {
                let hybrid_tag_map = types::HYBRID_TAG_MAP.read().unwrap();
                try!(s.emit_struct_field("hybrid_tag_map", field_i, |s| hybrid_tag_map.encode(s)));
qinsoon's avatar
qinsoon committed
122
            }
123
            field_i += 1;
qinsoon's avatar
qinsoon committed
124
125
            
            // backend_type_info
qinsoon's avatar
qinsoon committed
126
            trace!("...serializing backend_type_info");
qinsoon's avatar
qinsoon committed
127
128
            {
                let backend_type_info : &HashMap<_, _> = &self.backend_type_info.read().unwrap();
129
                try!(s.emit_struct_field("backend_type_info", field_i, |s| backend_type_info.encode(s)));
qinsoon's avatar
qinsoon committed
130
            }
131
            field_i += 1;
qinsoon's avatar
qinsoon committed
132
133
            
            // constants
qinsoon's avatar
qinsoon committed
134
            trace!("...serializing constants");
qinsoon's avatar
qinsoon committed
135
136
            {
                let constants : &HashMap<_, _> = &self.constants.read().unwrap();
137
                try!(s.emit_struct_field("constants", field_i, |s| constants.encode(s)));
qinsoon's avatar
qinsoon committed
138
            }
139
            field_i += 1;
qinsoon's avatar
qinsoon committed
140
141
            
            // globals
qinsoon's avatar
qinsoon committed
142
            trace!("...serializing globals");
qinsoon's avatar
qinsoon committed
143
144
            {
                let globals: &HashMap<_, _> = &self.globals.read().unwrap();
145
                try!(s.emit_struct_field("globals", field_i, |s| globals.encode(s)));
qinsoon's avatar
qinsoon committed
146
            }
147
            field_i += 1;
qinsoon's avatar
qinsoon committed
148
149
            
            // func sigs
qinsoon's avatar
qinsoon committed
150
            trace!("...serializing func_sigs");
qinsoon's avatar
qinsoon committed
151
152
            {
                let func_sigs: &HashMap<_, _> = &self.func_sigs.read().unwrap();
153
                try!(s.emit_struct_field("func_sigs", field_i, |s| func_sigs.encode(s)));
qinsoon's avatar
qinsoon committed
154
            }
155
            field_i += 1;
qinsoon's avatar
qinsoon committed
156
157
            
            // funcs
qinsoon's avatar
qinsoon committed
158
            trace!("...serializing funcs");
qinsoon's avatar
qinsoon committed
159
160
            {
                let funcs : &HashMap<_, _> = &self.funcs.read().unwrap();
161
                try!(s.emit_struct_field("funcs", field_i, |s| {
qinsoon's avatar
qinsoon committed
162
163
164
165
166
167
168
169
170
171
172
173
                    s.emit_map(funcs.len(), |s| {
                        let mut i = 0;
                        for (k,v) in funcs.iter() {
                            s.emit_map_elt_key(i, |s| k.encode(s)).ok();
                            let func : &MuFunction = &v.read().unwrap();
                            s.emit_map_elt_val(i, |s| func.encode(s)).ok();
                            i += 1;
                        }
                        Ok(())
                    })
                }));
            }
174
            field_i += 1;
qinsoon's avatar
qinsoon committed
175
176
            
            // func_vers
qinsoon's avatar
qinsoon committed
177
            trace!("...serializing func_vers");
qinsoon's avatar
qinsoon committed
178
179
            {
                let func_vers : &HashMap<_, _> = &self.func_vers.read().unwrap();
180
                try!(s.emit_struct_field("func_vers", field_i, |s| {
qinsoon's avatar
qinsoon committed
181
182
183
184
185
186
187
188
189
190
191
192
                    s.emit_map(func_vers.len(), |s| {
                        let mut i = 0;
                        for (k, v) in func_vers.iter() {
                            try!(s.emit_map_elt_key(i, |s| k.encode(s)));
                            let func_ver : &MuFunctionVersion = &v.read().unwrap();
                            try!(s.emit_map_elt_val(i, |s| func_ver.encode(s)));
                            i += 1;
                        }
                        Ok(())
                    })
                }));
            }
193
194
            field_i += 1;

qinsoon's avatar
qinsoon committed
195
            // primordial
qinsoon's avatar
qinsoon committed
196
            trace!("...serializing primordial");
qinsoon's avatar
qinsoon committed
197
198
            {
                let primordial = &self.primordial.read().unwrap();
199
                try!(s.emit_struct_field("primordial", field_i, |s| primordial.encode(s)));
qinsoon's avatar
qinsoon committed
200
            }
201
            field_i += 1;
qinsoon's avatar
qinsoon committed
202
203
            
            // is_running
qinsoon's avatar
qinsoon committed
204
            trace!("...serializing is_running");
qinsoon's avatar
qinsoon committed
205
            {
206
                try!(s.emit_struct_field("is_running", field_i, |s| self.is_running.load(Ordering::SeqCst).encode(s)));
207
            }
208
            field_i += 1;
qinsoon's avatar
qinsoon committed
209
210
211
212
213
214
215

            // options
            trace!("...serializing vm_options");
            {
                try!(s.emit_struct_field("vm_options", field_i, |s| self.vm_options.encode(s)));
            }
            field_i += 1;
216
            
qinsoon's avatar
qinsoon committed
217
            // compiled_funcs
qinsoon's avatar
qinsoon committed
218
            trace!("...serializing compiled_funcs");
qinsoon's avatar
qinsoon committed
219
220
            {
                let compiled_funcs : &HashMap<_, _> = &self.compiled_funcs.read().unwrap();
221
                try!(s.emit_struct_field("compiled_funcs", field_i, |s| {
qinsoon's avatar
qinsoon committed
222
223
224
225
226
227
228
229
230
231
232
233
                    s.emit_map(compiled_funcs.len(), |s| {
                        let mut i = 0;
                        for (k, v) in compiled_funcs.iter() {
                            try!(s.emit_map_elt_key(i, |s| k.encode(s)));
                            let compiled_func : &CompiledFunction = &v.read().unwrap();
                            try!(s.emit_map_elt_val(i, |s| compiled_func.encode(s)));
                            i += 1;
                        }
                        Ok(())
                    })
                }));
            }
234
            field_i += 1;
qinsoon's avatar
qinsoon committed
235
            
qinsoon's avatar
qinsoon committed
236
            trace!("serializing finished");
237
238
239
            Ok(())
        })
    }
qinsoon's avatar
qinsoon committed
240
241
}

qinsoon's avatar
qinsoon committed
242
243
impl Decodable for VM {
    fn decode<D: Decoder>(d: &mut D) -> Result<VM, D::Error> {
244
245
246
        let mut field_i = 0;

        d.read_struct("VM", VM_SERIALIZE_FIELDS + 2, |d| {
qinsoon's avatar
qinsoon committed
247
            // next_id
248
            let next_id = try!(d.read_struct_field("next_id", field_i, |d| {
qinsoon's avatar
qinsoon committed
249
250
                d.read_usize()
            }));
251
            field_i += 1;
qinsoon's avatar
qinsoon committed
252
253
            
            // id_name_map
254
255
256
            let id_name_map = try!(d.read_struct_field("id_name_map", field_i, |d| Decodable::decode(d)));
            field_i += 1;

qinsoon's avatar
qinsoon committed
257
            // name_id_map
258
259
            let name_id_map = try!(d.read_struct_field("name_id_map", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
260
261
            
            // types
262
263
264
265
            let types = try!(d.read_struct_field("types", field_i, |d| Decodable::decode(d)));
            field_i += 1;

            // struct tag map
qinsoon's avatar
qinsoon committed
266
            {
267
                let mut struct_tag_map : HashMap<MuName, StructType_> = try!(d.read_struct_field("struct_tag_map", field_i, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
268
269
270
271
272
273
                
                let mut map_guard = types::STRUCT_TAG_MAP.write().unwrap();
                map_guard.clear();
                for (k, v) in struct_tag_map.drain() {
                    map_guard.insert(k, v);
                }
274
275
276
277
278
279
280
281
282
283
284
285
286
                field_i += 1;
            }

            // hybrid tag map
            {
                let mut hybrid_tag_map : HashMap<MuName, HybridType_> = try!(d.read_struct_field("hybrid_tag_map", field_i, |d| Decodable::decode(d)));

                let mut map_guard = types::HYBRID_TAG_MAP.write().unwrap();
                map_guard.clear();
                for (k, v) in hybrid_tag_map.drain() {
                    map_guard.insert(k, v);
                }
                field_i += 1;
qinsoon's avatar
qinsoon committed
287
            }
qinsoon's avatar
qinsoon committed
288
289
            
            // backend_type_info
290
291
            let backend_type_info = try!(d.read_struct_field("backend_type_info", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
292
293
            
            // constants
294
295
            let constants = try!(d.read_struct_field("constants", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
296
297
            
            // globals
298
299
            let globals = try!(d.read_struct_field("globals", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
300
301
            
            // func sigs
302
303
            let func_sigs = try!(d.read_struct_field("func_sigs", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
304
305
            
            // funcs
306
            let funcs = try!(d.read_struct_field("funcs", field_i, |d| {
qinsoon's avatar
qinsoon committed
307
308
309
310
311
312
313
314
315
316
                d.read_map(|d, len| {
                    let mut map = HashMap::new();
                    for i in 0..len {
                        let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
                        let val = RwLock::new(try!(d.read_map_elt_val(i, |d| Decodable::decode(d))));
                        map.insert(key, val);
                    }
                    Ok(map)
                })
            }));
317
            field_i += 1;
qinsoon's avatar
qinsoon committed
318
319
            
            // func_vers
320
            let func_vers = try!(d.read_struct_field("func_vers", field_i, |d| {
qinsoon's avatar
qinsoon committed
321
322
323
324
325
326
327
328
329
330
                d.read_map(|d, len| {
                    let mut map = HashMap::new();
                    for i in 0..len {
                        let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
                        let val = RwLock::new(try!(d.read_map_elt_val(i, |d| Decodable::decode(d))));
                        map.insert(key, val);
                    }
                    Ok(map)
                })
            }));
331
            field_i += 1;
qinsoon's avatar
qinsoon committed
332
333
            
            // primordial
334
335
            let primordial = try!(d.read_struct_field("primordial", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
336
337

            // is_running
338
339
            let is_running = try!(d.read_struct_field("is_running", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
340
341
342
343

            // vm_options
            let vm_options = try!(d.read_struct_field("vm_options", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
344
            
qinsoon's avatar
qinsoon committed
345
            // compiled funcs
346
            let compiled_funcs = try!(d.read_struct_field("compiled_funcs", field_i, |d| {
qinsoon's avatar
qinsoon committed
347
348
349
350
351
352
353
354
355
356
                d.read_map(|d, len| {
                    let mut map = HashMap::new();
                    for i in 0..len {
                        let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
                        let val = RwLock::new(try!(d.read_map_elt_val(i, |d| Decodable::decode(d))));
                        map.insert(key, val);
                    }
                    Ok(map)
                })
            }));
357
            field_i += 1;
qinsoon's avatar
qinsoon committed
358
            
qinsoon's avatar
qinsoon committed
359
360
361
362
363
364
365
366
            let vm = VM{
                next_id: ATOMIC_USIZE_INIT,
                id_name_map: RwLock::new(id_name_map),
                name_id_map: RwLock::new(name_id_map),
                types: RwLock::new(types),
                backend_type_info: RwLock::new(backend_type_info),
                constants: RwLock::new(constants),
                globals: RwLock::new(globals),
367
                global_locations: RwLock::new(hashmap!{}),
qinsoon's avatar
qinsoon committed
368
369
370
371
372
                func_sigs: RwLock::new(func_sigs),
                funcs: RwLock::new(funcs),
                func_vers: RwLock::new(func_vers),
                primordial: RwLock::new(primordial),
                is_running: ATOMIC_BOOL_INIT,
qinsoon's avatar
qinsoon committed
373
                vm_options: vm_options,
qinsoon's avatar
qinsoon committed
374
                compiled_funcs: RwLock::new(compiled_funcs),
375
376

                active_handles: RwLock::new(hashmap!{})
qinsoon's avatar
qinsoon committed
377
378
379
380
381
382
383
384
385
386
            };
            
            vm.next_id.store(next_id, Ordering::SeqCst);
            vm.is_running.store(is_running, Ordering::SeqCst);
            
            Ok(vm)
        })
    }
}

qinsoon's avatar
qinsoon committed
387
388
impl <'a> VM {
    pub fn new() -> VM {
qinsoon's avatar
qinsoon committed
389
390
391
392
393
394
395
396
397
        VM::new_internal(VMOptions::default())
    }

    pub fn new_with_opts(str: &str) -> VM {
        VM::new_internal(VMOptions::init(str))
    }

    fn new_internal(options: VMOptions) -> VM {
        VM::start_logging(options.flag_log_level);
qinsoon's avatar
qinsoon committed
398

qinsoon's avatar
qinsoon committed
399
        let ret = VM {
400
            next_id: ATOMIC_USIZE_INIT,
401
            is_running: ATOMIC_BOOL_INIT,
qinsoon's avatar
qinsoon committed
402
403
            vm_options: options,

qinsoon's avatar
qinsoon committed
404
405
            id_name_map: RwLock::new(HashMap::new()),
            name_id_map: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
406

qinsoon's avatar
qinsoon committed
407
            constants: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
408

qinsoon's avatar
qinsoon committed
409
            types: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
410
            backend_type_info: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
411

qinsoon's avatar
qinsoon committed
412
            globals: RwLock::new(HashMap::new()),
413
            global_locations: RwLock::new(hashmap!{}),
qinsoon's avatar
qinsoon committed
414

qinsoon's avatar
qinsoon committed
415
            func_sigs: RwLock::new(HashMap::new()),
416
            func_vers: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
417
            funcs: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
418
            compiled_funcs: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
419

420
421
            primordial: RwLock::new(None),
            active_handles: RwLock::new(hashmap!{})
422
        };
qinsoon's avatar
qinsoon committed
423

qinsoon's avatar
qinsoon committed
424
425
426
427
428
429
        {
            let mut types = ret.types.write().unwrap();
            for ty in INTERNAL_TYPES.iter() {
                types.insert(ty.id(), ty.clone());
            }
        }
qinsoon's avatar
qinsoon committed
430

431
        ret.is_running.store(false, Ordering::SeqCst);
Kunshan Wang's avatar
Kunshan Wang committed
432
433
434
435
436
437
438
439
440
441

        // Does not need SeqCst.
        //
        // If VM creates Mu threads and Mu threads calls traps, the trap handler still "happens
        // after" the creation of the VM itself. Rust does not have a proper memory model, but this
        // is how C++ works.
        //
        // If the client needs to create client-level threads, however, the client should properly
        // synchronise at the time of inter-thread communication, rather than creation of the VM.
        ret.next_id.store(USER_ID_START, Ordering::Relaxed);
qinsoon's avatar
qinsoon committed
442
443
444

        ret.init_vm();

445
446
        ret
    }
qinsoon's avatar
qinsoon committed
447

qinsoon's avatar
qinsoon committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    fn init_vm(&self) {
        // init log
        VM::start_logging(self.vm_options.flag_log_level);

        // init gc
        {
            let ref options = self.vm_options;
            gc::gc_init(options.flag_gc_immixspace_size, options.flag_gc_lospace_size, options.flag_gc_nthreads);
        }
    }

    fn start_logging(level: MuLogLevel) {
        match level {
            MuLogLevel::None  => {},
            MuLogLevel::Error => VM::start_logging_internal(LogLevel::Error),
            MuLogLevel::Warn  => VM::start_logging_internal(LogLevel::Warn),
            MuLogLevel::Info  => VM::start_logging_internal(LogLevel::Info),
            MuLogLevel::Debug => VM::start_logging_internal(LogLevel::Debug),
            MuLogLevel::Trace => VM::start_logging_internal(LogLevel::Trace),
        }
qinsoon's avatar
qinsoon committed
468
469
470
    }

    pub fn start_logging_trace() {
qinsoon's avatar
qinsoon committed
471
472
473
474
        VM::start_logging_internal(LogLevel::Trace)
    }

    fn start_logging_internal(level: LogLevel) {
qinsoon's avatar
qinsoon committed
475
476
        use simple_logger;

qinsoon's avatar
qinsoon committed
477
        match simple_logger::init_with_level(level) {
qinsoon's avatar
qinsoon committed
478
479
480
481
            Ok(_) => {},
            Err(_) => {}
        }
    }
482
    
483
484
485
    pub fn resume_vm(serialized_vm: &str) -> VM {
        use rustc_serialize::json;
        
qinsoon's avatar
qinsoon committed
486
        let vm : VM = json::decode(serialized_vm).unwrap();
487
        
qinsoon's avatar
qinsoon committed
488
        vm.init_vm();
qinsoon's avatar
qinsoon committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519

        // restore gc types
        {
            let type_info_guard = vm.backend_type_info.read().unwrap();
            let mut type_info_vec: Vec<Box<BackendTypeInfo>> = type_info_guard.values().map(|x| x.clone()).collect();
            type_info_vec.sort_by(|a, b| a.gc_type.id.cmp(&b.gc_type.id));

            let mut expect_id = 0;
            for ty_info in type_info_vec.iter() {
                use runtime::mm;

                let ref gc_type = ty_info.gc_type;

                if gc_type.id != expect_id {
                    debug_assert!(expect_id < gc_type.id);

                    while expect_id < gc_type.id {
                        use runtime::mm::common::gctype::GCType;

                        mm::add_gc_type(GCType::new_noreftype(0));
                        expect_id += 1;
                    }
                }

                // now expect_id == gc_type.id
                debug_assert!(expect_id == gc_type.id);

                mm::add_gc_type(gc_type.as_ref().clone());
                expect_id += 1;
            }
        }
520
521
522
523
        
        vm
    }
    
524
    pub fn next_id(&self) -> MuID {
Kunshan Wang's avatar
Kunshan Wang committed
525
526
527
528
        // This only needs to be atomic, and does not need to be a synchronisation operation. The
        // only requirement for IDs is that all IDs obtained from `next_id()` are different. So
        // `Ordering::Relaxed` is sufficient.
        self.next_id.fetch_add(1, Ordering::Relaxed)
529
530
    }
    
531
532
533
534
535
536
    pub fn run_vm(&self) {
        self.is_running.store(true, Ordering::SeqCst);
    }
    
    pub fn is_running(&self) -> bool {
        self.is_running.load(Ordering::Relaxed)
qinsoon's avatar
qinsoon committed
537
538
    }
    
539
    pub fn set_name(&self, entity: &MuEntity, name: MuName) {
qinsoon's avatar
qinsoon committed
540
        let id = entity.id();
541
        entity.set_name(name.clone());
qinsoon's avatar
qinsoon committed
542
543
        
        let mut map = self.id_name_map.write().unwrap();
544
        map.insert(id, name.clone());
qinsoon's avatar
qinsoon committed
545
546
547
548
549
        
        let mut map2 = self.name_id_map.write().unwrap();
        map2.insert(name, id);
    }
    
Kunshan Wang's avatar
Kunshan Wang committed
550
    pub fn id_of_by_refstring(&self, name: &String) -> MuID {
qinsoon's avatar
qinsoon committed
551
        let map = self.name_id_map.read().unwrap();
Kunshan Wang's avatar
Kunshan Wang committed
552
553
554
555
556
        *map.get(name).unwrap()
    }
    
    pub fn id_of(&self, name: &str) -> MuID {
        self.id_of_by_refstring(&name.to_string())
qinsoon's avatar
qinsoon committed
557
558
559
560
    }
    
    pub fn name_of(&self, id: MuID) -> MuName {
        let map = self.id_name_map.read().unwrap();
561
        map.get(&id).unwrap().clone()
qinsoon's avatar
qinsoon committed
562
563
    }
    
qinsoon's avatar
qinsoon committed
564
    pub fn declare_const(&self, id: MuID, ty: P<MuType>, val: Constant) -> P<Value> {
qinsoon's avatar
qinsoon committed
565
        let mut constants = self.constants.write().unwrap();
qinsoon's avatar
qinsoon committed
566
        debug_assert!(!constants.contains_key(&id));
qinsoon's avatar
qinsoon committed
567
        
568
        let ret = P(Value{hdr: MuEntityHeader::unnamed(id), ty: ty, v: Value_::Constant(val)});
569
        trace!("declare const #{} = {}", id, ret);
qinsoon's avatar
qinsoon committed
570
        constants.insert(id, ret.clone());
qinsoon's avatar
qinsoon committed
571
572
573
574
        
        ret
    }
    
575
576
577
578
579
580
581
582
    pub fn get_const(&self, id: MuID) -> P<Value> {
        let const_lock = self.constants.read().unwrap();
        match const_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find const #{}", id)
        }
    }
    
qinsoon's avatar
qinsoon committed
583
584
    pub fn declare_global(&self, id: MuID, ty: P<MuType>) -> P<Value> {
        let global = P(Value{
585
            hdr: MuEntityHeader::unnamed(id),
586
            ty: self.declare_type(self.next_id(), MuType_::iref(ty.clone())),
587
            v: Value_::Global(ty)
qinsoon's avatar
qinsoon committed
588
        });
qinsoon's avatar
qinsoon committed
589
590
        
        let mut globals = self.globals.write().unwrap();
591
        trace!("declare global #{} = {}", id, global);
qinsoon's avatar
qinsoon committed
592
        globals.insert(id, global.clone());
593
594

        // allocate global
595
        let loc = gc::allocate_global(global.clone(), self);
596
        let mut global_locs = self.global_locations.write().unwrap();
597
        trace!("allocate global #{} as {}", id, loc);
598
        global_locs.insert(id, loc);
qinsoon's avatar
qinsoon committed
599
        
qinsoon's avatar
qinsoon committed
600
        global
qinsoon's avatar
qinsoon committed
601
602
    }
    
qinsoon's avatar
qinsoon committed
603
    pub fn declare_type(&self, id: MuID, ty: MuType_) -> P<MuType> {
604
        let ty = P(MuType{hdr: MuEntityHeader::unnamed(id), v: ty});
qinsoon's avatar
qinsoon committed
605
        
qinsoon's avatar
qinsoon committed
606
        let mut types = self.types.write().unwrap();
qinsoon's avatar
qinsoon committed
607
        debug_assert!(!types.contains_key(&id));
608
609

        trace!("declare type #{} = {}", ty.id(), ty);
qinsoon's avatar
qinsoon committed
610
        types.insert(ty.id(), ty.clone());
qinsoon's avatar
qinsoon committed
611
612
613
614
        
        ty
    }
    
615
616
617
618
619
620
621
622
    pub fn get_type(&self, id: MuID) -> P<MuType> {
        let type_lock = self.types.read().unwrap();
        match type_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find type #{}", id)
        }
    }    
    
qinsoon's avatar
qinsoon committed
623
    pub fn declare_func_sig(&self, id: MuID, ret_tys: Vec<P<MuType>>, arg_tys: Vec<P<MuType>>) -> P<MuFuncSig> {
qinsoon's avatar
qinsoon committed
624
        let mut func_sigs = self.func_sigs.write().unwrap();
qinsoon's avatar
qinsoon committed
625
        debug_assert!(!func_sigs.contains_key(&id));
qinsoon's avatar
qinsoon committed
626
        
627
        let ret = P(MuFuncSig{hdr: MuEntityHeader::unnamed(id), ret_tys: ret_tys, arg_tys: arg_tys});
qinsoon's avatar
qinsoon committed
628
        func_sigs.insert(id, ret.clone());
qinsoon's avatar
qinsoon committed
629
630
631
632
        
        ret
    }
    
633
634
635
636
637
638
639
640
    pub fn get_func_sig(&self, id: MuID) -> P<MuFuncSig> {
        let func_sig_lock = self.func_sigs.read().unwrap();
        match func_sig_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find func sig #{}", id)
        }
    }
    
641
    pub fn declare_func (&self, func: MuFunction) {
qinsoon's avatar
qinsoon committed
642
        info!("declare function {}", func);
qinsoon's avatar
qinsoon committed
643
        let mut funcs = self.funcs.write().unwrap();
qinsoon's avatar
qinsoon committed
644
        funcs.insert(func.id(), RwLock::new(func));
645
646
    }
    
647
648
649
650
651
652
653
654
655
    /// The IR builder needs to look-up the function signature from the existing function ID.
    pub fn get_func_sig_for_func(&self, id: MuID) -> P<MuFuncSig> {
        let funcs_lock = self.funcs.read().unwrap();
        match funcs_lock.get(&id) {
            Some(func) => func.read().unwrap().sig.clone(),
            None => panic!("cannot find Mu function #{}", id)
        }
    }    
    
656
    pub fn define_func_version (&self, func_ver: MuFunctionVersion) {
qinsoon's avatar
qinsoon committed
657
        info!("define function version {}", func_ver);
658
        // record this version
qinsoon's avatar
qinsoon committed
659
        let func_ver_id = func_ver.id();
660
661
        {
            let mut func_vers = self.func_vers.write().unwrap();
qinsoon's avatar
qinsoon committed
662
            func_vers.insert(func_ver_id, RwLock::new(func_ver));
663
664
665
666
        }
        
        // acquire a reference to the func_ver
        let func_vers = self.func_vers.read().unwrap();
qinsoon's avatar
qinsoon committed
667
        let func_ver = func_vers.get(&func_ver_id).unwrap().write().unwrap();
668
669
670
        
        // change current version to this (obsolete old versions)
        let funcs = self.funcs.read().unwrap();
qinsoon's avatar
qinsoon committed
671
        debug_assert!(funcs.contains_key(&func_ver.func_id)); // it should be declared before defining
qinsoon's avatar
qinsoon committed
672
        let mut func = funcs.get(&func_ver.func_id).unwrap().write().unwrap();
673
        
674
675
676
677
        func.new_version(func_ver.id());
        
        // redefinition happens here
        // do stuff        
678
    }
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744

    /// Add a new bundle into VM.
    ///
    /// This function will drain the contents of all arguments.
    ///
    /// Ideally, this function should happen atomically. e.g. The client should not see a new type
    /// added without also seeing a new function added.
    pub fn declare_many(&self,
                        new_id_name_map: &mut HashMap<MuID, MuName>,
                        new_types: &mut HashMap<MuID, P<MuType>>,
                        new_func_sigs: &mut HashMap<MuID, P<MuFuncSig>>,
                        new_constants: &mut HashMap<MuID, P<Value>>,
                        new_globals: &mut HashMap<MuID, P<Value>>,
                        new_funcs: &mut HashMap<MuID, Box<MuFunction>>,
                        new_func_vers: &mut HashMap<MuID, Box<MuFunctionVersion>>
                        ) {
        // Make sure other components, if ever acquiring multiple locks at the same time, acquire
        // them in this order, to prevent deadlock.
        let mut id_name_map = self.id_name_map.write().unwrap();
        let mut name_id_map = self.name_id_map.write().unwrap();
        let mut types = self.types.write().unwrap();
        let mut constants = self.constants.write().unwrap();
        let mut globals = self.globals.write().unwrap();
        let mut func_sigs = self.func_sigs.write().unwrap();
        let mut funcs = self.funcs.write().unwrap();
        let mut func_vers = self.func_vers.write().unwrap();

        for (id, name) in new_id_name_map.drain() {
            id_name_map.insert(id, name.clone());
            name_id_map.insert(name, id);
        }

        for (id, obj) in new_types.drain() {
            types.insert(id, obj);
        }

        for (id, obj) in new_constants.drain() {
            constants.insert(id, obj);
        }

        for (id, obj) in new_globals.drain() {
            globals.insert(id, obj);
        }

        for (id, obj) in new_func_sigs.drain() {
            func_sigs.insert(id, obj);
        }

        for (id, obj) in new_funcs.drain() {
            funcs.insert(id, RwLock::new(*obj));
        }

        for (id, obj) in new_func_vers.drain() {
            let func_id = obj.func_id;
            func_vers.insert(id, RwLock::new(*obj));

            {
                trace!("Adding funcver {} as a version of {}...", id, func_id);
                let func = funcs.get_mut(&func_id).unwrap();
                func.write().unwrap().new_version(id);
                trace!("Added funcver {} as a version of {} {:?}.", id, func_id, func);
            }
        }

        // Locks released here
    }
745
    
746
    pub fn add_compiled_func (&self, func: CompiledFunction) {
qinsoon's avatar
qinsoon committed
747
        debug_assert!(self.funcs.read().unwrap().contains_key(&func.func_id));
qinsoon's avatar
qinsoon committed
748
        debug_assert!(self.func_vers.read().unwrap().contains_key(&func.func_ver_id));
qinsoon's avatar
qinsoon committed
749

qinsoon's avatar
qinsoon committed
750
        self.compiled_funcs.write().unwrap().insert(func.func_ver_id, RwLock::new(func));
qinsoon's avatar
qinsoon committed
751
752
    }
    
qinsoon's avatar
qinsoon committed
753
    pub fn get_backend_type_info(&self, tyid: MuID) -> Box<BackendTypeInfo> {        
qinsoon's avatar
qinsoon committed
754
755
756
        {
            let read_lock = self.backend_type_info.read().unwrap();
        
757
            match read_lock.get(&tyid) {
qinsoon's avatar
qinsoon committed
758
759
760
761
                Some(info) => {return info.clone();},
                None => {}
            }
        }
762
763

        let types = self.types.read().unwrap();
qinsoon's avatar
qinsoon committed
764
765
766
767
        let ty = match types.get(&tyid) {
            Some(ty) => ty,
            None => panic!("invalid type id during get_backend_type_info(): {}", tyid)
        };
qinsoon's avatar
qinsoon committed
768
        let resolved = Box::new(backend::resolve_backend_type_info(ty, self));
qinsoon's avatar
qinsoon committed
769
770
        
        let mut write_lock = self.backend_type_info.write().unwrap();
771
        write_lock.insert(tyid, resolved.clone());
qinsoon's avatar
qinsoon committed
772
773
774
775
        
        resolved        
    }
    
qinsoon's avatar
qinsoon committed
776
777
778
779
    pub fn get_type_size(&self, tyid: MuID) -> ByteSize {
        self.get_backend_type_info(tyid).size
    }
    
qinsoon's avatar
qinsoon committed
780
    pub fn globals(&self) -> &RwLock<HashMap<MuID, P<Value>>> {
qinsoon's avatar
qinsoon committed
781
782
783
        &self.globals
    }
    
qinsoon's avatar
qinsoon committed
784
    pub fn funcs(&self) -> &RwLock<HashMap<MuID, RwLock<MuFunction>>> {
qinsoon's avatar
qinsoon committed
785
        &self.funcs
786
    }
787
    
qinsoon's avatar
qinsoon committed
788
    pub fn func_vers(&self) -> &RwLock<HashMap<MuID, RwLock<MuFunctionVersion>>> {
789
790
        &self.func_vers
    }
qinsoon's avatar
qinsoon committed
791
792
793
794
795
796
797
798
799
800
801

    pub fn get_cur_version_of(&self, fid: MuID) -> Option<MuID> {
        let funcs_guard = self.funcs.read().unwrap();
        match funcs_guard.get(&fid) {
            Some(rwlock_func) => {
                let func_guard = rwlock_func.read().unwrap();
                func_guard.cur_ver
            },
            None => None
        }
    }
802
    
qinsoon's avatar
qinsoon committed
803
    pub fn compiled_funcs(&self) -> &RwLock<HashMap<MuID, RwLock<CompiledFunction>>> {
804
805
        &self.compiled_funcs
    }
806
807
808
809
810
811
812
813
    
    pub fn types(&self) -> &RwLock<HashMap<MuID, P<MuType>>> {
        &self.types
    }
    
    pub fn func_sigs(&self) -> &RwLock<HashMap<MuID, P<MuFuncSig>>> {
        &self.func_sigs
    }
qinsoon's avatar
qinsoon committed
814
    
815
816
817
818
819
820
821
    pub fn resolve_function_address(&self, func_id: MuID) -> ValueLocation {
        let funcs = self.funcs.read().unwrap();
        let func : &MuFunction = &funcs.get(&func_id).unwrap().read().unwrap();
                
        if self.is_running() {
            unimplemented!()
        } else {
822
            ValueLocation::Relocatable(backend::RegGroup::GPR, func.name().unwrap())
823
824
825
        }
    }
    
qinsoon's avatar
qinsoon committed
826
    pub fn new_stack(&self, func_id: MuID) -> Box<MuStack> {
qinsoon's avatar
qinsoon committed
827
828
829
        let funcs = self.funcs.read().unwrap();
        let func : &MuFunction = &funcs.get(&func_id).unwrap().read().unwrap();
        
830
831
832
833
834
835
        Box::new(MuStack::new(self.next_id(), self.resolve_function_address(func_id), func))
    }
    
    pub fn make_primordial_thread(&self, func_id: MuID, args: Vec<Constant>) {
        let mut guard = self.primordial.write().unwrap();
        *guard = Some(MuPrimordialThread{func_id: func_id, args: args});
qinsoon's avatar
qinsoon committed
836
837
    }
    
qinsoon's avatar
qinsoon committed
838
839
840
841
842
843
844
845
    #[allow(unused_variables)]
    pub fn make_boot_image(self, output: &path::Path) {
        use rustc_serialize::json;
        
        let serialized = json::encode(&self).unwrap();
        
        unimplemented!() 
    }
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

    pub fn handle_from_global(&self, id: MuID) -> Arc<APIHandle> {
        let global_iref = {
            let global_locs = self.global_locations.read().unwrap();
            global_locs.get(&id).unwrap().to_address()
        };

        let handle_id = self.next_id();

        let ret = Arc::new(APIHandle {
            id: handle_id,
            v : APIHandleValue::IRef(global_iref)
        });

        let mut handles = self.active_handles.write().unwrap();
        handles.insert(handle_id, ret.clone());

        ret
    }

    pub fn handle_from_uint64(&self, num: u64, len: BitSize) -> Arc<APIHandle> {
        let handle_id = self.next_id();

        let ret = Arc::new(APIHandle {
            id: handle_id,
            v : APIHandleValue::Int(num, len)
        });

        let mut handles = self.active_handles.write().unwrap();
        handles.insert(handle_id, ret.clone());

        ret
    }
Kunshan Wang's avatar
Kunshan Wang committed
879
}