asm_backend.rs 35.2 KB
Newer Older
1 2
#![allow(unused_variables)]

3
use compiler::backend;
qinsoon's avatar
qinsoon committed
4
use utils::ByteSize;
5
use compiler::backend::x86_64;
6
use compiler::backend::x86_64::CodeGenerator;
qinsoon's avatar
qinsoon committed
7
use vm::MachineCode;
qinsoon's avatar
qinsoon committed
8
use vm::VM;
9

10 11
use utils::string_utils;

12 13 14
use ast::ptr::P;
use ast::ir::*;

15 16
use std::collections::HashMap;
use std::str;
17
use std::usize;
18
use std::slice::Iter;
19
use std::ops;
20 21

struct ASMCode {
qinsoon's avatar
qinsoon committed
22
    name: MuName, 
23 24
    code: Vec<ASM>,
    reg_defines: HashMap<MuID, Vec<ASMLocation>>,
25 26
    reg_uses: HashMap<MuID, Vec<ASMLocation>>,
    
qinsoon's avatar
qinsoon committed
27 28
    mem_op_used: HashMap<usize, bool>,
    
29 30 31
    preds: Vec<Vec<usize>>,
    succs: Vec<Vec<usize>>,
    
qinsoon's avatar
qinsoon committed
32 33 34 35
    idx_to_blk: HashMap<usize, MuName>,
    blk_to_idx: HashMap<MuName, usize>,
    cond_branches: HashMap<usize, MuName>,
    branches: HashMap<usize, MuName>,
36
    
qinsoon's avatar
qinsoon committed
37 38 39
    blocks: Vec<MuName>,
    block_start: HashMap<MuName, usize>,
    block_range: HashMap<MuName, ops::Range<usize>>,
40
    
qinsoon's avatar
qinsoon committed
41 42
    block_livein: HashMap<MuName, Vec<MuID>>,
    block_liveout: HashMap<MuName, Vec<MuID>>
43 44
}

45 46 47 48
impl MachineCode for ASMCode {
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }
49
    
50 51 52 53 54 55 56 57
    fn is_move(&self, index: usize) -> bool {
        let inst = self.code.get(index);
        match inst {
            Some(inst) => inst.code.starts_with("mov"),
            None => false
        }
    }
    
qinsoon's avatar
qinsoon committed
58 59 60 61
    fn is_using_mem_op(&self, index: usize) -> bool {
        *self.mem_op_used.get(&index).unwrap()
    }
    
qinsoon's avatar
qinsoon committed
62 63 64 65 66 67 68 69
    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.succs[index]
    }
    
    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.preds[index]
    }
    
70
    fn get_inst_reg_uses(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
71
        &self.code[index].uses
72 73
    }
    
74
    fn get_inst_reg_defines(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
75
        &self.code[index].defines
76
    }
77
    
78
    fn replace_reg(&mut self, from: MuID, to: MuID) {
79
        let to_reg_tag : MuName = backend::all_regs().get(&to).unwrap().name().unwrap();
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        let to_reg_string = "%".to_string() + to_reg_tag;
        
        match self.reg_defines.get(&from) {
            Some(defines) => {
                for loc in defines {
                    let ref mut inst_to_patch = self.code[loc.line];
                    for i in 0..loc.len {
                        string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
                    }
                }
            },
            None => {}
        }
        
        match self.reg_uses.get(&from) {
            Some(uses) => {
                for loc in uses {
                    let ref mut inst_to_patch = self.code[loc.line];
                    for i in 0..loc.len {
                        string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
                    }   
                }
            },
            None => {}
        }
    }
    
107 108 109 110 111
    fn set_inst_nop(&mut self, index: usize) {
        self.code.remove(index);
        self.code.insert(index, ASM::nop());
    }
    
112 113 114 115 116 117 118 119 120 121 122
    fn emit(&self) -> Vec<u8> {
        let mut ret = vec![];
        
        for inst in self.code.iter() {
            ret.append(&mut inst.code.clone().into_bytes());
            ret.append(&mut "\n".to_string().into_bytes());
        }
        
        ret
    }
    
123 124
    fn trace_mc(&self) {
        trace!("");
125

126 127
        trace!("code for {}: \n", self.name);
        
128 129
        let n_insts = self.code.len();
        for i in 0..n_insts {
130
            self.trace_inst(i);
131 132
        }
        
133 134 135 136 137 138 139
        trace!("")      
    }
    
    fn trace_inst(&self, i: usize) {
        trace!("#{}\t{:30}\t\tdefine: {:?}\tuses: {:?}\tpred: {:?}\tsucc: {:?}", 
            i, self.code[i].code, self.get_inst_reg_defines(i), self.get_inst_reg_uses(i),
            self.preds[i], self.succs[i]);
140
    }
141
    
qinsoon's avatar
qinsoon committed
142
    fn get_ir_block_livein(&self, block: MuName) -> Option<&Vec<MuID>> {
143 144 145
        self.block_livein.get(&block)
    }
    
