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

3
use compiler::backend;
4 5
use compiler::backend::AOT_EMIT_CONTEXT_FILE;
use compiler::backend::AOT_EMIT_DIR;
qinsoon's avatar
qinsoon committed
6
use compiler::backend::RegGroup;
qinsoon's avatar
qinsoon committed
7
use utils::ByteSize;
8
use compiler::backend::x86_64;
9
use compiler::backend::x86_64::CodeGenerator;
qinsoon's avatar
qinsoon committed
10
use compiler::machine_code::MachineCode;
qinsoon's avatar
qinsoon committed
11
use vm::VM;
qinsoon's avatar
qinsoon committed
12
use runtime::ValueLocation;
13

qinsoon's avatar
qinsoon committed
14
use utils::vec_utils;
15
use utils::string_utils;
16 17 18
use ast::ptr::P;
use ast::ir::*;

19 20
use std::collections::HashMap;
use std::str;
21
use std::usize;
22
use std::slice::Iter;
23
use std::ops;
24 25

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

qinsoon's avatar
qinsoon committed
49 50 51
unsafe impl Send for ASMCode {} 
unsafe impl Sync for ASMCode {}

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 107 108 109 110 111 112 113 114 115 116 117 118
impl ASMCode {
    fn rewrite_insert(
        &self,
        insert_before: HashMap<usize, Vec<Box<ASMCode>>>,
        insert_after: HashMap<usize, Vec<Box<ASMCode>>>) -> Box<ASMCode>
    {
        let mut ret = ASMCode {
            name: self.name.clone(),
            code: vec![],
            reg_defines: HashMap::new(),
            reg_uses: HashMap::new(),
            mem_op_used: HashMap::new(),
            preds: vec![],
            succs: vec![],
            idx_to_blk: HashMap::new(),
            blk_to_idx: HashMap::new(),
            cond_branches: HashMap::new(),
            branches: HashMap::new(),
            blocks: vec![],
            block_start: HashMap::new(),
            block_range: HashMap::new(),
            block_livein: HashMap::new(),
            block_liveout: HashMap::new()
        };

        // iterate through old machine code
        let mut inst_offset = 0;    // how many instructions has been inserted

        for i in 0..self.number_of_insts() {
            // insert code before this instruction
            if insert_before.contains_key(&i) {
                for insert in insert_before.get(&i).unwrap() {
                    ret.append_code_sequence_all(insert);
                    inst_offset += insert.number_of_insts();
                }
            }

            // copy this instruction


            // insert code after this instruction
            if insert_after.contains_key(&i) {

            }
        }

        unimplemented!()
    }

    fn append_code_sequence(
        &mut self,
        another: &Box<ASMCode>,
        start_inst: usize,
        n_insts: usize)
    {
        let self_index = self.number_of_insts();
        unimplemented!()
    }

    fn append_code_sequence_all(&mut self, another: &Box<ASMCode>) {
        let n_insts = another.number_of_insts();
        self.append_code_sequence(another, 0, n_insts)
    }
}

use std::any::Any;

119
impl MachineCode for ASMCode {
120 121 122
    fn as_any(&self) -> &Any {
        self
    }
123 124 125
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }
126
    
127 128 129 130 131 132 133 134
    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
135 136 137 138
    fn is_using_mem_op(&self, index: usize) -> bool {
        *self.mem_op_used.get(&index).unwrap()
    }
    
qinsoon's avatar
qinsoon committed
139 140 141 142 143 144 145 146
    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.succs[index]
    }
    
    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.preds[index]
    }
    
147
    fn get_inst_reg_uses(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
148
        &self.code[index].uses
149 150
    }
    
151
    fn get_inst_reg_defines(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
152
        &self.code[index].defines
153
    }
154
    
155
    fn replace_reg(&mut self, from: MuID, to: MuID) {
156 157 158 159
        let to_reg_tag : MuName = match backend::all_regs().get(&to) {
            Some(reg) => reg.name().unwrap(),
            None => panic!("expecting a machine register, but we are required to replace to {}", to)
        };
160
        let to_reg_string = "%".to_string() + &to_reg_tag;
161 162 163 164 165 166 167 168 169 170 171 172
        
        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 => {}
        }
173

174 175 176 177 178 179
        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());
180
                    }
181 182 183 184 185
                }
            },
            None => {}
        }
    }
