inst_sel.rs 222 KB
Newer Older
1
use ast::ir::*;
2
use ast::ptr::*;
qinsoon's avatar
qinsoon committed
3
use ast::inst::*;
4
use ast::op;
qinsoon's avatar
qinsoon committed
5
use ast::op::*;
qinsoon's avatar
qinsoon committed
6
use ast::types;
qinsoon's avatar
qinsoon committed
7
use ast::types::*;
qinsoon's avatar
qinsoon committed
8
use vm::VM;
9
use runtime::mm;
10 11
use runtime::mm::objectmodel::OBJECT_HEADER_SIZE;
use runtime::mm::objectmodel::OBJECT_HEADER_OFFSET;
12 13 14 15
use runtime::ValueLocation;
use runtime::thread;
use runtime::entrypoints;
use runtime::entrypoints::RuntimeEntrypoint;
16 17

use compiler::CompilerPass;
18
use compiler::backend;
19
use compiler::backend::RegGroup;
qinsoon's avatar
qinsoon committed
20
use compiler::backend::PROLOGUE_BLOCK_NAME;
qinsoon's avatar
qinsoon committed
21 22 23
use compiler::backend::x86_64;
use compiler::backend::x86_64::CodeGenerator;
use compiler::backend::x86_64::ASMCodeGen;
qinsoon's avatar
qinsoon committed
24 25
use compiler::machine_code::CompiledFunction;
use compiler::frame::Frame;
26

27
use utils::math;
qinsoon's avatar
qinsoon committed
28
use utils::POINTER_SIZE;
29

30
use std::collections::HashMap;
31 32
use std::collections::LinkedList;

qinsoon's avatar
qinsoon committed
33
use std::any::Any;
34

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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
lazy_static! {
    pub static ref LONG_4_TYPE : P<MuType> = P(
        MuType::new(new_internal_id(), MuType_::mustruct(Mu("long_4"), vec![UINT32_TYPE.clone(); 4]))
    );

    pub static ref UITOFP_C0 : P<Value> = P(Value{
        hdr: MuEntityHeader::named(new_internal_id(), Mu("UITOFP_C0")),
        ty : LONG_4_TYPE.clone(),
        v  : Value_::Constant(Constant::List(vec![
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT32_TYPE.clone(),
                v : Value_::Constant(Constant::Int(1127219200u64))
            }),
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT32_TYPE.clone(),
                v : Value_::Constant(Constant::Int(1160773632u64))
            }),
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT32_TYPE.clone(),
                v : Value_::Constant(Constant::Int(0u64))
            }),
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT32_TYPE.clone(),
                v : Value_::Constant(Constant::Int(0u64))
            })
        ]))
    });

    pub static ref QUAD_2_TYPE : P<MuType> = P(
        MuType::new(new_internal_id(), MuType_::mustruct(Mu("quad_2"), vec![UINT64_TYPE.clone(); 2]))
    );

    pub static ref UITOFP_C1 : P<Value> = P(Value{
        hdr: MuEntityHeader::named(new_internal_id(), Mu("UITOFP_C1")),
        ty : QUAD_2_TYPE.clone(),
        v  : Value_::Constant(Constant::List(vec![
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT64_TYPE.clone(),
                v : Value_::Constant(Constant::Int(4841369599423283200u64))
            }),
            P(Value{
                hdr: MuEntityHeader::unnamed(new_internal_id()),
                ty: UINT64_TYPE.clone(),
                v : Value_::Constant(Constant::Int(4985484787499139072u64))
            })
        ]))
    });
87

88 89
    pub static ref FPTOUI_C_DOUBLE : P<Value> = P(Value{
        hdr: MuEntityHeader::named(new_internal_id(), Mu("FPTOUI_C_DOUBLE")),
90 91 92
        ty : UINT64_TYPE.clone(),
        v  : Value_::Constant(Constant::Int(4890909195324358656u64))
    });
93 94 95 96 97 98

    pub static ref FPTOUI_C_FLOAT : P<Value> = P(Value{
        hdr: MuEntityHeader::named(new_internal_id(), Mu("FPTOUI_C_FLOAT")),
        ty : UINT32_TYPE.clone(),
        v  : Value_::Constant(Constant::Int(1593835520u64))
    });
99 100
}

101 102
const INLINE_FASTPATH : bool = false;

103
pub struct InstructionSelection {
104
    name: &'static str,
105
    backend: Box<CodeGenerator>,
106 107

    current_fv_id: MuID,
qinsoon's avatar
qinsoon committed
108
    current_callsite_id: usize,
qinsoon's avatar
qinsoon committed
109 110
    current_frame: Option<Frame>,
    current_block: Option<MuName>,
111
    current_block_in_ir: Option<MuName>,
qinsoon's avatar
qinsoon committed
112
    current_func_start: Option<ValueLocation>,
113 114 115 116
    // Technically this is a map in that each Key is unique, but we will never try and add duplicate
    // keys, or look things up, so a list of pairs is faster than a Map.
    // A list of pairs, the first is the name of a callsite the second
    current_callsites: LinkedList<(MuName, MuID)>,
qinsoon's avatar
qinsoon committed
117
    // key: block id, val: block location
118
    current_exn_blocks: HashMap<MuID, MuName>,
119 120 121

    current_constants: HashMap<MuID, P<Value>>,
    current_constants_locs: HashMap<MuID, P<Value>>
122 123
}

124
impl <'a> InstructionSelection {
qinsoon's avatar
qinsoon committed
125
    #[cfg(feature = "aot")]
126
    pub fn new() -> InstructionSelection {
127 128
        InstructionSelection{
            name: "Instruction Selection (x64)",
129
            backend: Box::new(ASMCodeGen::new()),
130

131
            current_fv_id: 0,
qinsoon's avatar
qinsoon committed
132
            current_callsite_id: 0,
qinsoon's avatar
qinsoon committed
133
            current_frame: None,
134 135 136 137 138 139 140
            current_block: None,        // which block we are generating code for
            current_block_in_ir: None,  // it is possible the block is newly created in instruction selection
                                        // but sometimes we want to know its control flow
                                        // so we need to track what block it is from the IR

                                        // FIXME: ideally we should not create new blocks in instruction selection
                                        // see Issue #6
qinsoon's avatar
qinsoon committed
141
            current_func_start: None,
142
            current_callsites: LinkedList::new(),
143 144 145 146
            current_exn_blocks: HashMap::new(),

            current_constants: HashMap::new(),
            current_constants_locs: HashMap::new()
147 148
        }
    }
qinsoon's avatar
qinsoon committed
149 150 151 152 153

    #[cfg(feature = "jit")]
    pub fn new() -> InstructionSelection {
        unimplemented!()
    }
154 155
    
    // in this pass, we assume that
qinsoon's avatar
qinsoon committed
156
    // * we do not need to backup/restore caller-saved registers
157 158
    // if any of these assumption breaks, we will need to re-emit the code
    #[allow(unused_variables)]