qinsoon's avatar
qinsoon committed
146
    fn get_ir_block_liveout(&self, block: MuName) -> Option<&Vec<MuID>> {
147 148 149
        self.block_liveout.get(&block)
    }
    
qinsoon's avatar
qinsoon committed
150
    fn get_all_blocks(&self) -> &Vec<MuName> {
151 152 153
        &self.blocks
    }
    
qinsoon's avatar
qinsoon committed
154
    fn get_block_range(&self, block: MuName) -> Option<ops::Range<usize>> {
155 156 157 158 159
        match self.block_range.get(&block) {
            Some(r) => Some(r.clone()),
            None => None
        }
    }
160 161 162 163 164 165
}

struct ASM {
    code: String,
    defines: Vec<MuID>,
    uses: Vec<MuID>
166 167
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
impl ASM {
    fn symbolic(line: String) -> ASM {
        ASM {
            code: line,
            defines: vec![],
            uses: vec![]
        }
    }
    
    fn inst(inst: String, defines: Vec<MuID>, uses: Vec<MuID>) -> ASM {
        ASM {
            code: inst,
            defines: defines,
            uses: uses
        }
    }
    
    fn branch(line: String) -> ASM {
        ASM {
            code: line,
            defines: vec![],
            uses: vec![]
        }
    }
192 193 194 195 196 197 198 199
    
    fn nop() -> ASM {
        ASM {
            code: "".to_string(),
            defines: vec![],
            uses: vec![]
        }
    }
200 201
}

202
#[derive(Clone, Debug)]
203 204 205 206 207 208 209
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize
}

impl ASMLocation {
210 211
    /// the 'line' field will be updated later
    fn new(index: usize, len: usize) -> ASMLocation {
212
        ASMLocation{
213
            line: usize::MAX,
214 215 216 217 218 219
            index: index,
            len: len
        }
    }
}

220
pub struct ASMCodeGen {
221
    cur: Option<Box<ASMCode>>
222 223
}

224
const REG_PLACEHOLDER_LEN : usize = 5;
225 226 227 228 229 230
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];
        
        format!("%{}", str::from_utf8(&blank_spaces).unwrap())
    };
231 232 233 234
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
235
        ASMCodeGen {
236
            cur: None
237 238 239 240 241 242 243 244 245 246 247
        }
    }
    
    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }
    
    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }
    
248 249 250 251 252 253 254 255 256 257 258 259
    fn line(&self) -> usize {
        self.cur().code.len()
    }
    
    fn add_asm_block_label(&mut self, code: String, block_name: &'static str) {
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
        
        self.cur_mut().idx_to_blk.insert(l, block_name);
        self.cur_mut().blk_to_idx.insert(block_name, l);
    }
    
260 261 262 263
    fn add_asm_symbolic(&mut self, code: String){
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
264 265 266 267
    fn prepare_machine_regs(&self, regs: Iter<P<Value>>) -> Vec<MuID> {
        regs.map(|x| self.prepare_machine_reg(x)).collect()
    } 
    
268
    fn add_asm_call(&mut self, code: String) {
269 270 271 272 273 274
        let mut uses : Vec<MuID> = self.prepare_machine_regs(x86_64::ARGUMENT_GPRs.iter());
        uses.append(&mut self.prepare_machine_regs(x86_64::ARGUMENT_FPRs.iter()));
        
        let mut defines : Vec<MuID> = self.prepare_machine_regs(x86_64::RETURN_GPRs.iter());
        defines.append(&mut self.prepare_machine_regs(x86_64::RETURN_FPRs.iter()));
          
qinsoon's avatar
qinsoon committed
275
        self.add_asm_inst(code, defines, vec![], uses, vec![], false);
276 277 278
    }
    
    fn add_asm_ret(&mut self, code: String) {
279 280 281
        let mut uses : Vec<MuID> = self.prepare_machine_regs(x86_64::RETURN_GPRs.iter());
        uses.append(&mut self.prepare_machine_regs(x86_64::RETURN_FPRs.iter()));
        
qinsoon's avatar
qinsoon committed
282
        self.add_asm_inst(code, vec![], vec![], uses, vec![], false);
283 284 285 286 287
    }
    
    fn add_asm_branch(&mut self, code: String, target: &'static str) {
        let l = self.line();
        self.cur_mut().branches.insert(l, target);
qinsoon's avatar
qinsoon committed
288 289
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
290 291 292 293 294
    }
    
    fn add_asm_branch2(&mut self, code: String, target: &'static str) {
        let l = self.line();
        self.cur_mut().cond_branches.insert(l, target);
qinsoon's avatar
qinsoon committed
295 296
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
297 298 299 300 301 302
    }
    
    fn add_asm_inst(
        &mut self, 
        code: String, 
        defines: Vec<MuID>,
303
        mut define_locs: Vec<ASMLocation>, 
304
        uses: Vec<MuID>,
qinsoon's avatar
qinsoon committed
305 306
        mut use_locs: Vec<ASMLocation>,
        is_using_mem_op: bool) 
307
    {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        let line = self.line();
        
        trace!("asm: {}", code);
        trace!("     defines: {:?}, def_locs: {:?}", defines, define_locs);
        trace!("     uses: {:?}, use_locs: {:?}", uses, use_locs);
        let mc = self.cur_mut();
       
        // add locations of defined registers
        for i in 0..define_locs.len() {
            let id = defines[i];
            
            // update line in location
            let ref mut loc = define_locs[i];
            loc.line = line;
            
            if mc.reg_defines.contains_key(&id) {
                mc.reg_defines.get_mut(&id).unwrap().push(loc.clone());
            } else {
                mc.reg_defines.insert(id, vec![loc.clone()]);
            }
        }
       
        for i in 0..use_locs.len() {
            let id = uses[i];
            
            // update line in location
            let ref mut loc = use_locs[i];
            loc.line = line;
            
            if mc.reg_uses.contains_key(&id) {
338
                mc.reg_uses.get_mut(&id).unwrap().push(loc.clone());
339
            } else {
340
                mc.reg_uses.insert(id, vec![loc.clone()]);
341 342
            }
        }
343
       
344 345
        // put the instruction
        mc.code.push(ASM::inst(code, defines, uses));
qinsoon's avatar
qinsoon committed
346
        mc.mem_op_used.insert(line, is_using_mem_op);
347 348 349 350
    }
    
    fn define_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
351
        
352 353 354 355 356 357 358
        let code = self.cur_mut();
        if code.reg_defines.contains_key(&id) {
            let regs = code.reg_defines.get_mut(&id).unwrap();
            regs.push(loc);
        } else {
            code.reg_defines.insert(id, vec![loc]);
        } 
359 360 361 362 363 364
    }
    
    fn use_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
        
        let code = self.cur_mut();