186

187
    fn replace_tmp_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        let to_reg_string : MuName = match backend::all_regs().get(&to) {
            Some(ref machine_reg) => {
                let name = machine_reg.name().unwrap();
                "%".to_string() + &name
            },
            None => REG_PLACEHOLDER.clone()
        };

        {
            let asm = &mut self.code[inst];
            // if this reg is defined, replace the define
            if asm.defines.contains(&from) {
                vec_utils::remove_value(&mut asm.defines, from);
                asm.defines.push(to);
            }
            // if this reg is used, replace the use
            if asm.uses.contains(&from) {
                vec_utils::remove_value(&mut asm.uses, from);
                asm.uses.push(to);
            }
        }

        // replace the define
        // replace code
        match self.reg_defines.get(&from) {
            Some(defines) => {
                for loc in defines {
                    if loc.line == inst {
                        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 => {}
        }
        // replace info
        let replaced_define = match self.reg_defines.get_mut(&from) {
            Some(defines) => {
                Some(vec_utils::remove_value_if_true(defines, |x| {x.line == inst}))
            },
            None => None
        };
        match replaced_define {
            Some(mut defines) => {
                if self.reg_defines.contains_key(&to) {
                    self.reg_defines.get_mut(&to).unwrap().append(&mut defines);
                } else {
                    self.reg_defines.insert(to, defines);
                }
            }
            None => {}
        };

        // replace the use
        // replace code
        match self.reg_uses.get(&from) {
            Some(uses) => {
                for loc in uses {
                    if loc.line == inst {
                        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 => {}
        }
        // replace info
        let replaced_use = match self.reg_uses.get_mut(&from) {
            Some(uses) => {
                Some(vec_utils::remove_value_if_true(uses, |x| {x.line == inst}))
            },
            None => None
        };
        match replaced_use {
            Some(mut uses) => {
                if self.reg_uses.contains_key(&to) {
                    self.reg_uses.get_mut(&to).unwrap().append(&mut uses);
                } else {
                    self.reg_uses.insert(to, uses);
                }
            }
            None => {}
        };
    }
276
    
277
    fn set_inst_nop(&mut self, index: usize) {
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        // FIXME: changing these info is inefficient - plus we probably do not need to

        // remove any reg use of this instruction
        // clone the vec otherwise since we need to borrow 'self' again
        for reg in self.get_inst_reg_uses(index).to_vec() {
            let mut locs = self.reg_uses.get_mut(&reg).unwrap();
            let mut new_locs : Vec<ASMLocation> = vec![];

            while !locs.is_empty() {
                let loc = locs.pop().unwrap();
                if loc.line != index {
                    new_locs.push(loc);
                }
            }

            debug_assert!(locs.is_empty());
            locs.append(&mut new_locs);
        }

        // remove any reg define of this instruction
        for reg in self.get_inst_reg_defines(index).to_vec() {
            let mut locs = self.reg_defines.get_mut(&reg).unwrap();
            let mut new_locs : Vec<ASMLocation> = vec![];

            while !locs.is_empty() {
                let loc = locs.pop().unwrap();
                if loc.line != index {
                    new_locs.push(loc);
                }
            }

            debug_assert!(locs.is_empty());
            locs.append(&mut new_locs);
        }

        // nop doesnt use memop
        self.mem_op_used.insert(index, false);

316 317 318 319
        self.code.remove(index);
        self.code.insert(index, ASM::nop());
    }
    
320 321 322 323 324 325 326 327 328 329 330
    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
    }
    
331 332
    fn trace_mc(&self) {
        trace!("");
333

334 335
        trace!("code for {}: \n", self.name);
        
336 337
        let n_insts = self.code.len();
        for i in 0..n_insts {
338
            self.trace_inst(i);
339 340
        }
        
341 342 343 344 345 346 347
        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]);
348
    }
349
    
350 351
    fn get_ir_block_livein(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_livein.get(&block.to_string())
352 353
    }
    
354 355
    fn get_ir_block_liveout(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_liveout.get(&block.to_string())
356 357
    }
    
358 359 360 361 362 363 364 365
    fn set_ir_block_livein(&mut self, block: &str, set: Vec<MuID>) {
        self.block_livein.insert(block.to_string(), set);
    }
    
    fn set_ir_block_liveout(&mut self, block: &str, set: Vec<MuID>) {
        self.block_liveout.insert(block.to_string(), set);
    }
    
qinsoon's avatar
qinsoon committed
366
    fn get_all_blocks(&self) -> &Vec<MuName> {
367 368 369
        &self.blocks
    }
    
370 371
    fn get_block_range(&self, block: &str) -> Option<ops::Range<usize>> {
        match self.block_range.get(&block.to_string()) {
372 373 374 375
            Some(r) => Some(r.clone()),
            None => None
        }
    }
376 377 378 379 380 381
}

struct ASM {
    code: String,
    defines: Vec<MuID>,
    uses: Vec<MuID>
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
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![]
        }
    }
