asm_backend.rs 137 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
// Copyright 2017 The Australian National University
2
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
use compiler::backend::aarch64::*;
16
use compiler::backend::RegGroup;
17 18
use compiler::backend::AOT_EMIT_CONTEXT_FILE;
use runtime::mm::*;
19
use utils::Address;
20
use utils::ByteSize;
21 22
use utils::POINTER_SIZE;

23
use compiler::backend::{Mem, Reg};
24 25
use compiler::machine_code::MachineCode;
use runtime::ValueLocation;
26
use vm::VM;
27 28

use utils::string_utils;
29
use utils::vec_utils;
30 31 32
use utils::LinkedHashMap;

use ast::ir::*;
33
use ast::ptr::P;
34
use ast::types;
35

36
use std::collections::HashSet;
37
use std::io::Write;
38 39 40 41
use std::ops;
use std::str;
use std::sync::RwLock;
use std::usize;
42

43 44 45 46 47
macro_rules! trace_emit {
    ($arg1:tt $($arg:tt)*) => {
        trace!(concat!("emit: ", $arg1) $($arg)*)
    }
}
48 49 50 51
struct ASMCode {
    name: MuName,
    code: Vec<ASMInst>,

52
    entry: MuName,
53 54
    blocks: LinkedHashMap<MuName, ASMBlock>,

55
    frame_size_lower_patchpoints: Vec<ASMLocation>,
56
    frame_size_upper_patchpoints: Vec<ASMLocation>
57 58 59 60 61 62 63 64 65 66 67 68 69
}

unsafe impl Send for ASMCode {}
unsafe impl Sync for ASMCode {}

impl ASMCode {
    fn get_use_locations(&self, reg: MuID) -> Vec<ASMLocation> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            match inst.uses.get(&reg) {
                Some(ref locs) => {
                    ret.append(&mut locs.to_vec());
70
                }
71 72 73 74 75 76 77 78 79 80 81 82 83 84
                None => {}
            }
        }

        ret
    }

    fn get_define_locations(&self, reg: MuID) -> Vec<ASMLocation> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            match inst.defines.get(&reg) {
                Some(ref locs) => {
                    ret.append(&mut locs.to_vec());
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
                None => {}
            }
        }

        ret
    }

    fn is_block_start(&self, inst: usize) -> bool {
        for block in self.blocks.values() {
            if block.start_inst == inst {
                return true;
            }
        }
        false
    }

    fn is_last_inst_in_block(&self, inst: usize) -> bool {
        for block in self.blocks.values() {
            if block.end_inst == inst + 1 {
                return true;
            }
        }
        false
    }

111
    fn get_block_by_inst(&self, inst: usize) -> (&MuName, &ASMBlock) {
112 113 114 115 116 117 118 119 120 121 122 123
        for (name, block) in self.blocks.iter() {
            if inst >= block.start_inst && inst < block.end_inst {
                return (name, block);
            }
        }

        panic!("didnt find any block for inst {}", inst)
    }

    fn rewrite_insert(
        &self,
        insert_before: LinkedHashMap<usize, Vec<Box<ASMCode>>>,
124
        insert_after: LinkedHashMap<usize, Vec<Box<ASMCode>>>
125
    ) -> Box<ASMCode> {
126 127 128 129 130
        trace!("insert spilling code");
        let mut ret = ASMCode {
            name: self.name.clone(),
            entry: self.entry.clone(),
            code: vec![],
131
            blocks: linked_hashmap! {},
132
            frame_size_lower_patchpoints: vec![],
133
            frame_size_upper_patchpoints: vec![]
134 135 136
        };

        // iterate through old machine code
137
        let mut inst_offset = 0; // how many instructions has been inserted
138 139 140 141
        let mut cur_block_start = usize::MAX;

        // inst N in old machine code is N' in new machine code
        // this map stores the relationship
142 143
        let mut location_map: LinkedHashMap<usize, usize> =
            LinkedHashMap::new();
144 145 146 147 148 149 150 151 152 153 154 155 156 157

        for i in 0..self.number_of_insts() {
            trace!("Inst{}", i);

            if self.is_block_start(i) {
                cur_block_start = i + inst_offset;
                trace!("  block start is shifted to {}", cur_block_start);
            }

            // 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();
158 159 160 161
                    trace!(
                        "  inserted {} insts before",
                        insert.number_of_insts()
                    );
162 163 164 165 166 167 168 169 170 171
                }
            }

            // copy this instruction
            let mut inst = self.code[i].clone();

            // old ith inst is now the (i + inst_offset)th instruction
            location_map.insert(i, i + inst_offset);
            trace!("  Inst{} is now Inst{}", i, i + inst_offset);