365 366 367
        if code.reg_uses.contains_key(&id) {
            let reg_uses = code.reg_uses.get_mut(&id).unwrap();
            reg_uses.push(loc);
368
        } else {
369
            code.reg_uses.insert(id, vec![loc]);
370 371 372
        } 
    }
    
373
    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
374 375 376 377 378 379 380
        let str = self.asm_reg_op(op);
        let len = str.len();
        (str, op.extract_ssa_id().unwrap(), ASMLocation::new(loc, len)) 
    }
    
    fn prepare_machine_reg(&self, op: &P<Value>) -> MuID {
        op.extract_ssa_id().unwrap()
381
    }
382
    
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 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 461 462 463 464 465 466 467 468 469 470 471 472
    #[allow(unused_assignments)]
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, Vec<MuID>, Vec<ASMLocation>) {
        let mut ids : Vec<MuID> = vec![];
        let mut locs : Vec<ASMLocation> = vec![];
        let mut result_str : String = "".to_string();
        
        let mut loc_cursor : usize = 0;
        
        match op.v {
            // offset(base,index,scale)
            Value_::Memory(MemoryLocation::Address{ref base, ref offset, ref index, scale}) => {
                // deal with offset
                if offset.is_some() {
                    let offset = offset.as_ref().unwrap();
                    
                    match offset.v {
                        Value_::SSAVar(id) => {
                            // temp as offset
                            let (str, id, loc) = self.prepare_reg(offset, 0);
                            
                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);
                            
                            loc_cursor += str.len();
                        },
                        Value_::Constant(Constant::Int(val)) => {
                            let str = val.to_string();
                            
                            result_str.push_str(&str);
                            loc_cursor += str.len();
                        },
                        _ => panic!("unexpected offset type: {:?}", offset)
                    }
                }
                
                result_str.push('(');
                loc_cursor += 1; 
                
                // deal with base, base is ssa
                let (str, id, loc) = self.prepare_reg(base, loc_cursor);
                result_str.push_str(&str);
                ids.push(id);
                locs.push(loc);
                loc_cursor += str.len();
                
                // deal with index (ssa or constant)
                if index.is_some() {
                    result_str.push(',');
                    loc_cursor += 1; // plus 1 for ,                    
                    
                    let index = index.as_ref().unwrap();
                    
                    match index.v {
                        Value_::SSAVar(id) => {
                            // temp as offset
                            let (str, id, loc) = self.prepare_reg(index, loc_cursor);
                            
                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);
                            
                            loc_cursor += str.len();
                        },
                        Value_::Constant(Constant::Int(val)) => {
                            let str = val.to_string();
                            
                            result_str.push_str(&str);
                            loc_cursor += str.len();
                        },
                        _ => panic!("unexpected index type: {:?}", index)
                    }
                    
                    // scale
                    if scale.is_some() {
                        result_str.push(',');
                        loc_cursor += 1;
                        
                        let scale = scale.unwrap();
                        let str = scale.to_string();
                        
                        result_str.push_str(&str);
                        loc_cursor += str.len();
                    }
                }
                
                result_str.push(')');
                loc_cursor += 1;
            },
            Value_::Memory(MemoryLocation::Symbolic{ref base, label}) => {
qinsoon's avatar
qinsoon committed
473
                result_str.push_str(&symbol(label));
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
                loc_cursor += label.len();
                
                if base.is_some() {
                    result_str.push('(');
                    loc_cursor += 1;
                    
                    let (str, id, loc) = self.prepare_reg(base.as_ref().unwrap(), loc_cursor);
                    result_str.push_str(&str);
                    ids.push(id);
                    locs.push(loc);
                    loc_cursor += str.len();
                    
                    result_str.push(')');
                    loc_cursor += 1;                    
                }
            },
            _ => panic!("expect mem location as value")
        }
        
        (result_str, ids, locs)
    }
    