408 409 410 411 412 413 414 415
    
    fn nop() -> ASM {
        ASM {
            code: "".to_string(),
            defines: vec![],
            uses: vec![]
        }
    }
416 417
}

418
#[derive(Clone, Debug)]
419 420 421 422 423 424 425
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize
}

impl ASMLocation {
426 427
    /// the 'line' field will be updated later
    fn new(index: usize, len: usize) -> ASMLocation {
428
        ASMLocation{
429
            line: usize::MAX,
430 431 432 433 434 435
            index: index,
            len: len
        }
    }
}

436
pub struct ASMCodeGen {
437
    cur: Option<Box<ASMCode>>
438 439
}

440
const REG_PLACEHOLDER_LEN : usize = 5;
441 442 443 444 445 446
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];
        
        format!("%{}", str::from_utf8(&blank_spaces).unwrap())
    };
447 448 449 450
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
451
        ASMCodeGen {
452
            cur: None
453 454 455 456 457 458 459 460 461 462 463
        }
    }
    
    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }
    
    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }
    
464 465 466 467
    fn line(&self) -> usize {
        self.cur().code.len()
    }
    
468 469 470 471 472
    fn add_asm_label(&mut self, code: String) {
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
473
    fn add_asm_block_label(&mut self, code: String, block_name: MuName) {
474 475 476
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
        
477
        self.cur_mut().idx_to_blk.insert(l, block_name.clone());
478 479 480
        self.cur_mut().blk_to_idx.insert(block_name, l);
    }
    
481 482 483 484
    fn add_asm_symbolic(&mut self, code: String){
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
485 486 487 488
    fn prepare_machine_regs(&self, regs: Iter<P<Value>>) -> Vec<MuID> {
        regs.map(|x| self.prepare_machine_reg(x)).collect()
    } 
    
489
    fn add_asm_call(&mut self, code: String) {
qinsoon's avatar
qinsoon committed
490
        // a call instruction will use all the argument registers
491 492
        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()));
qinsoon's avatar
qinsoon committed
493 494

        // defines: return registers
495 496
        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
497 498 499
        // defines: caller saved registers
        vec_utils::append_unique(&mut defines, &mut self.prepare_machine_regs(x86_64::CALLER_SAVED_GPRs.iter()));
        vec_utils::append_unique(&mut defines, &mut self.prepare_machine_regs(x86_64::CALLER_SAVED_FPRs.iter()));
500
          
qinsoon's avatar
qinsoon committed
501
        self.add_asm_inst(code, defines, vec![], uses, vec![], false);
502 503 504
    }
    
    fn add_asm_ret(&mut self, code: String) {
505 506 507
        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
508
        self.add_asm_inst(code, vec![], vec![], uses, vec![], false);
509 510
    }
    
511
    fn add_asm_branch(&mut self, code: String, target: MuName) {
512 513
        let l = self.line();
        self.cur_mut().branches.insert(l, target);
qinsoon's avatar
qinsoon committed
514 515
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
516 517
    }
    
518
    fn add_asm_branch2(&mut self, code: String, target: MuName) {
519 520
        let l = self.line();
        self.cur_mut().cond_branches.insert(l, target);
qinsoon's avatar
qinsoon committed
521 522
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
523 524 525 526 527 528
    }
    
    fn add_asm_inst(
        &mut self, 
        code: String, 
        defines: Vec<MuID>,
529
        mut define_locs: Vec<ASMLocation>, 
530
        uses: Vec<MuID>,
qinsoon's avatar
qinsoon committed
531 532
        mut use_locs: Vec<ASMLocation>,
        is_using_mem_op: bool) 
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
        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) {
564
                mc.reg_uses.get_mut(&id).unwrap().push(loc.clone());
565
            } else {
566
                mc.reg_uses.insert(id, vec![loc.clone()]);
567 568
            }
        }