172 173
            // this instruction has been offset by several
            // instructions('inst_offset') update its info
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
            // 1. fix defines and uses
            for locs in inst.defines.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line += inst_offset;
                }
            }
            for locs in inst.uses.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line += inst_offset;
                }
            }
            // 2. we need to delete existing preds/succs - CFA is required later
            inst.preds.clear();
            inst.succs.clear();
            // 3. add the inst
            ret.code.push(inst);

            // insert code after this instruction
            if insert_after.contains_key(&i) {
                for insert in insert_after.get(&i).unwrap() {
                    ret.append_code_sequence_all(insert);
                    inst_offset += insert.number_of_insts();
198 199 200 201
                    trace!(
                        "  inserted {} insts after",
                        insert.number_of_insts()
                    );
202 203 204 205 206 207 208 209 210
                }
            }

            if self.is_last_inst_in_block(i) {
                let cur_block_end = i + 1 + inst_offset;

                // copy the block
                let (name, block) = self.get_block_by_inst(i);

211
                let new_block = ASMBlock {
212 213 214 215
                    start_inst: cur_block_start,
                    end_inst: cur_block_end,

                    livein: vec![],
216
                    liveout: vec![]
217 218 219 220 221 222 223 224 225 226 227 228 229
                };

                trace!("  old block: {:?}", block);
                trace!("  new block: {:?}", new_block);

                cur_block_start = usize::MAX;

                // add to the new code
                ret.blocks.insert(name.clone(), new_block);
            }
        }

        // fix patchpoint
230
        for patchpoint in self.frame_size_lower_patchpoints.iter() {
231 232 233 234
            let new_patchpoint = ASMLocation {
                line: *location_map.get(&patchpoint.line).unwrap(),
                index: patchpoint.index,
                len: patchpoint.len,
235
                oplen: patchpoint.oplen
236 237
            };

238
            ret.frame_size_lower_patchpoints.push(new_patchpoint);
239 240
        }

241 242 243 244 245 246
        // fix patchpoint
        for patchpoint in self.frame_size_upper_patchpoints.iter() {
            let new_patchpoint = ASMLocation {
                line: *location_map.get(&patchpoint.line).unwrap(),
                index: patchpoint.index,
                len: patchpoint.len,
247
                oplen: patchpoint.oplen
248 249 250 251
            };

            ret.frame_size_upper_patchpoints.push(new_patchpoint);
        }
252 253 254 255 256
        ret.control_flow_analysis();

        Box::new(ret)
    }

257 258 259 260 261 262
    fn append_code_sequence(
        &mut self,
        another: &Box<ASMCode>,
        start_inst: usize,
        n_insts: usize
    ) {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        let base_line = self.number_of_insts();

        for i in 0..n_insts {
            let cur_line_in_self = base_line + i;
            let cur_line_from_copy = start_inst + i;

            let mut inst = another.code[cur_line_from_copy].clone();

            // fix info
            for locs in inst.defines.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line = cur_line_in_self;
                }
            }
            for locs in inst.uses.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line = cur_line_in_self;
                }
            }
            // ignore preds/succs

            // add to self
            self.code.push(inst);
        }
    }

    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)
    }

    fn control_flow_analysis(&mut self) {
297
        const TRACE_CFA: bool = true;
298 299 300 301 302 303 304

        // control flow analysis
        let n_insts = self.number_of_insts();

        let ref mut asm = self.code;

        for i in 0..n_insts {
305
            trace_if!(TRACE_CFA, "---inst {}---", i);
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

            // skip symbol
            if asm[i].is_symbol {
                continue;
            }

            // determine predecessor

            // we check if it is a fallthrough block
            if i != 0 {
                let last_inst = ASMCode::find_prev_inst(i, asm);

                match last_inst {
                    Some(last_inst) => {
                        let last_inst_branch = asm[last_inst].branch.clone();
                        match last_inst_branch {
322 323
                            // if it is a fallthrough, we set its preds as last
                            // inst
324 325 326 327
                            ASMBranchTarget::None => {
                                if !asm[i].preds.contains(&last_inst) {
                                    asm[i].preds.push(last_inst);

328 329 330 331 332 333
                                    trace_if!(
                                        TRACE_CFA,
                                        "inst {}: set PREDS as previous inst - fallthrough {}",
                                        i,
                                        last_inst
                                    );
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
                                }
                            }
                            // otherwise do nothing
                            _ => {}
                        }
                    }
                    None => {}
                }
            }

            // determine successor
            let branch = asm[i].branch.clone();
            match branch {
                ASMBranchTarget::Unconditional(ref target) => {
                    // branch to target
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur inst's succ is target
                    asm[i].succs.push(target_n);

                    // target's pred is cur
                    asm[target_n].preds.push(i);

357 358 359 360 361 362 363 364 365 366 367 368
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: is a branch to {}",
                        i,
                        target
                    );
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: branch target index is {}",
                        i,
                        target_n
                    );
369 370 371 372 373 374 375 376 377 378 379 380 381
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: set SUCCS as branch target {}",
                        i,
                        target_n
                    );
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: set PREDS as branch source {}",
                        target_n,
                        i
                    );
                }