496 497
    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
qinsoon's avatar
qinsoon committed
498
        if id < MACHINE_ID_END {
499
            // machine reg
500
            format!("%{}", op.name().unwrap())
501 502 503 504 505 506
        } else {
            // virtual register, use place holder
            REG_PLACEHOLDER.clone()
        }
    }
    
qinsoon's avatar
qinsoon committed
507
    fn asm_block_label(&self, label: MuName) -> String {
qinsoon's avatar
qinsoon committed
508
        symbol(&format!("{}_{}", self.cur().name, label))
509
    }
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    
    fn control_flow_analysis(&mut self) {
        // control flow analysis
        let n_insts = self.line();
        
        let code = self.cur_mut();
        code.preds = vec![vec![]; n_insts];
        code.succs = vec![vec![]; n_insts];
        
        for i in 0..n_insts {
            // determine predecessor - if cur is not block start, its predecessor is previous insts
            let is_block_start = code.idx_to_blk.get(&i);
            if is_block_start.is_none() {
                if i > 0 {
                    code.preds[i].push(i - 1);
                }
            } else {
                // if cur is a branch target, we already set its predecessor
                // if cur is a fall-through block, we set it in a sanity check pass
            }
            
            // determine successor
            let is_branch = code.branches.get(&i);
            if is_branch.is_some() {
                // branch to target
                let target = is_branch.unwrap();
                let target_n = code.blk_to_idx.get(target).unwrap();
                
                // cur inst's succ is target
                code.succs[i].push(*target_n);
                
                // target's pred is cur
                code.preds[*target_n].push(i);
            } else {
                let is_cond_branch = code.cond_branches.get(&i);
                if is_cond_branch.is_some() {
                    // branch to target
                    let target = is_cond_branch.unwrap();
                    let target_n = code.blk_to_idx.get(target).unwrap();
                    
                    // cur insts' succ is target and next inst
                    code.succs[i].push(*target_n);
                    if i < n_insts - 1 {
                        code.succs[i].push(i + 1);
                    }
                    
                    // target's pred is cur
                    code.preds[*target_n].push(i);
                } else {
                    // not branch nor cond branch, succ is next inst
                    if i < n_insts - 1 {
                        code.succs[i].push(i + 1);
                    }
                }
            } 
        }
        
        // a sanity check for fallthrough blocks
        for i in 0..n_insts {
            if i != 0 && code.preds[i].len() == 0 {
                code.preds[i].push(i - 1);
            }
        }        
    }
574 575 576
}

impl CodeGenerator for ASMCodeGen {
qinsoon's avatar
qinsoon committed
577
    fn start_code(&mut self, func_name: MuName) {
578
        self.cur = Some(Box::new(ASMCode {
579 580
                name: func_name,
                code: vec![],
581
                reg_defines: HashMap::new(),
582 583
                reg_uses: HashMap::new(),
                
qinsoon's avatar
qinsoon committed
584 585
                mem_op_used: HashMap::new(),
                
586 587 588 589 590 591
                preds: vec![],
                succs: vec![],
                
                idx_to_blk: HashMap::new(),
                blk_to_idx: HashMap::new(),
                cond_branches: HashMap::new(),
592 593
                branches: HashMap::new(),
                
594 595 596 597
                blocks: vec![],
                block_start: HashMap::new(),
                block_range: HashMap::new(),
                
598 599
                block_livein: HashMap::new(),
                block_liveout: HashMap::new()
600
            }));
601
        
qinsoon's avatar
qinsoon committed
602
        // to link with C sources via gcc
qinsoon's avatar
qinsoon committed
603 604
        self.add_asm_symbolic(directive_globl(symbol(func_name)));
        self.add_asm_symbolic(format!("{}:", symbol(func_name)));
605 606
    }
    
607 608 609
    fn finish_code(&mut self) -> Box<MachineCode> {
        self.control_flow_analysis();
        self.cur.take().unwrap()
610 611 612 613 614 615 616 617 618
    }
    