569
       
570 571
        // put the instruction
        mc.code.push(ASM::inst(code, defines, uses));
qinsoon's avatar
qinsoon committed
572
        mc.mem_op_used.insert(line, is_using_mem_op);
573 574 575 576
    }
    
    fn define_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
577
        
578 579 580 581 582 583 584
        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]);
        } 
585 586 587 588 589 590
    }
    
    fn use_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
        
        let code = self.cur_mut();
591 592 593
        if code.reg_uses.contains_key(&id) {
            let reg_uses = code.reg_uses.get_mut(&id).unwrap();
            reg_uses.push(loc);
594
        } else {
595
            code.reg_uses.insert(id, vec![loc]);
596 597 598
        } 
    }
    
599
    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
600 601 602 603 604 605 606
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting register op")
            }
        }
        
607 608 609 610 611 612
        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 {
613 614 615 616 617 618 619
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting machine register op")
            }
        }        
        
620
        op.extract_ssa_id().unwrap()
621
    }
622
    
623 624
    #[allow(unused_assignments)]
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, Vec<MuID>, Vec<ASMLocation>) {
625 626 627 628 629 630 631
        if cfg!(debug_assertions) {
            match op.v {
                Value_::Memory(_) => {},
                _ => panic!("expecting register op")
            }
        }        
        
632 633 634 635
        let mut ids : Vec<MuID> = vec![];
        let mut locs : Vec<ASMLocation> = vec![];
        let mut result_str : String = "".to_string();
        
636
        let mut loc_cursor : usize = loc;
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 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
        
        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;
            },
719 720
            Value_::Memory(MemoryLocation::Symbolic{ref base, ref label}) => {
                result_str.push_str(&symbol(label.clone()));
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
                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)
    }
    
743 744
    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
qinsoon's avatar
qinsoon committed
745
        if id < MACHINE_ID_END {
746
            // machine reg
747
            format!("%{}", op.name().unwrap())
748 749 750 751 752 753
        } else {
            // virtual register, use place holder
            REG_PLACEHOLDER.clone()
        }
    }
    
qinsoon's avatar
qinsoon committed
754
    fn asm_block_label(&self, label: MuName) -> String {
755
        symbol(format!("{}_{}", self.cur().name, label))
756
    }
757 758 759 760 761 762 763 764 765 766 767 768 769 770
    
    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 {
771 772
                    trace!("inst {}: not a block start", i);
                    trace!("inst {}: set PREDS as previous inst {}", i, i-1);
773 774 775 776 777 778 779 780 781 782 783 784
                    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();
785 786
                trace!("inst {}: is a branch to {}", i, target);
                                
787
                let target_n = code.blk_to_idx.get(target).unwrap();
788
                trace!("inst {}: branch target index is {}", i, target_n);
789 790
                
                // cur inst's succ is target
791
                trace!("inst {}: set SUCCS as branch target {}", i, target_n);
792 793 794
                code.succs[i].push(*target_n);
                
                // target's pred is cur
795
                trace!("inst {}: set PREDS as branch source {}", target_n, i);
796 797 798 799 800 801
                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();
802 803
                    trace!("inst {}: is a cond branch to {}", i, target);
                    
804
                    let target_n = code.blk_to_idx.get(target).unwrap();
805
                    trace!("inst {}: branch target index is {}", i, target_n);
806 807 808
                    
                    // cur insts' succ is target and next inst
                    code.succs[i].push(*target_n);
809
                    trace!("inst {}: set SUCCS as branch target {}", i, target_n);
810
                    if i < n_insts - 1 {
811
                        trace!("inst {}: set SUCCS as next inst", i + 1);                        
812 813 814 815 816
                        code.succs[i].push(i + 1);
                    }
                    
                    // target's pred is cur
                    code.preds[*target_n].push(i);
817
                    trace!("inst {}: set PREDS as {}", *target_n, i);
818 819
                } else {
                    // not branch nor cond branch, succ is next inst
820
                    trace!("inst {}: not a branch inst", i);
821
                    if i < n_insts - 1 {
822
                        trace!("inst {}: set SUCCS as next inst {}", i, i + 1);
823 824 825 826 827 828 829 830 831 832 833 834 835
                        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);
            }
        }        
    }