382 383 384 385 386 387 388
                ASMBranchTarget::Conditional(ref target) => {
                    // branch to target
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur insts' succ is target
                    asm[i].succs.push(target_n);

389 390 391 392 393 394 395 396 397 398 399 400
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: is a cond branch to {}",
                        i,
                        target
                    );
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: branch target index is {}",
                        i,
                        target_n
                    );
401 402 403 404 405 406
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: set SUCCS as branch target {}",
                        i,
                        target_n
                    );
407 408 409

                    // target's pred is cur
                    asm[target_n].preds.push(i);
410 411 412 413 414 415
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: set PREDS as {}",
                        target_n,
                        i
                    );
416 417 418 419 420 421 422 423

                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
                        // cur succ is next inst
                        asm[i].succs.push(next_inst);

                        // next inst's pred is cur
                        asm[next_inst].preds.push(i);

424 425 426 427 428 429
                        trace_if!(
                            TRACE_CFA,
                            "inst {}: SET SUCCS as c-branch fallthrough target {}",
                            i,
                            next_inst
                        );
430 431 432
                    } else {
                        panic!("conditional branch does not have a fallthrough target");
                    }
433
                }
434
                ASMBranchTarget::PotentiallyExcepting(ref target) => {
435 436
                    // may trigger exception and jump to target - similar as
                    // conditional branch
437 438 439 440 441
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur inst's succ is target
                    asm[i].succs.push(target_n);

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: is potentially excepting to {}",
                        i,
                        target
                    );
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: excepting target index is {}",
                        i,
                        target_n
                    );
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: set SUCCS as excepting target {}",
                        i,
                        target_n
                    );
460 461 462 463 464 465 466 467 468 469

                    asm[target_n].preds.push(i);

                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
                        // cur succ is next inst
                        asm[i].succs.push(next_inst);

                        // next inst's pred is cur
                        asm[next_inst].preds.push(i);

470 471 472 473 474 475
                        trace_if!(
                            TRACE_CFA,
                            "inst {}: SET SUCCS as PEI fallthrough target {}",
                            i,
                            next_inst
                        );
476 477 478
                    } else {
                        panic!("PEI does not have a fallthrough target");
                    }
479
                }
480
                ASMBranchTarget::Return => {
481 482
                    trace_if!(TRACE_CFA, "inst {}: is a return", i);
                    trace_if!(TRACE_CFA, "inst {}: has no successor", i);
483 484 485
                }
                ASMBranchTarget::None => {
                    // not branch nor cond branch, succ is next inst
486
                    trace_if!(TRACE_CFA, "inst {}: not a branch inst", i);
487
                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
488 489 490 491 492 493
                        trace_if!(
                            TRACE_CFA,
                            "inst {}: set SUCCS as next inst {}",
                            i,
                            next_inst
                        );
494 495 496 497
                        asm[i].succs.push(next_inst);
                    }
                }
                ASMBranchTarget::UnconditionalReg(id) => {
498 499 500 501 502 503
                    trace_if!(
                        TRACE_CFA,
                        "inst {}: is an unconditional branch to reg {}",
                        i,
                        id
                    );
504
                    trace_if!(TRACE_CFA, "inst {}: has no successor", i);
505 506 507 508 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
                }
            }
        }
    }

    fn find_prev_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i == 0 {
            None
        } else {
            let mut cur = i - 1;
            while cur != 0 {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                if cur == 0 {
                    return None;
                } else {
                    cur -= 1;
                }
            }

            None
        }
    }

    fn find_next_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i >= asm.len() - 1 {
            None
        } else {
            let mut cur = i + 1;
            while cur < asm.len() {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                cur += 1;
            }

            None
        }
    }

    fn find_last_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i == 0 {
            None
        } else {
            let mut cur = i;
            loop {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                if cur == 0 {
                    return None;
                } else {
                    cur -= 1;
                }
            }
        }
    }

567 568 569 570 571
    fn add_frame_size_lower_patchpoint(&mut self, patchpoint: ASMLocation) {
        self.frame_size_lower_patchpoints.push(patchpoint);
    }
    fn add_frame_size_upper_patchpoint(&mut self, patchpoint: ASMLocation) {
        self.frame_size_upper_patchpoints.push(patchpoint);
572 573 574 575 576 577
    }
}

use std::any::Any;