    fn print_cur_code(&self) {
        println!("");
        
        if self.cur.is_some() {
            let code = self.cur.as_ref().unwrap();
            
            println!("code for {}: ", code.name);
619 620 621 622
            let n_insts = code.code.len();
            for i in 0..n_insts {
                let ref line = code.code[i];
                println!("#{}\t{}", i, line.code);
623 624 625 626 627 628 629 630
            }
        } else {
            println!("no current code");
        }
        
        println!("");
    }
    
qinsoon's avatar
qinsoon committed
631
    fn start_block(&mut self, block_name: MuName) {
632 633
        let label = format!("{}:", self.asm_block_label(block_name));        
        self.add_asm_block_label(label, block_name);
634 635 636 637 638 639
        self.cur_mut().blocks.push(block_name);
        
        let start = self.line();
        self.cur_mut().block_start.insert(block_name, start);
    }
    
qinsoon's avatar
qinsoon committed
640
    fn end_block(&mut self, block_name: MuName) {
641 642 643 644
        let start : usize = *self.cur().block_start.get(&block_name).unwrap();
        let end : usize = self.line();
        
        self.cur_mut().block_range.insert(block_name, (start..end));
645 646
    }
    
qinsoon's avatar
qinsoon committed
647
    fn set_block_livein(&mut self, block_name: MuName, live_in: &Vec<P<Value>>) {
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_livein.contains_key(&block_name) {
                cur.block_livein.insert(block_name, vec![]);
            } else {
                panic!("seems we are inserting livein to block {} twice", block_name);
            }
            
            cur.block_livein.get_mut(&block_name).unwrap()
        };
        
        for value in live_in {
            res.push(value.extract_ssa_id().unwrap());
        }
    }
    
qinsoon's avatar
qinsoon committed
665
    fn set_block_liveout(&mut self, block_name: MuName, live_out: &Vec<P<Value>>) {
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_liveout.contains_key(&block_name) {
                cur.block_liveout.insert(block_name, vec![]);
            } else {
                panic!("seems we are inserting livein to block {} twice", block_name);
            }
            
            cur.block_liveout.get_mut(&block_name).unwrap()
        };
        
        for value in live_out {
            match value.extract_ssa_id() {
                Some(id) => res.push(id),
                None => {}
            }
        }        
    }
    
686
    fn emit_cmp_r64_r64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
687
        trace!("emit: cmp {} {}", op1, op2);
688
        
689 690
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(op2, 4 + 1 + reg1.len() + 1);
691
        
qinsoon's avatar
qinsoon committed
692
        let asm = format!("cmpq {},{}", reg1, reg2);
693
        
694 695 696 697 698
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
699 700
            vec![loc1, loc2],
            false
701
        );
702 703
    }
    
qinsoon's avatar
qinsoon committed
704 705
    fn emit_cmp_r64_imm32(&mut self, op1: &P<Value>, op2: u32) {
        trace!("emit: cmp {} {}", op1, op2);
706
        
707
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1 + 1 + op2.to_string().len() + 1);
708
        
qinsoon's avatar
qinsoon committed
709
        let asm = format!("cmpq ${},{}", op2, reg1);
710
        
711 712 713 714 715
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1],
qinsoon's avatar
qinsoon committed
716 717
            vec![loc1],
            false
718
        )
719 720 721
    }
    
    fn emit_cmp_r64_mem64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
722
        trace!("emit: cmp {} {}", op1, op2);
723
        unimplemented!()
724 725
    }
    
qinsoon's avatar
qinsoon committed
726 727
    fn emit_mov_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: mov {} -> {}", src, dest);
728
        
729
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
730
        
qinsoon's avatar
qinsoon committed
731
        let asm = format!("movq ${},{}", src, reg1);
732
        
733 734 735
        self.add_asm_inst(
            asm,
            vec![id1],
736 737
            vec![loc1],
            vec![],
qinsoon's avatar
qinsoon committed
738 739
            vec![],
            false
740
        )
741 742 743
    }
    
    fn emit_mov_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
qinsoon's avatar
qinsoon committed
744
        trace!("emit: mov {} -> {}", src, dest);
745 746 747 748 749 750 751 752 753 754 755
        
        let (mem, id1, loc1) = self.prepare_mem(src, 4 + 1);
        let (reg, id2, loc2) = self.prepare_reg(dest, 4 + 1 + mem.len() + 1);
        
        let asm = format!("movq {},{}", mem, reg);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2],
            id1,