836 837 838 839

    fn finish_code_sequence_asm(&mut self) -> Box<ASMCode> {
        self.cur.take().unwrap()
    }
840 841 842
}

impl CodeGenerator for ASMCodeGen {
qinsoon's avatar
qinsoon committed
843
    fn start_code(&mut self, func_name: MuName) -> ValueLocation {
844
        self.cur = Some(Box::new(ASMCode {
845
                name: func_name.clone(),
846
                code: vec![],
847
                reg_defines: HashMap::new(),
848 849
                reg_uses: HashMap::new(),
                
qinsoon's avatar
qinsoon committed
850 851
                mem_op_used: HashMap::new(),
                
852 853 854 855 856 857
                preds: vec![],
                succs: vec![],
                
                idx_to_blk: HashMap::new(),
                blk_to_idx: HashMap::new(),
                cond_branches: HashMap::new(),
858 859
                branches: HashMap::new(),
                
860 861 862 863
                blocks: vec![],
                block_start: HashMap::new(),
                block_range: HashMap::new(),
                
864 865
                block_livein: HashMap::new(),
                block_liveout: HashMap::new()
866
            }));
867
        
qinsoon's avatar
qinsoon committed
868
        // to link with C sources via gcc
qinsoon's avatar
qinsoon committed
869 870 871 872
        let func_symbol = symbol(func_name.clone());
        self.add_asm_symbolic(directive_globl(func_symbol.clone()));
        self.add_asm_symbolic(format!("{}:", func_symbol.clone()));
        
873
        ValueLocation::Relocatable(RegGroup::GPR, func_name)
874 875
    }
    
876
    fn finish_code(&mut self, func_name: MuName) -> (Box<MachineCode + Sync + Send>, ValueLocation) {
877 878
        let func_end = {
            let mut symbol = func_name.clone();
qinsoon's avatar
qinsoon committed
879 880 881
            symbol.push_str("_end");
            symbol
        };
882 883
        self.add_asm_symbolic(directive_globl(symbol(func_end.clone())));
        self.add_asm_symbolic(format!("{}:", symbol(func_end.clone())));
qinsoon's avatar
qinsoon committed
884
        
885
        self.control_flow_analysis();
qinsoon's avatar
qinsoon committed
886 887 888
        
        (
            self.cur.take().unwrap(),
889
            ValueLocation::Relocatable(RegGroup::GPR, func_end)
qinsoon's avatar
qinsoon committed
890
        )
891
    }
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

    fn start_code_sequence(&mut self) {
        self.cur = Some(Box::new(ASMCode {
            name: "snippet".to_string(),
            code: vec![],
            reg_defines: HashMap::new(),
            reg_uses: HashMap::new(),

            mem_op_used: HashMap::new(),

            preds: vec![],
            succs: vec![],

            idx_to_blk: HashMap::new(),
            blk_to_idx: HashMap::new(),
            cond_branches: HashMap::new(),
            branches: HashMap::new(),

            blocks: vec![],
            block_start: HashMap::new(),
            block_range: HashMap::new(),

            block_livein: HashMap::new(),
            block_liveout: HashMap::new()
        }));
    }

    fn finish_code_sequence(&mut self) -> Box<MachineCode + Sync + Send> {
920
        self.finish_code_sequence_asm()
921 922
    }

923 924 925 926 927 928 929
    fn print_cur_code(&self) {
        println!("");
        
        if self.cur.is_some() {
            let code = self.cur.as_ref().unwrap();
            
            println!("code for {}: ", code.name);
930 931 932 933
            let n_insts = code.code.len();
            for i in 0..n_insts {
                let ref line = code.code[i];
                println!("#{}\t{}", i, line.code);
934 935 936 937 938 939 940 941
            }
        } else {
            println!("no current code");
        }
        
        println!("");
    }
    
qinsoon's avatar
qinsoon committed
942
    fn start_block(&mut self, block_name: MuName) {
943 944 945
        let label = format!("{}:", self.asm_block_label(block_name.clone()));        
        self.add_asm_block_label(label, block_name.clone());
        self.cur_mut().blocks.push(block_name.clone());
946 947 948 949 950
        
        let start = self.line();
        self.cur_mut().block_start.insert(block_name, start);
    }
    
qinsoon's avatar
qinsoon committed
951
    fn start_exception_block(&mut self, block_name: MuName) -> ValueLocation {
952 953 954
        let block = self.asm_block_label(block_name.clone());
        self.add_asm_symbolic(directive_globl(symbol(block.clone())));
        self.add_asm_symbolic(format!("{}:", symbol(block.clone())));
qinsoon's avatar
qinsoon committed
955 956 957
        
        self.start_block(block_name);
        
958
        ValueLocation::Relocatable(RegGroup::GPR, block)
qinsoon's avatar
qinsoon committed
959 960
    }
    
qinsoon's avatar
qinsoon committed
961
    fn end_block(&mut self, block_name: MuName) {
962 963 964 965
        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));