impl MachineCode for ASMCode {
578 579 580 581 582 583 584 585
    fn is_nop(&self, index: usize) -> bool {
        let ref inst = self.code[index];
        if inst.code == "" || inst.code == "NOP" {
            true
        } else {
            false
        }
    }
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    fn as_any(&self) -> &Any {
        self
    }
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }

    fn is_move(&self, index: usize) -> bool {
        let inst = self.code.get(index);
        match inst {
            Some(inst) => {
                let ref inst = inst.code;

                if inst.starts_with("MOV ") || inst.starts_with("FMOV ") {
                    // normal mov
                    true
                } else {
                    false
                }
605
            }
606
            None => false
607 608 609 610 611 612 613 614 615 616
        }
    }

    fn is_using_mem_op(&self, index: usize) -> bool {
        self.code[index].is_mem_op_used
    }

    fn is_jmp(&self, index: usize) -> Option<MuName> {
        let inst = self.code.get(index);
        match inst {
617 618 619 620
            Some(inst)
                if inst.code.starts_with("B.")
                    || inst.code.starts_with("B ") =>
            {
621
                // Destination is the first argument
622
                let split: Vec<&str> = inst.code.split(' ').collect();
623
                Some(demangle_name(String::from(split[1])))
624
            }
625
            _ => None
626 627 628 629 630 631 632
        }
    }

    fn is_label(&self, index: usize) -> Option<MuName> {
        let inst = self.code.get(index);
        match inst {
            Some(inst) if inst.code.ends_with(':') => {
633
                let split: Vec<&str> = inst.code.split(':').collect();
634

635
                Some(demangle_name(String::from(split[0])))
636
            }
637
            _ => None
638 639 640 641 642 643 644
        }
    }

    fn is_spill_load(&self, index: usize) -> Option<P<Value>> {
        if let Some(inst) = self.code.get(index) {
            match inst.spill_info {
                Some(SpillMemInfo::Load(ref p)) => Some(p.clone()),
645
                _ => None
646 647 648 649 650 651 652 653 654 655
            }
        } else {
            None
        }
    }

    fn is_spill_store(&self, index: usize) -> Option<P<Value>> {
        if let Some(inst) = self.code.get(index) {
            match inst.spill_info {
                Some(SpillMemInfo::Store(ref p)) => Some(p.clone()),
656
                _ => None
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
            }
        } else {
            None
        }
    }

    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.code[index].succs
    }

    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.code[index].preds
    }

    fn get_inst_reg_uses(&self, index: usize) -> Vec<MuID> {
        self.code[index].uses.keys().map(|x| *x).collect()
    }

    fn get_inst_reg_defines(&self, index: usize) -> Vec<MuID> {
        self.code[index].defines.keys().map(|x| *x).collect()
    }

    fn replace_reg(&mut self, from: MuID, to: MuID) {
        for loc in self.get_define_locations(from) {
            let ref mut inst_to_patch = self.code[loc.line];

            // pick the right reg based on length
            let to_reg = get_alias_for_length(to, loc.oplen);
685
            let to_reg_string = to_reg.name();
686

687 688 689 690
            string_utils::replace(
                &mut inst_to_patch.code,
                loc.index,
                &to_reg_string,
691
                to_reg_string.len()
692
            );
693 694 695 696 697 698 699
        }

        for loc in self.get_use_locations(from) {
            let ref mut inst_to_patch = self.code[loc.line];

            // pick the right reg based on length
            let to_reg = get_alias_for_length(to, loc.oplen);
700
            let to_reg_string = to_reg.name();
701

702 703 704 705
            string_utils::replace(
                &mut inst_to_patch.code,
                loc.index,
                &to_reg_string,
706
                to_reg_string.len()
707
            );
708 709 710
        }
    }

711 712 713 714 715 716
    fn replace_define_tmp_for_inst(
        &mut self,
        from: MuID,
        to: MuID,
        inst: usize
    ) {
717
        let to_reg_string: MuName = REG_PLACEHOLDER.clone();
718 719 720 721 722 723 724

        let asm = &mut self.code[inst];
        // if this reg is defined, replace the define
        if asm.defines.contains_key(&from) {
            let define_locs = asm.defines.get(&from).unwrap().to_vec();
            // replace temps
            for loc in define_locs.iter() {
725 726 727 728
                string_utils::replace(
                    &mut asm.code,
                    loc.index,
                    &to_reg_string,
729
                    to_reg_string.len()
730
                );
731 732 733 734 735 736 737 738 739
            }

            // remove old key, insert new one
            asm.defines.remove(&from);
            asm.defines.insert(to, define_locs);
        }
    }

    fn replace_use_tmp_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
740
        let to_reg_string: MuName = REG_PLACEHOLDER.clone();
741 742 743 744 745 746 747 748

        let asm = &mut self.code[inst];

        // if this reg is used, replace the use
        if asm.uses.contains_key(&from) {
            let use_locs = asm.uses.get(&from).unwrap().to_vec();
            // replace temps
            for loc in use_locs.iter() {
749 750 751 752
                string_utils::replace(
                    &mut asm.code,
                    loc.index,
                    &to_reg_string,
753
                    to_reg_string.len()
754
                );
755 756 757 758 759 760 761 762
            }

            // remove old key, insert new one
            asm.uses.remove(&from);
            asm.uses.insert(to, use_locs);
        }
    }