qinsoon's avatar
qinsoon committed
756 757
            loc1,
            true
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
        )
    }
    
    fn emit_mov_mem64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
        
        let (reg, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (mem, mut id2, mut loc2) = self.prepare_mem(dest, 4 + 1 + reg.len() + 1);
        
        // the register we used for the memory location is counted as 'use'
        id2.push(id1);
        loc2.push(loc1);
        
        let asm = format!("movq {},{}", reg, mem);
        
        self.add_asm_inst(
            asm,
            vec![], // not defining anything (write to memory)
            vec![],
            id2,
qinsoon's avatar
qinsoon committed
778 779
            loc2,
            true
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
        )
    }
    
    fn emit_mov_mem64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: mov {} -> {}", src, dest);
        
        let (mem, id, loc) = self.prepare_mem(dest, 4 + 1 + 1 + src.to_string().len() + 1);
        
        let asm = format!("movq ${},{}", src, mem);
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            id,
qinsoon's avatar
qinsoon committed
795 796
            loc,
            true
797
        )
qinsoon's avatar
qinsoon committed
798 799 800 801
    }
    
    fn emit_mov_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
802
        
803 804
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
805
        
qinsoon's avatar
qinsoon committed
806
        let asm = format!("movq {},{}", reg1, reg2);
807
        
808 809 810
        self.add_asm_inst(
            asm,
            vec![id2],
811 812
            vec![loc2],
            vec![id1],
qinsoon's avatar
qinsoon committed
813 814
            vec![loc1],
            false
815
        )
qinsoon's avatar
qinsoon committed
816 817 818 819
    }
    
    fn emit_add_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
820
        
821 822
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
823
        
qinsoon's avatar
qinsoon committed
824
        let asm = format!("addq {},{}", reg1, reg2);
825
        
826 827
        self.add_asm_inst(
            asm,
828 829
            vec![id2],
            vec![loc2.clone()],
830
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
831 832
            vec![loc1, loc2],
            false
833
        )
qinsoon's avatar
qinsoon committed
834 835 836 837
    }
    
    fn emit_add_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
838
        unimplemented!()
qinsoon's avatar
qinsoon committed
839 840 841 842
    }
    
    fn emit_add_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
843
        
844
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1);
845
        
qinsoon's avatar
qinsoon committed
846
        let asm = format!("addq {},${}", src, reg1);
847
        
848 849 850 851 852
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
853 854
            vec![loc1],
            false
855
        )
qinsoon's avatar
qinsoon committed
856 857 858 859
    }
    
    fn emit_sub_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
860
        
861 862
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
863
        
qinsoon's avatar
qinsoon committed
864
        let asm = format!("subq {},{}", reg1, reg2);
865
        
866 867
        self.add_asm_inst(
            asm,
868 869
            vec![id2],
            vec![loc2.clone()],
870
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
871 872
            vec![loc1, loc2],
            false
873
        )        
qinsoon's avatar
qinsoon committed
874 875 876 877
    }
    
    fn emit_sub_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
878
        unimplemented!()
qinsoon's avatar
qinsoon committed
879 880 881 882
    }
    
    fn emit_sub_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
883
        
884
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
885
        
qinsoon's avatar
qinsoon committed
886
        let asm = format!("subq ${},{}", src, reg1);
887
        
888 889 890 891 892
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
893 894
            vec![loc1],
            false
895
        )        
qinsoon's avatar
qinsoon committed
896 897
    }
    
898
    fn emit_mul_r64(&mut self, src: &P<Value>) {
899
        trace!("emit: mul rax, {} -> (rdx, rax)", src);
900
        
901
        let (reg, id, loc) = self.prepare_reg(src, 3 + 1);
902 903
        let rax = self.prepare_machine_reg(&x86_64::RAX);
        let rdx = self.prepare_machine_reg(&x86_64::RDX);
904 905 906
        
        let asm = format!("mul {}", reg);
        
907 908 909 910 911
        self.add_asm_inst(
            asm,
            vec![rax, rdx],
            vec![],
            vec![id, rax],
qinsoon's avatar
qinsoon committed
912 913
            vec![loc],
            false
914
        )
915 916 917 918
    }
    
    fn emit_mul_mem64(&mut self, src: &P<Value>) {
        trace!("emit: mul rax, {} -> rax", src);
919
        unimplemented!()
920 921
    }
    
qinsoon's avatar
qinsoon committed
922
    fn emit_jmp(&mut self, dest: &Block) {
923
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
924
        trace!("emit: jmp {}", dest_name);
925 926
        
        // symbolic label, we dont need to patch it
qinsoon's avatar
qinsoon committed
927 928
        let asm = format!("jmp {}", self.asm_block_label(dest_name));
        self.add_asm_branch(asm, dest_name)
qinsoon's avatar
qinsoon committed
929 930
    }
    