966 967
    }
    
qinsoon's avatar
qinsoon committed
968
    fn set_block_livein(&mut self, block_name: MuName, live_in: &Vec<P<Value>>) {
969 970 971 972
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_livein.contains_key(&block_name) {
973
                cur.block_livein.insert(block_name.clone(), vec![]);
974 975 976 977 978 979 980 981 982 983 984 985
            } 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
986
    fn set_block_liveout(&mut self, block_name: MuName, live_out: &Vec<P<Value>>) {
987 988 989 990
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_liveout.contains_key(&block_name) {
991
                cur.block_liveout.insert(block_name.clone(), vec![]);
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
            } 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 => {}
            }
        }        
    }
    
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    fn emit_nop(&mut self, bytes: usize) {
        trace!("emit: nop ({} bytes)", bytes);
        
        let asm = String::from("nop");
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![],
            vec![],
            false
        );
    }
    
1022
    fn emit_cmp_r64_r64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
1023
        trace!("emit: cmp {} {}", op1, op2);
1024
        
1025 1026
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(op2, 4 + 1 + reg1.len() + 1);
1027
        
qinsoon's avatar
qinsoon committed
1028
        let asm = format!("cmpq {},{}", reg1, reg2);
1029
        
1030 1031 1032 1033 1034
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
1035 1036
            vec![loc1, loc2],
            false
1037
        );
1038 1039
    }
    
1040
    fn emit_cmp_r64_imm32(&mut self, op1: &P<Value>, op2: i32) {
qinsoon's avatar
qinsoon committed
1041
        trace!("emit: cmp {} {}", op1, op2);
1042
        
1043
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1 + 1 + op2.to_string().len() + 1);
1044
        
qinsoon's avatar
qinsoon committed
1045
        let asm = format!("cmpq ${},{}", op2, reg1);
1046
        
1047 1048 1049 1050 1051
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1],
qinsoon's avatar
qinsoon committed
1052 1053
            vec![loc1],
            false
1054
        )
1055 1056 1057
    }
    
    fn emit_cmp_r64_mem64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
1058
        trace!("emit: cmp {} {}", op1, op2);
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        
        let (reg, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (mem, mut id2, mut loc2) = self.prepare_mem(op2, 4 + 1 + reg.len() + 1);
        
        let asm = format!("cmpq {},{}", reg, mem);
        
        // merge use vec
        id2.push(id1);
        loc2.push(loc1);
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            id2,
            loc2,
            true
        )
1077 1078
    }
    
1079
    fn emit_mov_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1080
        trace!("emit: mov {} -> {}", src, dest);
1081
        
1082
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1083
        
qinsoon's avatar
qinsoon committed
1084
        let asm = format!("movq ${},{}", src, reg1);
1085
        
1086 1087 1088
        self.add_asm_inst(
            asm,
            vec![id1],
1089 1090
            vec![loc1],
            vec![],
qinsoon's avatar
qinsoon committed
1091 1092
            vec![],
            false
1093
        )
1094 1095
    }
    
1096
    // load
1097
    fn emit_mov_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
qinsoon's avatar
qinsoon committed
1098
        trace!("emit: mov {} -> {}", src, dest);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        
        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
1110 1111
            loc1,
            true
1112 1113 1114
        )
    }
    
1115
    // store
1116 1117 1118 1119 1120 1121 1122
    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'
1123
        // use the vec from mem as 'use' (push use reg from src to it)
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        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
1134 1135
            loc2,
            true
1136 1137 1138
        )
    }
    
1139
    fn emit_mov_mem64_imm32(&mut self, dest: &P<Value>, src: i32) {
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
        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
1151 1152
            loc,
            true
1153
        )