159
    fn instruction_select(&mut self, node: &'a TreeNode, f_content: &FunctionContent, f_context: &mut FunctionContext, vm: &VM) {
160
        trace!("instsel on node#{} {}", node.id(), node);
qinsoon's avatar
qinsoon committed
161 162
        
        match node.v {
163 164
            TreeNode_::Instruction(ref inst) => {
                match inst.v {
qinsoon's avatar
qinsoon committed
165
                    Instruction_::Branch2{cond, ref true_dest, ref false_dest, true_prob} => {
qinsoon's avatar
qinsoon committed
166
                        trace!("instsel on BRANCH2");
167 168
                        // 'branch_if_true' == true, we emit cjmp the same as CmpOp  (je  for EQ, jne for NE)
                        // 'branch_if_true' == false, we emit opposite cjmp as CmpOp (jne for EQ, je  for NE)
169
                        let (fallthrough_dest, branch_dest, branch_if_true) = {
170
                            // get current block and next block in trace (fallthrough block)
171
                            let cur_block = f_content.get_block_by_name(self.current_block_in_ir.as_ref().unwrap().clone());
172 173 174
                            let next_block_in_trace = cur_block.control_flow.get_hottest_succ().unwrap();

                            if next_block_in_trace == true_dest.target {
175 176 177
                                (true_dest, false_dest, false)
                            } else {
                                (false_dest, true_dest, true)
178
                            }
179
                        };
180
                        
181
                        let ref ops = inst.ops;
182
                        
183 184
                        self.process_dest(&ops, fallthrough_dest, f_content, f_context, vm);
                        self.process_dest(&ops, branch_dest, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
185
                        
186
                        let branch_target = f_content.get_block(branch_dest.target).name().unwrap();
187 188 189
    
                        let ref cond = ops[cond];
                        
qinsoon's avatar
qinsoon committed
190
                        if self.match_cmp_res(cond) {
191
                            trace!("emit cmp_res-branch2");
192
                            match self.emit_cmp_res(cond, f_content, f_context, vm) {
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
                                op::CmpOp::EQ => {
                                    if branch_if_true {
                                        self.backend.emit_je(branch_target);
                                    } else {
                                        self.backend.emit_jne(branch_target);
                                    }
                                },
                                op::CmpOp::NE => {
                                    if branch_if_true {
                                        self.backend.emit_jne(branch_target);
                                    } else {
                                        self.backend.emit_je(branch_target);
                                    }
                                },
                                op::CmpOp::UGE => {
                                    if branch_if_true {
                                        self.backend.emit_jae(branch_target);
                                    } else {
                                        self.backend.emit_jb(branch_target);
                                    }
                                },
                                op::CmpOp::UGT => {
                                    if branch_if_true {
                                        self.backend.emit_ja(branch_target);
                                    } else {
                                        self.backend.emit_jbe(branch_target);
                                    }
                                },
                                op::CmpOp::ULE => {
                                    if branch_if_true {
                                        self.backend.emit_jbe(branch_target);
                                    } else {
                                        self.backend.emit_ja(branch_target);
                                    }
                                },
                                op::CmpOp::ULT => {
                                    if branch_if_true {
                                        self.backend.emit_jb(branch_target);
                                    } else {
                                        self.backend.emit_jae(branch_target);
                                    }
                                },
                                op::CmpOp::SGE => {
                                    if branch_if_true {
                                        self.backend.emit_jge(branch_target);
                                    } else {
                                        self.backend.emit_jl(branch_target);
                                    }
                                },
                                op::CmpOp::SGT => {
                                    if branch_if_true {
                                        self.backend.emit_jg(branch_target);
                                    } else {
                                        self.backend.emit_jle(branch_target);
                                    }
                                },
                                op::CmpOp::SLE => {
                                    if branch_if_true {
                                        self.backend.emit_jle(branch_target);
                                    } else {
                                        self.backend.emit_jg(branch_target);
                                    }
                                },
                                op::CmpOp::SLT => {
                                    if branch_if_true {
                                        self.backend.emit_jl(branch_target);
                                    } else {
                                        self.backend.emit_jge(branch_target);
                                    }
                                },
qinsoon's avatar
qinsoon committed
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 297 298 299 300 301 302 303 304 305 306 307 308

                                // floating point

                                op::CmpOp::FOEQ | op::CmpOp::FUEQ => {
                                    if branch_if_true {
                                        self.backend.emit_je(branch_target);
                                    } else {
                                        self.backend.emit_jne(branch_target);
                                    }
                                },
                                op::CmpOp::FONE | op::CmpOp::FUNE => {
                                    if branch_if_true {
                                        self.backend.emit_jne(branch_target);
                                    } else {
                                        self.backend.emit_je(branch_target);
                                    }
                                },
                                op::CmpOp::FOGT | op::CmpOp::FUGT => {
                                    if branch_if_true {
                                        self.backend.emit_ja(branch_target);
                                    } else {
                                        self.backend.emit_jbe(branch_target);
                                    }
                                },
                                op::CmpOp::FOGE | op::CmpOp::FUGE => {
                                    if branch_if_true {
                                        self.backend.emit_jae(branch_target);
                                    } else {
                                        self.backend.emit_jb(branch_target);
                                    }
                                },
                                op::CmpOp::FOLT | op::CmpOp::FULT => {
                                    if branch_if_true {
                                        self.backend.emit_jb(branch_target);
                                    } else {
                                        self.backend.emit_jae(branch_target);
                                    }
                                },
                                op::CmpOp::FOLE | op::CmpOp::FULE => {
                                    if branch_if_true {
                                        self.backend.emit_jbe(branch_target);
                                    } else {
                                        self.backend.emit_ja(branch_target);
                                    }
                                },

qinsoon's avatar
qinsoon committed
309 310 311 312
                                _ => unimplemented!()
                            }
                        } else if self.match_ireg(cond) {
                            trace!("emit ireg-branch2");
313
                            
314
                            let cond_reg = self.emit_ireg(cond, f_content, f_context, vm);
315
                            
qinsoon's avatar
qinsoon committed
316
                            // emit: cmp cond_reg 1
317
                            self.backend.emit_cmp_imm_r(1, &cond_reg);
qinsoon's avatar
qinsoon committed
318
                            // emit: je #branch_dest
319 320 321 322 323
                            if branch_if_true {
                                self.backend.emit_je(branch_target);
                            } else {
                                self.backend.emit_jne(branch_target);
                            }
qinsoon's avatar
qinsoon committed
324 325
                        } else {
                            unimplemented!();
326
                        }
327 328 329 330 331 332 333 334 335 336

                        // it is possible that the fallthrough block is scheduled somewhere else
                        // we need to explicitly jump to it
                        self.finish_block();

                        let fallthrough_temp_block = format!("{}_{}_branch_fallthrough", self.current_fv_id, node.id());
                        self.start_block(fallthrough_temp_block);

                        let fallthrough_target = f_content.get_block(fallthrough_dest.target).name().unwrap();
                        self.backend.emit_jmp(fallthrough_target);
337
                    },
qinsoon's avatar
qinsoon committed
338 339

                    Instruction_::Select{cond, true_val, false_val} => {
qinsoon's avatar
qinsoon committed
340 341
                        use ast::op::CmpOp::*;

qinsoon's avatar
qinsoon committed
342
                        trace!("instsel on SELECT");
343
                        let ref ops = inst.ops;
qinsoon's avatar
qinsoon committed
344 345 346 347 348

                        let ref cond = ops[cond];
                        let ref true_val = ops[true_val];
                        let ref false_val = ops[false_val];

349 350 351 352 353 354 355 356 357 358 359 360 361
                        // generate compare
                        let cmpop = if self.match_cmp_res(cond) {
                            self.emit_cmp_res(cond, f_content, f_context, vm)
                        } else if self.match_ireg(cond) {
                            let tmp_cond = self.emit_ireg(cond, f_content, f_context, vm);
                            // emit: cmp cond_reg 1
                            self.backend.emit_cmp_imm_r(1, &tmp_cond);

                            EQ
                        } else {
                            panic!("expected cond to be ireg, found {}", cond)
                        };

qinsoon's avatar
qinsoon committed
362 363 364
                        if self.match_ireg(true_val) {
                            // moving integers/pointers
                            let tmp_res   = self.get_result_value(node);
365

366
                            // use cmov for 16/32/64bit integer
qinsoon's avatar
qinsoon committed
367
                            // use jcc  for 8 bit
368
                            // FIXME: could use 32bit register to implement 8bit select
qinsoon's avatar
qinsoon committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
                            match tmp_res.ty.get_int_length() {
                                // cmov
                                Some(len) if len > 8 => {
                                    let tmp_true  = self.emit_ireg(true_val, f_content, f_context, vm);
                                    let tmp_false = self.emit_ireg(false_val, f_content, f_context, vm);

                                    // mov tmp_false -> tmp_res
                                    self.backend.emit_mov_r_r(&tmp_res, &tmp_false);

                                    match cmpop {
                                        EQ  => self.backend.emit_cmove_r_r (&tmp_res, &tmp_true),
                                        NE  => self.backend.emit_cmovne_r_r(&tmp_res, &tmp_true),
                                        SGE => self.backend.emit_cmovge_r_r(&tmp_res, &tmp_true),
                                        SGT => self.backend.emit_cmovg_r_r (&tmp_res, &tmp_true),
                                        SLE => self.backend.emit_cmovle_r_r(&tmp_res, &tmp_true),
                                        SLT => self.backend.emit_cmovl_r_r (&tmp_res, &tmp_true),
                                        UGE => self.backend.emit_cmovae_r_r(&tmp_res, &tmp_true),
                                        UGT => self.backend.emit_cmova_r_r (&tmp_res, &tmp_true),
                                        ULE => self.backend.emit_cmovbe_r_r(&tmp_res, &tmp_true),
                                        ULT => self.backend.emit_cmovb_r_r (&tmp_res, &tmp_true),

                                        FOEQ | FUEQ => self.backend.emit_cmove_r_r (&tmp_res, &tmp_true),
                                        FONE | FUNE => self.backend.emit_cmovne_r_r(&tmp_res, &tmp_true),
                                        FOGT | FUGT => self.backend.emit_cmova_r_r (&tmp_res, &tmp_true),
                                        FOGE | FUGE => self.backend.emit_cmovae_r_r(&tmp_res, &tmp_true),
                                        FOLT | FULT => self.backend.emit_cmovb_r_r (&tmp_res, &tmp_true),
                                        FOLE | FULE => self.backend.emit_cmovbe_r_r(&tmp_res, &tmp_true),

                                        _ => unimplemented!()
                                    }
                                }
                                // jcc
                                _ => {
402 403 404
                                    let blk_true  = format!("{}_{}_select_true",  self.current_fv_id, node.id());
                                    let blk_false = format!("{}_{}_select_false", self.current_fv_id, node.id());
                                    let blk_end   = format!("{}_{}_select_end",   self.current_fv_id, node.id());
qinsoon's avatar
qinsoon committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

                                    // jump to blk_true if true
                                    match cmpop {
                                        EQ  => self.backend.emit_je (blk_true.clone()),
                                        NE  => self.backend.emit_jne(blk_true.clone()),
                                        SGE => self.backend.emit_jge(blk_true.clone()),
                                        SGT => self.backend.emit_jg (blk_true.clone()),
                                        SLE => self.backend.emit_jle(blk_true.clone()),
                                        SLT => self.backend.emit_jl (blk_true.clone()),
                                        UGE => self.backend.emit_jae(blk_true.clone()),
                                        UGT => self.backend.emit_ja (blk_true.clone()),
                                        ULE => self.backend.emit_jbe(blk_true.clone()),
                                        ULT => self.backend.emit_jb (blk_true.clone()),

                                        FOEQ | FUEQ => self.backend.emit_je (blk_true.clone()),
                                        FONE | FUNE => self.backend.emit_jne(blk_true.clone()),
                                        FOGT | FUGT => self.backend.emit_ja (blk_true.clone()),
                                        FOGE | FUGE => self.backend.emit_jae(blk_true.clone()),
                                        FOLT | FULT => self.backend.emit_jb (blk_true.clone()),
                                        FOLE | FULE => self.backend.emit_jbe(blk_true.clone()),

                                        _ => unimplemented!()
                                    }

429
                                    // finishing current block
qinsoon's avatar
qinsoon committed
430
                                    self.finish_block();
431 432

                                    // blk_false:
qinsoon's avatar
qinsoon committed
433
                                    self.start_block(blk_false.clone());
qinsoon's avatar
qinsoon committed
434 435 436 437 438 439
                                    // mov false result here
                                    self.emit_move_node_to_value(&tmp_res, &false_val, f_content, f_context, vm);
                                    // jmp to end
                                    self.backend.emit_jmp(blk_end.clone());

                                    // finishing current block
qinsoon's avatar
qinsoon committed
440
                                    self.finish_block();
qinsoon's avatar
qinsoon committed
441 442

                                    // blk_true:
qinsoon's avatar
qinsoon committed
443
                                    self.start_block(blk_true.clone());
qinsoon's avatar
qinsoon committed
444 445
                                    // mov true value -> result
                                    self.emit_move_node_to_value(&tmp_res, &true_val, f_content, f_context, vm);
446
                                    self.finish_block();
qinsoon's avatar
qinsoon committed
447 448

                                    // blk_end:
449
                                    self.start_block(blk_end.clone());
qinsoon's avatar
qinsoon committed
450
                                }
qinsoon's avatar
qinsoon committed
451
                            }
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
                        } else if self.match_fpreg(true_val) {
                            let tmp_res = self.get_result_value(node);

                            let blk_true  = format!("{}_{}_select_true",  self.current_fv_id, node.id());
                            let blk_false = format!("{}_{}_select_false", self.current_fv_id, node.id());
                            let blk_end   = format!("{}_{}_select_end",   self.current_fv_id, node.id());

                            // jump to blk_true if true
                            match cmpop {
                                EQ  => self.backend.emit_je (blk_true.clone()),
                                NE  => self.backend.emit_jne(blk_true.clone()),
                                SGE => self.backend.emit_jge(blk_true.clone()),
                                SGT => self.backend.emit_jg (blk_true.clone()),
                                SLE => self.backend.emit_jle(blk_true.clone()),
                                SLT => self.backend.emit_jl (blk_true.clone()),
                                UGE => self.backend.emit_jae(blk_true.clone()),
                                UGT => self.backend.emit_ja (blk_true.clone()),
                                ULE => self.backend.emit_jbe(blk_true.clone()),
                                ULT => self.backend.emit_jb (blk_true.clone()),

                                FOEQ | FUEQ => self.backend.emit_je (blk_true.clone()),
                                FONE | FUNE => self.backend.emit_jne(blk_true.clone()),
                                FOGT | FUGT => self.backend.emit_ja (blk_true.clone()),
                                FOGE | FUGE => self.backend.emit_jae(blk_true.clone()),
                                FOLT | FULT => self.backend.emit_jb (blk_true.clone()),
                                FOLE | FULE => self.backend.emit_jbe(blk_true.clone()),

                                _ => unimplemented!()
                            }

                            // finishing current block
qinsoon's avatar
qinsoon committed
483
                            self.finish_block();
484 485

                            // blk_false:
qinsoon's avatar
qinsoon committed
486
                            self.start_block(blk_false.clone());
487 488 489 490 491 492
                            // mov false result here
                            self.emit_move_node_to_value(&tmp_res, &false_val, f_content, f_context, vm);
                            // jmp to end
                            self.backend.emit_jmp(blk_end.clone());

                            // finishing current block
qinsoon's avatar
qinsoon committed
493
                            self.finish_block();
494 495

                            // blk_true:
qinsoon's avatar
qinsoon committed
496
                            self.start_block(blk_true.clone());
497 498
                            // mov true value -> result
                            self.emit_move_node_to_value(&tmp_res, &true_val, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
499
                            self.finish_block();
500 501

                            // blk_end:
qinsoon's avatar
qinsoon committed
502
                            self.start_block(blk_end.clone());
qinsoon's avatar
qinsoon committed
503 504 505 506 507
                        } else {
                            unimplemented!()
                        }
                    },

508
                    Instruction_::CmpOp(op, op1, op2) => {
qinsoon's avatar
qinsoon committed
509 510
                        use ast::op::CmpOp::*;

qinsoon's avatar
qinsoon committed
511
                        trace!("instsel on CMPOP");
512
                        let ref ops = inst.ops;
513 514 515
                        let ref op1 = ops[op1];
                        let ref op2 = ops[op2];

qinsoon's avatar
qinsoon committed
516
                        let tmp_res = self.get_result_value(node);
517 518 519
                        
                        debug_assert!(tmp_res.ty.get_int_length().is_some());
                        debug_assert!(tmp_res.ty.get_int_length().unwrap() == 1);
520

521
                        // set byte to result
qinsoon's avatar
qinsoon committed
522
                        match self.emit_cmp_res(node, f_content, f_context, vm) {
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
                            EQ  => self.backend.emit_sete_r (&tmp_res),
                            NE  => self.backend.emit_setne_r(&tmp_res),
                            SGE => self.backend.emit_setge_r(&tmp_res),
                            SGT => self.backend.emit_setg_r (&tmp_res),
                            SLE => self.backend.emit_setle_r(&tmp_res),
                            SLT => self.backend.emit_setl_r (&tmp_res),
                            UGE => self.backend.emit_setae_r(&tmp_res),
                            UGT => self.backend.emit_seta_r (&tmp_res),
                            ULE => self.backend.emit_setbe_r(&tmp_res),
                            ULT => self.backend.emit_setb_r (&tmp_res),

                            FOEQ | FUEQ => self.backend.emit_sete_r (&tmp_res),
                            FONE | FUNE => self.backend.emit_setne_r(&tmp_res),
                            FOGT | FUGT => self.backend.emit_seta_r (&tmp_res),
                            FOGE | FUGE => self.backend.emit_setae_r(&tmp_res),
                            FOLT | FULT => self.backend.emit_setb_r (&tmp_res),
                            FOLE | FULE => self.backend.emit_setbe_r(&tmp_res),
qinsoon's avatar
qinsoon committed
540 541

                            _ => unimplemented!()
542 543 544
                        }
                    }

qinsoon's avatar
qinsoon committed
545
                    Instruction_::Branch1(ref dest) => {
qinsoon's avatar
qinsoon committed
546
                        trace!("instsel on BRANCH1");
547
                        let ref ops = inst.ops;
548
                                            
549
                        self.process_dest(&ops, dest, f_content, f_context, vm);
550
                        
551
                        let target = f_content.get_block(dest.target).name().unwrap();
qinsoon's avatar
qinsoon committed
552
                        
qinsoon's avatar
qinsoon committed
553
                        trace!("emit branch1");
554
                        // jmp
qinsoon's avatar
qinsoon committed
555
                        self.backend.emit_jmp(target);
556
                    },
qinsoon's avatar
qinsoon committed
557 558

                    Instruction_::Switch{cond, ref default, ref branches} => {
qinsoon's avatar
qinsoon committed
559
                        trace!("instsel on SWITCH");
560
                        let ref ops = inst.ops;
qinsoon's avatar
qinsoon committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

                        let ref cond = ops[cond];

                        if self.match_ireg(cond) {
                            let tmp_cond = self.emit_ireg(cond, f_content, f_context, vm);

                            // emit each branch
                            for &(case_op_index, ref case_dest) in branches {
                                let ref case_op = ops[case_op_index];

                                // process dest
                                self.process_dest(&ops, case_dest, f_content, f_context, vm);

                                let target = f_content.get_block(case_dest.target).name().unwrap();

                                if self.match_iimm(case_op) {
                                    let imm = self.node_iimm_to_i32(case_op);

                                    // cmp case cond
580
                                    self.backend.emit_cmp_imm_r(imm, &tmp_cond);
qinsoon's avatar
qinsoon committed
581 582 583 584 585 586
                                    // je dest
                                    self.backend.emit_je(target);
                                } else if self.match_ireg(case_op) {
                                    let tmp_case_op = self.emit_ireg(case_op, f_content, f_context, vm);

                                    // cmp case cond
587
                                    self.backend.emit_cmp_r_r(&tmp_case_op, &tmp_cond);
qinsoon's avatar
qinsoon committed
588 589 590 591 592
                                    // je dest
                                    self.backend.emit_je(target);
                                } else {
                                    panic!("expecting ireg cond to be either iimm or ireg: {}", cond);
                                }
593 594 595

                                self.finish_block();
                                self.start_block(format!("{}_switch_not_met_case_{}", node.id(), case_op_index));
qinsoon's avatar
qinsoon committed
596 597 598 599 600 601 602 603 604 605 606
                            }

                            // emit default
                            self.process_dest(&ops, default, f_content, f_context, vm);
                            
                            let default_target = f_content.get_block(default.target).name().unwrap();
                            self.backend.emit_jmp(default_target);
                        } else {
                            panic!("expecting cond in switch to be ireg: {}", cond);
                        }
                    }
607
                    
qinsoon's avatar
qinsoon committed
608
                    Instruction_::ExprCall{ref data, is_abort} => {
qinsoon's avatar
qinsoon committed
609 610
                        trace!("instsel on EXPRCALL");

qinsoon's avatar
qinsoon committed
611 612
                        if is_abort {
                            unimplemented!()
613
                        }
614
                        
qinsoon's avatar
qinsoon committed
615 616 617 618 619
                        self.emit_mu_call(
                            inst, // inst: &Instruction,
                            data, // calldata: &CallData,
                            None, // resumption: Option<&ResumptionData>,
                            node, // cur_node: &TreeNode, 
620
                            f_content, f_context, vm);
621 622
                    },
                    
qinsoon's avatar
qinsoon committed
623
                    Instruction_::Call{ref data, ref resume} => {
qinsoon's avatar
qinsoon committed
624 625
                        trace!("instsel on CALL");

qinsoon's avatar
qinsoon committed
626 627 628 629 630 631
                        self.emit_mu_call(
                            inst, 
                            data, 
                            Some(resume), 
                            node, 
                            f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
632 633 634
                    },

                    Instruction_::ExprCCall{ref data, is_abort} => {
qinsoon's avatar
qinsoon committed
635 636
                        trace!("instsel on EXPRCCALL");

qinsoon's avatar
qinsoon committed
637 638 639 640 641 642 643 644
                        if is_abort {
                            unimplemented!()
                        }

                        self.emit_c_call_ir(inst, data, None, node, f_content, f_context, vm);
                    }

                    Instruction_::CCall{ref data, ref resume} => {
qinsoon's avatar
qinsoon committed
645 646
                        trace!("instsel on CCALL");

qinsoon's avatar
qinsoon committed
647
                        self.emit_c_call_ir(inst, data, Some(resume), node, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
648 649
                    }
                    
650
                    Instruction_::Return(_) => {
qinsoon's avatar
qinsoon committed
651 652
                        trace!("instsel on RETURN");

653
                        self.emit_common_epilogue(inst, f_content, f_context, vm);
654
                        
qinsoon's avatar
qinsoon committed
655
                        self.backend.emit_ret();
656 657
                    },
                    
qinsoon's avatar
qinsoon committed
658
                    Instruction_::BinOp(op, op1, op2) => {
qinsoon's avatar
qinsoon committed
659 660
                        trace!("instsel on BINOP");

qinsoon's avatar
qinsoon committed
661 662
                        self.emit_binop(node, inst, op, op1, op2, f_content, f_context, vm);
                    },
qinsoon's avatar
qinsoon committed
663

qinsoon's avatar
qinsoon committed
664 665
                    Instruction_::BinOpWithStatus(op, status, op1, op2) => {
                        trace!("instsel on BINOP_STATUS");
qinsoon's avatar
qinsoon committed
666

qinsoon's avatar
qinsoon committed
667
                        self.emit_binop(node, inst, op, op1, op2, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
668

qinsoon's avatar
qinsoon committed
669 670
                        let values = inst.value.as_ref().unwrap();
                        let mut status_value_index = 1;
qinsoon's avatar
qinsoon committed
671

672
                        // status flags only works with int operations
673
                        if RegGroup::get_from_value(&values[0]) == RegGroup::GPR {
674 675 676 677 678 679 680
                            // negative flag
                            if status.flag_n {
                                let tmp_status = values[status_value_index].clone();
                                status_value_index += 1;

                                self.backend.emit_sets_r8(&tmp_status);
                            }
qinsoon's avatar
qinsoon committed
681

682 683 684 685
                            // zero flag
                            if status.flag_z {
                                let tmp_status = values[status_value_index].clone();
                                status_value_index += 1;
qinsoon's avatar
qinsoon committed
686

687 688
                                self.backend.emit_setz_r8(&tmp_status);
                            }
qinsoon's avatar
qinsoon committed
689

690 691 692 693
                            // unsigned overflow
                            if status.flag_c {
                                let tmp_status = values[status_value_index].clone();
                                status_value_index += 1;
qinsoon's avatar
qinsoon committed
694

695 696 697 698 699
                                match op {
                                    BinOp::Add | BinOp::Sub | BinOp::Mul => {
                                        self.backend.emit_setb_r8(&tmp_status);
                                    }
                                    _ => panic!("Only Add/Sub/Mul has #C flag")
qinsoon's avatar
qinsoon committed
700 701
                                }
                            }
702

703 704 705
                            // signed overflow
                            if status.flag_v {
                                let tmp_status = values[status_value_index].clone();
706

707 708 709 710 711
                                match op {
                                    BinOp::Add | BinOp::Sub | BinOp::Mul => {
                                        self.backend.emit_seto_r8(&tmp_status);
                                    }
                                    _ => panic!("Only Add/Sub/Mul has #V flag")
712 713
                                }
                            }
714 715
                        }
                    }
qinsoon's avatar
qinsoon committed
716 717

                    Instruction_::ConvOp{operation, ref from_ty, ref to_ty, operand} => {
qinsoon's avatar
qinsoon committed
718 719
                        trace!("instsel on CONVOP");

720
                        let ref ops = inst.ops;
qinsoon's avatar
qinsoon committed
721 722 723 724 725

                        let ref op = ops[operand];

                        match operation {
                            op::ConvOp::TRUNC => {
qinsoon's avatar
qinsoon committed
726 727 728
                                let tmp_res = self.get_result_value(node);
                                let to_ty_size = vm.get_backend_type_info(tmp_res.ty.id()).size;

qinsoon's avatar
qinsoon committed
729 730
                                if self.match_ireg(op) {
                                    let tmp_op = self.emit_ireg(op, f_content, f_context, vm);
731

qinsoon's avatar
qinsoon committed
732
                                    // mov op -> result
qinsoon's avatar
qinsoon committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746
                                    match to_ty_size {
                                        1 => self.backend.emit_mov_r_r(&tmp_res, unsafe {&tmp_op.as_type(UINT8_TYPE.clone())}),
                                        2 => self.backend.emit_mov_r_r(&tmp_res, unsafe {&tmp_op.as_type(UINT16_TYPE.clone())}),
                                        4 => self.backend.emit_mov_r_r(&tmp_res, unsafe {&tmp_op.as_type(UINT32_TYPE.clone())}),
                                        8 => self.backend.emit_mov_r_r(&tmp_res, unsafe {&tmp_op.as_type(UINT64_TYPE.clone())}),
                                        _  => panic!("unsupported int size: {}", to_ty_size)
                                    }
                                } else if self.match_ireg_ex(op) {
                                    let (op_l, op_h) = self.emit_ireg_ex(op, f_content, f_context, vm);

                                    match to_ty_size {
                                        1 | 2 => self.backend.emit_movz_r_r(unsafe {&tmp_res.as_type(UINT32_TYPE.clone())}, &op_l),
                                        4 | 8 => self.backend.emit_mov_r_r(&tmp_res, &op_l),
                                        _ => panic!("unsupported int size: {}", to_ty_size)
747
                                    }
qinsoon's avatar
qinsoon committed
748 749 750 751 752
                                } else {
                                    panic!("unexpected op (expect ireg): {}", op);
                                }
                            }
                            op::ConvOp::ZEXT => {
753 754 755
                                if self.match_ireg(op) {
                                    let tmp_op = self.emit_ireg(op, f_content, f_context, vm);
                                    let tmp_res = self.get_result_value(node);
qinsoon's avatar
qinsoon committed
756

757 758 759
                                    // movz op -> result
                                    let from_ty_size = vm.get_backend_type_info(from_ty.id()).size;
                                    let to_ty_size   = vm.get_backend_type_info(to_ty.id()).size;
qinsoon's avatar
qinsoon committed
760

761
                                    if from_ty_size != to_ty_size {
qinsoon's avatar
qinsoon committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
                                        match (from_ty_size, to_ty_size) {
                                            // int32 to int64
                                            (4, 8) => {
                                                // zero extend from 32 bits to 64 bits is a mov instruction
                                                // x86 does not have movzlq (32 to 64)

                                                // tmp_op is int32, but tmp_res is int64
                                                // we want to force a 32-to-32 mov, so high bits of the destination will be zeroed

                                                let tmp_res32 = unsafe {tmp_res.as_type(UINT32_TYPE.clone())};

                                                self.backend.emit_mov_r_r(&tmp_res32, &tmp_op);
                                            }
                                            // any int to int128
                                            (_, 16) => {
                                                let (res_l, res_h) = self.split_int128(&tmp_res, f_context, vm);

                                                self.backend.emit_mov_r_r(&res_l, unsafe {&tmp_op.as_type(UINT64_TYPE.clone())});
                                                self.backend.emit_mov_r_imm(&res_h, 0);
                                            }
                                            // else
                                            _ => {
                                                self.backend.emit_movz_r_r(&tmp_res, &tmp_op);
                                            }
qinsoon's avatar
qinsoon committed
786
                                        }
787
                                    } else {
788
                                        self.backend.emit_mov_r_r(&tmp_res, &tmp_op);
789
                                    }
790 791
                                } else {
                                    panic!("unexpected op (expect ireg): {}", op);
qinsoon's avatar
qinsoon committed
792 793 794
                                }
                            },
                            op::ConvOp::SEXT => {
795 796 797
                                if self.match_ireg(op) {
                                    let tmp_op = self.emit_ireg(op, f_content, f_context, vm);
                                    let tmp_res = self.get_result_value(node);
qinsoon's avatar
qinsoon committed
798

799 800 801
                                    // movs op -> result
                                    let from_ty_size = vm.get_backend_type_info(from_ty.id()).size;
                                    let to_ty_size   = vm.get_backend_type_info(to_ty.id()).size;
802

803
                                    if from_ty_size != to_ty_size {
qinsoon's avatar
qinsoon committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
                                        match (from_ty_size, to_ty_size) {
                                            // int64 to int128
                                            (8, 16) => {
                                                let (res_l, res_h) = self.split_int128(&tmp_res, f_context, vm);

                                                // mov tmp_op -> res_h
                                                // sar res_h 63
                                                self.backend.emit_mov_r_r(&res_h, &tmp_op);
                                                self.backend.emit_sar_r_imm8(&res_h, 63i8);

                                                // mov tmp_op -> res_l
                                                self.backend.emit_mov_r_r(&res_l, &tmp_op);
                                            }
                                            // int32 to int128
                                            (_, 16) => {
                                                let (res_l, res_h) = self.split_int128(&tmp_res, f_context, vm);

                                                // movs tmp_op -> res_l
                                                self.backend.emit_movs_r_r(&res_l, &tmp_op);

                                                // mov res_l -> res_h
                                                // sar res_h 63
                                                self.backend.emit_mov_r_r(&res_h, unsafe {&res_l.as_type(UINT32_TYPE.clone())});
                                                self.backend.emit_sar_r_imm8(&res_h, 63i8);
                                            }
                                            _ => self.backend.emit_movs_r_r(&tmp_res, &tmp_op)
                                        }
831
                                    } else {
832
                                        self.backend.emit_mov_r_r(&tmp_res, &tmp_op);
833
                                    }
834 835
                                } else {
                                    panic!("unexpected op (expect ireg): {}", op)
qinsoon's avatar
qinsoon committed
836 837
                                }
                            }
838 839 840 841 842 843
                            op::ConvOp::REFCAST | op::ConvOp::PTRCAST => {
                                // just a mov (and hopefully reg alloc will coalesce it)
                                let tmp_res = self.get_result_value(node);

                                if self.match_ireg(op) {
                                    let tmp_op = self.emit_ireg(op, f_content, f_context, vm);
844
                                    self.backend.emit_mov_r_r(&tmp_res, &tmp_op);
845 846 847 848
                                } else {
                                    panic!("unexpected op (expect ireg): {}", op)
                                }
                            }
849 850 851
                            op::ConvOp::SITOFP => {
                                let tmp_res = self.get_result_value(node);

852 853 854 855 856 857 858
                                assert!(self.match_ireg(op), "unexpected op (expected ireg): {}", op);
                                let tmp_op = self.emit_ireg(op, f_content, f_context, vm);

                                match to_ty.v {
                                    MuType_::Double => self.backend.emit_cvtsi2sd_f64_r(&tmp_res, &tmp_op),
                                    MuType_::Float  => self.backend.emit_cvtsi2ss_f32_r(&tmp_res, &tmp_op),
                                    _ => panic!("expecing fp type as to type in SITOFP, found {}", to_ty)
859 860 861 862 863
                                }
                            }
                            op::ConvOp::FPTOSI => {
                                let tmp_res = self.get_result_value(node);

864 865 866 867
                                assert!(self.match_fpreg(op), "unexpected op (expected fpreg): {}", op);
                                let tmp_op = self.emit_fpreg(op, f_content, f_context, vm);

                                if from_ty.is_double() {
868
                                    self.backend.emit_cvtsd2si_r_f64(&tmp_res, &tmp_op);
869 870
                                } else if from_ty.is_float() {
                                    self.backend.emit_cvtss2si_r_f32(&tmp_res, &tmp_op);
871
                                } else {
872
                                    panic!("expected fp type as from type in FPTOSI, found {}", to_ty)
873 874
                                }
                            }
875 876 877
                            op::ConvOp::UITOFP => {
                                let tmp_res = self.get_result_value(node);

878 879
                                assert!(self.match_ireg(op), "unexpected op (expected ireg): {}", op);
                                let tmp_op = self.emit_ireg(op, f_content, f_context, vm);
880

881
                                let op_ty_size = vm.get_backend_type_info(tmp_op.ty.id()).size;
882

883 884 885 886 887
                                if to_ty.is_double() {
                                    match op_ty_size {
                                        8 => {
                                            // movd/movq op -> res
                                            self.backend.emit_mov_fpr_r64(&tmp_res, &tmp_op);
888

889 890 891 892
                                            // punpckldq UITOFP_C0, tmp_res -> tmp_res
                                            // (interleaving low bytes: xmm = xmm[0] mem[0] xmm[1] mem[1]
                                            let mem_c0 = self.get_mem_for_const(UITOFP_C0.clone(), vm);
                                            self.backend.emit_punpckldq_f64_mem128(&tmp_res, &mem_c0);
893

894 895 896
                                            // subpd UITOFP_C1, tmp_res -> tmp_res
                                            let mem_c1 = self.get_mem_for_const(UITOFP_C1.clone(), vm);
                                            self.backend.emit_subpd_f64_mem128(&tmp_res, &mem_c1);
897

898 899 900 901 902
                                            // haddpd tmp_res, tmp_res -> tmp_res
                                            self.backend.emit_haddpd_f64_f64(&tmp_res, &tmp_res);
                                        }
                                        4 => {
                                            let tmp = self.make_temporary(f_context, UINT64_TYPE.clone(), vm);
903

904 905 906
                                            // movl op -> tmp(32)
                                            let tmp32 = unsafe { tmp.as_type(UINT32_TYPE.clone()) };
                                            self.backend.emit_mov_r_r(&tmp32, &tmp_op);
907

908 909 910 911 912 913 914 915
                                            // cvtsi2sd %tmp(64) -> %tmp_res
                                            self.backend.emit_cvtsi2sd_f64_r(&tmp_res, &tmp);
                                        }
                                        2 | 1 => {
                                            let tmp_op32 = unsafe { tmp_op.as_type(UINT32_TYPE.clone()) };
                                            self.backend.emit_cvtsi2sd_f64_r(&tmp_res, &tmp_op32);
                                        }
                                        _ => panic!("not implemented int length {}", op_ty_size)
916
                                    }
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                                } else if to_ty.is_float() {
                                    match op_ty_size {
                                        8 => {
                                            // movl %tmp_op -> %tmp1
                                            let tmp1 = self.make_temporary(f_context, UINT32_TYPE.clone(), vm);
                                            self.backend.emit_mov_r_r(&tmp1, unsafe {&tmp_op.as_type(UINT32_TYPE.clone())});

                                            // andl %tmp1 $1 -> %tmp1
                                            self.backend.emit_and_r_imm(&tmp1, 1);

                                            // testq %tmp_op %tmp_op
                                            self.backend.emit_test_r_r(&tmp_op, &tmp_op);

                                            let blk_if_signed     = format!("{}_{}_uitofp_float_if_signed", self.current_fv_id, node.id());
                                            let blk_if_not_signed = format!("{}_{}_uitofp_float_if_not_signed", self.current_fv_id, node.id());
                                            let blk_done          = format!("{}_{}_uitofp_float_done", self.current_fv_id, node.id());

                                            // js %if_signed
                                            self.backend.emit_js(blk_if_signed.clone());
                                            self.finish_block();

                                            // blk_if_not_signed:
                                            self.start_block(blk_if_not_signed);

                                            // cvtsi2ss %tmp_op -> %tmp_res
                                            self.backend.emit_cvtsi2ss_f32_r(&tmp_res, &tmp_op);

                                            // jmp blk_done
                                            self.backend.emit_jmp(blk_done.clone());
                                            self.finish_block();

                                            // blk_if_signed:
                                            self.start_block(blk_if_signed);

                                            // shr %tmp_op $1 -> %tmp_op
                                            self.backend.emit_shr_r_imm8(&tmp_op, 1);

                                            // or %tmp_op %tmp1 -> %tmp1
                                            self.backend.emit_or_r_r(unsafe {&tmp1.as_type(UINT64_TYPE.clone())}, &tmp_op);

                                            // cvtsi2ss %tmp1 -> %tmp_res
                                            self.backend.emit_cvtsi2ss_f32_r(&tmp_res, &tmp1);

                                            // addss %tmp_res %tmp_res -> %tmp_res
                                            self.backend.emit_addss_f32_f32(&tmp_res, &tmp_res);
                                            self.finish_block();

                                            self.start_block(blk_done);
                                        }
                                        4 => {
                                            // movl %tmp_op -> %tmp1
                                            let tmp1 = self.make_temporary(f_context, UINT32_TYPE.clone(), vm);
                                            self.backend.emit_mov_r_r(&tmp1, &tmp_op);

                                            // cvtsi2ssq %tmp1(64) -> %tmp_res
                                            self.backend.emit_cvtsi2ss_f32_r(&tmp_res, unsafe {&tmp1.as_type(UINT64_TYPE.clone())});
                                        }
                                        2 | 1 => {
                                            let tmp_op32 = unsafe {tmp_op.as_type(UINT32_TYPE.clone())};

                                            // cvtsi2ss %tmp_op32 -> %tmp_res
                                            self.backend.emit_cvtsi2ss_f32_r(&tmp_res, &tmp_op32);
                                        }
                                        _ => panic!("not implemented int length {}", op_ty_size)
981
                                    }
982 983
                                } else {
                                    panic!("expect double or float")
984 985 986 987 988
                                }
                            }
                            op::ConvOp::FPTOUI => {
                                let tmp_res = self.get_result_value(node);

989
                                assert!(self.match_fpreg(op), "unexpected op (expected fpreg): {}", op);
990
                                let tmp_op = self.emit_fpreg(op, f_content, f_context, vm);
991
                                let res_ty_size = vm.get_backend_type_info(tmp_res.ty.id()).size;
992

993 994 995 996 997
                                if from_ty.is_double() {
                                    match res_ty_size {
                                        8 => {
                                            let tmp1 = self.make_temporary(f_context, DOUBLE_TYPE.clone(), vm);
                                            let tmp2 = self.make_temporary(f_context, DOUBLE_TYPE.clone(), vm);
998

999 1000 1001
                                            // movsd FPTOUI_C_DOUBLE -> %tmp1
                                            let mem_c = self.get_mem_for_const(FPTOUI_C_DOUBLE.clone(), vm);
                                            self.backend.emit_movsd_f64_mem64(&tmp1, &mem_c);
1002

1003 1004
                                            // movapd %tmp_op -> %tmp2
                                            self.backend.emit_movapd_f64_f64(&tmp2, &tmp_op);
1005

1006 1007
                                            // subsd %tmp1, %tmp2 -> %tmp2
                                            self.backend.emit_subsd_f64_f64(&tmp2, &tmp1);
1008

1009 1010
                                            // cvttsd2si %tmp2 -> %tmp_res
                                            self.backend.emit_cvttsd2si_r_f64(&tmp_res, &tmp2);
1011

1012 1013 1014
                                            let tmp_const = self.make_temporary(f_context, UINT64_TYPE.clone(), vm);
                                            // mov 0x8000000000000000 -> %tmp_const
                                            self.backend.emit_mov_r64_imm64(&tmp_const, -9223372036854775808i64);
1015

1016 1017
                                            // xor %tmp_res, %tmp_const -> %tmp_const
                                            self.backend.emit_xor_r_r(&tmp_const, &tmp_res);
qinsoon's avatar
qinsoon committed
1018

1019 1020
                                            // cvttsd2si %tmp_op -> %tmp_res
                                            self.backend.emit_cvttsd2si_r_f64(&tmp_res, &tmp_op);
1021

1022 1023
                                            // ucomisd %tmp_op %tmp1
                                            self.backend.emit_ucomisd_f64_f64(&tmp1, &tmp_op);
1024

1025 1026 1027 1028 1029
                                            // cmovaeq %tmp_const -> %tmp_res
                                            self.backend.emit_cmovae_r_r(&tmp_res, &tmp_const);
                                        }
                                        4 => {
                                            let tmp_res64 = unsafe { tmp_res.as_type(UINT64_TYPE.clone()) };
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                                            // cvttsd2si %tmp_op -> %tmp_res(64)
                                            self.backend.emit_cvttsd2si_r_f64(&tmp_res64, &tmp_op);
                                        }
                                        2 | 1 => {
                                            let tmp_res32 = unsafe { tmp_res.as_type(UINT32_TYPE.clone()) };

                                            // cvttsd2si %tmp_op -> %tmp_res(32)
                                            self.backend.emit_cvttsd2si_r_f64(&tmp_res32, &tmp_op);

                                            // movz %tmp_res -> %tmp_res(32)
                                            self.backend.emit_movz_r_r(&tmp_res32, &tmp_res);
                                        }
                                        _ => panic!("not implemented int length {}", res_ty_size)
1044
                                    }
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
                                } else if from_ty.is_float() {
                                    match res_ty_size {
                                        8 => {
                                            let tmp1 = self.make_temporary(f_context, FLOAT_TYPE.clone(), vm);
                                            let tmp2 = self.make_temporary(f_context, FLOAT_TYPE.clone(), vm);

                                            // movss FPTOUI_C_FLOAT -> %tmp1
                                            let mem_c = self.get_mem_for_const(FPTOUI_C_FLOAT.clone(), vm);
                                            self.backend.emit_movss_f32_mem32(&tmp1, &mem_c);

                                            // movaps %tmp_op -> %tmp2
                                            self.backend.emit_movaps_f32_f32(&tmp2, &tmp_op);

                                            // subss %tmp1, %tmp2 -> %tmp2
                                            self.backend.emit_subss_f32_f32(&tmp2, &tmp1);

                                            // cvttss2si %tmp2 -> %tmp_res
                                            self.backend.emit_cvttss2si_r_f32(&tmp_res, &tmp2);

                                            let tmp_const = self.make_temporary(f_context, UINT64_TYPE.clone(), vm);
                                            // mov 0x8000000000000000 -> %tmp_const
                                            self.backend.emit_mov_r64_imm64(&tmp_const, -9223372036854775808i64);

                                            // xor %tmp_res, %tmp_const -> %tmp_const
                                            self.backend.emit_xor_r_r(&tmp_const, &tmp_res);
1070

1071 1072
                                            // cvttss2si %tmp_op -> %tmp_res
                                            self.backend.emit_cvttss2si_r_f32(&tmp_res, &tmp_op);
1073

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
                                            // ucomiss %tmp_op %tmp1
                                            self.backend.emit_ucomiss_f32_f32(&tmp1, &tmp_op);

                                            // cmovaeq %tmp_const -> %tmp_res
                                            self.backend.emit_cmovae_r_r(&tmp_res, &tmp_const);
                                        }
                                        4 => {
                                            let tmp_res64 = unsafe { tmp_res.as_type(UINT64_TYPE.clone())};

                                            // cvttss2si %tmp_op -> %tmp_res(64)
                                            self.backend.emit_cvttss2si_r_f32(&tmp_res64, &tmp_op);
                                        }
                                        2 | 1 => {
                                            let tmp_res32 = unsafe {tmp_res.as_type(UINT32_TYPE.clone())};

                                            // cvttss2si %tmp_op -> %tmp_res(32)
                                            self.backend.emit_cvttss2si_r_f32(&tmp_res32, &tmp_op);

                                            // movz %tmp_res(32) -> %tmp_res
                                            self.backend.emit_movz_r_r(&tmp_res32, &tmp_res);
                                        }
                                        _ => panic!("not implemented int length {}", res_ty_size)
1096
                                    }
1097 1098
                                } else {
                                    panic!("expect double or float")
1099 1100
                                }
                            }
qinsoon's avatar
qinsoon committed
1101 1102 1103
                            _ => unimplemented!()
                        }
                    }
1104
                    
1105 1106
                    // load on x64 generates mov inst (no matter what order is specified)
                    // https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
1107
                    Instruction_::Load{is_ptr, order, mem_loc} => {
qinsoon's avatar
qinsoon committed
1108 1109
                        trace!("instsel on LOAD");

1110
                        let ref ops = inst.ops;
1111
                        let ref loc_op = ops[mem_loc];
1112 1113 1114 1115 1116 1117
                        
                        // check order
                        match order {
                            MemoryOrder::Relaxed 
                            | MemoryOrder::Consume 
                            | MemoryOrder::Acquire
1118 1119
                            | MemoryOrder::SeqCst
                            | MemoryOrder::NotAtomic => {},
1120 1121
                            _ => panic!("didnt expect order {:?} with store inst", order)
                        }                        
1122

1123
                        let resolved_loc = self.emit_node_addr_to_value(loc_op, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
1124
                        let res_temp = self.get_result_value(node);
1125

1126 1127
                        if self.match_ireg(node) {
                            self.backend.emit_mov_r_mem(&res_temp, &resolved_loc);
qinsoon's avatar
qinsoon committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
                        } else if self.match_ireg_ex(node) {
                            let (res_l, res_h) = self.split_int128(&res_temp, f_context, vm);

                            // load lower half
                            self.backend.emit_mov_r_mem(&res_l, &resolved_loc);

                            // shift ptr, and load higher half
                            let loc = self.addr_const_offset_adjust(resolved_loc.extract_memory_location().unwrap(), POINTER_SIZE as u64, vm);
                            let val_loc = self.make_value_memory_location(loc, vm);
                            self.backend.emit_mov_r_mem(&res_h, &val_loc);
1138 1139 1140 1141 1142 1143 1144 1145 1146
                        } else if self.match_fpreg(node) {
                            match res_temp.ty.v {
                                MuType_::Double => self.backend.emit_movsd_f64_mem64(&res_temp, &resolved_loc),
                                MuType_::Float  => self.backend.emit_movss_f32_mem32(&res_temp, &resolved_loc),
                                _ => panic!("expect double or float")
                            }
                        } else {
                            unimplemented!()
                        }
1147 1148 1149
                    }
                    
                    Instruction_::Store{is_ptr, order, mem_loc, value} => {
qinsoon's avatar
qinsoon committed
1150 1151
                        trace!("instsel on STORE");

1152
                        let ref ops = inst.ops;
1153 1154 1155 1156 1157
                        let ref loc_op = ops[mem_loc];
                        let ref val_op = ops[value];
                        
                        let generate_plain_mov : bool = {
                            match order {
1158 1159 1160
                                MemoryOrder::Relaxed
                                | MemoryOrder::Release
                                | MemoryOrder::NotAtomic => true,
1161 1162 1163 1164 1165
                                MemoryOrder::SeqCst => false,
                                _ => panic!("didnt expect order {:?} with store inst", order)
                            }
                        };
                        
1166 1167 1168
                        let resolved_loc = self.emit_node_addr_to_value(loc_op, f_content, f_context, vm);

                        if self.match_iimm(val_op) {
1169
                            let (val, len) = self.node_iimm_to_i32_with_len(val_op);
1170
                            if generate_plain_mov {
1171
                                self.backend.emit_mov_mem_imm(&resolved_loc, val, len);
1172 1173 1174
                            } else {
                                unimplemented!()
                            }
1175 1176
                        } else if self.match_ireg(val_op) {
                            let val = self.emit_ireg(val_op, f_content, f_context, vm);
1177
                            if generate_plain_mov {
1178
                                self.backend.emit_mov_mem_r(&resolved_loc, &val);
1179 1180 1181
                            } else {
                                unimplemented!()
                            }
qinsoon's avatar
qinsoon committed
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
                        } else if self.match_ireg_ex(val_op) {
                            let (val_l, val_h) = self.emit_ireg_ex(val_op, f_content, f_context, vm);
                            if generate_plain_mov {
                                // store lower half
                                self.backend.emit_mov_mem_r(&resolved_loc, &val_l);

                                // shift pointer, and store higher hal
                                let loc = self.addr_const_offset_adjust(resolved_loc.extract_memory_location().unwrap(),
                                                                        POINTER_SIZE as u64, vm);
                                let loc_val = self.make_value_memory_location(loc, vm);

                                self.backend.emit_mov_mem_r(&loc_val, &val_h);
                            } else {
                                unimplemented!()
                            }
1197
                        } else if self.match_fpreg(val_op) {
qinsoon's avatar
qinsoon committed
1198 1199
                            let val = self.emit_fpreg(val_op, f_content, f_context, vm);

1200 1201 1202 1203 1204 1205 1206
                            match val.ty.v {
                                MuType_::Double => self.backend.emit_movsd_mem64_f64(&resolved_loc, &val),
                                MuType_::Float  => self.backend.emit_movss_mem32_f32(&resolved_loc, &val),
                                _ => panic!("unexpected fp type: {}", val.ty)
                            }
                        } else {
                            unimplemented!()
1207 1208
                        }
                    }
1209

1210 1211 1212 1213
                    // memory insts: calculate the address, then lea
                    Instruction_::GetIRef(_)
                    | Instruction_::GetFieldIRef{..}
                    | Instruction_::GetVarPartIRef{..}
1214 1215 1216
                    | Instruction_::ShiftIRef{..}
                    | Instruction_::GetElementIRef{..} => {
                        trace!("instsel on GET/FIELD/VARPART/SHIFT/ELEM IREF");
qinsoon's avatar
qinsoon committed
1217

1218 1219
                        let mem_addr = self.emit_get_mem_from_inst(node, f_content, f_context, vm);
                        let tmp_res  = self.get_result_value(node);
1220

1221
                        self.backend.emit_lea_r64(&tmp_res, &mem_addr);
1222
                    }
1223
                    
1224
                    Instruction_::ThreadExit => {
qinsoon's avatar
qinsoon committed
1225
                        trace!("instsel on THREADEXIT");
1226
                        // emit a call to swap_back_to_native_stack(sp_loc: Address)
1227 1228
                        
                        // get thread local and add offset to get sp_loc
qinsoon's avatar
qinsoon committed
1229
                        let tl = self.emit_get_threadlocal(Some(node), f_content, f_context, vm);
1230
                        self.backend.emit_add_r_imm(&tl, *thread::NATIVE_SP_LOC_OFFSET as i32);
1231
                        
qinsoon's avatar
qinsoon committed
1232
                        self.emit_runtime_entry(&entrypoints::SWAP_BACK_TO_NATIVE_STACK, vec![tl.clone()], None, Some(node), f_content, f_context, vm);
1233
                    }
1234 1235

                    Instruction_::CommonInst_GetThreadLocal => {
qinsoon's avatar
qinsoon committed
1236
                        trace!("instsel on GETTHREADLOCAL");
1237 1238 1239 1240 1241 1242 1243 1244 1245
                        // get thread local
                        let tl = self.emit_get_threadlocal(Some(node), f_content, f_context, vm);

                        let tmp_res = self.get_result_value(node);

                        // load [tl + USER_TLS_OFFSET] -> tmp_res
                        self.emit_load_base_offset(&tmp_res, &tl, *thread::USER_TLS_OFFSET as i32, vm);
                    }
                    Instruction_::CommonInst_SetThreadLocal(op) => {
qinsoon's avatar
qinsoon committed
1246 1247
                        trace!("instsel on SETTHREADLOCAL");

1248
                        let ref ops = inst.ops;
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
                        let ref op = ops[op];

                        debug_assert!(self.match_ireg(op));

                        let tmp_op = self.emit_ireg(op, f_content, f_context, vm);

                        // get thread local
                        let tl = self.emit_get_threadlocal(Some(node), f_content, f_context, vm);

                        // store tmp_op -> [tl + USER_TLS_OFFSTE]
                        self.emit_store_base_offset(&tl, *thread::USER_TLS_OFFSET as i32, &tmp_op, vm);
                    }
1261

1262 1263 1264 1265 1266
                    Instruction_::CommonInst_Pin(op) => {
                        trace!("instsel on PIN");

                        if !mm::GC_MOVES_OBJECT {
                            // non-moving GC: pin is a nop (move from op to result)
1267
                            let ref ops = inst.ops;
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
                            let ref op = ops[op];

                            let tmp_res = self.get_result_value(node);

                            self.emit_move_node_to_value(&tmp_res, op, f_content, f_context, vm);
                        } else {
                            unimplemented!()
                        }
                    }
                    Instruction_::CommonInst_Unpin(_) => {
                        trace!("instsel on UNPIN");

                        if !mm::GC_MOVES_OBJECT {
                            // do nothing
                        } else {
                            unimplemented!()
                        }
                    }


1288
                    Instruction_::Move(op) => {
qinsoon's avatar
qinsoon committed
1289 1290
                        trace!("instsel on MOVE (internal IR)");

1291
                        let ref ops = inst.ops;
1292 1293 1294 1295 1296 1297
                        let ref op = ops[op];

                        let tmp_res = self.get_result_value(node);

                        self.emit_move_node_to_value(&tmp_res, op, f_content, f_context, vm);
                    }
1298 1299
                    
                    Instruction_::New(ref ty) => {
qinsoon's avatar
qinsoon committed
1300 1301
                        trace!("instsel on NEW");

qinsoon's avatar
qinsoon committed
1302 1303 1304 1305 1306 1307 1308
                        if cfg!(debug_assertions) {
                            match ty.v {
                                MuType_::Hybrid(_) => panic!("cannot use NEW for hybrid, use NEWHYBRID instead"),
                                _ => {}
                            }
                        }

1309
                        let ty_info = vm.get_backend_type_info(ty.id());
qinsoon's avatar
qinsoon committed
1310
                        let size = ty_info.size;
1311
                        let ty_align= ty_info.alignment;
qinsoon's avatar
qinsoon committed
1312 1313

                        let const_size = self.make_value_int_const(size as u64, vm);
qinsoon's avatar
qinsoon committed
1314 1315

                        let tmp_allocator = self.emit_get_allocator(node, f_content, f_context, vm);
1316
                        let tmp_res = self.emit_alloc_sequence(tmp_allocator.clone(), const_size, ty_align, node, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
1317 1318 1319 1320 1321 1322 1323 1324 1325

                        // ASM: call muentry_init_object(%allocator, %tmp_res, %encode)
                        let encode = self.make_value_int_const(mm::get_gc_type_encode(ty_info.gc_type.id), vm);
                        self.emit_runtime_entry(
                            &entrypoints::INIT_OBJ,
                            vec![tmp_allocator.clone(), tmp_res.clone(), encode],
                            None,
                            Some(node), f_content, f_context, vm
                        );
qinsoon's avatar
qinsoon committed
1326 1327 1328
                    }

                    Instruction_::NewHybrid(ref ty, var_len) => {
qinsoon's avatar
qinsoon committed
1329 1330
                        trace!("instsel on NEWHYBRID");

qinsoon's avatar
qinsoon committed
1331 1332 1333 1334 1335
                        if cfg!(debug_assertions) {
                            match ty.v {
                                MuType_::Hybrid(_) => {},
                                _ => panic!("NEWHYBRID is only for allocating hybrid types, use NEW for others")
                            }
1336
                        }
qinsoon's avatar
qinsoon committed
1337 1338 1339 1340

                        let ty_info = vm.get_backend_type_info(ty.id());
                        let ty_align = ty_info.alignment;
                        let fix_part_size = ty_info.size;
1341 1342 1343
                        let var_ty_size = match ty_info.elem_padded_size {
                            Some(sz) => sz,
                            None => panic!("expect HYBRID type here with elem_padded_size, found {}", ty_info)
qinsoon's avatar
qinsoon committed
1344 1345 1346
                        };

                        // actual size = fix_part_size + var_ty_size * len
qinsoon's avatar
qinsoon committed
1347
                        let (actual_size, length) = {
1348
                            let ref ops = inst.ops;
qinsoon's avatar
qinsoon committed
1349 1350 1351 1352 1353 1354
                            let ref var_len = ops[var_len];

                            if self.match_iimm(var_len) {
                                let var_len = self.node_iimm_to_i32(var_len);
                                let actual_size = fix_part_size + var_ty_size * (var_len as usize);

qinsoon's avatar
qinsoon committed
1355 1356 1357 1358
                                (
                                    self.make_value_int_const(actual_size as u64, vm),
                                    self.make_value_int_const(var_len as u64, vm)
                                )
qinsoon's avatar
qinsoon committed
1359 1360 1361 1362
                            } else {
                                let tmp_actual_size = self.make_temporary(f_context, UINT64_TYPE.clone(), vm);
                                let tmp_var_len = self.emit_ireg(var_len, f_content, f_context, vm);

1363
                                match math::is_power_of_two(var_ty_size) {
qinsoon's avatar
qinsoon committed
1364
                                    Some(shift) => {
1365 1366 1367
                                        // use tmp_actual_size as result - we do not want to change tmp_var_len
                                        self.backend.emit_mov_r_r(&tmp_actual_size, &tmp_var_len);

qinsoon's avatar
qinsoon committed
1368 1369
                                        if shift != 0 {
                                            // a shift-left will get the total size of var part
1370
                                            self.backend.emit_shl_r_imm8(&tmp_actual_size, shift as i8);
qinsoon's avatar
qinsoon committed
1371
                                        }
qinsoon's avatar
qinsoon committed
1372 1373

                                        // add with fix-part size
1374
                                        self.backend.emit_add_r_imm(&tmp_actual_size, fix_part_size as i32);
qinsoon's avatar
qinsoon committed
1375 1376 1377 1378 1379
                                    }
                                    None => {
                                        // we need to do a multiply

                                        // mov var_ty_size -> rax
1380
                                        self.backend.emit_mov_r_imm(&x86_64::RAX, var_ty_size as i32);
qinsoon's avatar
qinsoon committed
1381 1382

                                        // mul tmp_var_len, rax -> rdx:rax
1383
                                        self.backend.emit_mul_r(&tmp_var_len);
qinsoon's avatar
qinsoon committed
1384 1385

                                        // add with fix-part size
1386
                                        self.backend.emit_add_r_imm(&x86_64::RAX, fix_part_size as i32);
qinsoon's avatar
qinsoon committed
1387 1388

                                        // mov result to tmp_actual_size
1389
                                        self.backend.emit_mov_r_r(&tmp_actual_size, &x86_64::RAX);
qinsoon's avatar
qinsoon committed
1390 1391 1392
                                    }
                                }

qinsoon's avatar
qinsoon committed
1393
                                (tmp_actual_size, tmp_var_len)
qinsoon's avatar
qinsoon committed
1394 1395 1396
                            }
                        };

qinsoon's avatar
qinsoon committed
1397
                        let tmp_allocator = self.emit_get_allocator(node, f_content, f_context, vm);
1398
                        let tmp_res = self.emit_alloc_sequence(tmp_allocator.clone(), actual_size, ty_align, node, f_content, f_context, vm);
qinsoon's avatar
qinsoon committed
1399 1400 1401 1402 1403 1404 1405 1406 1407

                        // ASM: call muentry_init_object(%allocator, %tmp_res, %encode)
                        let encode = self.make_value_int_const(mm::get_gc_type_encode(ty_info.gc_type.id), vm);
                        self.emit_runtime_entry(
                            &entrypoints::INIT_HYBRID,
                            vec![tmp_allocator.clone(), tmp_res.clone(), encode, length],
                            None,
                            Some(node), f_content, f_context, vm
                        );
<