qinsoon's avatar
qinsoon committed
931
    fn emit_je(&mut self, dest: &Block) {
932
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
933
        trace!("emit: je {}", dest_name);
934
        
qinsoon's avatar
qinsoon committed
935 936
        let asm = format!("je {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
qinsoon's avatar
qinsoon committed
937 938
    }
    
qinsoon's avatar
qinsoon committed
939
    fn emit_jne(&mut self, dest: &Block) {
940
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
941
        trace!("emit: jne {}", dest_name);
942
        
qinsoon's avatar
qinsoon committed
943 944
        let asm = format!("jne {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);
qinsoon's avatar
qinsoon committed
945 946
    }
    
qinsoon's avatar
qinsoon committed
947
    fn emit_ja(&mut self, dest: &Block) {
948
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
949
        trace!("emit: ja {}", dest_name);
950
        
qinsoon's avatar
qinsoon committed
951 952
        let asm = format!("ja {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);
qinsoon's avatar
qinsoon committed
953 954
    }
    
qinsoon's avatar
qinsoon committed
955
    fn emit_jae(&mut self, dest: &Block) {
956
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
957
        trace!("emit: jae {}", dest_name);
958
        
qinsoon's avatar
qinsoon committed
959 960
        let asm = format!("jae {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
qinsoon's avatar
qinsoon committed
961 962
    }
    
qinsoon's avatar
qinsoon committed
963
    fn emit_jb(&mut self, dest: &Block) {
964
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
965
        trace!("emit: jb {}", dest_name);
966
        
qinsoon's avatar
qinsoon committed
967 968
        let asm = format!("jb {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);
qinsoon's avatar
qinsoon committed
969 970
    }
    
qinsoon's avatar
qinsoon committed
971
    fn emit_jbe(&mut self, dest: &Block) {
972
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
973
        trace!("emit: jbe {}", dest_name);
974
        
qinsoon's avatar
qinsoon committed
975 976
        let asm = format!("jbe {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
qinsoon's avatar
qinsoon committed
977 978
    }
    
qinsoon's avatar
qinsoon committed
979
    fn emit_jg(&mut self, dest: &Block) {
980
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
981
        trace!("emit: jg {}", dest_name);
982
        
qinsoon's avatar
qinsoon committed
983 984
        let asm = format!("jg {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
985 986
    }
    
qinsoon's avatar
qinsoon committed
987
    fn emit_jge(&mut self, dest: &Block) {
988
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
989
        trace!("emit: jge {}", dest_name);
990
        
qinsoon's avatar
qinsoon committed
991 992
        let asm = format!("jge {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
993 994
    }
    
qinsoon's avatar
qinsoon committed
995
    fn emit_jl(&mut self, dest: &Block) {
996
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
997
        trace!("emit: jl {}", dest_name);
998
        
qinsoon's avatar
qinsoon committed
999 1000
        let asm = format!("jl {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
1001 1002
    }
    
qinsoon's avatar
qinsoon committed
1003
    fn emit_jle(&mut self, dest: &Block) {
1004
        let dest_name = dest.name().unwrap();
qinsoon's avatar
qinsoon committed
1005
        trace!("emit: jle {}", dest_name);
1006
        
qinsoon's avatar
qinsoon committed
1007 1008
        let asm = format!("jle {}", self.asm_block_label(dest_name));
        self.add_asm_branch2(asm, dest_name);        
1009 1010
    }    
    
qinsoon's avatar
qinsoon committed
1011
    fn emit_call_near_rel32(&mut self, func: MuName) {
1012
        trace!("emit: call {}", func);
1013
        
qinsoon's avatar
qinsoon committed
1014
        let asm = format!("call {}", symbol(func));
1015
        self.add_asm_call(asm);
1016 1017
        
        // FIXME: call interferes with machine registers
1018 1019 1020 1021
    }
    
    fn emit_call_near_r64(&mut self, func: &P<Value>) {
        trace!("emit: call {}", func);
1022
        unimplemented!()
1023 1024 1025
    }
    
    fn emit_call_near_mem64(&mut self, func: &P<Value>) {
qinsoon's avatar
qinsoon committed
1026
        trace!("emit: call {}", func);
1027
        unimplemented!()
qinsoon's avatar
qinsoon committed
1028 1029 1030 1031
    }
    
    fn emit_ret(&mut self) {
        trace!("emit: ret");
1032 1033
        
        let asm = format!("ret");
1034
        self.add_asm_ret(asm);
1035
    }
1036
    
1037
    fn emit_push_r64(&mut self, src: &P<Value>) {
1038
        trace!("emit: push {}", src);
1039
        
1040
        let (reg, id, loc) = self.prepare_reg(src, 5 + 1);
1041
        let rsp = self.prepare_machine_reg(&x86_64::RSP);
1042 1043 1044
        
        let asm = format!("pushq {}", reg);
        
1045 1046
        self.add_asm_inst(
            asm,
1047
            vec![rsp],
1048 1049
            vec![],
            vec![id, rsp],
qinsoon's avatar
qinsoon committed
1050 1051
            vec![loc],
            false
1052
        )
1053 1054
    }
    
1055
    fn emit_pop_r64(&mut self, dest: &P<Value>) {
1056
        trace!("emit: pop {}", dest);
1057
        
1058
        let (reg, id, loc) = self.prepare_reg(dest, 4 + 1);
1059
        let rsp = self.prepare_machine_reg(&x86_64::RSP);
1060 1061 1062
        
        let asm = format!("popq {}", reg);
        
1063 1064
        self.add_asm_inst(
            asm,
1065
            vec![id, rsp],
1066
            vec![loc.clone()],
1067
            vec![rsp],
qinsoon's avatar
qinsoon committed
1068 1069
            vec![],
            false
1070
        )        
1071
    }    
1072
}
1073

qinsoon's avatar
qinsoon committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
const EMIT_DIR : &'static str = "emit";

fn create_emit_directory() {
    use std::fs;    
    match fs::create_dir(EMIT_DIR) {
        Ok(_) => {},
        Err(_) => {}
    }    
}

qinsoon's avatar
qinsoon committed
1084
pub fn emit_code(fv: &mut MuFunctionVersion, vm: &VM) {
1085 1086
    use std::io::prelude::*;
    use std::fs::File;
qinsoon's avatar
qinsoon committed
1087
    use std::path;
qinsoon's avatar
qinsoon committed
1088 1089 1090
    
    let funcs = vm.funcs().read().unwrap();
    let func = funcs.get(&fv.func_id).unwrap().borrow();
1091 1092

    let compiled_funcs = vm.compiled_funcs().read().unwrap();
1093
    let cf = compiled_funcs.get(&fv.id()).unwrap().borrow();
1094 1095 1096

    let code = cf.mc.emit();

qinsoon's avatar
qinsoon committed
1097 1098
    // create 'emit' directory
    create_emit_directory();
1099

qinsoon's avatar
qinsoon committed
1100 1101
    let mut file_path = path::PathBuf::new();
    file_path.push(EMIT_DIR);
1102
    file_path.push(func.name().unwrap().to_string() + ".s");
qinsoon's avatar
qinsoon committed
1103 1104
    let mut file = match File::create(file_path.as_path()) {
        Err(why) => panic!("couldn't create emission file {}: {}", file_path.to_str().unwrap(), why),
1105 1106 1107 1108
        Ok(file) => file
    };

    match file.write_all(code.as_slice()) {
qinsoon's avatar
qinsoon committed
1109 1110
        Err(why) => panic!("couldn'd write to file {}: {}", file_path.to_str().unwrap(), why),
        Ok(_) => println!("emit code to {}", file_path.to_str().unwrap())
1111 1112 1113
    }
}

qinsoon's avatar
qinsoon committed
1114
const CONTEXT_FILE : &'static str = "context.s";
qinsoon's avatar
qinsoon committed
1115
pub fn emit_context(vm: &VM) {
qinsoon's avatar
qinsoon committed
1116 1117 1118 1119
    use std::path;
    use std::fs::File;
    use std::io::prelude::*;
    
1120
    debug!("---Emit VM Context---");
qinsoon's avatar
qinsoon committed
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    create_emit_directory();
    
    let mut file_path = path::PathBuf::new();
    file_path.push(EMIT_DIR);
    file_path.push(CONTEXT_FILE);
    
    let mut file = match File::create(file_path.as_path()) {
        Err(why) => panic!("couldn't create context file {}: {}", file_path.to_str().unwrap(), why),
        Ok(file) => file
    };
    
    // put globals into bss section
    file.write_fmt(format_args!("\t.bss\n")).unwrap();
    
    let globals = vm.globals().read().unwrap();
qinsoon's avatar
qinsoon committed
1136
    for global in globals.values() {
1137
        debug!("emit global: {}", global);
qinsoon's avatar
qinsoon committed
1138
        let (size, align) = {
1139 1140 1141 1142 1143 1144 1145 1146 1147
            let alloc_ty = {
                match global.v {
                    Value_::Global(ref ty) => ty,
                    _ => panic!("expected a global")
                }
            };
            
            debug!("getting type: {:?}", alloc_ty);
            let ty_info = vm.get_backend_type_info(alloc_ty.id());
qinsoon's avatar
qinsoon committed
1148 1149 1150
            (ty_info.size, ty_info.alignment)
        };
        
1151 1152
        file.write_fmt(format_args!("\t{}\n", directive_globl(symbol(global.name().unwrap())))).unwrap();
        file.write_fmt(format_args!("\t{}\n", directive_comm(symbol(global.name().unwrap()), size, align))).unwrap();
qinsoon's avatar
qinsoon committed
1153 1154
        file.write("\n".as_bytes()).unwrap();
    }
1155 1156
    
    debug!("---finish---");
qinsoon's avatar
qinsoon committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
}

fn directive_globl(name: String) -> String {
    format!(".globl {}", name)
}

fn directive_comm(name: String, size: ByteSize, align: ByteSize) -> String {
    format!(".comm {},{},{}", name, size, align)
}

#[cfg(target_os = "linux")]
fn symbol(name: &str) -> String {
    name.to_string()
}

#[cfg(target_os = "macos")]
fn symbol(name: &str) -> String {
    format!("_{}", name)
qinsoon's avatar
qinsoon committed
1175
}