763 764 765 766 767 768 769
    fn replace_branch_dest(
        &mut self,
        inst: usize,
        old_succ: usize,
        new_dest: &str,
        succ: usize
    ) {
770 771 772
        {
            let asm = &mut self.code[inst];

773 774 775 776 777 778 779
            let inst =
                String::from(asm.code.split_whitespace().next().unwrap());
            asm.code = format!(
                "{} {}",
                inst,
                mangle_name(Arc::new(new_dest.to_string()))
            );
780
            asm.succs.retain(|&x| x != old_succ);
781 782 783 784 785 786 787 788 789 790 791
            asm.succs.push(succ);
        }
        {
            let asm = &mut self.code[succ];

            if !asm.preds.contains(&inst) {
                asm.preds.push(inst);
            }
        }
    }

792
    fn set_inst_nop(&mut self, index: usize) {
793
        self.code[index].code.clear();
794 795
    }

796 797 798 799
    fn remove_unnecessary_callee_saved(
        &mut self,
        used_callee_saved: Vec<MuID>
    ) -> HashSet<MuID> {
800
        // every push pair (STP)/and pop pair (LDP) will use/define SP
801
        let fp = FP.extract_ssa_id().unwrap();
802

803 804
        // Note: this version assumes only 1 callee is pushed or poped
        let find_op_other_than_fp = |inst: &ASMInst| -> MuID {
805
            for id in inst.defines.keys() {
806 807
                if *id != fp {
                    return *id;
808 809 810
                }
            }
            for id in inst.uses.keys() {
811 812
                if *id != fp {
                    return *id;
813 814 815
                }
            }

816
            panic!("Expected to find a used register other than the FP");
817 818 819
        };

        let mut inst_to_remove = vec![];
820
        let mut regs_to_remove = HashSet::new();
821 822 823 824

        for i in 0..self.number_of_insts() {
            let ref inst = self.code[i];

825 826 827 828 829 830
            match inst.spill_info {
                Some(SpillMemInfo::CalleeSaved) => {
                    let reg = find_op_other_than_fp(inst);
                    if !used_callee_saved.contains(&reg) {
                        inst_to_remove.push(i);
                        regs_to_remove.insert(reg);
831 832
                    }
                }
833
                _ => {}
834 835 836 837 838 839
            }
        }

        for i in inst_to_remove {
            self.set_inst_nop(i);
        }
840
        regs_to_remove
841 842
    }

843
    fn patch_frame_size(&mut self, size: usize) {
844
        debug_assert!(size % 16 == 0);
845 846 847 848
        let size = size as u64;
        let lower_size = (size & bits_ones(12)).to_string();
        let upper_size = (size >> 12).to_string();
        assert!(size <= bits_ones(24)); // Maximum frame size (16 MiB - 1B)
849

850
        for loc in self.frame_size_lower_patchpoints.iter() {
851
            let ref mut inst = self.code[loc.line];
852 853 854 855 856 857
            if size & bits_ones(12) == 0 {
                //self.set_inst_nop(loc.line);
                inst.code.clear();
                inst.defines.clear();
                inst.uses.clear();
            } else {
858 859 860 861 862 863
                string_utils::replace(
                    &mut inst.code,
                    loc.index,
                    &lower_size,
                    lower_size.len()
                );
864 865 866 867 868 869 870 871 872
            }
        }
        for loc in self.frame_size_upper_patchpoints.iter() {
            let ref mut inst = self.code[loc.line];
            if size >> 12 == 0 {
                inst.code.clear();
                inst.defines.clear();
                inst.uses.clear();
            } else {
873 874 875 876 877 878
                string_utils::replace(
                    &mut inst.code,
                    loc.index,
                    &upper_size,
                    upper_size.len()
                );
879
            }
880 881 882 883 884 885 886 887 888 889 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 920 921 922 923 924 925
        }
    }

    fn emit(&self) -> Vec<u8> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            if !inst.is_symbol {
                ret.append(&mut "\t".to_string().into_bytes());
            }

            ret.append(&mut inst.code.clone().into_bytes());
            ret.append(&mut "\n".to_string().into_bytes());
        }

        ret
    }

    fn emit_inst(&self, index: usize) -> Vec<u8> {
        let mut ret = vec![];

        let ref inst = self.code[index];

        if !inst.is_symbol {
            ret.append(&mut "\t".to_string().into_bytes());
        }

        ret.append(&mut inst.code.clone().into_bytes());

        ret
    }

    fn trace_mc(&self) {
        trace!("");

        trace!("code for {}: \n", self.name);

        let n_insts = self.code.len();
        for i in 0..n_insts {
            self.trace_inst(i);
        }

        trace!("")
    }

    fn trace_inst(&self, i: usize) {
926 927 928
        trace!(
            "#{}\t{:30}\t\tdefine: {:?}\tuses: {:?}\tpred: {:?}\tsucc: {:?}",
            i,
929
            demangle_text(&self.code[i].code),
930 931 932 933 934
            self.get_inst_reg_defines(i),
            self.get_inst_reg_uses(i),
            self.code[i].preds,
            self.code[i].succs
        );
935 936 937
    }

    fn get_ir_block_livein(&self, block: &str) -> Option<&Vec<MuID>> {
938
        match self.blocks.get(&block.to_string()) {
939
            Some(ref block) => Some(&block.livein),
940
            None => None
941 942 943 944
        }
    }

    fn get_ir_block_liveout(&self, block: &str) -> Option<&Vec<MuID>> {
945
        match self.blocks.get(&block.to_string()) {
946
            Some(ref block) => Some(&block.liveout),
947
            None => None
948 949 950 951
        }
    }

    fn set_ir_block_livein(&mut self, block: &str, set: Vec<MuID>) {
952
        let block = self.blocks.get_mut(&block.to_string()).unwrap();
953 954 955 956
        block.livein = set;
    }

    fn set_ir_block_liveout(&mut self, block: &str, set: Vec<MuID>) {
957
        let block = self.blocks.get_mut(&block.to_string()).unwrap();
958 959 960
        block.liveout = set;
    }