qinsoon's avatar
qinsoon committed
1154 1155 1156 1157
    }
    
    fn emit_mov_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
1158
        
1159 1160
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1161
        
qinsoon's avatar
qinsoon committed
1162
        let asm = format!("movq {},{}", reg1, reg2);
1163
        
1164 1165 1166
        self.add_asm_inst(
            asm,
            vec![id2],
1167 1168
            vec![loc2],
            vec![id1],
qinsoon's avatar
qinsoon committed
1169 1170
            vec![loc1],
            false
1171
        )
qinsoon's avatar
qinsoon committed
1172 1173 1174 1175
    }
    
    fn emit_add_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1176
        
1177 1178
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1179
        
qinsoon's avatar
qinsoon committed
1180
        let asm = format!("addq {},{}", reg1, reg2);
1181
        
1182 1183
        self.add_asm_inst(
            asm,
1184 1185
            vec![id2],
            vec![loc2.clone()],
1186
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
1187 1188
            vec![loc1, loc2],
            false
1189
        )
qinsoon's avatar
qinsoon committed
1190 1191
    }
    
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    fn emit_lea_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: lea {} -> {}", src, dest);
        
        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!("leaq {},{}", mem, reg);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2],
            id1,
            loc1,
            true
        ) 
    }
    
1210
    fn emit_and_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
        trace!("emit: and {}, {} -> {}", src, dest, dest);
        
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);

        let asm = format!("andq ${},{}", src, reg1);
        
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
            vec![loc1],
            false
        )
    }
    
    fn emit_and_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: and {}, {} -> {}", src, dest, dest);
        
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1); 

        let asm = format!("andq {},{}", reg1, reg2);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2.clone()],
            vec![id1, id2],
            vec![loc1, loc2],
            false
        )
    }    
    
qinsoon's avatar
qinsoon committed
1245 1246
    fn emit_add_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1247
        unimplemented!()
qinsoon's avatar
qinsoon committed
1248 1249
    }
    
1250
    fn emit_add_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1251
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1252
        
1253
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1254
        
1255
        let asm = format!("addq ${},{}", src, reg1);
1256
        
1257 1258 1259 1260 1261
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
1262 1263
            vec![loc1],
            false
1264
        )
qinsoon's avatar
qinsoon committed
1265 1266 1267 1268
    }
    
    fn emit_sub_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1269
        
1270 1271
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1272
        
qinsoon's avatar
qinsoon committed
1273
        let asm = format!("subq {},{}", reg1, reg2);
1274
        
1275 1276
        self.add_asm_inst(
            asm,
1277 1278
            vec![id2],
            vec![loc2.clone()],
1279
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
1280 1281
            vec![loc1, loc2],
            false
1282
        )        
qinsoon's avatar
qinsoon committed
1283 1284 1285 1286
    }
    
    fn emit_sub_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1287
        unimplemented!()
qinsoon's avatar
qinsoon committed
1288 1289
    }
    
1290
    fn emit_sub_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1291
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1292
        
1293
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1294
        
qinsoon's avatar
qinsoon committed
1295
        let asm = format!("subq ${},{}", src, reg1);
1296
        
1297 1298 1299 1300 1301
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
1302 1303
            vec![loc1],
            false
1304
        )        
qinsoon's avatar
qinsoon committed
1305 1306
    }
    
1307
    fn emit_mul_r64(&mut self, src: &P<Value>) {
1308
        trace!("emit: mul rax, {} -> (rdx, rax)", src);
1309
        
1310
        let (reg, id, loc) = self.prepare_reg(src, 3 + 1);
1311 1312
        let rax = self.prepare_machine_reg(&x86_64::RAX);
        let rdx = self.prepare_machine_reg(&x86_64::RDX);
1313 1314 1315
        
        let asm = format!("mul {}", reg);
        
1316 1317 1318 1319 1320
        self.add_asm_inst(
            asm,
            vec![rax, rdx],
            vec![],
            vec![id, rax],
qinsoon's avatar
qinsoon committed
1321 1322
            vec![loc],
            false
1323
        )
1324 1325 1326 1327
    }
    
    fn emit_mul_mem64(&mut self, src: &P<Value>) {
        trace!("emit: mul rax, {} -> rax", src);
1328
        unimplemented!()
1329 1330
    }