961 962 963
    fn get_all_blocks(&self) -> Vec<MuName> {
        self.blocks.keys().map(|x| x.clone()).collect()
    }
964 965 966 967 968 969

    fn get_entry_block(&self) -> MuName {
        self.entry.clone()
    }

    fn get_block_range(&self, block: &str) -> Option<ops::Range<usize>> {
970
        match self.blocks.get(&block.to_string()) {
971
            Some(ref block) => Some(block.start_inst..block.end_inst),
972
            None => None
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
        }
    }

    fn get_block_for_inst(&self, index: usize) -> Option<MuName> {
        for (name, block) in self.blocks.iter() {
            if index >= block.start_inst && index < block.end_inst {
                return Some(name.clone());
            }
        }
        None
    }

    fn get_next_inst(&self, index: usize) -> Option<usize> {
        ASMCode::find_next_inst(index, &self.code)
    }

    fn get_last_inst(&self, index: usize) -> Option<usize> {
        ASMCode::find_last_inst(index, &self.code)
    }
}

#[derive(Clone, Debug)]
enum ASMBranchTarget {
    None,
    Conditional(MuName),
    Unconditional(MuName),
    PotentiallyExcepting(MuName),
    Return,
1001
    UnconditionalReg(MuID)
1002 1003 1004 1005 1006
}

#[derive(Clone, Debug)]
enum SpillMemInfo {
    Load(P<Value>),
1007
    Store(P<Value>),
1008
    CalleeSaved // Callee saved record
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
}

#[derive(Clone, Debug)]
struct ASMInst {
    code: String,

    defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
    uses: LinkedHashMap<MuID, Vec<ASMLocation>>,

    is_mem_op_used: bool,
    is_symbol: bool,

    preds: Vec<usize>,
    succs: Vec<usize>,
    branch: ASMBranchTarget,

1025
    spill_info: Option<SpillMemInfo>
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
}

impl ASMInst {
    fn symbolic(line: String) -> ASMInst {
        ASMInst {
            code: line,
            defines: LinkedHashMap::new(),
            uses: LinkedHashMap::new(),
            is_mem_op_used: false,
            is_symbol: true,
            preds: vec![],
            succs: vec![],
            branch: ASMBranchTarget::None,

1040
            spill_info: None
1041 1042 1043 1044 1045 1046 1047 1048 1049
        }
    }

    fn inst(
        inst: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_mem_op_used: bool,
        target: ASMBranchTarget,
1050
        spill_info: Option<SpillMemInfo>
1051
    ) -> ASMInst {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        ASMInst {
            code: inst,
            defines: defines,
            uses: uses,
            is_symbol: false,
            is_mem_op_used: is_mem_op_used,
            preds: vec![],
            succs: vec![],
            branch: target,

1062
            spill_info: spill_info
1063 1064 1065 1066 1067 1068 1069 1070 1071
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize,
1072
    oplen: usize
1073 1074 1075 1076
}

impl ASMLocation {
    fn new(line: usize, index: usize, len: usize, oplen: usize) -> ASMLocation {
1077
        ASMLocation {
1078 1079 1080
            line: line,
            index: index,
            len: len,
1081
            oplen: oplen
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        }
    }
}

#[derive(Clone, Debug)]
/// [start_inst, end_inst)
struct ASMBlock {
    start_inst: usize,
    end_inst: usize,

    livein: Vec<MuID>,
1093
    liveout: Vec<MuID>
1094 1095 1096 1097 1098 1099 1100 1101
}

impl ASMBlock {
    fn new() -> ASMBlock {
        ASMBlock {
            start_inst: usize::MAX,
            end_inst: usize::MAX,
            livein: vec![],
1102
            liveout: vec![]
1103 1104 1105 1106 1107
        }
    }
}

pub struct ASMCodeGen {
1108
    cur: Option<Box<ASMCode>>
1109 1110
}

1111
const REG_PLACEHOLDER_LEN: usize = 5;
1112
lazy_static! {
1113
    pub static ref REG_PLACEHOLDER: MuName = {
1114 1115
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];

1116
        Arc::new(format!("{}", str::from_utf8(&blank_spaces).unwrap()))
1117 1118 1119
    };
}

1120 1121 1122
// Maximum frame size is:  '4095; SUB SP, SP,
const FRAME_SIZE_PART_PLACEHOLDER_LEN: usize = 4; // maximum 'frame' size part is 4095
const FRAME_SIZE_PART_PLACEHOLDER: &str = "    "; // maximum 'frame' size part is 4095
1123 1124 1125

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
1126
        ASMCodeGen { cur: None }
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    }

    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }

    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }

    fn line(&self) -> usize {
        self.cur().code.len()
    }

1141
    fn add_asm_symbolic(&mut self, code: String) {
1142
        trace_emit!("{}", demangle_text(&code));
1143 1144 1145 1146 1147 1148 1149 1150
        self.cur_mut().code.push(ASMInst::symbolic(code));
    }

    fn add_asm_inst(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
1151
        is_using_mem_op: bool
1152
    ) {
1153 1154 1155 1156 1157 1158
        self.add_asm_inst_internal(
            code,
            defines,
            uses,
            is_using_mem_op,
            ASMBranchTarget::None,
1159
            None
1160
        )
1161 1162
    }

1163 1164 1165 1166 1167
    fn add_asm_inst_with_callee_saved(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
1168
        is_using_mem_op: bool
1169
    ) {
1170 1171 1172 1173 1174 1175
        self.add_asm_inst_internal(
            code,
            defines,
            uses,
            is_using_mem_op,
            ASMBranchTarget::None,
1176
            Some(SpillMemInfo::CalleeSaved)
1177
        )
1178 1179
    }

1180 1181 1182 1183 1184 1185
    fn add_asm_inst_with_spill(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
1186
        spill_info: SpillMemInfo
1187
    ) {
1188 1189 1190 1191 1192 1193
        self.add_asm_inst_internal(
            code,
            defines,
            uses,
            is_using_mem_op,
            ASMBranchTarget::None,
1194
            Some(spill_info)
1195
        )
1196 1197 1198 1199 1200 1201 1202 1203 1204
    }

    fn add_asm_inst_internal(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
        target: ASMBranchTarget,
1205
        spill_info: Option<SpillMemInfo>
1206
    ) {
1207
        trace!("asm: {}", demangle_text(&code));
1208 1209
        trace!("     defines: {:?}", defines);
        trace!("     uses: {:?}", uses);
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1210
        trace!("     target: {:?}", target);
1211 1212 1213
        let mc = self.cur_mut();

        // put the instruction
1214 1215 1216 1217 1218 1219
        mc.code.push(ASMInst::inst(
            code,
            defines,
            uses,
            is_using_mem_op,
            target,
1220
            spill_info
1221
        ));
1222 1223
    }

1224 1225 1226 1227 1228
    fn prepare_reg(
        &self,
        op: &P<Value>,
        loc: usize
    ) -> (String, MuID, ASMLocation) {
1229 1230
        if cfg!(debug_assertions) {
            match op.v {
1231
                Value_::SSAVar(_) => {}
1232
                _ => panic!("expecting register op")
1233 1234 1235 1236 1237
            }
        }

        let str = self.asm_reg_op(op);
        let len = str.len();
1238 1239 1240
        (
            str,
            op.extract_ssa_id().unwrap(),
1241
            ASMLocation::new(self.line(), loc, len, check_op_len(&op.ty))
1242
        )
1243 1244
    }

1245 1246 1247
    fn prepare_mem(
        &self,
        op: &P<Value>,
1248
        loc: usize
1249
    ) -> (String, LinkedHashMap<MuID, Vec<ASMLocation>>) {
1250 1251
        if cfg!(debug_assertions) {
            match op.v {
1252
                Value_::Memory(_) => {}
1253
                _ => panic!("expecting memory op")
1254 1255 1256
            }
        }

1257 1258 1259
        let mut ids: Vec<MuID> = vec![];
        let mut locs: Vec<ASMLocation> = vec![];
        let mut result_str: String = "".to_string();
1260

1261
        let mut loc_cursor: usize = loc;
1262 1263
        match op.v {
            // offset(base,index,scale)
1264 1265 1266 1267
            Value_::Memory(MemoryLocation::Address {
                ref base,
                ref offset,
                shift,
1268
                signed
1269
            }) => {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
                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 offset
                if offset.is_some() {
                    result_str.push(',');
                    loc_cursor += 1;

                    let offset = offset.as_ref().unwrap();
                    match offset.v {
                        Value_::SSAVar(_) => {
                            // temp as offset
1288 1289
                            let (str, id, loc) =
                                self.prepare_reg(offset, loc_cursor);
1290 1291 1292 1293 1294 1295 1296

                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);

                            result_str.push_str(",");
                            let n = offset.ty.get_int_length().unwrap();
1297 1298
                            let shift_type = if n == 64 {
                                if signed {
1299
                                    "LSL"
1300
                                //"SXTX"
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                                } else {
                                    "LSL"
                                }
                            } else if n == 32 {
                                if signed {
                                    "SXTW"
                                } else {
                                    "UXTW"
                                }
                            } else {
                                panic!("Unexpected size for offset register")
                            };
1313 1314 1315 1316 1317

                            result_str.push_str(&shift_type);
                            result_str.push_str(" #");
                            let shift_str = shift.to_string();
                            result_str.push_str(&shift_str);
1318
                        }
1319 1320 1321 1322 1323
                        Value_::Constant(Constant::Int(val)) => {
                            let str = (val as i32).to_string();

                            result_str.push('#');
                            result_str.push_str(&str);
1324
                        }
1325 1326 1327 1328
                        Value_::Constant(Constant::ExternSym(ref name)) => {
                            result_str.push('#');
                            result_str.push_str(name.as_str());
                        }
1329
                        _ => panic!("unexpected offset type: {:?}", offset)
1330 1331 1332 1333
                    }
                }

                // scale (for LSL type)
1334
                if shift != 0 {}
1335 1336

                result_str.push(']');
1337
            }
1338

1339 1340 1341
            Value_::Memory(MemoryLocation::Symbolic {
                ref label,
                is_global,
1342
                is_native
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
            }) => {
                let label = if is_native {
                    "/*C*/".to_string() + label.as_str()
                } else {
                    mangle_name(label.clone())
                };
                let label = if is_global {
                    format!(":got:{}", label.clone())
                } else {
                    label.clone()
                };
1354
                result_str.push_str(label.as_str());
1355
            }
1356

1357
            Value_::Memory(MemoryLocation::VirtualAddress { .. }) => {
1358 1359
                panic!("Can't directly use a virtual adress (try calling emit_mem first)");
            }
1360
            _ => panic!("expect mem location as value")
1361 1362
        }

1363
        let uses: LinkedHashMap<MuID, Vec<ASMLocation>> = {
1364 1365
            let mut map: LinkedHashMap<MuID, Vec<ASMLocation>> =
                linked_hashmap! {};
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
            for i in 0..ids.len() {
                let id = ids[i];
                let loc = locs[i].clone();

                if map.contains_key(&id) {
                    map.get_mut(&id).unwrap().push(loc);
                } else {
                    map.insert(id, vec![loc]);
                }
            }
            map
        };

        (result_str, uses)
    }

    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
        if id < MACHINE_ID_END {
            // machine reg
1386
            format!("{}", op.name())
1387 1388
        } else {
            // virtual register, use place holder
1389
            (**REG_PLACEHOLDER).clone()
1390 1391 1392 1393 1394 1395 1396
        }
    }

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

1397
    fn internal_simple(&mut self, inst: &str) {
1398
        let inst = inst.to_string();
1399
        trace_emit!("\t{}", inst);
1400 1401 1402

        let asm = inst;

1403
        self.add_asm_inst(asm, linked_hashmap! {}, linked_hashmap! {}, false)
1404 1405
    }

1406
    fn internal_simple_imm(&mut self, inst: &str, val: u64) {
1407
        let inst = inst.to_string();
1408
        trace_emit!("\t{} {}", inst, val);
1409 1410 1411

        let asm = format!("{} #{}", inst, val);

1412
        self.add_asm_inst(asm, linked_hashmap! {}, linked_hashmap! {}, false)
1413 1414
    }

1415
    fn internal_simple_str(&mut self, inst: &str, option: &str) {
1416 1417
        let inst = inst.to_string();
        let option = option.to_string();
1418
        trace_emit!("\t{} {}", inst, option);
1419 1420 1421

        let asm = format!("{} {}", inst, option);

1422
        self.add_asm_inst(asm, linked_hashmap! {}, linked_hashmap! {}, false)
1423 1424
    }

1425
    // A system instruction
1426
    fn internal_system(&mut self, inst: &str, option: &str, src: &P<Value>) {
1427 1428
        let inst = inst.to_string();
        let option = option.to_string();
1429
        trace_emit!("\t{} {} {}", inst, option, src);
1430